<commit_before>// This file is part of BenchExec, a framework for reliable benchmarking:
// https://github.com/sosy-lab/benchexec
//
// SPDX-FileCopyrightText: 2019-2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0

import { isNil, getRawOrDefault, omit } from "./utils";

/**
 * Prepares raw data for filtering by retrieving available distinct values as min
 * and max values of numeric fields
 *
 * @param {Object} data -  Data object received from json data
 */
const getFilterableData = ({ tools, rows }) => {
  const start = Date.now();
  const mapped = tools.map((tool, idx) => {
    let statusIdx;
    const { tool: toolName, date, niceName } = tool;
    let name = `${toolName} ${date} ${niceName}`;
    const columns = tool.columns.map((col, idx) => {
      if (!col) {
        return undefined;
      }
      if (col.type === "status") {
        statusIdx = idx;
        return { ...col, categories: {}, statuses: {}, idx };
      }
      if (col.type === "text") {
        return { ...col, distincts: {}, idx };
      }
      return { ...col, min: Infinity, max: -Infinity, idx };
    });

    if (isNil(statusIdx)) {
      console.log(`Couldn't find any status columns in tool ${idx}`);
      return undefined;
    }

    columns[statusIdx] = {
      ...columns[statusIdx],
      categories: {},
      statuses: {},
    };

    for (const row of rows) {
      for (const result of row.results) {
        // convention as of writing this commit is to postfix categories with a space character
        columns[statusIdx].categories[`${result.category} `] = true;

        for (const colIdx in result.values) {
          const col = result.values[colIdx];
          const { raw } = col;
          const filterCol = columns[colIdx];
          if (!filterCol || isNil(raw)) {
            continue;
          }

          if (filterCol.type === "status") {
            filterCol.statuses[raw] = true;
          } else if (filterCol.type === "text") {
            filterCol.distincts[raw] = true;
          } else {
            filterCol.min = Math.min(filterCol.min, Number(raw));
            filterCol.max = Math.max(filterCol.max, Number(raw));
          }
        }
      }
    }

    return {
      name,
      columns: columns.map(({ distincts, categories, statuses, ...col }) => {
        if (distincts) {
          return { ...col, distincts: Object.keys(distincts) };
        }
        if (categories) {
          return {
            ...col,
            categories: Object.keys(categories),
            statuses: Object.keys(statuses),
          };
        }
        return col;
      }),
    };
  });
  console.log({ mapped, creationTime: `${Date.now() - start} ms` });
  return mapped;
};

const applyNumericFilter = (filter, row, cell) => {
  const raw = getRawOrDefault(row[filter.id]);
  if (raw === undefined) {
    // empty cells never match
    return;
  }
  const filterParams = filter.value.split(":");

  if (filterParams.length === 2) {
    const [start, end] = filterParams;

    const numRaw = Number(raw);
    const numStart = start ? Number(start) : -Infinity;
    const numEnd = end ? Number(end) : Infinity;

    return numRaw >= numStart && numRaw <= numEnd;
  }

  if (filterParams.length === 1) {
    return raw.startsWith(filterParams[0]);
  }
  return false;
};
const applyTextFilter = (filter, row, cell) => {
  const raw = getRawOrDefault(row[filter.id]);
  if (raw === undefined) {
    // empty cells never match
    return;
  }
  return raw.includes(filter.value);
};

/**
 * Transforms a list of filter objects into a matcher.
 * The matcher helps with data access and provides clear, parsed information
 * on what the filter should do.
 *
 * for example:
 *
 * Filter object: [
 *    {id: "0_status_1", value: "false"},
 *    {id: "0_status_1", value: "TIMEOUT"},
 *    {id: "0_cputime_3", value: "50: 1337"},
 * ]
 *
 * matcher: {
 *  0: {
 *      1: [{value: "false"}, {value: "TIMEOUT"}],   // all values on this level are disjunctively connected
 *      3: [{min: 50, max: 1337}],
 *    }
 * }
 *
 * @param {Array<Object>} filters - List of filters
 */
const buildMatcher = (filters) => {
  const start = Date.now();
  const out = filters.reduce((acc, { id, value }) => {
    if (isNil(value) || (typeof value === "string" && value.trim() === "all")) {
      return acc;
    }
    if (id === "id") {
      acc.id = { value };
      return acc;
    }
    const [tool, , columnIdx] = id.split("_");
    if (value === "diff") {
      // this branch is noop as of now
      if (!acc.diff) {
        acc.diff = [];
      }
      acc.diff.push({ col: columnIdx });
      return acc;
    }
    if (!acc[tool]) {
      acc[tool] = {};
    }
    let filter;
    if (value.includes(":")) {
      let [minV, maxV] = value.split(":");
      minV = minV === "" ? -Infinity : Number(minV);
      maxV = maxV === "" ? Infinity : Number(maxV);
      filter = { min: minV, max: maxV };
    } else {
      if (value[value.length - 1] === " ") {
        filter = { category: value.substr(0, value.length - 1) };
      } else {
        filter = { value };
      }
    }
    if (!acc[tool][columnIdx]) {
      acc[tool][columnIdx] = [];
    }
    acc[tool][columnIdx].push(filter);
    return acc;
  }, {});
  console.log(`Creating matcher took ${Date.now() - start} ms`);
  return out;
};

/**
 * @typedef (function(Object[])) MatchingFunction
 * @param {Object[]} data - the data of the current Table context
 * @returns {Object[]} filtered data
 */

/**
 *
 * @param {matcher} matcher - the pre-compiled matcher
 * @returns {MatchingFunction} - the built matching function. It requires
 */
const applyMatcher = (matcher) => (data) => {
  const start = Date.now();
  let diffd = [...data];
  if (matcher.diff) {
    diffd = diffd.filter((row) => {
      for (const { col } of matcher.diff) {
        const vals = {};
        for (const tool of row.results) {
          const val = tool.values[col].raw;
          if (!vals[val]) {
            vals[val] = true;
          }
        }
        if (Object.keys(vals).length === 1) {
          return false;
        }
      }
      return true;
    });
  }
  if (!isNil(matcher.id)) {
    const { value: idValue } = matcher.id;
    diffd = diffd.filter(
      ({ href }) => href === idValue || href.includes(idValue),
    );
  }
  const out = diffd.filter((row) => {
    for (const tool in omit(["diff", "id"], matcher)) {
      for (const column in matcher[tool]) {
        let columnPass = false;
        for (const filter of matcher[tool][column]) {
          const { value, min, max, category } = filter;

          if (!isNil(min) && !isNil(max)) {
            const rawValue = row.results[tool].values[column].raw;
            if (isNil(rawValue)) {
              columnPass = false;
              continue;
            }
            const num = Number(rawValue);
            columnPass = columnPass || (num >= min && num <= max);
          } else if (!isNil(category)) {
            columnPass = columnPass || row.results[tool].category === category;
          } else {
            const rawValue = row.results[tool].values[column].raw;
            if (isNil(rawValue)) {
              columnPass = false;
              continue;
            }
            columnPass =
              columnPass || value === rawValue || rawValue.includes(value);
          }

          if (columnPass) {
            // as multiple values of the same column are OR connected,
            // we can abort if we pass since the result will always be true.
            break;
          }
        }
        if (!columnPass) {
          // values of the same column are OR connected
          // multiple columns in the same row are AND connected
          // if the matcher fails for one column, the whole row fails
          return false;
        }
      }
    }
    // all filter requirements were satisfied
    return true;
  });
  console.log(`matching took ${Date.now() - start} ms`);
  return out;
};

export {
  getFilterableData,
  applyNumericFilter,
  applyTextFilter,
  applyMatcher,
  buildMatcher,
};
<commit_msg>conjugate category and status filters<commit_after>// This file is part of BenchExec, a framework for reliable benchmarking:
// https://github.com/sosy-lab/benchexec
//
// SPDX-FileCopyrightText: 2019-2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0

import { isNil, getRawOrDefault, omit } from "./utils";

/**
 * Prepares raw data for filtering by retrieving available distinct values as min
 * and max values of numeric fields
 *
 * @param {Object} data -  Data object received from json data
 */
const getFilterableData = ({ tools, rows }) => {
  const start = Date.now();
  const mapped = tools.map((tool, idx) => {
    let statusIdx;
    const { tool: toolName, date, niceName } = tool;
    let name = `${toolName} ${date} ${niceName}`;
    const columns = tool.columns.map((col, idx) => {
      if (!col) {
        return undefined;
      }
      if (col.type === "status") {
        statusIdx = idx;
        return { ...col, categories: {}, statuses: {}, idx };
      }
      if (col.type === "text") {
        return { ...col, distincts: {}, idx };
      }
      return { ...col, min: Infinity, max: -Infinity, idx };
    });

    if (isNil(statusIdx)) {
      console.log(`Couldn't find any status columns in tool ${idx}`);
      return undefined;
    }

    columns[statusIdx] = {
      ...columns[statusIdx],
      categories: {},
      statuses: {},
    };

    for (const row of rows) {
      for (const result of row.results) {
        // convention as of writing this commit is to postfix categories with a space character
        columns[statusIdx].categories[`${result.category} `] = true;

        for (const colIdx in result.values) {
          const col = result.values[colIdx];
          const { raw } = col;
          const filterCol = columns[colIdx];
          if (!filterCol || isNil(raw)) {
            continue;
          }

          if (filterCol.type === "status") {
            filterCol.statuses[raw] = true;
          } else if (filterCol.type === "text") {
            filterCol.distincts[raw] = true;
          } else {
            filterCol.min = Math.min(filterCol.min, Number(raw));
            filterCol.max = Math.max(filterCol.max, Number(raw));
          }
        }
      }
    }

    return {
      name,
      columns: columns.map(({ distincts, categories, statuses, ...col }) => {
        if (distincts) {
          return { ...col, distincts: Object.keys(distincts) };
        }
        if (categories) {
          return {
            ...col,
            categories: Object.keys(categories),
            statuses: Object.keys(statuses),
          };
        }
        return col;
      }),
    };
  });
  console.log({ mapped, creationTime: `${Date.now() - start} ms` });
  return mapped;
};

const applyNumericFilter = (filter, row, cell) => {
  const raw = getRawOrDefault(row[filter.id]);
  if (raw === undefined) {
    // empty cells never match
    return;
  }
  const filterParams = filter.value.split(":");

  if (filterParams.length === 2) {
    const [start, end] = filterParams;

    const numRaw = Number(raw);
    const numStart = start ? Number(start) : -Infinity;
    const numEnd = end ? Number(end) : Infinity;

    return numRaw >= numStart && numRaw <= numEnd;
  }

  if (filterParams.length === 1) {
    return raw.startsWith(filterParams[0]);
  }
  return false;
};
const applyTextFilter = (filter, row, cell) => {
  const raw = getRawOrDefault(row[filter.id]);
  if (raw === undefined) {
    // empty cells never match
    return;
  }
  return raw.includes(filter.value);
};

/**
 * Transforms a list of filter objects into a matcher.
 * The matcher helps with data access and provides clear, parsed information
 * on what the filter should do.
 *
 * for example:
 *
 * Filter object: [
 *    {id: "0_status_1", value: "false"},
 *    {id: "0_status_1", value: "TIMEOUT"},
 *    {id: "0_cputime_3", value: "50: 1337"},
 * ]
 *
 * matcher: {
 *  0: {
 *      1: [{value: "false"}, {value: "TIMEOUT"}],   // all values on this level are disjunctively connected
 *      3: [{min: 50, max: 1337}],
 *    }
 * }
 *
 * @param {Array<Object>} filters - List of filters
 */
