<commit_before>/** @format */
import statemachine from "@/statemachine"
import { setDefaultConfigValues } from "./settings"

const korpFailImg = require("../img/korp_fail.svg")
const deparam = require("jquery-deparam")

import jStorage from "../lib/jstorage"

window.authenticationProxy = new model.AuthenticationProxy()
window.timeProxy = new model.TimeProxy()

const creds = jStorage.get("creds")
if (creds) {
    authenticationProxy.loginObj = creds
    statemachine.send("USER_FOUND", creds)
} else {
    statemachine.send("USER_NOT_FOUND")
}

// rewriting old url format to the angular one
if (location.hash.length && location.hash[1] !== "?") {
    location.hash = `#?${_.trimStart(location.hash, "#")}`
}

$.ajaxSetup({
    dataType: "json",
    traditional: true,
})

$.ajaxPrefilter("json", function (options) {
    if (options.crossDomain && !$.support.cors) {
        return "jsonp"
    }
})

const loc_dfd = window.initLocales()
$(document).keyup(function (event) {
    if (event.keyCode === 27) {
        if (kwicResults) {
            kwicResults.abort()
        }
        if ("lemgramResults" in window) {
            lemgramResults.abort()
        }
        if (statsResults) {
            statsResults.abort()
        }
    }
})

const corpusSettingsPromise = new Promise((resolve, reject) => {
    const labParam = window.isLab ? "&include_lab" : ""
    fetch(`${settings.korpBackendURL}/corpus_config?mode=${window.currentMode}${labParam}`).then((response) => {
        response.json().then((modeSettings) => {

            function rename(obj, from, to) {
                if (obj[from]) {
                    obj[to] = obj[from]
                    delete obj[from]
                }
            }

            rename(modeSettings["attributes"], "pos_attributes", "attributes")
            rename(modeSettings["attributes"], "struct_attributes", "structAttributes")
            rename(modeSettings["attributes"], "custom_attributes", "customAttributes")

            for (const attrType of ["attributes", "structAttributes", "customAttributes"]) {
                for (const attrId in modeSettings["attributes"][attrType]) {
                    const attr = modeSettings["attributes"][attrType][attrId]
                    rename(attr, "extended_component", "extendedComponent")
                    rename(attr, "sidebar_component", "sidebarComponent")
                    rename(attr, "external_search", "externalSearch")
                    rename(attr, "display_type", "displayType")
                    rename(attr, "group_by", "groupBy")
                    rename(attr, "hide_sidebar", "hideSidebar")
                    rename(attr, "hide_statistics", "hideStatistics")
                    rename(attr, "hide_extended", "hideExtended")
                    rename(attr, "hide_compare", "hideCompare")
                    rename(attr, "extended_template", "extendedTemplate")
                    rename(attr, "sidebar_info_url", "sidebarInfoUrl")
                    rename(attr, "internal_search", "internalSearch")
                    rename(attr, "is_struct_attr", "isStructAttr")
                    rename(attr, "custom_type", "customType")
                }
            }

            // take the backend configuration format for attributes and expand it
            // TODO the internal representation should be changed to a new, more compact one.
            for (const corpusId in modeSettings["corpora"]) {
                const corpus = modeSettings["corpora"][corpusId]

                rename(corpus, "pos_attributes", "attributes")
                rename(corpus, "struct_attributes", "structAttributes")
                rename(corpus, "custom_attributes", "customAttributes")
                rename(corpus, "linked_to", "linkedTo")
                rename(corpus, "limited_access", "limitedAccess")
                rename(corpus, "reading_mode", "readingMode")

                // These are not used in our backend configuration, but it should be possible?
                rename(corpus, "default_language", "defaultLanguage")

                // These should not be done in the backend probably
                rename(corpus, "visible_modes", "visibleModes")
                rename(corpus, "mode_config", "modeConfig")

                // TODO the error is that the attributes should be fixed once, while traversing the top level "attributes"-object
                // Then expand format for each corpus

                for (const attrType of ["attributes", "structAttributes", "customAttributes"]) {
                    const attrList = corpus[attrType]
                    const attrs = {}
                    for (const attrIdx in attrList) {
                        const attr = modeSettings["attributes"][attrType][attrList[attrIdx]]
                        attrs[attr.name] = attr
                    }
                    // attrs is an object of attribute settings
                    corpus[attrType] = attrs
                    // attrList is an ordered list of the preferred order of attributes
                    corpus[attrType + "Order"] = attrList
                }
            }

            delete modeSettings["attributes"]

            rename(modeSettings, "folders", "corporafolders")
            if (!modeSettings["corporafolders"]) {
                modeSettings["corporafolders"] = {}
            }
            rename(modeSettings, "preselected_corpora", "preselectedCorpora")
            rename(modeSettings, "start_lang", "startLang")
            rename(modeSettings, "default_overview_context", "defaultOverviewContext")
            rename(modeSettings, "default_reading_context", "defaultReadingContext")
            rename(modeSettings, "default_within", "defaultWithin")
            rename(modeSettings, "hits_per_page_default", "hitsPerPageDefault")
            rename(modeSettings, "hits_per_page_values", "hitsPerPageValues")

            resolve(modeSettings)
        })
    })
})

Promise.all([loc_dfd, corpusSettingsPromise]).then(([locData, modeSettings]) => {
    _.assign(window.settings, modeSettings)

    setDefaultConfigValues()

    const corpora = settings.corpora

    if (!window.currentModeParallel) {
        settings.corpusListing = new CorpusListing(corpora)
    } else {
        settings.corpusListing = new ParallelCorpusListing(corpora)
    }

    // rewriting old language codes to new ones
    if (location.hash.includes("lang=")) {
        const match = /lang\=(.*?)(&|$)/.exec(location.hash)
        if (match) {
            const lang = match[1]
            if (settings.isoLanguages[lang]) {
                location.hash = location.hash.replace(`lang=${lang}`, `lang=${settings.isoLanguages[lang]}`)
            }
        }
    }

    try {
        angular.bootstrap(document, ["korpApp"])
    } catch (error) {
        c.error(error)
    }

    try {
        const corpus = locationSearch()["corpus"]
        if (corpus) {
            settings.corpusListing.select(corpus.split(","))
        }
        view.updateSearchHistory()
    } catch (error1) {
        c.error("ERROR setting corpora from location", error1)
    }

    if (isLab) {
        $("body").addClass("lab")
    }

    $("body").addClass(`mode-${window.currentMode}`)
    util.browserWarn()

    $("#search_history").change(function (event) {
        const target = $(this).find(":selected")
        if (_.includes(["http://", "https:/"], target.val().slice(0, 7))) {
            location.href = target.val()
        } else if (target.is(".clear")) {
            jStorage.set("searches", [])
            view.updateSearchHistory()
        }
    })

    let prevFragment = {}
    // Note that this is _not_ window.onhashchange (lowercase only) and is not called by the browser
    window.onHashChange = function (event, isInit) {
        const hasChanged = (key) => prevFragment[key] !== locationSearch()[key]
        if (hasChanged("lang")) {
            const newLang = locationSearch().lang || settings.defaultLanguage
            $("body").scope().lang = newLang
            window.lang = newLang
            util.localize()

            $("#languages").radioList("select", newLang)
        }

        if (isInit) {
            util.localize()
        }

        prevFragment = _.extend({}, locationSearch())
    }

    $("#languages").radioList({
        change() {
            const currentLang = $(this).radioList("getSelected").data("mode")
            locationSearch({
                lang: currentLang !== settings.defaultLanguage ? currentLang : null,
            })
        },
        // TODO: this does nothing?
        selected: settings.defaultLanguage,
    })

    setTimeout(() => window.onHashChange(null, true), 0)
    $("body").animate({ opacity: 1 }, function () {
        $(this).css("opacity", "")
    })
})
<commit_msg>reformat<commit_after>/** @format */
import statemachine from "@/statemachine"
import { setDefaultConfigValues } from "./settings"

const korpFailImg = require("../img/korp_fail.svg")
const deparam = require("jquery-deparam")

import jStorage from "../lib/jstorage"

window.authenticationProxy = new model.AuthenticationProxy()
window.timeProxy = new model.TimeProxy()