const buildMatcher = (filters) => {
  const start = Date.now();
  const out = filters.reduce((acc, { id, value }) => {
    if (isNil(value) || (typeof value === "string" && value.trim() === "all")) {
      return acc;
    }
    if (id === "id") {
      acc.id = { value };
      return acc;
    }
    const [tool, name, columnIdx] = id.split("_");
    if (value === "diff") {
      // this branch is noop as of now
      if (!acc.diff) {
        acc.diff = [];
      }
      acc.diff.push({ col: columnIdx });
      return acc;
    }
    if (!acc[tool]) {
      acc[tool] = {};
    }
    let filter;
    if (value.includes(":")) {
      let [minV, maxV] = value.split(":");
      minV = minV === "" ? -Infinity : Number(minV);
      maxV = maxV === "" ? Infinity : Number(maxV);
      filter = { min: minV, max: maxV };
    } else {
      if (value[value.length - 1] === " ") {
        filter = { category: value.substr(0, value.length - 1) };
      } else if (name === "status") {
        filter = { status: value };
      } else {
        filter = { value };
      }
    }
    if (!acc[tool][columnIdx]) {
      acc[tool][columnIdx] = [];
    }
    acc[tool][columnIdx].push(filter);
    return acc;
  }, {});
  console.log(`Creating matcher took ${Date.now() - start} ms`);
  console.log({ matcher: out });
  return out;
};

/**
 * @typedef (function(Object[])) MatchingFunction
 * @param {Object[]} data - the data of the current Table context
 * @returns {Object[]} filtered data
 */

/**
 *
 * @param {matcher} matcher - the pre-compiled matcher
 * @returns {MatchingFunction} - the built matching function. It requires
 */
const applyMatcher = (matcher) => (data) => {
  const start = Date.now();
  let diffd = [...data];
  if (matcher.diff) {
    diffd = diffd.filter((row) => {
      for (const { col } of matcher.diff) {
        const vals = {};
        for (const tool of row.results) {
          const val = tool.values[col].raw;
          if (!vals[val]) {
            vals[val] = true;
          }
        }
        if (Object.keys(vals).length === 1) {
          return false;
        }
      }
      return true;
    });
  }
  if (!isNil(matcher.id)) {
    const { value: idValue } = matcher.id;
    diffd = diffd.filter(
      ({ href }) => href === idValue || href.includes(idValue),
    );
  }
  const out = diffd.filter((row) => {
    for (const tool in omit(["diff", "id"], matcher)) {
      for (const column in matcher[tool]) {
        let columnPass = false;
        let categoryPass = false;
        let statusPass = false;
        for (const filter of matcher[tool][column]) {
          const { value, min, max, category, status } = filter;

          if (!isNil(min) && !isNil(max)) {
            const rawValue = row.results[tool].values[column].raw;
            if (isNil(rawValue)) {
              columnPass = false;
              continue;
            }
            const num = Number(rawValue);
            columnPass = columnPass || (num >= min && num <= max);
          } else if (!isNil(category)) {
            categoryPass =
              row.results[tool].category === category || categoryPass;
            columnPass = categoryPass && statusPass;
          } else if (!isNil(status)) {
            statusPass =
              row.results[tool].values[column].raw === status || statusPass;
            columnPass = categoryPass && statusPass;
          } else {
            const rawValue = row.results[tool].values[column].raw;
            if (isNil(rawValue)) {
              columnPass = false;
              continue;
            }
            columnPass =
              columnPass || value === rawValue || rawValue.includes(value);
          }

          if (columnPass) {
            // as multiple values of the same column are OR connected,
            // we can abort if we pass since the result will always be true.
            break;
          }
        }
        if (!columnPass) {
          // values of the same column are OR connected
          // multiple columns in the same row are AND connected
          // if the matcher fails for one column, the whole row fails
          return false;
        }
      }
    }
    // all filter requirements were satisfied
    return true;
  });
  console.log(`matching took ${Date.now() - start} ms`);
  return out;
};

export {
  getFilterableData,
  applyNumericFilter,
  applyTextFilter,
  applyMatcher,
  buildMatcher,
};
<|endoftext|>


<commit_before>var http = require('http');
var Pusher = require('pusher');

// https://pusher.com/docs/server_api_guide/interact_rest_api
var pusher = new Pusher({
    appId: process.env.PUSHER_APP_ID,
    key: process.env.PUSHER_KEY,
    secret: process.env.PUSHER_SECRET
});

/**
 * Reverse object keys and values.
 */
function reverse(o) {
  var result = {};
  for(var key in o) {
    result[o[key]] = key;
  }
  return result;
}

/**
 * Extract the base64 data encoded in the kinesis record to an object.
 * @return {Object}
 */
function decode(record) {
    var data = new Buffer(record.kinesis.data, 'base64').toString();
    try {
        return JSON.parse(data);
    } catch (SyntaxError) {
        return {};
    }
}

/**
 * If the sensor maps to an available feature of interest, provide it, otherwise
 * reject it as null.
 * @return {Object}
 */
function format(record, networkMap) {
    var node = record.node;
    var sensor = record.sensor;

    var nodeMetadata;
    var sensorMetadata;

    nodeMetadata = networkMap[node];

    if (!nodeMetadata) return null;

    sensorMetadata = nodeMetadata[sensor];

    if (!sensorMetadata) return null;

    var mapping = reverse(sensorMetadata);
    var feature = '';

    for (var property in record.data) {
        if (!(property in mapping)) return null;

        feature = mapping[property].split('.')[0];
        var formalName = mapping[property].split('.')[1];
        record.data[formalName] = record.data[property];
        delete record.data[property];
    }

    record.feature = feature;
    record.results = record.data;
    delete record.data;
    return record;
}

/**
 * Iterate through incoming records and emit to the appropriate channels.
 */
function emit(records, channels) {
    records.forEach((record) => {
        if (!record) return;

        channels.forEach((channel) => {
            var message = JSON.stringify(record);

            if (channel === 'private-all')
                pusher.trigger('private-all', 'data', { message: message });
            if ('private-' + record.node === channel)
                pusher.trigger(channel, 'data', { message: message });
        });
    });
}

/**
 * Get sensor network metadata from plenario.
 */
function getNetworkMap() {
    return new Promise((resolve, reject) => {
        http.get(process.env.PLENARIO_MAP_URI, (response) => {
            var chunks = '';
            response.on('data', (chunk) => chunks += chunk);
            response.on('end', () => resolve(JSON.parse(chunks)));
        });
    });
}

/**
 * Implementation of required handler for an incoming batch of kinesis records.
 * http://docs.aws.amazon.com/lambda/latest/dg/with-kinesis-example-deployment-pkg.html#with-kinesis-example-deployment-pkg-nodejs
 */
function handler(event, context) {
    var records = event.Records.map(decode);

    getNetworkMap().then((networkMap) => {
        records = records.map((record) => format(record, networkMap));

        pusher.get({path: '/channels'}, (error, request, response) => {
            var result = JSON.parse(response.body);
            var channels = Object.keys(result.channels);
            emit(records, channels);
        });
    });
}

exports.handler = handler;
<commit_msg>Fix bug involved with mapping formal property name<commit_after>var http = require('http');
var Pusher = require('pusher');

// https://pusher.com/docs/server_api_guide/interact_rest_api
var pusher = new Pusher({
    appId: process.env.PUSHER_APP_ID,
    key: process.env.PUSHER_KEY,
    secret: process.env.PUSHER_SECRET
});

/**
 * Reverse object keys and values.
 */
function reverse(o) {
  var result = {};
  for(var key in o) {
    result[o[key]] = key;
  }
  return result;
}

/**
 * Extract the base64 data encoded in the kinesis record to an object.
 * @return {Object}
 */
function decode(record) {
    var data = new Buffer(record.kinesis.data, 'base64').toString();
    try {
        return JSON.parse(data);
    } catch (SyntaxError) {
        return {};
    }
}

/**
 * If the sensor maps to an available feature of interest, provide it, otherwise
 * reject it as null.
 * @return {Object}
 */
function format(record, networkMap) {
    var node = record.node;
    var sensor = record.sensor;

    var nodeMetadata;
    var sensorMetadata;

    nodeMetadata = networkMap[node];

    if (!nodeMetadata) return null;

    sensorMetadata = nodeMetadata[sensor];

    if (!sensorMetadata) return null;

    var mapping = reverse(sensorMetadata);
    var feature = '';

    for (var property in record.data) {
        if (!(property in mapping)) return null;

        feature = mapping[property].split('.')[0];
        var formalName = mapping[property].split('.')[1];
        record.data[formalName] = record.data[property];
        if (formalName != property) {
            delete record.data[property];
        }
    }

    record.feature = feature;
    record.results = record.data;
    delete record.data;
    return record;
}

/**
 * Iterate through incoming records and emit to the appropriate channels.
 */
function emit(records, channels) {
    records.forEach((record) => {
        if (!record) return;

        channels.forEach((channel) => {
            var message = JSON.stringify(record);

            if (channel === 'private-all') {
                pusher.trigger('private-all', 'data', { message: message });
                console.log('published to ' + channel);
                console.log(record);
            }
            if ('private-' + record.node === channel) {
                pusher.trigger(channel, 'data', { message: message });
                console.log('published to ' + channel);
                console.log(record);
            }
        });
    });
}

/**
 * Get sensor network metadata from plenario.
 */
function getNetworkMap() {
    return new Promise((resolve, reject) => {
        http.get(process.env.PLENARIO_MAP_URI, (response) => {
            var chunks = '';
            response.on('data', (chunk) => chunks += chunk);
            response.on('end', () => resolve(JSON.parse(chunks)));
        });
    });
}

/**
 * Implementation of required handler for an incoming batch of kinesis records.
 * http://docs.aws.amazon.com/lambda/latest/dg/with-kinesis-example-deployment-pkg.html#with-kinesis-example-deployment-pkg-nodejs
 */
function handler(event, context) {
    var records = event.Records.map(decode);
    console.log('----- records ------');
    console.log(records);

    getNetworkMap().then((networkMap) => {
        records = records.map((record) => format(record, networkMap));

        pusher.get({path: '/channels'}, (error, request, response) => {
            var result = JSON.parse(response.body);
            var channels = Object.keys(result.channels);
            emit(records, channels);
        });
    });
}

exports.handler = handler;
<|endoftext|>


<commit_before>'use strict';

// This module is the single source of truth for versioning packages that we
// publish to npm.
//
// Packages will not be published unless they are added here.
//
// The @latest channel uses the version as-is, e.g.:
//
//   18.0.0
//
// The @next channel appends additional information, with the scheme
// <version>-<label>-<commit_sha>, e.g.:
//
//   18.0.0-alpha-a1c2d3e4
//
// The @experimental channel doesn't include a version, only a date and a sha, e.g.:
//
//   0.0.0-experimental-241c4467e-20200129

const ReactVersion = '18.0.0-rc.1';

// The label used by the @next channel. Represents the upcoming release's
// stability. Could be "alpha", "beta", "rc", etc.
const nextChannelLabel = 'next';

const stablePackages = {
  'create-subscription': ReactVersion,
  'eslint-plugin-react-hooks': '4.2.1-rc.1',
  'jest-react': '0.12.1-rc.1',
  react: ReactVersion,
  'react-art': ReactVersion,
  'react-dom': ReactVersion,
  'react-is': ReactVersion,
  'react-reconciler': '0.27.0-rc.1',
  'react-refresh': '0.11.0-rc.1',
  'react-test-renderer': ReactVersion,
  'use-subscription': '1.6.0-rc.1',
  'use-sync-external-store': '1.0.0-rc.1',
  scheduler: '0.21.0-rc.1',
};

// These packages do not exist in the @next or @latest channel, only
// @experimental. We don't use semver, just the commit sha, so this is just a
// list of package names instead of a map.
const experimentalPackages = [
  'react-fetch',
  'react-fs',
  'react-pg',
  'react-server-dom-webpack',
];

module.exports = {
  ReactVersion,
  nextChannelLabel,
  stablePackages,
  experimentalPackages,
};
<commit_msg>Bump versions to rc.2<commit_after>'use strict';

// This module is the single source of truth for versioning packages that we
// publish to npm.
//
// Packages will not be published unless they are added here.
//
// The @latest channel uses the version as-is, e.g.:
//
//   18.0.0
//
// The @next channel appends additional information, with the scheme
// <version>-<label>-<commit_sha>, e.g.:
//
//   18.0.0-alpha-a1c2d3e4
//
// The @experimental channel doesn't include a version, only a date and a sha, e.g.:
//
//   0.0.0-experimental-241c4467e-20200129

const ReactVersion = '18.0.0-rc.2';

// The label used by the @next channel. Represents the upcoming release's
// stability. Could be "alpha", "beta", "rc", etc.
const nextChannelLabel = 'next';

const stablePackages = {
  'create-subscription': ReactVersion,
  'eslint-plugin-react-hooks': '4.2.1-rc.2',
  'jest-react': '0.12.1-rc.2',
  react: ReactVersion,
  'react-art': ReactVersion,
  'react-dom': ReactVersion,
  'react-is': ReactVersion,
  'react-reconciler': '0.27.0-rc.2',
  'react-refresh': '0.11.0-rc.2',
  'react-test-renderer': ReactVersion,
  'use-subscription': '1.6.0-rc.2',
  'use-sync-external-store': '1.0.0-rc.2',
  scheduler: '0.21.0-rc.2',
};

// These packages do not exist in the @next or @latest channel, only
// @experimental. We don't use semver, just the commit sha, so this is just a
// list of package names instead of a map.
const experimentalPackages = [
  'react-fetch',
  'react-fs',
  'react-pg',
  'react-server-dom-webpack',
];

module.exports = {
  ReactVersion,
  nextChannelLabel,
  stablePackages,
  experimentalPackages,
};
<|endoftext|>


<commit_before>// this sets the background color of the master UIView (when there are no windows/tab groups on it)
Titanium.UI.setBackgroundColor('#000');

// create tab group
var tabGroup = Titanium.UI.createTabGroup();

var contactwin = Titanium.UI.createWindow({
	url:'contacts_db.js',
	titleid:'controls_win_title'
});
//
// create base UI tab and root window
//
var win = Titanium.UI.createWindow({
    fullscreen: true,
    visible: true
});

var win1 = Titanium.UI.createWindow({
    title:'Menu',
    backgroundColor:'#FFFFFF',
    backgroundImage:'/images/table_cloth.png'

});

var tab1 = Titanium.UI.createTab({
    icon:'KS_nav_views.png',
    title:'Tab 1',
    window:win1
});

var imageView = Titanium.UI.createImageView({
	image:'/images/bell.png',
	width:200,
	height:100,
	top:30
});

imageView.addEventListener('load', function()
{
	Ti.API.info('LOAD CALLED');
});
win1.add(imageView);

//
// create controls tab and root window
//
var win2 = Titanium.UI.createWindow({
    title:'Tab 2',
    backgroundColor:'#fff'
});
var tab2 = Titanium.UI.createTab({
    icon:'KS_nav_ui.png',
    title:'Tab 2',
    window:win2
});

var label2 = Titanium.UI.createLabel({
	color:'#999',
	text:'unavailable',
	font:{fontSize:20,fontFamily:'Helvetica Neue'},
	textAlign:'center',
	width:'auto'
});

win2.add(label2);

//////Menu Buttons
var schedulemeals = Titanium.UI.createButton({
	title : 'Schedule Meals',
	width : 200,
	height: 40,
	top : 130,

})

var ringbell = Titanium.UI.createButton({
	title : 'Ring the Bell',
	width : 200,
	height: 40,
	top : 190,

})

var contacts = Titanium.UI.createButton({
	title : 'Contacts',
	width : 200,
	height: 40,
	top : 250,
})

contacts.addEventListener('click', function()
{
	contactwin.open();
})

win1.add(schedulemeals);
win1.add(ringbell);
win1.add(contacts)

//open to Contacts screen

// Loading Screen Start

var actInd = Titanium.UI.createActivityIndicator({
	bottom:10,
	height:50,
	width:10,
	topMost: true,
	style:Titanium.UI.iPhone.ActivityIndicatorStyle.PLAIN
});

function loadingScreen(){
	actInd.style = Titanium.UI.iPhone.ActivityIndicatorStyle.PLAIN;
	actInd.font = {fontFamily:'Helvetica Neue', fontSize:15,fontWeight:'bold'};
	actInd.color = 'white';
	actInd.message = 'Loading...';
	actInd.width = 210;
	actInd.show();
	var imageView = Titanium.UI.createImageView({
		image:'/iphone/default.png',
		width:'100%',
		height:'100%'
	});
	win.add(imageView);
	win.add(actInd);

	setTimeout(function()
	{
		actInd.hide();
		//
		// Create Windows
		//
		//  add tabs
		//
		tabGroup.addTab(tab1);
		tabGroup.addTab(tab2);
		// open tab group
		tabGroup.open();

	},5000);
}

// end loading screen

//Load Screen
loadingScreen();
win.open();
<commit_msg>moved home into position<commit_after>// this sets the background color of the master UIView (when there are no windows/tab groups on it)
Titanium.UI.setBackgroundColor('#000');

// create tab group
var tabGroup = Titanium.UI.createTabGroup();

var contactwin = Titanium.UI.createWindow({
	url:'contacts_db.js',
	titleid:'controls_win_title'
});
//
// create base UI tab and root window
//
var win = Titanium.UI.createWindow({
    fullscreen: true,
    visible: true
});

var win1 = Titanium.UI.createWindow({
    backgroundColor:'#FFFFFF',
    backgroundImage:'/images/table_cloth.png'

});

var tab1 = Titanium.UI.createTab({
    icon:'KS_nav_views.png',
    title:'Tab 1',
    window:win1
});

var imageView = Titanium.UI.createImageView({
	image:'/images/bell.png',
	width:143,
	height:128,
	top:40
	});

imageView.addEventListener('load', function()
{
	Ti.API.info('LOAD CALLED');
});
win1.add(imageView);

//
// create controls tab and root window
//
var win2 = Titanium.UI.createWindow({
    title:'Tab 2',
    backgroundColor:'#fff'
});
var tab2 = Titanium.UI.createTab({
    icon:'KS_nav_ui.png',
    title:'Tab 2',
    window:win2
});

var label2 = Titanium.UI.createLabel({
	color:'#999',
	text:'unavailable',
	font:{fontSize:20,fontFamily:'Helvetica Neue'},
	textAlign:'center',
	width:'auto'
});

win2.add(label2);

//////Menu Buttons
var schedulemeals = Titanium.UI.createButton({
	title : 'Schedule Meals',
	width : 200,
	height: 40,
	top : 250,

})

var ringbell = Titanium.UI.createButton({
	title : 'Ring the Bell',
	width : 200,
	height: 40,
	top : 310,

})

var contacts = Titanium.UI.createButton({
	title : 'Contacts',
	width : 200,
	height: 40,
	top : 370,
})

contacts.addEventListener('click', function()
{
	contactwin.open();
})

win1.add(schedulemeals);
win1.add(ringbell);
win1.add(contacts)

//open to Contacts screen

// Loading Screen Start

var actInd = Titanium.UI.createActivityIndicator({
	bottom:10,
	height:50,
	width:10,
	topMost: true,
	style:Titanium.UI.iPhone.ActivityIndicatorStyle.PLAIN
});

function loadingScreen(){
	actInd.style = Titanium.UI.iPhone.ActivityIndicatorStyle.PLAIN;
	actInd.font = {fontFamily:'Helvetica Neue', fontSize:15,fontWeight:'bold'};
	actInd.color = 'white';
	actInd.message = 'Loading...';
	actInd.width = 210;
	actInd.show();
	var imageView = Titanium.UI.createImageView({
		image:'/iphone/default.png',
		width:'100%',
		height:'100%'
	});
	win.add(imageView);
	win.add(actInd);

	setTimeout(function()
	{
		actInd.hide();
		//
		// Create Windows
		//
		//  add tabs
		//
		win1.open();

	},5000);
}

// end loading screen

//Load Screen
loadingScreen();
win.open();
<|endoftext|>


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

// Declaring variables to prevent implied global error in jslint
var Ti, Titanium, Drupal, desc, menu, refresh, logout;

// this sets the background color of the master UIView (when there are no windows/tab groups on it)
Titanium.UI.setBackgroundColor('#414444');

// Include the Drupal connection libraries.
Ti.include(
  'lib/phpjs.js',
  'lib/misc.js',
  'lib/menu.js',
  'drupal/drupal.js',
  'drupal/services.js',
  'drupal/db.js',
  'drupal/entity.js',
  'drupalcon/drupalcon.js',
  'drupalcon/entity.js'
);

//Ti.include('drupalcon/entity.js');

// Define our connection information.  This is very similar to the DB layer's
// $databases array in settings.php.
Drupal.services.addConnectionInfo('main', {
  endpointUrl: 'http://chicago2011.drupal.org/services/mobile',
  user: '',
  pass: ''
});

// Register our database information.
Drupal.db.addConnectionInfo('main');

// Pre-create the database.  This is a snapshot of the dataset taken shortly
// prior to shipping.
var dbVersion = 1.0;
//Ti.Database.install('main.sql', 'codestrong' + dbVersion);
Ti.Database.install('main.sql', 'main');

// If we haven't created the tables yet, make empty ones to ensure that the
// app doesn't crash.
if (!Drupal.db.getConnection('main').tableExists('node')) {
  Drupal.entity.db('main', 'node').initializeSchema();
}
if (!Drupal.db.getConnection('main').tableExists('user')) {
  Drupal.entity.db('main', 'user').initializeSchema();
}

// If there's no record of having synchronized data with the site before, default
// to 15 Feb as the oldest to pull from.  That avoids ever downloading the entire
// site, since we have a pre-loaded database.
// if ('' == Titanium.App.Properties.getString('drupalcon:fetcher:lastNodeUpdate:session', '')) {
  // Titanium.App.Properties.setString('drupalcon:fetcher:lastNodeUpdate:session', '2011-02-28T12:00:00');
// }

// This is just for testing purposes. In practice we wouldn't
// actually want to wipe the DB on every app start. :-)
//Drupal.entity.db('main', 'node').initializeSchema();
//Drupal.entity.db('main', 'user').initializeSchema();

// Download tests, for now.  These must get moved eventually.
//Drupal.db.errorMode = Drupal.db.ERROR_LEVEL_DEBUG;

Ti.include(
  'windows/ModalActivityIndicatorWindow.js',
  'windows/DayWindow.js',
  'windows/TwitterWindow.js',
  'windows/MapWindow.js',
  'windows/AboutWindow.js',
  'windows/TwitterDetailWindow.js',
  'windows/StarredWindow.js',
  'windows/FeedbackWindow.js',
  'windows/PresentersWindow.js',
  'windows/SessionsWindow.js',
  'windows/SessionDetailWindow.js',
  'windows/PresenterDetailWindow.js',
  'windows/HtmlWindow.js'
);

Ti.include('windows/main.js');

Ti.App.addEventListener('openURL', function(e){
  Ti.Platform.openURL(e.url);
});

/*
// Download tests, for now.  These must get moved eventually.
Drupal.db.errorMode = Drupal.db.ERROR_LEVEL_DEBUG;

// This is just for testing purposes. In practice we wouldn't
// actually want to wipe the DB on every app start. :-)
var store = Drupal.entity.db('main', 'node').initializeSchema();

//Drupal.entity.db('main', 'node').fetchUpdates('session');

//Drupal.entity.mirror('main', 'node', 464);

// This will actually not have the updated number of records,
// since the mirror request is asynchronous.
//Ti.API.info('Number of nodes on file: ' + Drupal.entity.db('main', 'node').connection.query("SELECT COUNT(*) FROM node").field(0));
*/
<commit_msg>added a Codestrong namespace and function, needs a real home at some point<commit_after>/**
 * This file is part of DrupalCon Mobile.
 *
 * DrupalCon Mobile is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * DrupalCon Mobile is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with DrupalCon Mobile.  If not, see <http://www.gnu.org/licenses/>.
 */

// Declaring variables to prevent implied global error in jslint
var Ti, Titanium, Drupal, desc, menu, refresh, logout;

// this sets the background color of the master UIView (when there are no windows/tab groups on it)
Titanium.UI.setBackgroundColor('#414444');

// Include the Drupal connection libraries.
Ti.include(
  'lib/phpjs.js',
  'lib/misc.js',
  'lib/menu.js',
  'drupal/drupal.js',
  'drupal/services.js',
  'drupal/db.js',
  'drupal/entity.js',
  'drupalcon/drupalcon.js',
  'drupalcon/entity.js'
);

//Ti.include('drupalcon/entity.js');

// Define our connection information.  This is very similar to the DB layer's
// $databases array in settings.php.
Drupal.services.addConnectionInfo('main', {
  endpointUrl: 'http://chicago2011.drupal.org/services/mobile',
  user: '',
  pass: ''
});