const creds = jStorage.get("creds")
if (creds) {
    authenticationProxy.loginObj = creds
    statemachine.send("USER_FOUND", creds)
} else {
    statemachine.send("USER_NOT_FOUND")
}

// rewriting old url format to the angular one
if (location.hash.length && location.hash[1] !== "?") {
    location.hash = `#?${_.trimStart(location.hash, "#")}`
}

$.ajaxSetup({
    dataType: "json",
    traditional: true,
})

$.ajaxPrefilter("json", function (options) {
    if (options.crossDomain && !$.support.cors) {
        return "jsonp"
    }
})

const loc_dfd = window.initLocales()
$(document).keyup(function (event) {
    if (event.keyCode === 27) {
        if (kwicResults) {
            kwicResults.abort()
        }
        if ("lemgramResults" in window) {
            lemgramResults.abort()
        }
        if (statsResults) {
            statsResults.abort()
        }
    }
})

const corpusSettingsPromise = new Promise((resolve, reject) => {
    const labParam = window.isLab ? "&include_lab" : ""
    fetch(`${settings.korpBackendURL}/corpus_config?mode=${window.currentMode}${labParam}`).then((response) => {
        response.json().then((modeSettings) => {
            function rename(obj, from, to) {
                if (obj[from]) {
                    obj[to] = obj[from]
                    delete obj[from]
                }
            }

            rename(modeSettings["attributes"], "pos_attributes", "attributes")
            rename(modeSettings["attributes"], "struct_attributes", "structAttributes")
            rename(modeSettings["attributes"], "custom_attributes", "customAttributes")

            for (const attrType of ["attributes", "structAttributes", "customAttributes"]) {
                for (const attrId in modeSettings["attributes"][attrType]) {
                    const attr = modeSettings["attributes"][attrType][attrId]
                    rename(attr, "extended_component", "extendedComponent")
                    rename(attr, "sidebar_component", "sidebarComponent")
                    rename(attr, "external_search", "externalSearch")
                    rename(attr, "display_type", "displayType")
                    rename(attr, "group_by", "groupBy")
                    rename(attr, "hide_sidebar", "hideSidebar")
                    rename(attr, "hide_statistics", "hideStatistics")
                    rename(attr, "hide_extended", "hideExtended")
                    rename(attr, "hide_compare", "hideCompare")
                    rename(attr, "extended_template", "extendedTemplate")
                    rename(attr, "sidebar_info_url", "sidebarInfoUrl")
                    rename(attr, "internal_search", "internalSearch")
                    rename(attr, "is_struct_attr", "isStructAttr")
                    rename(attr, "custom_type", "customType")
                }
            }

            // take the backend configuration format for attributes and expand it
            // TODO the internal representation should be changed to a new, more compact one.
            for (const corpusId in modeSettings["corpora"]) {
                const corpus = modeSettings["corpora"][corpusId]

                rename(corpus, "pos_attributes", "attributes")
                rename(corpus, "struct_attributes", "structAttributes")
                rename(corpus, "custom_attributes", "customAttributes")
                rename(corpus, "linked_to", "linkedTo")
                rename(corpus, "limited_access", "limitedAccess")
                rename(corpus, "reading_mode", "readingMode")

                // These are not used in our backend configuration, but it should be possible?
                rename(corpus, "default_language", "defaultLanguage")

                // These should not be done in the backend probably
                rename(corpus, "visible_modes", "visibleModes")
                rename(corpus, "mode_config", "modeConfig")

                // TODO the error is that the attributes should be fixed once, while traversing the top level "attributes"-object
                // Then expand format for each corpus

                for (const attrType of ["attributes", "structAttributes", "customAttributes"]) {
                    const attrList = corpus[attrType]
                    const attrs = {}
                    for (const attrIdx in attrList) {
                        const attr = modeSettings["attributes"][attrType][attrList[attrIdx]]
                        attrs[attr.name] = attr
                    }
                    // attrs is an object of attribute settings
                    corpus[attrType] = attrs
                    // attrList is an ordered list of the preferred order of attributes
                    corpus[attrType + "Order"] = attrList
                }
            }

            delete modeSettings["attributes"]

            rename(modeSettings, "folders", "corporafolders")
            if (!modeSettings["corporafolders"]) {
                modeSettings["corporafolders"] = {}
            }
            rename(modeSettings, "preselected_corpora", "preselectedCorpora")
            rename(modeSettings, "start_lang", "startLang")
            rename(modeSettings, "default_overview_context", "defaultOverviewContext")
            rename(modeSettings, "default_reading_context", "defaultReadingContext")
            rename(modeSettings, "default_within", "defaultWithin")
            rename(modeSettings, "hits_per_page_default", "hitsPerPageDefault")
            rename(modeSettings, "hits_per_page_values", "hitsPerPageValues")

            resolve(modeSettings)
        })
    })
})