// Register our database information.
Drupal.db.addConnectionInfo('main');

// Pre-create the database.  This is a snapshot of the dataset taken shortly
// prior to shipping.
var dbVersion = 1.0;
//Ti.Database.install('main.sql', 'codestrong' + dbVersion);
Ti.Database.install('main.sql', 'main');

// If we haven't created the tables yet, make empty ones to ensure that the
// app doesn't crash.
if (!Drupal.db.getConnection('main').tableExists('node')) {
  Drupal.entity.db('main', 'node').initializeSchema();
}
if (!Drupal.db.getConnection('main').tableExists('user')) {
  Drupal.entity.db('main', 'user').initializeSchema();
}

// If there's no record of having synchronized data with the site before, default
// to 15 Feb as the oldest to pull from.  That avoids ever downloading the entire
// site, since we have a pre-loaded database.
// if ('' == Titanium.App.Properties.getString('drupalcon:fetcher:lastNodeUpdate:session', '')) {
  // Titanium.App.Properties.setString('drupalcon:fetcher:lastNodeUpdate:session', '2011-02-28T12:00:00');
// }

// This is just for testing purposes. In practice we wouldn't
// actually want to wipe the DB on every app start. :-)
//Drupal.entity.db('main', 'node').initializeSchema();
//Drupal.entity.db('main', 'user').initializeSchema();

// Download tests, for now.  These must get moved eventually.
//Drupal.db.errorMode = Drupal.db.ERROR_LEVEL_DEBUG;

Codestrong = {};

Codestrong.createHeaderRow = function(title) {
	var headerRow = Ti.UI.createTableViewRow({
    	classname: 'header_row',
    	height:26,
    	backgroundGradient: {
			type:'linear',
			colors:[
				{color:'#888',position:0.0},
				{color:'#414444',position:0.50},
				{color:'#414444',position:1.0}
			]
		},
    	touchEnabled: true
    });
    var headerLabel = Ti.UI.createLabel({
    	text: title,
    	color: '#fff',
    	font: {
    		fontSize:16,
    		fontWeight:'bold'
    	},
    	left: 10
    });
    headerRow.add(headerLabel);

    return headerRow;
};

Ti.include(
  'windows/ModalActivityIndicatorWindow.js',
  'windows/DayWindow.js',
  'windows/TwitterWindow.js',
  'windows/MapWindow.js',
  'windows/AboutWindow.js',
  'windows/TwitterDetailWindow.js',
  'windows/StarredWindow.js',
  'windows/FeedbackWindow.js',
  'windows/PresentersWindow.js',
  'windows/SessionsWindow.js',
  'windows/SessionDetailWindow.js',
  'windows/PresenterDetailWindow.js',
  'windows/HtmlWindow.js'
);

Ti.include('windows/main.js');

Ti.App.addEventListener('openURL', function(e){
  Ti.Platform.openURL(e.url);
});

/*
// Download tests, for now.  These must get moved eventually.
Drupal.db.errorMode = Drupal.db.ERROR_LEVEL_DEBUG;

// This is just for testing purposes. In practice we wouldn't
// actually want to wipe the DB on every app start. :-)
var store = Drupal.entity.db('main', 'node').initializeSchema();

//Drupal.entity.db('main', 'node').fetchUpdates('session');

//Drupal.entity.mirror('main', 'node', 464);

// This will actually not have the updated number of records,
// since the mirror request is asynchronous.
//Ti.API.info('Number of nodes on file: ' + Drupal.entity.db('main', 'node').connection.query("SELECT COUNT(*) FROM node").field(0));
*/
<|endoftext|>


<commit_before>/*
* Single Window Application Template:
* A basic starting point for your application.  Mostly a blank canvas.
*
* In app.js, we generally take care of a few things:
* - Bootstrap the application with any data we need
* - Check for dependencies like device type, platform version or network connection
* - Require and open our top-level UI component
*
*/

// Setup database
Ti.App.joli = require('lib/joli').connect('TestDBAfterOptions', 'db/main.sqlite');

//bootstrap and check dependencies
if (Ti.version < 1.8) {
	alert('Sorry - this application template requires Titanium Mobile SDK 1.8 or later');
}

// This is a single context application with mutliple windows in a stack
(function() {
	//determine platform and form factor and render approproate components
	var osname = Ti.Platform.osname, version = Ti.Platform.version, height = Ti.Platform.displayCaps.platformHeight, width = Ti.Platform.displayCaps.platformWidth;

	//considering tablet to have one dimension over 900px - this is imperfect, so you should feel free to decide
	//yourself what you consider a tablet form factor for android
	var isTablet = osname === 'ipad' || (osname === 'android' && (width > 899 || height > 899));

	var Window;

	// Android uses platform-specific properties to create windows.
	// All other platforms follow a similar UI pattern.
	if (osname === 'android') {
		Window = require('ui/handheld/android/SurveysIndexWindow');
		new Window().open();
	} else {
		Window = Ti.UI.createWindow();
		navGroup = Ti.UI.iPhone.createNavigationGroup({
			window: require('ui/handheld/iphone/SurveysIndexWindow')()
		});
		Window.add(navGroup);
		Window.open();
	}
	if (Ti.App.Properties.getString('server_url') == null) {
		Ti.App.Properties.setString('server_url', 'http://survey-web-staging.herokuapp.com');
	}
	Ti.include('/test/tests.js');
})();
<commit_msg>Used absolute path to db<commit_after>/*
* Single Window Application Template:
* A basic starting point for your application.  Mostly a blank canvas.
*
* In app.js, we generally take care of a few things:
* - Bootstrap the application with any data we need
* - Check for dependencies like device type, platform version or network connection
* - Require and open our top-level UI component
*
*/

// Setup database
Ti.App.joli = require('lib/joli').connect('TestDBAfterOptions', '/db/main.sqlite');

//bootstrap and check dependencies
if (Ti.version < 1.8) {
	alert('Sorry - this application template requires Titanium Mobile SDK 1.8 or later');
}

// This is a single context application with mutliple windows in a stack
(function() {
	//determine platform and form factor and render approproate components
	var osname = Ti.Platform.osname, version = Ti.Platform.version, height = Ti.Platform.displayCaps.platformHeight, width = Ti.Platform.displayCaps.platformWidth;

	//considering tablet to have one dimension over 900px - this is imperfect, so you should feel free to decide
	//yourself what you consider a tablet form factor for android
	var isTablet = osname === 'ipad' || (osname === 'android' && (width > 899 || height > 899));

	var Window;

	// Android uses platform-specific properties to create windows.
	// All other platforms follow a similar UI pattern.
	if (osname === 'android') {
		Window = require('ui/handheld/android/SurveysIndexWindow');
		new Window().open();
	} else {
		Window = Ti.UI.createWindow();
		navGroup = Ti.UI.iPhone.createNavigationGroup({
			window: require('ui/handheld/iphone/SurveysIndexWindow')()
		});
		Window.add(navGroup);
		Window.open();
	}
	if (Ti.App.Properties.getString('server_url') == null) {
		Ti.App.Properties.setString('server_url', 'http://survey-web-staging.herokuapp.com');
	}
	Ti.include('/test/tests.js');
})();
<|endoftext|>


<commit_before>// this sets the background color of the master UIView (when there are no windows/tab groups on it)
Ti.UI.setBackgroundColor('#fff');

// Add in Ti.APP methods for isAndroid

Ti.App.myTools ={};
Ti.App.myTools = {
	isAndroid : function(){
		return (Ti.Platform.name == 'android');
	},
	noNetworkAlertMsg : function(){
	  	Ti.UI.createAlertDialog({
	  	  title:'No Network',
	  	  message:'Unable to find a network, please try again'
	  	}).show();
	},
	customMsg : function(inputTitle,inputMsg){
	  	Ti.UI.createAlertDialog({
	  	  title:inputTitle,
	  	  message:inputMsg
	  	}).show();
	}
};

// create tab group
var tabGroup = Ti.UI.createTabGroup();
//
// create base UI tab and root window
//
var wMain = Ti.UI.createWindow({
    title:'TiGroupon',
    backgroundColor:'#ebd077',
    barColor:'#76A045',
    tabBarHidden:true,
	url:'Modules/main_ui.js',
	navBarHidden : (Ti.Platform.name == 'android')
});

if(Ti.Platform.name!='android'){
	var tab1 = Ti.UI.createTab({window:wMain});
	tabGroup.addTab(tab1);
	// open tab group
	tabGroup.open();
}else{
	wMain.open();
}

<commit_msg>adding update to include table<commit_after>// this sets the background color of the master UIView (when there are no windows/tab groups on it)
Ti.UI.setBackgroundColor('#fff');

// Add in Ti.APP methods for isAndroid

Ti.App.myTools ={};
Ti.App.myTools = {
	isAndroid : function(){
		return (Ti.Platform.name == 'android');
	},
	noNetworkAlertMsg : function(){
	  	Ti.UI.createAlertDialog({
	  	  title:'No Network',
	  	  message:'Unable to find a network, please try again'
	  	}).show();
	},
	customMsg : function(inputTitle,inputMsg){
	  	Ti.UI.createAlertDialog({
	  	  title:inputTitle,
	  	  message:inputMsg
	  	}).show();
	}
};

// create tab group
var tabGroup = Ti.UI.createTabGroup();
//
// create base UI tab and root window
//
var wMain = Ti.UI.createWindow({
    title:'TiGroupon',
    backgroundColor:'#ebd077',
    barColor:'#76A045',
    tabBarHidden:true,
	url:'Modules/main_ui.js',
	navBarHidden : (Ti.Platform.name == 'android')
});

var wTable = Ti.UI.createWindow({
    title:'TiGroupon',
    backgroundColor:'#ebd077',
    barColor:'#76A045',
    tabBarHidden:false,
        url:'Modules/list_ui.js'
//      navBarHidden : (Ti.Platform.name != 'android')
});

if(Ti.Platform.name!='android'){
	var tab1 = Ti.UI.createTab({window:wMain});
	var tab2 = Ti.UI.createTab({window:wTable});
    tabGroup.addTab(tab1);
    tabGroup.addTab(tab2);
	// open tab group
	tabGroup.open();
}else{
	wMain.open();
}

<|endoftext|>


<commit_before>var _ = require('lib/underscore');
var Admob = require('ti.admob');
DebugMode = false;
AdEnabled = true;

var GA = require('analytics.google');
// GA.setDryRun(true);
GA.localDispatchPeriod = 10;

Tracker = GA.getTracker((Ti.Platform.osname === 'android')?'UA-56040292-2':'UA-56040292-3');

// tracker.trackEvent({
	// category: "category",
	// action: "test",
	// label: "label",
	// value: 1
// });
//
// tracker.trackSocial({
	// network: "facebook",
	// action: "action",
	// target: "target"
// });
//
// tracker.trackTiming({
	// category: "",
	// time: 10,
	// name: "",
	// label: ""
// });
//
// tracker.trackScreen({ path: "Home", customDimension: { 1: "free" }});

Ti.Media.audioSessionMode = Ti.Media.AUDIO_SESSION_MODE_PLAYBACK;
screenSize = Ti.Platform.displayCaps;

if (screenSize.platformHeight < screenSize.platformWidth) {
	F = screenSize.platformHeight/768;
} else {
	F = screenSize.platformWidth/768;
}

var textFont = 'Janda Closer To Free'; // use the friendly-name on iOS
if(Ti.Platform.osname=='android') {
   // on Android, use the "base name" of the file (name without extension)
   textFont = 'JandaCloserToFree';
}

MainWindow = Ti.UI.createWindow({
	height: Ti.UI.FILL,
		width: Ti.UI.FILL,
		backgroundColor: 'black',
		orientationModes: [Titanium.UI.LANDSCAPE_LEFT,  Titanium.UI.LANDSCAPE_RIGHT],
		navBarHidden: true,
		fullscreen: true,
		backgroundImage: '/appFiles/backgrounds/background-noise.png'
});

MainWindow.open();

ANIM = {};

ANIM.fadeIn = Ti.UI.createAnimation({
	duration:100,
	opacity:1
});

ANIM.fadeOut = Ti.UI.createAnimation({
	duration:100,
	opacity:0
});

console.log('Height:',screenSize.platformHeight,' Width:',screenSize.platformWidth);

var menuFactory = require('roomFactories/menuFactory');
var PageController = require('/controllers/roomController');

var options = require('/appFiles/story')();

console.log(options);

pageController = new PageController(options);
menu = new menuFactory();

menu.open();

<commit_msg>adenabled false<commit_after>var _ = require('lib/underscore');
var Admob = require('ti.admob');
DebugMode = false;
AdEnabled = false;

var GA = require('analytics.google');
// GA.setDryRun(true);
GA.localDispatchPeriod = 10;

Tracker = GA.getTracker((Ti.Platform.osname === 'android')?'UA-56040292-2':'UA-56040292-3');

// tracker.trackEvent({
	// category: "category",
	// action: "test",
	// label: "label",
	// value: 1
// });
//
// tracker.trackSocial({
	// network: "facebook",
	// action: "action",
	// target: "target"
// });
//
// tracker.trackTiming({
	// category: "",
	// time: 10,
	// name: "",
	// label: ""
// });
//
// tracker.trackScreen({ path: "Home", customDimension: { 1: "free" }});

Ti.Media.audioSessionMode = Ti.Media.AUDIO_SESSION_MODE_PLAYBACK;
screenSize = Ti.Platform.displayCaps;

if (screenSize.platformHeight < screenSize.platformWidth) {
	F = screenSize.platformHeight/768;
} else {
	F = screenSize.platformWidth/768;
}

var textFont = 'Janda Closer To Free'; // use the friendly-name on iOS
if(Ti.Platform.osname=='android') {
   // on Android, use the "base name" of the file (name without extension)
   textFont = 'JandaCloserToFree';
}

MainWindow = Ti.UI.createWindow({
	height: Ti.UI.FILL,
		width: Ti.UI.FILL,
		backgroundColor: 'black',
		orientationModes: [Titanium.UI.LANDSCAPE_LEFT,  Titanium.UI.LANDSCAPE_RIGHT],
		navBarHidden: true,
		fullscreen: true,
		backgroundImage: '/appFiles/backgrounds/background-noise.png'
});

MainWindow.open();

ANIM = {};

ANIM.fadeIn = Ti.UI.createAnimation({
	duration:100,
	opacity:1
});

ANIM.fadeOut = Ti.UI.createAnimation({
	duration:100,
	opacity:0
});

console.log('Height:',screenSize.platformHeight,' Width:',screenSize.platformWidth);

var menuFactory = require('roomFactories/menuFactory');
var PageController = require('/controllers/roomController');

var options = require('/appFiles/story')();

console.log(options);

pageController = new PageController(options);
menu = new menuFactory();

menu.open();

<|endoftext|>


<commit_before>'use strict';

var React = require('react-native');
var {
  Component,
  StyleSheet,
  ListView,
  Image,
  View,
  Text,
  TouchableHighlight
} = React;

class SearchResults extends Component {
  constructor(props) {
    super(props);
    var dataSource = new ListView.DataSource({
      rowHasChanged: (r1, r2) => r1.guid !== r2.guid
    });
    this.state = {
      dataSource: dataSource.cloneWithRows(this.props.listings)
    };
  }

  renderRow(rowData, sectionID, rowID) {
    return (
      <TouchableHighlight
        underlayColor='#DDDDDD'>
        <View>
          <Text>{rowData.title}</Text>
        </View>
      </TouchableHighlight>
    );
  }

  render() {
    return (
      <ListView
        dataSource={this.state.dataSource}
        renderRow={this.renderRow.bind(this)}/>
    );
  }
}

module.exports = SearchResults;
<commit_msg>a touch of style<commit_after>'use strict';

var React = require('react-native');
var {
  Component,
  StyleSheet,
  ListView,
  Image,
  View,
  Text,
  TouchableHighlight
} = React;

class SearchResults extends Component {
  constructor(props) {
    super(props);
    var dataSource = new ListView.DataSource({
      rowHasChanged: (r1, r2) => r1.guid !== r2.guid
    });
    this.state = {
      dataSource: dataSource.cloneWithRows(this.props.listings)
    };
  }

  rowPressed(propertyGuid) {
    var property = this.props.listings.filter(prop => prop.guid === propertyGuid)[0];
  }

  renderRow(rowData, sectionID, rowID) {
    var price = rowData.price_formatted.split(' ')[0];
    return (
      <TouchableHighlight onPress={() => this.rowPressed(rowData.guid)}
        underlayColor='#DDDDDD'>
        <View>
          <View style={styles.rowContainer}>
            <Image style={styles.thumb} source={{uri: rowData.img_url}} />
            <View style={styles.textContainer}>
              <Text style={styles.price}>${price}</Text>
              <Text style={styles.title} numberOfLines={1}>{rowData.title}</Text>
            </View>
          </View>
          <View style={styles.separator}/>
        </View>
      </TouchableHighlight>
    );
  }

  render() {
    return (
      <ListView
        dataSource={this.state.dataSource}
        renderRow={this.renderRow.bind(this)}/>
    );
  }
}

var styles = StyleSheet.create({
  thumb: {
    width: 80,
    height: 80,
    marginRight: 10,
  },
  textContainer: {
    flex: 1
  },
  separator: {
    height: 1,
    backgroundColor: '#DDDDDD'
  },
  price: {
    fontSize: 25,
    fontWeight: 'bold',
    color: '#48BBEC'
  },
  title: {
    fontSize: 20,
    color: '#656565'
  },
  rowContainer: {
    flexDirection: 'row',
    padding: 10
  }
});

module.exports = SearchResults;
<|endoftext|>


<commit_before>var cluster = require('cluster');

if (cluster.isMaster) {

  // Count the machine's CPUs
  var cpuCount = require('os').cpus().length;

  // Create a worker for each CPU
  for (var i = 0; i < cpuCount; i += 1) {
      cluster.fork();
  }

  // Listen for dying workers
  cluster.on('exit', function (worker) {

    console.log('Worker died :(', worker.id);
    cluster.fork();

    });

} else {

var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var api = require('./routes/api');

var port = 3000;

var app = express();

var server = app.listen(port, function() {
  console.log('listening on port 3000');
});

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

app.use(cookieParser());

app.use(bodyParser.json());

app.use('/api', api);

app.get('/', function (req, res) {
	res.status(200).send('Hi. Tic Tac Toe Homepage');
});

app.all('*', function (req, res) {
  res.status(404).send('Nothing Here');
});

module.exports = server;
}<commit_msg>server file updated to include api route<commit_after>var cluster = require('cluster');

if (cluster.isMaster) {

  // Count the machine's CPUs
  var cpuCount = require('os').cpus().length;

  // Create a worker for each CPU
  for (var i = 0; i < cpuCount; i += 1) {
      cluster.fork();
  }

  // Listen for dying workers
  cluster.on('exit', function (worker) {

    console.log('Worker died :(', worker.id);
    cluster.fork();

    });

} else {

var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var api = require('./Routes/api');

var port = 3000;

var app = express();

var server = app.listen(port, function() {
  console.log('listening on port 3000');
});

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

app.use(cookieParser());

app.use(bodyParser.json());

app.use('/api', api);

app.get('/', function (req, res) {
	res.status(200).send('Hi. Tic Tac Toe Homepage');
});

app.all('*', function (req, res) {
  res.status(404).send('Nothing Here');
});

module.exports = server;
}<|endoftext|>


<commit_before>QUnit.test("QuadTreeCanAddObject", function (assert) {
    var tree    = new TameGame.QuadTree();
    var someRef = tree.addObject({ x: 0.5, y: 0.5, width: 0.25, height: 0.25 }, {});

    assert.ok(someRef !== null);
});

QUnit.test("QuadTreeCanRemoveObject", function (assert) {
    var tree    = new TameGame.QuadTree();
    var someRef = tree.addObject({ x: 0.5, y: 0.5, width: 0.25, height: 0.25 }, {});
    tree.removeObject(someRef);

    assert.ok(someRef !== null);
});

QUnit.test("QuadTreeCanFindObject", function (assert) {
    var tree    = new TameGame.QuadTree();
    var someRef = tree.addObject({ x: 0.5, y: 0.5, width: 0.25, height: 0.25 }, {});
    var count   = 0;

    tree.forAllInBounds({ x:0, y: 0, width: 1, height: 1 }, function (obj) { ++count });

    assert.ok(someRef !== null);
    assert.ok(count === 1);
});

QUnit.test("QuadTreeCanFindHugeObject", function (assert) {
    var tree    = new TameGame.QuadTree();
    var someRef = tree.addObject({ x: -100, y: -100, width: 200, height: 200 }, {});            // Forces the quadtree to expand outward
    var count   = 0;

    tree.forAllInBounds({ x:-2, y: -2, width: 4, height: 4 }, function (obj) { ++count });

    assert.ok(someRef !== null);
    assert.ok(count === 1);
});

QUnit.test("QuadTreeExcludeObjectOutOfBounds", function (assert) {
    var tree    = new TameGame.QuadTree();
    var someRef = tree.addObject({ x: 0.5, y: 0.5, width: 0.25, height: 0.25 }, {});
    var count   = 0;

    tree.forAllInBounds({ x:-1, y: -1, width: 1, height: 1 }, function (obj) { ++count });

    assert.ok(someRef !== null);
    assert.ok(count === 0);
});

// Populates a quadtree with a grid of objects from 0,0 to 1,1. Width, height indicate the number of cells in the appropriate dimension
function populateGrid(quadTree, width, height) {
    var distX = 1.0 / width;
    var distY = 1.0 / height;

    var xpos, ypos;
    var x,y;

    ypos = 0;
    for (y=0; y<height; ++y) {
        xpos = 0;
        for (x=0; x<width; ++x) {
            quadTree.addObject({ x: xpos, y: ypos, width: distX, height: distY }, { x: xpos, y: ypos });

            xpos += distX;
        }

        ypos += distY;
    }
}

QUnit.test("QuadTreeQuery100Objects", function (assert) {
    // Create a quadtree with 100 objects in it
    var tree = new TameGame.QuadTree();
    populateGrid(tree, 10, 10);
    var count = 0;

    // Should be 9 objects in a 3x3 square
    tree.forAllInBounds({ x:0, y:0, width:.3, height:.3 }, function () { ++count; });
    assert.ok(count === 9, "9 objects in 3x3 square");
    if (count !== 9) console.log('9 !== ', count);

    // Should be 100 objects overall
    count = 0;
    tree.forAllInBounds({ x: 0, y: 0, width:1, height: 1 }, function () { ++count; });
    assert.ok(count === 100, "100 objects overall");
    if (count !== 100) console.log('100 !== ', count);
});
<commit_msg>Check that we can overlap objects safely, plus expand the tree once there are objects in it<commit_after>QUnit.test("QuadTreeCanAddObject", function (assert) {
    var tree    = new TameGame.QuadTree();
    var someRef = tree.addObject({ x: 0.5, y: 0.5, width: 0.25, height: 0.25 }, {});

    assert.ok(someRef !== null);
});

QUnit.test("QuadTreeCanRemoveObject", function (assert) {
    var tree    = new TameGame.QuadTree();
    var someRef = tree.addObject({ x: 0.5, y: 0.5, width: 0.25, height: 0.25 }, {});
    tree.removeObject(someRef);

    assert.ok(someRef !== null);
});

QUnit.test("QuadTreeCanFindObject", function (assert) {
    var tree    = new TameGame.QuadTree();
    var someRef = tree.addObject({ x: 0.5, y: 0.5, width: 0.25, height: 0.25 }, {});
    var count   = 0;

    tree.forAllInBounds({ x:0, y: 0, width: 1, height: 1 }, function (obj) { ++count });

    assert.ok(someRef !== null);
    assert.ok(count === 1);
});

QUnit.test("QuadTreeCanFindHugeObject", function (assert) {
    var tree    = new TameGame.QuadTree();
    var someRef = tree.addObject({ x: -100, y: -100, width: 200, height: 200 }, {});            // Forces the quadtree to expand outward
    var count   = 0;

    tree.forAllInBounds({ x:-2, y: -2, width: 4, height: 4 }, function (obj) { ++count });

    assert.ok(someRef !== null);
    assert.ok(count === 1);
});