Promise.all([loc_dfd, corpusSettingsPromise]).then(([locData, modeSettings]) => {
    _.assign(window.settings, modeSettings)

    setDefaultConfigValues()

    const corpora = settings.corpora

    if (!window.currentModeParallel) {
        settings.corpusListing = new CorpusListing(corpora)
    } else {
        settings.corpusListing = new ParallelCorpusListing(corpora)
    }

    // rewriting old language codes to new ones
    if (location.hash.includes("lang=")) {
        const match = /lang\=(.*?)(&|$)/.exec(location.hash)
        if (match) {
            const lang = match[1]
            if (settings.isoLanguages[lang]) {
                location.hash = location.hash.replace(`lang=${lang}`, `lang=${settings.isoLanguages[lang]}`)
            }
        }
    }

    try {
        angular.bootstrap(document, ["korpApp"])
    } catch (error) {
        c.error(error)
    }

    try {
        const corpus = locationSearch()["corpus"]
        if (corpus) {
            settings.corpusListing.select(corpus.split(","))
        }
        view.updateSearchHistory()
    } catch (error1) {
        c.error("ERROR setting corpora from location", error1)
    }

    if (isLab) {
        $("body").addClass("lab")
    }

    $("body").addClass(`mode-${window.currentMode}`)
    util.browserWarn()

    $("#search_history").change(function (event) {
        const target = $(this).find(":selected")
        if (_.includes(["http://", "https:/"], target.val().slice(0, 7))) {
            location.href = target.val()
        } else if (target.is(".clear")) {
            jStorage.set("searches", [])
            view.updateSearchHistory()
        }
    })

    let prevFragment = {}
    // Note that this is _not_ window.onhashchange (lowercase only) and is not called by the browser
    window.onHashChange = function (event, isInit) {
        const hasChanged = (key) => prevFragment[key] !== locationSearch()[key]
        if (hasChanged("lang")) {
            const newLang = locationSearch().lang || settings.defaultLanguage
            $("body").scope().lang = newLang
            window.lang = newLang
            util.localize()

            $("#languages").radioList("select", newLang)
        }

        if (isInit) {
            util.localize()
        }

        prevFragment = _.extend({}, locationSearch())
    }

    $("#languages").radioList({
        change() {
            const currentLang = $(this).radioList("getSelected").data("mode")
            locationSearch({
                lang: currentLang !== settings.defaultLanguage ? currentLang : null,
            })
        },
        // TODO: this does nothing?
        selected: settings.defaultLanguage,
    })

    setTimeout(() => window.onHashChange(null, true), 0)
    $("body").animate({ opacity: 1 }, function () {
        $(this).css("opacity", "")
    })
})
<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.2;
      faketime(t_offset);
    }
    try {
      child_process.execFileSync('git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    var timeout;
    if (<commit_msg>Five bullets or six?<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.2;
      faketime(t_offset);
    }
    try {
      child_process.execFileSync('git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    var timeout;
    if (p<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.2;
      faketime(t_offset);
    }
    try {
      child_process.execFileSync('git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    var timeout;
    if (process.env.FAKETIME) {
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = randomIntFromInterval(0, max_sleep) * 1000
    }
    setTimeout(commit, timeout, t_offset, outFD, outFile, data, counter, length);
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [max_time_in_seconds] [step]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= endTime) {;}
}

function randomIntFromInterval(min,max)
{
   return Math.floor(Math.random()*(max-min+1)+min);
}

function commit(t_off<commit_msg>Fixing an important issue with the universe.<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.2;
      faketime(t_offset);
    }
    try {
      child_process.execFileSync('git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    var timeout;
    if (process.env.FAKETIME) {
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = randomIntFromInterval(0, max_sleep) * 1000
    }
    setTimeout(commit, timeout, t_offset, outFD, outFile, data, counter, length);
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [max_time_in_seconds] [step]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= endTime) {;}
}

function randomIntFromInterval(min,max)
{
   return Math.floor(Math.random()*(max-min+1)+min);
}

function commit(t_offs<|endoftext|>


<commit_before>'use strict';

var localforage = require('localforage');

var $body = $('body');
['theme', 'mode'].forEach(function (property) {
  localforage.getItem(property, function (value) {
    if (!value) {
      value = 'default';
      localforage.setItem(property, value);
    }
    $body.addClass(property + '-' + value);
    $body.attr('data-' + property, value);
    if (property === 'mode' && value !== 'default') {
      $('#mode').attr('href', '/styles/' + value + '.min.css');
    }
  });
});

var App = require('./app');
App.start();
<commit_msg>Analyse themes and modes<commit_after>'use strict';

var localforage = require('localforage');

var $body = $('body');
['theme', 'mode'].forEach(function (property) {
  localforage.getItem(property, function (value) {
    if (!value) {
      value = 'default';
      localforage.setItem(property, value);
    } else {
      // For non-first time users, we want to see what modes/themes they are using.
      if (property === 'theme') {
        ga('send', 'event', 'Theme', 'Load page with theme', value);
      }
      if (property === 'mode') {
        ga('send', 'event', 'Mode', 'Load page with mode', value);
      }
    }
    $body.addClass(property + '-' + value);
    $body.attr('data-' + property, value);
    if (property === 'mode' && value !== 'default') {
      $('#mode').attr('href', '/styles/' + value + '.min.css');
    }
  });
});

var App = require('./app');
App.start();
<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a t<commit_msg>Fixed a typo<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a ty<|endoftext|>


<commit_before>/*global require*/
'use strict';

requirejs.config({
  baseUrl: 'scripts',
  shim: {
    handlebars: {
      exports: 'Handlebars'
    },
    cryptojs: {
      exports: 'CryptoJS'
    },
    progressbar: {
      exports: 'ProgressBar'
    },
    minEmoji: {
      exports: 'minEmoji'
    },
    chromaHash: ['jquery']
  },
  paths: {
    // libs
    cryptojs: 'https://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/aes',
    videojs: '//vjs.zencdn.net/4.6/video',
    jquery: '../bower_components/jquery/dist/jquery',
    underscore: '../bower_components/underscore/underscore',
    // lodash: '../bower_components/lodash/dist/lodash',
    backbone: '../bower_components/backbone/backbone',
    handlebars: '../bower_components/handlebars/handlebars',
    quickblox: '../bower_components/quickblox/quickblox.min',
    progressbar: '../bower_components/progressbar.js/lib/control/progressbar',
    loadImage: '../bower_components/blueimp-load-image/js/load-image',
    canvasToBlob: '../bower_components/blueimp-canvas-to-blob/js/canvas-to-blob',
    mCustomScrollbar: '../bower_components/malihu-custom-scrollbar-plugin/jquery.mCustomScrollbar',
    nicescroll: '../bower_components/jquery.nicescroll/jquery.nicescroll',
    mousewheel: '../bower_components/jquery-mousewheel/jquery.mousewheel',
    timeago: '../bower_components/jquery-timeago/jquery.timeago',
    minEmoji: '../vendor/emoji/js/minEmoji',
    chromaHash: '../bower_components/Chroma-Hash/jquery.chroma-hash',

    // Q-municate application
    config: '../config',
    MainModule: 'app',
    // models
    UserModule: 'models/user',
    SessionModule: 'models/session',
    ContactModule: 'models/contact',
    DialogModule: 'models/dialog',
    MessageModule: 'models/message',
    AttachModule: 'models/attach',
    ContactListModule: 'models/contact_list',
    VideoChatModule: 'models/videochat',
    // views
    UserView: 'views/user',
    DialogView: 'views/dialog',
    MessageView: 'views/message',
    AttachView: 'views/attach',
    ContactListView: 'views/contact_list',
    VideoChatView: 'views/videochat',
    // routes and events
    Events: 'events',
    // Routes: 'routes',
    QBApiCalls: 'qbApiCalls'
  }
});

requirejs([
  'jquery', 'config',
  'minEmoji', 'MainModule',
  'backbone',
], function ($, QMCONFIG, minEmoji, QM, Backbone) {
  var APP;
  Backbone.history.start();

  // Application initialization
  $(document).ready(function() {
    $.ajaxSetup({ cache: true });
    $.getScript('https://connect.facebook.net/en_US/sdk.js', function() {
      FB.init({
        appId: QMCONFIG.fbAccount.appId,
        version: 'v2.1'
      });
      if (QMCONFIG.debug) console.log('FB init', FB);

      // emoji smiles run
      $('.smiles-group').each(function() {
        var obj = $(this);
        obj.html(minEmoji(obj.text()));
      });

      APP = new QM();
      APP.init();
    });
  });

});
<commit_msg>Backbone.history.start() commited<commit_after>/*global require*/
'use strict';

requirejs.config({
  baseUrl: 'scripts',
  shim: {
    handlebars: {
      exports: 'Handlebars'
    },
    cryptojs: {
      exports: 'CryptoJS'
    },
    progressbar: {
      exports: 'ProgressBar'
    },
    minEmoji: {
      exports: 'minEmoji'
    },
    chromaHash: ['jquery']
  },
  paths: {
    // libs
    cryptojs: 'https://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/aes',
    videojs: '//vjs.zencdn.net/4.6/video',
    jquery: '../bower_components/jquery/dist/jquery',
    underscore: '../bower_components/underscore/underscore',
    // lodash: '../bower_components/lodash/dist/lodash',
    backbone: '../bower_components/backbone/backbone',
    handlebars: '../bower_components/handlebars/handlebars',
    quickblox: '../bower_components/quickblox/quickblox.min',
    progressbar: '../bower_components/progressbar.js/lib/control/progressbar',
    loadImage: '../bower_components/blueimp-load-image/js/load-image',
    canvasToBlob: '../bower_components/blueimp-canvas-to-blob/js/canvas-to-blob',
    mCustomScrollbar: '../bower_components/malihu-custom-scrollbar-plugin/jquery.mCustomScrollbar',
    nicescroll: '../bower_components/jquery.nicescroll/jquery.nicescroll',
    mousewheel: '../bower_components/jquery-mousewheel/jquery.mousewheel',
    timeago: '../bower_components/jquery-timeago/jquery.timeago',
    minEmoji: '../vendor/emoji/js/minEmoji',
    chromaHash: '../bower_components/Chroma-Hash/jquery.chroma-hash',

    // Q-municate application
    config: '../config',
    MainModule: 'app',
    // models
    UserModule: 'models/user',
    SessionModule: 'models/session',
    ContactModule: 'models/contact',
    DialogModule: 'models/dialog',
    MessageModule: 'models/message',
    AttachModule: 'models/attach',
    ContactListModule: 'models/contact_list',
    VideoChatModule: 'models/videochat',
    // views
    UserView: 'views/user',
    DialogView: 'views/dialog',
    MessageView: 'views/message',
    AttachView: 'views/attach',
    ContactListView: 'views/contact_list',
    VideoChatView: 'views/videochat',
    // routes and events
    Events: 'events',
    // Routes: 'routes',
    QBApiCalls: 'qbApiCalls'
  }
});

requirejs([
  'jquery', 'config',
  'minEmoji', 'MainModule',
  'backbone',
], function ($, QMCONFIG, minEmoji, QM, Backbone) {
  var APP;
  // Backbone.history.start();

  // Application initialization
  $(document).ready(function() {
    $.ajaxSetup({ cache: true });
    $.getScript('https://connect.facebook.net/en_US/sdk.js', function() {
      FB.init({
        appId: QMCONFIG.fbAccount.appId,
        version: 'v2.1'
      });
      if (QMCONFIG.debug) console.log('FB init', FB);

      // emoji smiles run
      $('.smiles-group').each(function() {
        var obj = $(this);
        obj.html(minEmoji(obj.text()));
      });

      APP = new QM();
      APP.init();
    });
  });

});
<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the<commit_msg>Quick fix<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the <|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatib<commit_msg>Updated the readme again<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatibl<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var args = ['commit', outFile, '-m', 'Update character']
    for (var counter = 0; counter < length; counter++)
    {
      fs.writeSync(outFD, data.slice(counter, counter+1), 0, 1)
      sleep(Math.random() * max_sleep)
      child_process.execFileSync('/usr/bin/git', args)
    }
  })
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTi<commit_msg>Update character<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var args = ['commit', outFile, '-m', 'Update character']
    for (var counter = 0; counter < length; counter++)
    {
      fs.writeSync(outFD, data.slice(counter, counter+1), 0, 1)
      sleep(Math.random() * max_sleep)
      child_process.execFileSync('/usr/bin/git', args)
    }
  })
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTim<|endoftext|>


<commit_before>import { types, getParent, process } from "mobx-state-tree"

export const Book = types.model("Book", {
    id: types.identifier(),
    name: types.string,
    author: types.string,
    price: types.number,
    isAvailable: true
})

export const BookStore = types
    .model("BookStore", {
        isLoading: true,
        books: types.map(Book)
    })
    .views(self => ({
        get shop() {
            return getParent(self)
        },
        get sortedAvailableBooks() {
            return sortBooks(self.books.values())
        }
    }))
    .actions(self => {
        function markLoading(loading) {
            self.isLoading = loading
        }

        function updateBooks(json) {
            self.books.values().forEach(book => (book.isAvailable = false))
            json.forEach(bookJson => {
                self.books.put(bookJson)
                self.books.get(bookJson.id).isAvailable = true
            })
        }

        const loadBooks = process(function* loadBooks() {
            try {
                const json = yield self.shop.fetch("/books.json")
                updateBooks(json)
                markLoading(false)
            } catch (err) {
                console.error("Failed to load books ", err)
            }
        })

        return {
            updateBooks,
            loadBooks
        }
    })

function sortBooks(books) {
    return books
        .filter(b => b.isAvailable)
        .sort((a, b) => (a.name > b.name ? 1 : a.name === b.name ? 0 : -1))
}
<commit_msg>Update examples with flow<commit_after>import { types, getParent, flow } from "mobx-state-tree"

export const Book = types.model("Book", {
    id: types.identifier(),
    name: types.string,
    author: types.string,
    price: types.number,
    isAvailable: true
})

export const BookStore = types
    .model("BookStore", {
        isLoading: true,
        books: types.map(Book)
    })
    .views(self => ({
        get shop() {
            return getParent(self)
        },
        get sortedAvailableBooks() {
            return sortBooks(self.books.values())
        }
    }))
    .actions(self => {
        function markLoading(loading) {
            self.isLoading = loading
        }

        function updateBooks(json) {
            self.books.values().forEach(book => (book.isAvailable = false))
            json.forEach(bookJson => {
                self.books.put(bookJson)
                self.books.get(bookJson.id).isAvailable = true
            })
        }

        const loadBooks = flow(function* loadBooks() {
            try {
                const json = yield self.shop.fetch("/books.json")
                updateBooks(json)
                markLoading(false)
            } catch (err) {
                console.error("Failed to load books ", err)
            }
        })

        return {
            updateBooks,
            loadBooks
        }
    })

function sortBooks(books) {
    return books
        .filter(b => b.isAvailable)
        .sort((a, b) => (a.name > b.name ? 1 : a.name === b.name ? 0 : -1))
}
<|endoftext|>


<commit_before>import Audio from './components/AudioPlayback';
import Video from './components/VideoPlayback';
import SceneView from './components/SceneView';
import Resource from './components/Resource';

const audioClips = [
  new Resource('audio/Jove_1.wav'),
  new Resource('audio/Jove_2.wav'),
  new Resource('audio/Jove_3.wav'),
];
const videoClips = [
  new Resource('video/Empty Room.webm'),
  new Resource('video/Google.webm'),
  new Resource('video/Switch Channels.webm'),
];

const audio = new Audio();
const video = new Video();
const scenes = [
  {
    title: 'Scene 1',
    description: 'desc 1',
    actions: [
      video.loop(videoClips[0]),
    ],
  },
  {
    title: 'Scene 2',
    description: 'desc 2',
    actions: [
      video.play(videoClips[1]),
      audio.play(audioClips[0]),
    ],
    goNextWhenFinish: video,
  },
  {
    title: 'Scene 3',
    description: 'desc 3',
    actions: [
      video.play(videoClips[2]),
      audio.play(audioClips[2]),
    ],
  },
];

const interfaces = {
  screen: {
    layout: [
      video,
    ],
    background: [
      audio,
    ],
  },
  control: {
    layout: [
      [
        video.with({ muted: true }),
      ],
      SceneView,
    ],
    background: [],
  },
};

export default { interfaces, scenes };
<commit_msg>setup<commit_after>import Audio from './components/AudioPlayback';
import Video from './components/VideoPlayback';
import SceneView from './components/SceneView';
import Resource from './components/Resource';

const audioClips = [
  new Resource('audio/Jove_1.wav'),

  new Resource('audio/Mark_1.wav'),
  new Resource('audio/Mark_2.wav'),
  new Resource('audio/Mark_3.wav'),
  new Resource('audio/Mark_4.wav'),
  new Resource('audio/Mark_5.wav'),

  new Resource('audio/Mark_6.wav'),

  new Resource('audio/Mark_7.wav'),
  new Resource('audio/Jove_2.wav'),

  new Resource('audio/Jove_3.wav'),
];

const ringtone = new Resource('audio/Shuke.wav');

const videoClips = [
  new Resource('video/Meeting.webm'),

  new Resource('video/Meeting_ended.webm'),
  new Resource('video/Empty.webm'),

  new Resource('video/Appear.webm'),

  new Resource('video/Phone_first.webm'),

  new Resource('video/Google.webm'),

  new Resource('video/Basketball.webm'),

  new Resource('video/Channels.webm'),

  new Resource('video/Phone_second.webm'),

  new Resource('video/Pushup-1.webm'),
  new Resource('video/Pushup-2.webm'),
  new Resource('video/Pushup-3.webm'),
];

const audio = new Audio();
const video = new Video();
const scenes = [
  {
    title: '开会中',
    description: '开会中',
    actions: [
      video.loop(videoClips[0]),
      audio.play(audioClips[0]),
    ],
  },
  {
    title: '结束',
    description: '等起身',
    actions: [
      video.play(videoClips[1]),
    ],
    goNextWhenFinish: video,
  },
  {
    title: '空房间',
    description: '',
    actions: [
      video.loop(videoClips[2]),
    ],
  },
  {
    title: '成功',
    description: '等马克',
    actions: [
      video.play(videoClips[3]),
    ],
    goNextWhenFinish: video,
  },
  {
    title: '电话响',
    description: '',
    actions: [
      video.loop(videoClips[4]),
      audio.loop(ringtone),
    ],
  },
  {
    title: '接起电话',
    description: '等Lingda',
    actions: [
      audio.pause(),
    ],
  },
  {
    title: '马克电话1',
    description: '怎么回事',
    actions: [
      audio.play(audioClips[1]),
    ],
  },
  {
    title: '马克电话2',
    description: '打不开门',
    actions: [
      audio.play(audioClips[2]),
    ],
  },
  {
    title: '马克电话3',
    description: '好多次了',
    actions: [
      audio.play(audioClips[3]),
    ],
  },
  {
    title: '马克电话4',
    description: '赶紧赶紧',
    actions: [
      audio.play(audioClips[4]),
    ],
  },
  {
    title: '马克电话5',
    description: '那怎么办',
    actions: [
      audio.play(audioClips[5]),
    ],
  },
  {
    title: 'Google',
    description: '',
    actions: [
      video.play(videoClips[5]),
    ],
  },
  {
    title: '马克电话6',
    description: '等Linda',
    actions: [
      audio.play(audioClips[6]),
    ],
  },
  {
    title: '球赛',
    description: '等Strong',
    actions: [
      video.loop(videoClips[6]),
    ],
  },
  {
    title: '转台',
    description: '等抢回来',
    actions: [
      video.play(videoClips[7]),
    ],
  },
  {
    title: '电话响',
    description: '',
    actions: [
      audio.loop(ringtone),
    ],
  },
  {
    title: '接起来',
    description: '等Lingda',
    actions: [
      audio.pause(),
      video.loop(videoClips[8]),
    ],
  },
  {
    title: '马克电话7',
    description: '搞不定',
    actions: [
      audio.play(audioClips[7]),
    ],
  },
  {
    title: 'Jove',
    description: '小龙虾',
    actions: [
      audio.play(audioClips[8]),
    ],
  },
  {
    title: '结局-1',
    description: '等Lingda',
    actions: [
      video.play(videoClips[9]),
      audio.play(audioClips[9]),
    ],
    goNextWhenFinish: video,
  },
  {
    title: '结局-2',
    description: '',
    actions: [
      video.play(videoClips[10]),
    ],
    goNextWhenFinish: video,
  },
  {
    title: 'Credit',
    description: '',
    actions: [
      video.play(videoClips[11]),
    ],
  },
];

const interfaces = {
  screen: {
    layout: [
      video,
    ],
    background: [
      audio,
    ],
  },
  control: {
    layout: [
      [
        video.with({ muted: true }),
      ],
      SceneView,
    ],
    background: [],
  },
};

export default { interfaces, scenes };
<|endoftext|>


<commit_before>/* global showdown, json */

var ngComponents = ngComponents || {};

ngComponents.converterService = function () {

    var markdownConverter = new showdown.Converter();

    this.makeHtml = function (text) {
        return markdownConverter.makeHtml(text);
    };

};

ngComponents.postsService = function ($http, $sce, converterService) {

    var postsUrl = '/content/posts/';

    var cache = {}; // object of cached full posts

    var posts = []; // array of posts
    var post;
    while ( (post = json.posts.shift()) ) {
        post.file = post.filename.replace('.md', '');
        post.fileParts = post.file.split('_');
        posts.push({
            'date': post.fileParts[0],
            'alias': post.fileParts[1],
            'filename': post.filename
        });
    }

    this.getPosts = function () {
        return posts;
    };

    this.getPost = function (alias) {
        if (cache.alias) {
            return cache.alias;
        }
        var filename = posts.filter(function (obj) {
            if (obj.alias === alias) {
                return true;
            }
        });

        filename = filename[0] || false;
        filename = filename.filename || false;

        if (!filename) {
            return false;
        }

        var url = postsUrl + filename;
        return $http.get(url).then(function (response) {
            cache.alias = converterService.makeHtml(response.data);
            cache.alias = $sce.trustAsHtml(cache.alias);
            return cache.alias;
        });
    };

};<commit_msg>relative path<commit_after>/* global showdown, json */

var ngComponents = ngComponents || {};

ngComponents.converterService = function () {

    var markdownConverter = new showdown.Converter();

    this.makeHtml = function (text) {
        return markdownConverter.makeHtml(text);
    };

};

ngComponents.postsService = function ($http, $sce, converterService) {

    var postsUrl = 'content/posts/';

    var cache = {}; // object of cached full posts

    var posts = []; // array of posts
    var post;
    while ( (post = json.posts.shift()) ) {
        post.file = post.filename.replace('.md', '');
        post.fileParts = post.file.split('_');
        posts.push({
            'date': post.fileParts[0],
            'alias': post.fileParts[1],
            'filename': post.filename
        });
    }

    this.getPosts = function () {
        return posts;
    };

    this.getPost = function (alias) {
        if (cache.alias) {
            return cache.alias;
        }
        var filename = posts.filter(function (obj) {
            if (obj.alias === alias) {
                return true;
            }
        });

        filename = filename[0] || false;
        filename = filename.filename || false;

        if (!filename) {
            return false;
        }

        var url = postsUrl + filename;
        return $http.get(url).then(function (response) {
            cache.alias = converterService.makeHtml(response.data);
            cache.alias = $sce.trustAsHtml(cache.alias);
            return cache.alias;
        });
    };

};<|endoftext|>


<commit_before>/**
 * Describes the play state.
 */

var PlayState = function() {
	var mSelf = this;
	var mHud; 				// Game hud
	var mBackground;		// group with all the cards
	var mCards; 			// group with all the cards
	var mMonster;
	var mTrash;
	var mQuestionTime;		// Time, in seconds, the player has to answer the current question
	var mQuestionTimer;		// Counts from mQuestionTime until zero.
	var mQuestion;			// Info about the current question
	var mQuestionCounter;	// How many questions so far.
	var mMatchTime;			// Remaining time for the match
	var mIsThinking;		// Informs if the player is in a thinking part of the game (e.g. card analysis)
	var mHealth;			// Available health points.
	var mDifficultyIndex;	// Regulates the game difficulty.
	var mScore = {			// Info regarding global score (throughout the game session)
		right: 0,
		wrong: 0,
		miss: 0
	};
	var mTurnBasedScore = {		// Info regarding score for each new question
		right: 0,
		wrong: 0,
		miss: 0
	};
	var mSfxNewQuestion;
	var mTutorial;

	this.create = function() {
		var i,
			j = 0,
			aCard;

		mMonster = Game.add.sprite(Game.world.width * 0.85, Game.world.height * 0.42, 'monster');
		mMonster.animations.add('idle', [0,1], 2, true);
		mMonster.animations.add('sick', [2], 1, false);
		mMonster.animations.play('idle');

		mTrash = Game.add.sprite(Game.world.width * 0.85, mMonster.y + mMonster.height + 70, 'trash');
		mTrash.addChild(new Phaser.Text(Game, -40, 70, 'Trash', {fontSize: 26, fill: '#000', align: 'center'}));

		mMonster.anchor.setTo(0.5);
		mTrash.anchor.setTo(0.5);

		mBackground = Game.add.sprite(Game.world.width * 0.05, Game.world.height * 0.15, 'deck-background');
		mCards = Game.add.group();

		for(i = 0; i < Constants.CARDS_MAX; i++) {
			if(i != 0 && (i % Constants.CARDS_PER_ROW) == 0) {
				j++;
			}

			aCard = new Card(mBackground.x + 70 + 120 * (i % Constants.CARDS_PER_ROW), mBackground.y + 60 + 120 * j);
			mCards.add(aCard);
		}

		mDifficultyIndex = 0;

		mQuestionTime = getDifficulty().QUESTION_DURATION;
		mQuestionTimer = 0;
		mMatchTime = Constants.GAME_MATCH_DURATION;
		mHealth = Constants.GAME_HEALTH_MAX;
		mSfxNewQuestion = Game.add.audio('sfx-new-question', Constants.SFX_VOLUME);
		mIsThinking = false;

		mQuestion = 1;
		mQuestionCounter = 0;

		mHud = new Hud();
		Game.add.existing(mHud);

		mTutorial = new Tutorial();
		Game.add.existing(mTutorial);
	};

	this.update = function() {
		var aElapsed = Game.time.elapsedMS,
			aOldDifficultyIndex;

		aOldDifficultyIndex = mDifficultyIndex;
		updateDifficultiIndex();

		if(aOldDifficultyIndex != mDifficultyIndex) {
			console.log('Difficulty has changed to ' + mDifficultyIndex);

			if(GlobalInfo && GlobalInfo.data) {
				GlobalInfo.data.log({a: 'difficulty', v: mDifficultyIndex}, true);
			}
		}

		// Update everything related to turn control (time)
		// and generation of new questions.
		updateTurnAndNewQuestionControl(aElapsed);

		if(GlobalInfo) {
			if(GlobalInfo.expression) {
				var aEmotions = GlobalInfo.expression.getEmotions();
				var aPoints = GlobalInfo.expression.getPoints();

				// Emotions are available for reading?
				if(aEmotions.length > 0) {
					// Yeah, they are, collect them
					GlobalInfo.data.log({e: aEmotions, p: aPoints});
				}
			}

			if(Constants.GAME_ENABLE_DATA_LOG) {
				GlobalInfo.data.log({s: mTurnBasedScore});
				GlobalInfo.data.send(GlobalInfo.user, GlobalInfo.game);
			}
		}

		// Update match time
		mMatchTime -= aElapsed;

		if(mMatchTime <= 0 || mHealth <= 0) {
			// Match is over!
			if(GlobalInfo) {
				GlobalInfo.score = mScore;
			}
			// TODO: disable face tracking here
			Game.state.start('over');
		}
	};

	// theType can be 'right', 'wrong' or 'miss'
	this.countMove = function(theType) {
		if(theType == 'right') {
			mScore.right++;
			mTurnBasedScore.right++;
			mHealth += getDifficulty().GAME_CORRECT_HEALTH;

			if(GlobalInfo && GlobalInfo.data) {
				GlobalInfo.data.log({a: 'right'}, true);
			}

		} else if(theType == 'wrong') {
			mScore.wrong++;
			mTurnBasedScore.wrong++;
			mHealth -= getDifficulty().GAME_MISTAKE_HEALTH;

			if(GlobalInfo && GlobalInfo.data) {
				GlobalInfo.data.log({a: 'wrong'}, true);
			}

		} else {
			mScore.miss++;
			mTurnBasedScore.miss++;
			mHealth -= getDifficulty().GAME_MISTAKE_HEALTH;

			if(GlobalInfo && GlobalInfo.data) {
				GlobalInfo.data.log({a: 'miss'}, true);
			}
		}

		// Prevent overfeeding the monster.
		if(mHealth >= Constants.GAME_HEALTH_MAX) {
			mHealth = Constants.GAME_HEALTH_MAX;
		}

		mHud.refresh();
	}

	var updateDifficultiIndex = function() {
		mDifficultyIndex = (Constants.GAME_MATCH_DURATION - mMatchTime) / (Constants.GAME_MATCH_DURATION / Constants.DIFFICULTY.length);
		mDifficultyIndex |= 0; // cast to int
	};

	var updateTurnAndNewQuestionControl = function(theElapsed) {
		// Update counters regarding question
		mQuestionTimer -= theElapsed;

		// Check if it is time to ask a new question
		if(mQuestionTimer <= 0) {
			generateNewQuestion();
			mQuestionTime = mQuestionCounter == 1 ? Constants.QUESTION_DURATION_1ST : getDifficulty().QUESTION_DURATION;
			mQuestionTimer = mQuestionTime;

			if(GlobalInfo && GlobalInfo.data) {
				GlobalInfo.data.log({a: 'question'}, true);
			}
		}

		// If all cards have been analyzed already,
		// speed up the turn count down
		if(mIsThinking && countFlippingCards() == 0) {
			mQuestionTimer -= mQuestionCounter == 1 ? Constants.QUESTION_DOWN_PACE_1ST : getDifficulty().QUESTION_DOWN_PACE;
		}
	};

	var flipRandomCardsUp = function() {
		var aCard,
		 	i,
			aTotal = getDifficulty().CARDS_FLIPS_TURN;

		for(i = 0; i < aTotal; i++) {
			aCard = mCards.getRandom();

			if(aCard) {
				aCard.flip();
			}
		}
	};

	var penalizeStillFlippedUpCards = function() {
		var aCard,
			i,
			aTotal = mCards.length;

		for(i = 0; i < aTotal; i++) {
			aCard = mCards.getChildAt(i);

			if(aCard && aCard.isFlippedUp()) {
				mSelf.countMove('miss');
				mHud.showRightWrongSign(aCard, false);
				aCard.flipDown();
			}
		}
	};

	var countFlippingCards = function() {
		var aCard,
			i,
			aTotal = mCards.length,
			aRet = 0;

		for(i = 0; i < aTotal; i++) {
			aCard = mCards.getChildAt(i);

			if(aCard && (aCard.isFlippedUp() || aCard.isFlipping())) {
				aRet++;
			}
		}

		return aRet;
	};

	var clearTurnBasedScore = function() {
		mTurnBasedScore.right = 0;
		mTurnBasedScore.wrong = 0;
		mTurnBasedScore.miss = 0;
	};

	var flipCardsForNewRound = function() {
		// Is it the very first question the user sees?
		if(mQuestionCounter == 1) {
			// Yes! Let's flip some carefully selected cards
			// and show the tutorial info.
			mTutorial.activate();

		} else {
			// Is the tutorial active?
			if(mTutorial != null) {
				// Yeah, it is. Remove it because it's game time!
				mTutorial.destroy();
				mTutorial = null;

				// Reset match timer to ignore time spent during tutorial
				mMatchTime = Constants.GAME_MATCH_DURATION;
				updateDifficultiIndex();

				// Log start of the game
				GlobalInfo.data.logMilestone(GlobalInfo.user, GlobalInfo.game, 'game_start');
			}

			// No, the player already saw the tutorial.
			// Let's go on with the show then.
			flipRandomCardsUp();
		}

		mIsThinking = true;
	};

	var generateNewQuestion = function() {
		mIsThinking = false;
		mQuestion = Game.rnd.integerInRange(1, Constants.CARDS_COLORS - 1);

		mHud.refresh();
		mHud.highlightNewQuestion();

		penalizeStillFlippedUpCards();

		// Before clearing the turn based score, save information
		// regarding the current turn.
		if(GlobalInfo && GlobalInfo.data) {
			GlobalInfo.data.log({turn: mQuestionCounter, s: mTurnBasedScore}, true);
		}

		clearTurnBasedScore();

		// Schedule the cards to flip up and the
		// thinking phase to begin.
		Game.time.events.add(Phaser.Timer.SECOND * 0.5, flipCardsForNewRound, this);

		mQuestionCounter++;

		mSfxNewQuestion.play();
	};

	var getDifficulty = function() {
		return Constants.DIFFICULTY[mDifficultyIndex];
	};

	this.terminateCurrentTurn = function() {
		mQuestionTimer = 0;
	}

	// Getters
	this.getQuestion = function() {
		return mQuestion;
	};

	this.getCards = function() {
		return mCards;
	};

	this.getScore = function() {
		return mScore;
	};

	this.getMatchRemainingTime = function() {
		return mMatchTime;
	};

	this.getHud = function() {
		return mHud;
	};

	this.getMonster = function() {
		return mMonster;
	};

	this.getPercentageTimeRemainingAnswerQuestion = function() {
		return mQuestionTimer / mQuestionTime;
	};

	this.getTrash = function() {
		return mTrash;
	};

	this.getHealthPercentage = function() {
		return mHealth/Constants.GAME_HEALTH_MAX;
	};
};
<commit_msg>Fix time related bug in card game<commit_after>/**
 * Describes the play state.
 */

var PlayState = function() {
	var mSelf = this;
	var mHud; 				// Game hud
	var mBackground;		// group with all the cards
	var mCards; 			// group with all the cards
	var mMonster;
	var mTrash;
	var mQuestionTime;		// Time, in seconds, the player has to answer the current question
	var mQuestionTimer;		// Counts from mQuestionTime until zero.
	var mQuestion;			// Info about the current question
	var mQuestionCounter;	// How many questions so far.
	var mMatchTime;			// Remaining time for the match
	var mMatchStartTime;	// When the match started
	var mIsThinking;		// Informs if the player is in a thinking part of the game (e.g. card analysis)
	var mHealth;			// Available health points.
	var mDifficultyIndex;	// Regulates the game difficulty.
	var mScore = {			// Info regarding global score (throughout the game session)
		right: 0,
		wrong: 0,
		miss: 0
	};
	var mTurnBasedScore = {		// Info regarding score for each new question
		right: 0,
		wrong: 0,
		miss: 0
	};
	var mSfxNewQuestion;
	var mTutorial;

	this.create = function() {
		var i,
			j = 0,
			aCard;

		mMonster = Game.add.sprite(Game.world.width * 0.85, Game.world.height * 0.42, 'monster');
		mMonster.animations.add('idle', [0,1], 2, true);
		mMonster.animations.add('sick', [2], 1, false);
		mMonster.animations.play('idle');

		mTrash = Game.add.sprite(Game.world.width * 0.85, mMonster.y + mMonster.height + 70, 'trash');
		mTrash.addChild(new Phaser.Text(Game, -40, 70, 'Trash', {fontSize: 26, fill: '#000', align: 'center'}));

		mMonster.anchor.setTo(0.5);
		mTrash.anchor.setTo(0.5);

		mBackground = Game.add.sprite(Game.world.width * 0.05, Game.world.height * 0.15, 'deck-background');
		mCards = Game.add.group();

		for(i = 0; i < Constants.CARDS_MAX; i++) {
			if(i != 0 && (i % Constants.CARDS_PER_ROW) == 0) {
				j++;
			}

			aCard = new Card(mBackground.x + 70 + 120 * (i % Constants.CARDS_PER_ROW), mBackground.y + 60 + 120 * j);
			mCards.add(aCard);
		}

		mDifficultyIndex = 0;

		mQuestionTime = getDifficulty().QUESTION_DURATION;
		mQuestionTimer = 0;
		mMatchTime = Constants.GAME_MATCH_DURATION;
		mMatchStartTime = Date.now();
		mHealth = Constants.GAME_HEALTH_MAX;
		mSfxNewQuestion = Game.add.audio('sfx-new-question', Constants.SFX_VOLUME);
		mIsThinking = false;

		mQuestion = 1;
		mQuestionCounter = 0;

		mHud = new Hud();
		Game.add.existing(mHud);

		mTutorial = new Tutorial();
		Game.add.existing(mTutorial);
	};

	this.getTimeSinceMatchStarted = function() {
		return Date.now() - mMatchStartTime;
	};

	this.update = function() {
		var aElapsed = Game.time.elapsedMS,
			aOldDifficultyIndex;

		aOldDifficultyIndex = mDifficultyIndex;
		if(mTutorial == null) {
			updateDifficultiIndex();
		}

		if(aOldDifficultyIndex != mDifficultyIndex) {
			console.log('Difficulty has changed to ' + mDifficultyIndex);

			if(GlobalInfo && GlobalInfo.data) {
				GlobalInfo.data.log({a: 'difficulty', v: mDifficultyIndex}, true);
			}
		}

		// Update everything related to turn control (time)
		// and generation of new questions.
		updateTurnAndNewQuestionControl(aElapsed);

		if(GlobalInfo) {
			if(GlobalInfo.expression) {
				var aEmotions = GlobalInfo.expression.getEmotions();
				var aPoints = GlobalInfo.expression.getPoints();

				// Emotions are available for reading?
				if(aEmotions.length > 0) {
					// Yeah, they are, collect them
					GlobalInfo.data.log({e: aEmotions, p: aPoints});
				}
			}

			if(Constants.GAME_ENABLE_DATA_LOG) {
				GlobalInfo.data.log({s: mTurnBasedScore});
				GlobalInfo.data.send(GlobalInfo.user, GlobalInfo.game);
			}
		}

		// Update match time
		mMatchTime = Constants.GAME_MATCH_DURATION - this.getTimeSinceMatchStarted();

		if(mMatchTime <= 0 || mHealth <= 0) {
			// Match is over!
			if(GlobalInfo) {
				GlobalInfo.score = mScore;
			}
			// TODO: disable face tracking here
			Game.state.start('over');
		}
	};

	// theType can be 'right', 'wrong' or 'miss'
	this.countMove = function(theType) {
		if(theType == 'right') {
			mScore.right++;
			mTurnBasedScore.right++;
			mHealth += getDifficulty().GAME_CORRECT_HEALTH;

			if(GlobalInfo && GlobalInfo.data) {
				GlobalInfo.data.log({a: 'right'}, true);
			}

		} else if(theType == 'wrong') {
			mScore.wrong++;
			mTurnBasedScore.wrong++;
			mHealth -= getDifficulty().GAME_MISTAKE_HEALTH;

			if(GlobalInfo && GlobalInfo.data) {
				GlobalInfo.data.log({a: 'wrong'}, true);
			}

		} else {
			mScore.miss++;
			mTurnBasedScore.miss++;
			mHealth -= getDifficulty().GAME_MISTAKE_HEALTH;

			if(GlobalInfo && GlobalInfo.data) {
				GlobalInfo.data.log({a: 'miss'}, true);
			}
		}

		// Prevent overfeeding the monster.
		if(mHealth >= Constants.GAME_HEALTH_MAX) {
			mHealth = Constants.GAME_HEALTH_MAX;
		}

		mHud.refresh();
	}

	var updateDifficultiIndex = function() {
		mDifficultyIndex = (Constants.GAME_MATCH_DURATION - mMatchTime) / (Constants.GAME_MATCH_DURATION / Constants.DIFFICULTY.length);
		mDifficultyIndex |= 0; // cast to int
	};

	var updateTurnAndNewQuestionControl = function(theElapsed) {
		// Update counters regarding question
		mQuestionTimer -= theElapsed;

		// Check if it is time to ask a new question
		if(mQuestionTimer <= 0) {
			generateNewQuestion();
			mQuestionTime = mQuestionCounter == 1 ? Constants.QUESTION_DURATION_1ST : getDifficulty().QUESTION_DURATION;
			mQuestionTimer = mQuestionTime;

			if(GlobalInfo && GlobalInfo.data) {
				GlobalInfo.data.log({a: 'question'}, true);
			}
		}

		// If all cards have been analyzed already,
		// speed up the turn count down
		if(mIsThinking && countFlippingCards() == 0) {
			mQuestionTimer -= mQuestionCounter == 1 ? Constants.QUESTION_DOWN_PACE_1ST : getDifficulty().QUESTION_DOWN_PACE;
		}
	};

	var flipRandomCardsUp = function() {
		var aCard,
		 	i,
			aTotal = getDifficulty().CARDS_FLIPS_TURN;

		for(i = 0; i < aTotal; i++) {
			aCard = mCards.getRandom();

			if(aCard) {
				aCard.flip();
			}
		}
	};

	var penalizeStillFlippedUpCards = function() {
		var aCard,
			i,
			aTotal = mCards.length;

		for(i = 0; i < aTotal; i++) {
			aCard = mCards.getChildAt(i);

			if(aCard && aCard.isFlippedUp()) {
				mSelf.countMove('miss');
				mHud.showRightWrongSign(aCard, false);
				aCard.flipDown();
			}
		}
	};

	var countFlippingCards = function() {
		var aCard,
			i,
			aTotal = mCards.length,
			aRet = 0;

		for(i = 0; i < aTotal; i++) {
			aCard = mCards.getChildAt(i);

			if(aCard && (aCard.isFlippedUp() || aCard.isFlipping())) {
				aRet++;
			}
		}

		return aRet;
	};

	var clearTurnBasedScore = function() {
		mTurnBasedScore.right = 0;
		mTurnBasedScore.wrong = 0;
		mTurnBasedScore.miss = 0;
	};

	var flipCardsForNewRound = function() {
		// Is it the very first question the user sees?
		if(mQuestionCounter == 1) {
			// Yes! Let's flip some carefully selected cards
			// and show the tutorial info.
			mTutorial.activate();

		} else {
			// Is the tutorial active?
			if(mTutorial != null) {
				// Yeah, it is. Remove it because it's game time!
				mTutorial.destroy();
				mTutorial = null;

				// Reset match timer to ignore time spent during tutorial
				mMatchStartTime = Date.now();
				mMatchTime = Constants.GAME_MATCH_DURATION;
				updateDifficultiIndex();

				// Log start of the game
				GlobalInfo.data.logMilestone(GlobalInfo.user, GlobalInfo.game, 'game_start');
			}

			// No, the player already saw the tutorial.
			// Let's go on with the show then.
			flipRandomCardsUp();
		}

		mIsThinking = true;
	};

	var generateNewQuestion = function() {
		mIsThinking = false;
		mQuestion = Game.rnd.integerInRange(1, Constants.CARDS_COLORS - 1);

		mHud.refresh();
		mHud.highlightNewQuestion();

		penalizeStillFlippedUpCards();

		// Before clearing the turn based score, save information
		// regarding the current turn.
		if(GlobalInfo && GlobalInfo.data) {
			GlobalInfo.data.log({turn: mQuestionCounter, s: mTurnBasedScore}, true);
		}

		clearTurnBasedScore();

		// Schedule the cards to flip up and the
		// thinking phase to begin.
		Game.time.events.add(Phaser.Timer.SECOND * 0.5, flipCardsForNewRound, this);

		mQuestionCounter++;

		mSfxNewQuestion.play();
	};

	var getDifficulty = function() {
		return Constants.DIFFICULTY[mDifficultyIndex];
	};

	this.terminateCurrentTurn = function() {
		mQuestionTimer = 0;
	}

	// Getters
	this.getQuestion = function() {
		return mQuestion;
	};

	this.getCards = function() {
		return mCards;
	};

	this.getScore = function() {
		return mScore;
	};

	this.getMatchRemainingTime = function() {
		return mMatchTime;
	};

	this.getHud = function() {
		return mHud;
	};

	this.getMonster = function() {
		return mMonster;
	};

	this.getPercentageTimeRemainingAnswerQuestion = function() {
		return mQuestionTimer / mQuestionTime;
	};

	this.getTrash = function() {
		return mTrash;
	};

	this.getHealthPercentage = function() {
		return mHealth/Constants.GAME_HEALTH_MAX;
	};
};
<|endoftext|>


<commit_before>Conductor.require('/vendor/jquery.js');
Conductor.requireCSS('/cards/github-auth.css');

var card;
var ApiConsumer = Conductor.Oasis.Consumer.extend({
  requests: {
    ajax: function (promise, ajaxOpts) {
      console.log('card.accessTokenPromise.then');
      card.accessTokenPromise.then(function (accessToken) {
        if (!ajaxOpts.data)
          ajaxOpts.data = {};
        ajaxOpts.url = 'https://api.github.com' + ajaxOpts.url;
        ajaxOpts.data.access_token = accessToken;
        card.consumers.fullXhr.request('ajax', ajaxOpts).then(function (data) {
          promise.resolve(data);
        }, function (e) {
          promise.reject(e);
        });
      }, function (e) {
        console.error(e);
      });
    }
  }
});

card = Conductor.card({
  consumers: {
    configuration: Conductor.Oasis.Consumer,
    fullXhr: Conductor.Oasis.Consumer,
    'github:authenticated:read': ApiConsumer,
    userStorage: Conductor.Oasis.Consumer,
    login: Conductor.Oasis.Consumer,
    test: Conductor.Oasis.Consumer.extend({
      requests: {
        runTest:  function(promise, testData){
          var testFn = new Function('return ' + testData.fnString)();

          testFn.call(window, card, promise);
        }
      }
    })
  },
  render: function (intent, dimensions) {
    if (!dimensions) { dimensions = {width:500,height:500}; }
    document.body.innerHTML = "

Hooray world!
<button id=\"github_button\">Log In with GitHub</button>
";
    this.resize(dimensions);
  },
  accessTokenPromise: new Conductor.Oasis.RSVP.Promise(),

  activate: function() {
    console.log("activate github-auth");
    var card = this;
    var _configurationService = this.consumers.configuration;
    var githubClientIdPromise = _configurationService.request('configurationValue', 'github_client_id');
    $('body').on('click', '#github_button', function(){
      githubClientIdPromise.then(function(githubClientId){
        var githubUri = "https://github.com/login/oauth/authorize?scope=user,public_repo" +
          "&client_id=" +  githubClientId;
        window.open(githubUri, "authwindow", "menubar=0,resizable=1,width=960,height=410");
      });
      return false;
    });

    window.addEventListener("message", function(event) {
      // if (event.origin !== window.location.origin) {
      //   console.log("got unknown message", event);
      //   return;
      // }
      var authCode = event.data;
      // console.log("we got a code " + authCode);
      var fullXhrService = card.consumers.fullXhr;
      fullXhrService.request('ajax', {
        type: 'post',
        url: 'http://localhost:8000' + "/api/oauth/github/exchange?code=" + authCode
      }).then(function(data) {
        var accessToken = data;
        console.log('card.accessTokenPromise.resolve', accessToken);
        card.accessTokenPromise.resolve(accessToken);
        // view.set('controller.githubAccessToken', accessToken);
        card.consumers.login.request('loginWithGithub', {githubAccessToken: accessToken}).then(function(){
          card.consumers.userStorage.request('setItem', 'accessToken', accessToken).then(function(){
            // console.log("I saved my access token: ", accessToken);
          });
        });
      }, function(e){
        console.error(e);
      });
    });
  },

  metadata: {
    document: function(promise) {
      promise.resolve({
        title: "Github Auth"
      });
    }
  },

  resize: function(dimensions) {
    var width = Math.min(dimensions.width, 500);
    var height = Math.min(dimensions.height, 500);
    $('body>div').css({
      width: width
    });
  }
});
<commit_msg>fix params name<commit_after>Conductor.require('/vendor/jquery.js');
Conductor.requireCSS('/cards/github-auth.css');

var card;
var ApiConsumer = Conductor.Oasis.Consumer.extend({
  requests: {
    ajax: function (promise, ajaxOpts) {
      console.log('card.accessTokenPromise.then');
      card.accessTokenPromise.then(function (accessToken) {
        if (!ajaxOpts.data)
          ajaxOpts.data = {};
        ajaxOpts.url = 'https://api.github.com' + ajaxOpts.url;
        ajaxOpts.data.access_token = accessToken;
        card.consumers.fullXhr.request('ajax', ajaxOpts).then(function (data) {
          promise.resolve(data);
        }, function (e) {
          promise.reject(e);
        });
      }, function (e) {
        console.error(e);
      });
    }
  }
});

card = Conductor.card({
  consumers: {
    configuration: Conductor.Oasis.Consumer,
    fullXhr: Conductor.Oasis.Consumer,
    'github:authenticated:read': ApiConsumer,
    userStorage: Conductor.Oasis.Consumer,
    login: Conductor.Oasis.Consumer,
    test: Conductor.Oasis.Consumer.extend({
      requests: {
        runTest:  function(promise, testData){
          var testFn = new Function('return ' + testData.fnString)();

          testFn.call(window, card, promise);
        }
      }
    })
  },
  render: function (intent, dimensions) {
    if (!dimensions) { dimensions = {width:500,height:500}; }
    document.body.innerHTML = "

Hooray world!
<button id=\"github_button\">Log In with GitHub</button>
";
    this.resize(dimensions);
  },
  accessTokenPromise: new Conductor.Oasis.RSVP.Promise(),

  activate: function() {
    console.log("activate github-auth");
    var card = this;
    var _configurationService = this.consumers.configuration;
    var githubClientIdPromise = _configurationService.request('configurationValue', 'github_client_id');
    $('body').on('click', '#github_button', function(){
      githubClientIdPromise.then(function(githubClientId){
        var githubUri = "https://github.com/login/oauth/authorize?scope=user,public_repo" +
          "&client_id=" +  githubClientId;
        window.open(githubUri, "authwindow", "menubar=0,resizable=1,width=960,height=410");
      });
      return false;
    });

    window.addEventListener("message", function(event) {
      // if (event.origin !== window.location.origin) {
      //   console.log("got unknown message", event);
      //   return;
      // }
      var authCode = event.data;
      // console.log("we got a code " + authCode);
      var fullXhrService = card.consumers.fullXhr;
      fullXhrService.request('ajax', {
        type: 'post',
        url: 'http://localhost:8000' + "/api/oauth/github/exchange?code=" + authCode
      }).then(function(data) {
        var accessToken = data;
        console.log('card.accessTokenPromise.resolve', accessToken);
        card.accessTokenPromise.resolve(accessToken);
        // view.set('controller.githubAccessToken', accessToken);
        card.consumers.login.request('loginWithGithub', {accessToken: accessToken}).then(function(){
          card.consumers.userStorage.request('setItem', 'accessToken', accessToken).then(function(){
            // console.log("I saved my access token: ", accessToken);
          });
        });
      }, function(e){
        console.error(e);
      });
    });
  },

  metadata: {
    document: function(promise) {
      promise.resolve({
        title: "Github Auth"
      });
    }
  },

  resize: function(dimensions) {
    var width = Math.min(dimensions.width, 500);
    var height = Math.min(dimensions.height, 500);
    $('body>div').css({
      width: width
    });
  }
});
<|endoftext|>