QUnit.test("QuadTreeExcludeObjectOutOfBounds", function (assert) {
    var tree    = new TameGame.QuadTree();
    var someRef = tree.addObject({ x: 0.5, y: 0.5, width: 0.25, height: 0.25 }, {});
    var count   = 0;

    tree.forAllInBounds({ x:-1, y: -1, width: 1, height: 1 }, function (obj) { ++count });

    assert.ok(someRef !== null);
    assert.ok(count === 0);
});

// Populates a quadtree with a grid of objects from 0,0 to 1,1. Width, height indicate the number of cells in the appropriate dimension
function populateGrid(quadTree, width, height) {
    var distX = 1.0 / width;
    var distY = 1.0 / height;

    var xpos, ypos;
    var x,y;

    ypos = 0;
    for (y=0; y<height; ++y) {
        xpos = 0;
        for (x=0; x<width; ++x) {
            quadTree.addObject({ x: xpos, y: ypos, width: distX, height: distY }, { x: xpos, y: ypos });

            xpos += distX;
        }

        ypos += distY;
    }
}

QUnit.test("QuadTreeQuery100Objects", function (assert) {
    // Create a quadtree with 100 objects in it
    var tree = new TameGame.QuadTree();
    populateGrid(tree, 10, 10);
    var count = 0;

    // Should be 9 objects in a 3x3 square
    tree.forAllInBounds({ x:0, y:0, width:.3, height:.3 }, function () { ++count; });
    assert.ok(count === 9, "9 objects in 3x3 square");
    if (count !== 9) console.log('9 !== ', count);

    // Should be 100 objects overall
    count = 0;
    tree.forAllInBounds({ x: 0, y: 0, width:1, height: 1 }, function () { ++count; });
    assert.ok(count === 100, "100 objects overall");
    if (count !== 100) console.log('100 !== ', count);
});

QUnit.test("QuadTreeQuery100ObjectsExpandTree", function (assert) {
    // Create a quadtree with 100 objects in it
    var tree = new TameGame.QuadTree();
    populateGrid(tree, 10, 10);
    var count = 0;

    // Expand the tree with an object that won't appear in the result
    tree.addObject({ x: -2, y: -2, width: .5, height: .5 }, {});                // Shouldn't appear in the test; also expands a populated tree

    // Should be 9 objects in a 3x3 square
    tree.forAllInBounds({ x:0, y:0, width:.3, height:.3 }, function () { ++count; });
    assert.ok(count === 9, "9 objects in 3x3 square");
    if (count !== 9) console.log('9 !== ', count);

    // Should be 100 objects overall
    count = 0;
    tree.forAllInBounds({ x: 0, y: 0, width:1, height: 1 }, function () { ++count; });
    assert.ok(count === 100, "100 objects overall");
    if (count !== 100) console.log('100 !== ', count);
});

QUnit.test("QuadTreeQuery800Objects", function (assert) {
    // Create a quadtree with 800 objects in it (overlapped 8 deep)
    var tree = new TameGame.QuadTree();
    for (var x=0; x<8; ++x) {
        populateGrid(tree, 10, 10);
    }
    var count = 0;

    // Should be 9 objects in a 3x3 square
    tree.forAllInBounds({ x:0, y:0, width:.3, height:.3 }, function () { ++count; });
    assert.ok(count === 9*8, "9 objects in 3x3 square");
    if (count !== 9*8) console.log('9*8 !== ', count);

    // Should be 800 objects overall
    count = 0;
    tree.forAllInBounds({ x: 0, y: 0, width:1, height: 1 }, function () { ++count; });
    assert.ok(count === 800, "800 objects overall");
    if (count !== 800) console.log('800 !== ', count);
});

QUnit.test("QuadTreeQuery100ObjectsPlusSomeMore", function (assert) {
    // Create a quadtree with 100 objects in it
    var tree = new TameGame.QuadTree();
    populateGrid(tree, 10, 10);
    var count = 0;

    // Add some larger objects to the tree
    tree.addObject({ x: .1, y: .1, width: .2, height: .2 }, {});                // In the 3x3 square
    tree.addObject({ x: .5, y: .5, width: .5, height: .5 }, {});                // In the 10x10 square

    // Should be 9 objects in a 3x3 square
    tree.forAllInBounds({ x:0, y:0, width:.3, height:.3 }, function () { ++count; });
    assert.ok(count === 10, "10 objects in 3x3 square");
    if (count !== 10) console.log('10 !== ', count);

    // Should be 100 objects overall
    count = 0;
    tree.forAllInBounds({ x: 0, y: 0, width:1, height: 1 }, function () { ++count; });
    assert.ok(count === 102, "102 objects overall");
    if (count !== 102) console.log('102 !== ', count);
});
<|endoftext|>


<commit_before>'use strict';

import React, {
  PropTypes
} from 'react';
import ReactNative, {
  requireNativeComponent,
  EdgeInsetsPropType,
  StyleSheet,
  UIManager,
  View,
  NativeModules,
  Text
} from 'react-native';
import resolveAssetSource from 'react-native/Libraries/Image/resolveAssetSource';
import deprecatedPropType from 'react-native/Libraries/Utilities/deprecatedPropType';
import invariant from 'react-native/node_modules/fbjs/lib/invariant';
import keyMirror from 'react-native/node_modules/fbjs/lib/keyMirror';
var WKWebViewManager = NativeModules.WKWebViewManager;

var BGWASH = 'rgba(255,255,255,0.8)';
var RCT_WEBVIEW_REF = 'webview';

var WebViewState = keyMirror({
  IDLE: null,
  LOADING: null,
  ERROR: null,
});

const NavigationType = keyMirror({
  click: true,
  formsubmit: true,
  backforward: true,
  reload: true,
  formresubmit: true,
  other: true,
});

const JSNavigationScheme = 'react-js-navigation';

type ErrorEvent = {
  domain: any;
  code: any;
  description: any;
}

type Event = Object;

var defaultRenderLoading = () => (
  <View style={styles.loadingView}>
    <ActivityIndicatorIOS />
  </View>
);
var defaultRenderError = (errorDomain, errorCode, errorDesc) => (
  <View style={styles.errorContainer}>
    <Text style={styles.errorTextTitle}>
      Error loading page
    </Text>
    <Text style={styles.errorText}>
      {'Domain: ' + errorDomain}
    </Text>
    <Text style={styles.errorText}>
      {'Error Code: ' + errorCode}
    </Text>
    <Text style={styles.errorText}>
      {'Description: ' + errorDesc}
    </Text>
  </View>
);

/**
 * Renders a native WebView.
 */

var WKWebView = React.createClass({
  statics: {
    JSNavigationScheme: JSNavigationScheme,
    NavigationType: NavigationType,
  },
  propTypes: {
    ...View.propTypes,

    html: deprecatedPropType(
      PropTypes.string,
      'Use the `source` prop instead.'
    ),

    url: deprecatedPropType(
      PropTypes.string,
      'Use the `source` prop instead.'
    ),

    /**
     * Loads static html or a uri (with optional headers) in the WebView.
     */
    source: PropTypes.oneOfType([
      PropTypes.shape({
        /*
         * The URI to load in the WebView. Can be a local or remote file.
         */
        uri: PropTypes.string,
        /*
         * The HTTP Method to use. Defaults to GET if not specified.
         * NOTE: On Android, only GET and POST are supported.
         */
        method: PropTypes.string,
        /*
         * Additional HTTP headers to send with the request.
         * NOTE: On Android, this can only be used with GET requests.
         */
        headers: PropTypes.object,
        /*
         * The HTTP body to send with the request. This must be a valid
         * UTF-8 string, and will be sent exactly as specified, with no
         * additional encoding (e.g. URL-escaping or base64) applied.
         * NOTE: On Android, this can only be used with POST requests.
         */
        body: PropTypes.string,
      }),
      PropTypes.shape({
        /*
         * A static HTML page to display in the WebView.
         */
        html: PropTypes.string,
        /*
         * The base URL to be used for any relative links in the HTML.
         */
        baseUrl: PropTypes.string,
      }),
      /*
       * Used internally by packager.
       */
      PropTypes.number,
    ]),

    /**
     * Function that returns a view to show if there's an error.
     */
    renderError: PropTypes.func, // view to show if there's an error
    /**
     * Function that returns a loading indicator.
     */
    renderLoading: PropTypes.func,
    /**
     * Invoked when load finish
     */
    onLoad: PropTypes.func,
    /**
     * Invoked when load either succeeds or fails
     */
    onLoadEnd: PropTypes.func,
    /**
     * Invoked on load start
     */
    onLoadStart: PropTypes.func,
    /**
     * Invoked when load fails
     */
    onError: PropTypes.func,
    /**
     * @platform ios
     */
    bounces: PropTypes.bool,
    scrollEnabled: PropTypes.bool,
    automaticallyAdjustContentInsets: PropTypes.bool,
    bounces: PropTypes.bool,
    contentInset: EdgeInsetsPropType,
    onNavigationStateChange: PropTypes.func,
    scalesPageToFit: PropTypes.bool,
    startInLoadingState: PropTypes.bool,
    style: View.propTypes.style,
    /**
     * Sets the JS to be injected when the webpage loads.
     */
    injectedJavaScript: PropTypes.string,
    /**
     * Allows custom handling of any webview requests by a JS handler. Return true
     * or false from this method to continue loading the request.
     * @platform ios
     */
    onShouldStartLoadWithRequest: PropTypes.func,
  },
  getInitialState() {
    return {
      viewState: WebViewState.IDLE,
      lastErrorEvent: (null: ?ErrorEvent),
      startInLoadingState: true,
    };
  },

  componentWillMount: function() {
    if (this.props.startInLoadingState) {
      this.setState({viewState: WebViewState.LOADING});
    }
  },

  render() {
    var otherView = null;

    if (this.state.viewState === WebViewState.LOADING) {
      otherView = (this.props.renderLoading || defaultRenderLoading)();
    } else if (this.state.viewState === WebViewState.ERROR) {
      var errorEvent = this.state.lastErrorEvent;
      invariant(
        errorEvent != null,
        'lastErrorEvent expected to be non-null'
      );
      otherView = (this.props.renderError || defaultRenderError)(
        errorEvent.domain,
        errorEvent.code,
        errorEvent.description
      );
    } else if (this.state.viewState !== WebViewState.IDLE) {
      console.error(
        'RCTWKWebView invalid state encountered: ' + this.state.loading
      );
    }

    var webViewStyles = [styles.container, styles.webView, this.props.style];
    if (this.state.viewState === WebViewState.LOADING ||
      this.state.viewState === WebViewState.ERROR) {
      // if we're in either LOADING or ERROR states, don't show the webView
      webViewStyles.push(styles.hidden);
    }

    var onShouldStartLoadWithRequest = this.props.onShouldStartLoadWithRequest && ((event: Event) => {
      var shouldStart = this.props.onShouldStartLoadWithRequest &&
        this.props.onShouldStartLoadWithRequest(event.nativeEvent);
      WKWebViewManager.startLoadWithResult(!!shouldStart, event.nativeEvent.lockIdentifier);
    });

    var source = this.props.source || {};
    if (this.props.html) {
      source.html = this.props.html;
    } else if (this.props.url) {
      source.uri = this.props.url;
    }

    var webView =
      <RCTWKWebView
        ref={RCT_WEBVIEW_REF}
        key="webViewKey"
        style={webViewStyles}
        source={resolveAssetSource(source)}
        injectedJavaScript={this.props.injectedJavaScript}
        bounces={this.props.bounces}
        scrollEnabled={this.props.scrollEnabled}
        contentInset={this.props.contentInset}
        automaticallyAdjustContentInsets={this.props.automaticallyAdjustContentInsets}
        onLoadingStart={this._onLoadingStart}
        onLoadingFinish={this._onLoadingFinish}
        onLoadingError={this._onLoadingError}
        onShouldStartLoadWithRequest={onShouldStartLoadWithRequest}
      />;

    return (
      <View style={styles.container}>
        {webView}
        {otherView}
      </View>
    );
  },

  /**
   * Go forward one page in the webview's history.
   */
  goForward: function() {
    UIManager.dispatchViewManagerCommand(
      this.getWebViewHandle(),
      UIManager.RCTWKWebView.Commands.goForward,
      null
    );
  },

  /**
   * Go back one page in the webview's history.
   */
  goBack: function() {
    UIManager.dispatchViewManagerCommand(
      this.getWebViewHandle(),
      UIManager.RCTWKWebView.Commands.goBack,
      null
    );
  },

  /**
   * Reloads the current page.
   */
  reload: function() {
    UIManager.dispatchViewManagerCommand(
      this.getWebViewHandle(),
      UIManager.RCTWKWebView.Commands.reload,
      null
    );
  },

  /**
   * We return an event with a bunch of fields including:
   *  url, title, loading, canGoBack, canGoForward
   */
  _updateNavigationState: function(event: Event) {
    if (this.props.onNavigationStateChange) {
      this.props.onNavigationStateChange(event.nativeEvent);
    }
  },

  /**
   * Returns the native webview node.
   */
  getWebViewHandle: function(): any {
    return ReactNative.findNodeHandle(this.refs[RCT_WEBVIEW_REF]);
  },

  _onLoadingStart: function(event: Event) {
    var onLoadStart = this.props.onLoadStart;
    onLoadStart && onLoadStart(event);
    this._updateNavigationState(event);
  },

  _onLoadingError: function(event: Event) {
    event.persist(); // persist this event because we need to store it
    var {onError, onLoadEnd} = this.props;
    onError && onError(event);
    onLoadEnd && onLoadEnd(event);
    console.warn('Encountered an error loading page', event.nativeEvent);

    this.setState({
      lastErrorEvent: event.nativeEvent,
      viewState: WebViewState.ERROR
    });
  },

  _onLoadingFinish: function(event: Event) {
    var {onLoad, onLoadEnd} = this.props;
    onLoad && onLoad(event);
    onLoadEnd && onLoadEnd(event);
    this.setState({
      viewState: WebViewState.IDLE,
    });
    this._updateNavigationState(event);
  },
});

var RCTWKWebView = requireNativeComponent('RCTWKWebView', WKWebView, {
  nativeOnly: {
    onLoadingStart: true,
    onLoadingError: true,
    onLoadingFinish: true,
  }
});

var styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  errorContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: BGWASH,
  },
  errorText: {
    fontSize: 14,
    textAlign: 'center',
    marginBottom: 2,
  },
  errorTextTitle: {
    fontSize: 15,
    fontWeight: '500',
    marginBottom: 10,
  },
  hidden: {
    height: 0,
    flex: 0, // disable 'flex:1' when hiding a View
  },
  loadingView: {
    backgroundColor: BGWASH,
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    height: 100,
  },
  webView: {
    backgroundColor: '#ffffff',
  }
});

export default WKWebView;
<commit_msg>Remove duplicated def<commit_after>'use strict';

import React, {
  PropTypes
} from 'react';
import ReactNative, {
  requireNativeComponent,
  EdgeInsetsPropType,
  StyleSheet,
  UIManager,
  View,
  NativeModules,
  Text
} from 'react-native';
import resolveAssetSource from 'react-native/Libraries/Image/resolveAssetSource';
import deprecatedPropType from 'react-native/Libraries/Utilities/deprecatedPropType';
import invariant from 'react-native/node_modules/fbjs/lib/invariant';
import keyMirror from 'react-native/node_modules/fbjs/lib/keyMirror';
var WKWebViewManager = NativeModules.WKWebViewManager;

var BGWASH = 'rgba(255,255,255,0.8)';
var RCT_WEBVIEW_REF = 'webview';

var WebViewState = keyMirror({
  IDLE: null,
  LOADING: null,
  ERROR: null,
});

const NavigationType = keyMirror({
  click: true,
  formsubmit: true,
  backforward: true,
  reload: true,
  formresubmit: true,
  other: true,
});

const JSNavigationScheme = 'react-js-navigation';

type ErrorEvent = {
  domain: any;
  code: any;
  description: any;
}

type Event = Object;

var defaultRenderLoading = () => (
  <View style={styles.loadingView}>
    <ActivityIndicatorIOS />
  </View>
);
var defaultRenderError = (errorDomain, errorCode, errorDesc) => (
  <View style={styles.errorContainer}>
    <Text style={styles.errorTextTitle}>
      Error loading page
    </Text>
    <Text style={styles.errorText}>
      {'Domain: ' + errorDomain}
    </Text>
    <Text style={styles.errorText}>
      {'Error Code: ' + errorCode}
    </Text>
    <Text style={styles.errorText}>
      {'Description: ' + errorDesc}
    </Text>
  </View>
);

/**
 * Renders a native WebView.
 */

var WKWebView = React.createClass({
  statics: {
    JSNavigationScheme: JSNavigationScheme,
    NavigationType: NavigationType,
  },
  propTypes: {
    ...View.propTypes,

    html: deprecatedPropType(
      PropTypes.string,
      'Use the `source` prop instead.'
    ),

    url: deprecatedPropType(
      PropTypes.string,
      'Use the `source` prop instead.'
    ),

    /**
     * Loads static html or a uri (with optional headers) in the WebView.
     */
    source: PropTypes.oneOfType([
      PropTypes.shape({
        /*
         * The URI to load in the WebView. Can be a local or remote file.
         */
        uri: PropTypes.string,
        /*
         * The HTTP Method to use. Defaults to GET if not specified.
         * NOTE: On Android, only GET and POST are supported.
         */
        method: PropTypes.string,
        /*
         * Additional HTTP headers to send with the request.
         * NOTE: On Android, this can only be used with GET requests.
         */
        headers: PropTypes.object,
        /*
         * The HTTP body to send with the request. This must be a valid
         * UTF-8 string, and will be sent exactly as specified, with no
         * additional encoding (e.g. URL-escaping or base64) applied.
         * NOTE: On Android, this can only be used with POST requests.
         */
        body: PropTypes.string,
      }),
      PropTypes.shape({
        /*
         * A static HTML page to display in the WebView.
         */
        html: PropTypes.string,
        /*
         * The base URL to be used for any relative links in the HTML.
         */
        baseUrl: PropTypes.string,
      }),
      /*
       * Used internally by packager.
       */
      PropTypes.number,
    ]),

    /**
     * Function that returns a view to show if there's an error.
     */
    renderError: PropTypes.func, // view to show if there's an error
    /**
     * Function that returns a loading indicator.
     */
    renderLoading: PropTypes.func,
    /**
     * Invoked when load finish
     */
    onLoad: PropTypes.func,
    /**
     * Invoked when load either succeeds or fails
     */
    onLoadEnd: PropTypes.func,
    /**
     * Invoked on load start
     */
    onLoadStart: PropTypes.func,
    /**
     * Invoked when load fails
     */
    onError: PropTypes.func,
    /**
     * @platform ios
     */
    bounces: PropTypes.bool,
    scrollEnabled: PropTypes.bool,
    automaticallyAdjustContentInsets: PropTypes.bool,
    contentInset: EdgeInsetsPropType,
    onNavigationStateChange: PropTypes.func,
    scalesPageToFit: PropTypes.bool,
    startInLoadingState: PropTypes.bool,
    style: View.propTypes.style,
    /**
     * Sets the JS to be injected when the webpage loads.
     */
    injectedJavaScript: PropTypes.string,
    /**
     * Allows custom handling of any webview requests by a JS handler. Return true
     * or false from this method to continue loading the request.
     * @platform ios
     */
    onShouldStartLoadWithRequest: PropTypes.func,
  },
  getInitialState() {
    return {
      viewState: WebViewState.IDLE,
      lastErrorEvent: (null: ?ErrorEvent),
      startInLoadingState: true,
    };
  },

  componentWillMount: function() {
    if (this.props.startInLoadingState) {
      this.setState({viewState: WebViewState.LOADING});
    }
  },

  render() {
    var otherView = null;

    if (this.state.viewState === WebViewState.LOADING) {
      otherView = (this.props.renderLoading || defaultRenderLoading)();
    } else if (this.state.viewState === WebViewState.ERROR) {
      var errorEvent = this.state.lastErrorEvent;
      invariant(
        errorEvent != null,
        'lastErrorEvent expected to be non-null'
      );
      otherView = (this.props.renderError || defaultRenderError)(
        errorEvent.domain,
        errorEvent.code,
        errorEvent.description
      );
    } else if (this.state.viewState !== WebViewState.IDLE) {
      console.error(
        'RCTWKWebView invalid state encountered: ' + this.state.loading
      );
    }

    var webViewStyles = [styles.container, styles.webView, this.props.style];
    if (this.state.viewState === WebViewState.LOADING ||
      this.state.viewState === WebViewState.ERROR) {
      // if we're in either LOADING or ERROR states, don't show the webView
      webViewStyles.push(styles.hidden);
    }

    var onShouldStartLoadWithRequest = this.props.onShouldStartLoadWithRequest && ((event: Event) => {
      var shouldStart = this.props.onShouldStartLoadWithRequest &&
        this.props.onShouldStartLoadWithRequest(event.nativeEvent);
      WKWebViewManager.startLoadWithResult(!!shouldStart, event.nativeEvent.lockIdentifier);
    });

    var source = this.props.source || {};
    if (this.props.html) {
      source.html = this.props.html;
    } else if (this.props.url) {
      source.uri = this.props.url;
    }

    var webView =
      <RCTWKWebView
        ref={RCT_WEBVIEW_REF}
        key="webViewKey"
        style={webViewStyles}
        source={resolveAssetSource(source)}
        injectedJavaScript={this.props.injectedJavaScript}
        bounces={this.props.bounces}
        scrollEnabled={this.props.scrollEnabled}
        contentInset={this.props.contentInset}
        automaticallyAdjustContentInsets={this.props.automaticallyAdjustContentInsets}
        onLoadingStart={this._onLoadingStart}
        onLoadingFinish={this._onLoadingFinish}
        onLoadingError={this._onLoadingError}
        onShouldStartLoadWithRequest={onShouldStartLoadWithRequest}
      />;

    return (
      <View style={styles.container}>
        {webView}
        {otherView}
      </View>
    );
  },

  /**
   * Go forward one page in the webview's history.
   */
  goForward: function() {
    UIManager.dispatchViewManagerCommand(
      this.getWebViewHandle(),
      UIManager.RCTWKWebView.Commands.goForward,
      null
    );
  },

  /**
   * Go back one page in the webview's history.
   */
  goBack: function() {
    UIManager.dispatchViewManagerCommand(
      this.getWebViewHandle(),
      UIManager.RCTWKWebView.Commands.goBack,
      null
    );
  },

  /**
   * Reloads the current page.
   */
  reload: function() {
    UIManager.dispatchViewManagerCommand(
      this.getWebViewHandle(),
      UIManager.RCTWKWebView.Commands.reload,
      null
    );
  },

  /**
   * We return an event with a bunch of fields including:
   *  url, title, loading, canGoBack, canGoForward
   */
  _updateNavigationState: function(event: Event) {
    if (this.props.onNavigationStateChange) {
      this.props.onNavigationStateChange(event.nativeEvent);
    }
  },

  /**
   * Returns the native webview node.
   */
  getWebViewHandle: function(): any {
    return ReactNative.findNodeHandle(this.refs[RCT_WEBVIEW_REF]);
  },

  _onLoadingStart: function(event: Event) {
    var onLoadStart = this.props.onLoadStart;
    onLoadStart && onLoadStart(event);
    this._updateNavigationState(event);
  },

  _onLoadingError: function(event: Event) {
    event.persist(); // persist this event because we need to store it
    var {onError, onLoadEnd} = this.props;
    onError && onError(event);
    onLoadEnd && onLoadEnd(event);
    console.warn('Encountered an error loading page', event.nativeEvent);

    this.setState({
      lastErrorEvent: event.nativeEvent,
      viewState: WebViewState.ERROR
    });
  },

  _onLoadingFinish: function(event: Event) {
    var {onLoad, onLoadEnd} = this.props;
    onLoad && onLoad(event);
    onLoadEnd && onLoadEnd(event);
    this.setState({
      viewState: WebViewState.IDLE,
    });
    this._updateNavigationState(event);
  },
});

var RCTWKWebView = requireNativeComponent('RCTWKWebView', WKWebView, {
  nativeOnly: {
    onLoadingStart: true,
    onLoadingError: true,
    onLoadingFinish: true,
  }
});

var styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  errorContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: BGWASH,
  },
  errorText: {
    fontSize: 14,
    textAlign: 'center',
    marginBottom: 2,
  },
  errorTextTitle: {
    fontSize: 15,
    fontWeight: '500',
    marginBottom: 10,
  },
  hidden: {
    height: 0,
    flex: 0, // disable 'flex:1' when hiding a View
  },
  loadingView: {
    backgroundColor: BGWASH,
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    height: 100,
  },
  webView: {
    backgroundColor: '#ffffff',
  }
});

export default WKWebView;
<|endoftext|>


<commit_before>var compose = require('ksf/utils/compose');
var FocusableElement = require('./FocusableElement');

module.exports = compose(FocusableElement.prototype, function(args) {
	FocusableElement.call(this, 'input');
	this._asYouType = args && args.asYouType;

	// callbacks mapping
	this._inputCbMap = [];
}, {
	value: function(value) {
		if (arguments.length) {
			this._setValue(value);
			return this;
		} else {
			return this._getValue();
		}
	},
	onInput: function(cb) {
		var self = this;
		var inputCb = function() {
			cb(self._getValue());
		};
		this.on(this._asYouType ? 'input' : 'change', inputCb);
		this._inputCbMap.push([cb, inputCb]);
		return this;
	},
	offInput: function(cb) {
		var inputCb;
		// TODO: replace with ES6 Map?
		this._inputCbMap.some(function(couple, index) {
			if (couple[0] === cb) {
				inputCb = couple[1];
				this.splice(index, 1);
				return true;
			}
		});

		this.off(this._asYouType ? 'input' : 'change', inputCb);
		return this;
	},
});
<commit_msg>fix bug in _InputElement#offInput<commit_after>var compose = require('ksf/utils/compose');
var FocusableElement = require('./FocusableElement');

module.exports = compose(FocusableElement.prototype, function(args) {
	FocusableElement.call(this, 'input');
	this._asYouType = args && args.asYouType;

	// callbacks mapping
	this._inputCbMap = [];
}, {
	value: function(value) {
		if (arguments.length) {
			this._setValue(value);
			return this;
		} else {
			return this._getValue();
		}
	},
	onInput: function(cb) {
		var self = this;
		var inputCb = function() {
			cb(self._getValue());
		};
		this.on(this._asYouType ? 'input' : 'change', inputCb);
		this._inputCbMap.push([cb, inputCb]);
		return this;
	},
	offInput: function(cb) {
		var inputCb;
		var inputCbMap = this._inputCbMap
		// TODO: replace with ES6 Map?
		inputCbMap.some(function(couple, index) {
			if (couple[0] === cb) {
				inputCb = couple[1];
				inputCbMap.splice(index, 1);
				return true;
			}
		});

		this.off(this._asYouType ? 'input' : 'change', inputCb);
		return this;
	},
});
<|endoftext|>


<commit_before>/*global self, window, Math, amd_cf*/
/*jslint todo: true evil:true */

var amd_cf = (function () {
    'use strict';
    var isArray, main, $, checkjQ, workerScript, checkdata, gotten, createRetObj;

    //Note: This indicates that this package and fitCurvesWorkers must be in the same
    // Directory, if they are not, this location needs to be changed...
    workerScript = 'fitCurvesWorker.js';
    main = {};
    gotten = {};

    isArray = (function () {
        // Use compiler's own isArray when available
        if (Array.isArray) {
            return Array.isArray;
        }

        // Retain references to variables for performance
        // optimization
        var objectToStringFn = Object.prototype.toString,
            arrayToStringResult = objectToStringFn.call([]);

        return function (subject) {
            return objectToStringFn.call(subject) === arrayToStringResult;
        };
    }());

    checkjQ = function () {
        var ret;
        if (window.jQuery) {
            $ = window.jQuery;
            ret = true;
        } else {
            console.error('jQuery is required for this add on package.');
            ret = false;
        }
        return ret;
    };

    checkdata = function (data) {
        var ret = true;
        if (!data.hasOwnProperty('x_values')) {
            console.error('Must inlcude x_values as an property on data');
            ret = false;
        }
        if (!data.y_values) {
            console.error('Must inlcude y_values as an property on data');
            ret = false;
        }
        if (ret) {
            if (!isArray(data.x_values) || !isArray(data.y_values)) {
                console.error('Both x_values and y_values must be arrays');
                ret = false;
            }
            if (ret && data.x_values.length !== data.y_values.length) {
                console.error('The length of x_values and y_values must be the same');
                ret = false;
            }
            if (!isArray(data.x_values[0])) {
                console.error('data.x_values must be an array of arrays, each array represents the X vector for each point.');
                ret = false;
            }
//             if (!data.hasOwnProperty('equation') || typeof data.equation !== 'object' || !data.equation.loaded) {
//                 console.error('Equation must be loaded using "getEquation" function first');
//                 ret = false;
//             }
        }
        return ret;
    };

    main.getEquation = function (url, callback) {
        var ret;
        if (checkjQ()) {
            if (!callback || typeof callback !== 'function') {
                console.warn('Callback function should be defined and utilized, this is done asynchronously.');
                callback = function (eq) {
                    console.log('equation loaded', eq);
                };
            }
            //Return an object with fit equations and done fitting equations attached.
            ret = createRetObj(url, callback);
        } else {
            ret = false;
        }
        return ret;
    };

    createRetObj = function (url, callback) {
        var retObj, fitEquation, doneFitting, worker, checkWW, prop;

        retObj = {};
        retObj.equation = {}; // This is to pass things by reference

        fitEquation = function (data, callback) {
            if (checkdata(data)) {
                //Sanitizes data, this has to be done for web workers
                data.equation = retObj.equation;
                worker.submitJob(data, function (res) {
                    //This will return the results of the analysis and the original data
                    callback(res.data[1], res.data[0]);
                });
            }
        };

        checkWW = function () {
            var ret;
            if (window.amd_ww) {
                worker = window.amd_ww.startWorkers({filename: workerScript});
                worker.pause();
                checkWW = function () {
                    return true;
                };
                ret = true;
            } else {
                throw 'amd_ww is required for this curve fitting, download at: https://github.com/adussaq/amd_ww/';
            }
            return ret;
        };

        doneFitting = function (callback) {
            if (!callback || typeof callback !== 'function') {
                console.error('Callback function should be defined and utilized, this is done asynchronously.');
                callback = function () {
                    console.log('All fitting completed!');
                };
            }
            worker.onComplete(callback);
        };

        checkWW();
        //set out ajax call as needed for url
        if (gotten[url]) {
            retObj.equation = gotten[url];
            //Assign by property so it is passed by reference
            for (prop in gotten[url]) {
                if (gotten[url].hasOwnProperty(prop)) {
                    retObj.equation[prop] = gotten[url][prop];
                }
            }
            worker.resume();
            callback(gotten[url]);
        } else {
            $.ajax({
                dataType: "json",
                url: url,
                complete: function (res) {
                    var eq;
                    eq = {};
                    eval('eq = ' + res.responseText);
                    eq.string = res.responseText;
                    eq.loaded = true;
                    gotten[url] = eq;
                    retObj.equation = eq;
                    //Assign by property so it is passed by reference
                    for (prop in eq) {
                        if (eq.hasOwnProperty(prop)) {
                            retObj.equation[prop] = eq[prop];
                        }
                    }
                    worker.resume();
                    callback(eq);
                }
            });
        }

        retObj.fitEquation = fitEquation;
        retObj.doneFitting = doneFitting;
        retObj.url = url;

        return retObj;

    };

    return main;

}());<commit_msg>fix pass by reference nature of equation object.<commit_after>/*global self, window, Math, amd_cf*/
/*jslint todo: true evil:true */

var amd_cf = (function () {
    'use strict';
    var isArray, main, $, checkjQ, workerScript, checkdata, gotten, createRetObj;

    //Note: This indicates that this package and fitCurvesWorkers must be in the same
    // Directory, if they are not, this location needs to be changed...
    workerScript = 'fitCurvesWorker.js';
    main = {};
    gotten = {};

    isArray = (function () {
        // Use compiler's own isArray when available
        if (Array.isArray) {
            return Array.isArray;
        }

        // Retain references to variables for performance
        // optimization
        var objectToStringFn = Object.prototype.toString,
            arrayToStringResult = objectToStringFn.call([]);

        return function (subject) {
            return objectToStringFn.call(subject) === arrayToStringResult;
        };
    }());

    checkjQ = function () {
        var ret;
        if (window.jQuery) {
            $ = window.jQuery;
            ret = true;
        } else {
            console.error('jQuery is required for this add on package.');
            ret = false;
        }
        return ret;
    };

    checkdata = function (data) {
        var ret = true;
        if (!data.hasOwnProperty('x_values')) {
            console.error('Must inlcude x_values as an property on data');
            ret = false;
        }
        if (!data.y_values) {
            console.error('Must inlcude y_values as an property on data');
            ret = false;
        }
        if (ret) {
            if (!isArray(data.x_values) || !isArray(data.y_values)) {
                console.error('Both x_values and y_values must be arrays');
                ret = false;
            }
            if (ret && data.x_values.length !== data.y_values.length) {
                console.error('The length of x_values and y_values must be the same');
                ret = false;
            }
            if (!isArray(data.x_values[0])) {
                console.error('data.x_values must be an array of arrays, each array represents the X vector for each point.');
                ret = false;
            }
//             if (!data.hasOwnProperty('equation') || typeof data.equation !== 'object' || !data.equation.loaded) {
//                 console.error('Equation must be loaded using "getEquation" function first');
//                 ret = false;
//             }
        }
        return ret;
    };

    main.getEquation = function (url, callback) {
        var ret;
        if (checkjQ()) {
            if (!callback || typeof callback !== 'function') {
                console.warn('Callback function should be defined and utilized, this is done asynchronously.');
                callback = function (eq) {
                    console.log('equation loaded', eq);
                };
            }
            //Return an object with fit equations and done fitting equations attached.
            ret = createRetObj(url, callback);
        } else {
            ret = false;
        }
        return ret;
    };

    createRetObj = function (url, callback) {
        var retObj, fitEquation, doneFitting, worker, checkWW, prop;

        retObj = {};
        retObj.equation = {}; // This is to pass things by reference

        fitEquation = function (data, callback) {
            if (checkdata(data)) {
                //Sanitizes data, this has to be done for web workers
                data.equation = retObj.equation;
                worker.submitJob(data, function (res) {
                    //This will return the results of the analysis and the original data
                    callback(res.data[1], res.data[0]);
                });
            }
        };

        checkWW = function () {
            var ret;
            if (window.amd_ww) {
                worker = window.amd_ww.startWorkers({filename: workerScript});
                worker.pause();
                checkWW = function () {
                    return true;
                };
                ret = true;
            } else {
                throw 'amd_ww is required for this curve fitting, download at: https://github.com/adussaq/amd_ww/';
            }
            return ret;
        };

        doneFitting = function (callback) {
            if (!callback || typeof callback !== 'function') {
                console.error('Callback function should be defined and utilized, this is done asynchronously.');
                callback = function () {
                    console.log('All fitting completed!');
                };
            }
            worker.onComplete(callback);
        };

        checkWW();
        //set out ajax call as needed for url
        if (gotten[url]) {

            //Assign by property so it is passed by reference
            for (prop in gotten[url]) {
                if (gotten[url].hasOwnProperty(prop)) {
                    retObj.equation[prop] = gotten[url][prop];
                }
            }
            worker.resume();
            callback(gotten[url]);
        } else {
            $.ajax({
                dataType: "json",
                url: url,
                complete: function (res) {
                    var eq;
                    eq = {};
                    eval('eq = ' + res.responseText);
                    eq.string = res.responseText;
                    eq.loaded = true;
                    gotten[url] = eq;

                    //Assign by property so it is passed by reference
                    for (prop in eq) {
                        if (eq.hasOwnProperty(prop)) {
                            retObj.equation[prop] = eq[prop];
                        }
                    }
                    worker.resume();
                    callback(eq);
                }
            });
        }

        retObj.fitEquation = fitEquation;
        retObj.doneFitting = doneFitting;
        retObj.url = url;

        return retObj;

    };

    return main;

}());<|endoftext|>