Example #1
0
function vaoFromMesh(ctx, mesh) {
    var attributes = [];
    var indexBuffer = null;

    if (mesh.positions) {
        var buf  = ctx.createBuffer(ctx.ARRAY_BUFFER, new Float32Array(R.flatten(mesh.positions)));
        attributes.push({ buffer: buf, location: ctx.ATTRIB_POSITION, size: 3 });
    }

    if (mesh.uvs) {
        var buf  = ctx.createBuffer(ctx.ARRAY_BUFFER, new Float32Array(R.flatten(mesh.uvs)));
        attributes.push({ buffer: buf, location: ctx.ATTRIB_TEX_COORD_0, size: 2 });
    }

    if (mesh.normals) {
        var buf  = ctx.createBuffer(ctx.ARRAY_BUFFER, new Float32Array(R.flatten(mesh.normals)));
        attributes.push({ buffer: buf, location: ctx.ATTRIB_NORMAL, size: 3 });
    }

    if (mesh.colors) {
        var buf  = ctx.createBuffer(ctx.ARRAY_BUFFER, new Float32Array(R.flatten(mesh.colors)));
        attributes.push({ buffer: buf, location: ctx.ATTRIB_COLOR, size: 4 });
    }

    if (mesh.cells) {
        indexBuffer  = ctx.createBuffer(ctx.ELEMENT_ARRAY_BUFFER, new Uint16Array(R.flatten(mesh.cells)));
    }

    return ctx.createVertexArray(attributes, indexBuffer);
}
Example #2
0
    init: function() {
        var ctx = this.getContext();

        this.model = Mat4.create();
        this.projection = Mat4.perspective(Mat4.create(), 45, this.getAspectRatio(), 0.001, 10.0);
        this.view = Mat4.lookAt([], [3, 2, 2], [0, 0, 0], [0, 1, 0]);

        this.program = ctx.createProgram(VERT, FRAG);
        ctx.bindProgram(this.program);
        this.program.setUniform('repeat', [ 8, 8 ]);
        this.program.setUniform('iChannel0', 0);
        this.program.setUniform('model', this.model);
        this.program.setUniform('projection', this.projection);
        this.program.setUniform('view', this.view);

        var attributes = [
            { data: R.flatten(torus.positions), location: ctx.ATTRIB_POSITION, size: 3 },
            { data: R.flatten(torus.uvs), location: ctx.ATTRIB_TEX_COORD_0, size: 2 },
            { data: R.flatten(torus.normals), location: ctx.ATTRIB_NORMAL, size: 3 }
        ];
        var indices = { data: torus.cells, usage: ctx.STATIC_DRAW };
        this.mesh = ctx.createMesh(attributes, indices);

        var img = new Uint8Array(R.flatten([
            [0xff, 0xff, 0xff, 0xff], [0xcc, 0xcc, 0xcc, 0xff],
            [0xcc, 0xcc, 0xcc, 0xff], [0xff, 0xff, 0xff, 0xff]
        ]));

        this.tex = ctx.createTexture2D(img, 2, 2, {
          repeat: true,
          minFilter: ctx.NEAREST,
          magFilter: ctx.NEAREST
        })
    },
  R.map(function (feature) {
    var duration = R.compose(
      R.reduce(function (accumulator, current) {
        return accumulator + current;
      }, 0),
      R.flatten(),
      R.map(function (step) {
        return step.result.duration ? step.result.duration : 0;
      }),
      R.flatten(),
      R.map(function (element) {
        return element.steps;
      })
    )(feature.elements);

    if (duration && duration / 60000000000 >= 1) {

      //If the test ran for more than a minute, also display minutes.
      feature.duration = Math.trunc(duration / 60000000000) + " m " + round(2, (duration % 60000000000) / 1000000000) + " s";
    } else if (duration && duration / 60000000000 < 1) {

      //If the test ran for less than a minute, display only seconds.
      feature.duration = round(2, duration / 1000000000) + " s";
    }
    
  })(features);
Example #4
0
 it("should typecheck flatten", function() {
   const s: Array<number> = _.flatten([1, [2], ["1", [2, [3]]]]);
   const s1: Array<number> = _.flatten([
     ["1"],
     ["1", "2"],
     ["1", ["2", ["3"]]]
   ]);
 });
Example #5
0
    checkBlock(newBlock, previousBlock, referenceBlockchain = this.blocks) {
        const blockHash = newBlock.toHash();

        if (previousBlock.index + 1 !== newBlock.index) { // Check if the block is the last one
            console.error(`Invalid index: expected '${previousBlock.index + 1}' got '${newBlock.index}'`);
            throw new BlockAssertionError(`Invalid index: expected '${previousBlock.index + 1}' got '${newBlock.index}'`);
        } else if (previousBlock.hash !== newBlock.previousHash) { // Check if the previous block is correct
            console.error(`Invalid previoushash: expected '${previousBlock.hash}' got '${newBlock.previousHash}'`);
            throw new BlockAssertionError(`Invalid previoushash: expected '${previousBlock.hash}' got '${newBlock.previousHash}'`);
        } else if (blockHash !== newBlock.hash) { // Check if the hash is correct
            console.error(`Invalid hash: expected '${blockHash}' got '${newBlock.hash}'`);
            throw new BlockAssertionError(`Invalid hash: expected '${blockHash}' got '${newBlock.hash}'`);
        } else if (newBlock.getDifficulty() >= this.getDifficulty(newBlock.index)) { // If the difficulty level of the proof-of-work challenge is correct
            console.error(`Invalid proof-of-work difficulty: expected '${newBlock.getDifficulty()}' to be smaller than '${this.getDifficulty(newBlock.index)}'`);
            throw new BlockAssertionError(`Invalid proof-of-work difficulty: expected '${newBlock.getDifficulty()}' be smaller than '${this.getDifficulty()}'`);
        }

        // INFO: Here it would need to check if the block follows some expectation regarging the minimal number of transactions, value or data size to avoid empty blocks being mined.

        // For each transaction in this block, check if it is valid
        R.forEach(this.checkTransaction.bind(this), newBlock.transactions, referenceBlockchain);

        // Check if the sum of output transactions are equal the sum of input transactions + MINING_REWARD (representing the reward for the block miner)
        let sumOfInputsAmount = R.sum(R.flatten(R.map(R.compose(R.map(R.prop('amount')), R.prop('inputs'), R.prop('data')), newBlock.transactions))) + Config.MINING_REWARD;
        let sumOfOutputsAmount = R.sum(R.flatten(R.map(R.compose(R.map(R.prop('amount')), R.prop('outputs'), R.prop('data')), newBlock.transactions)));

        let isInputsAmountGreaterOrEqualThanOutputsAmount = R.gte(sumOfInputsAmount, sumOfOutputsAmount);

        if (!isInputsAmountGreaterOrEqualThanOutputsAmount) {
            console.error(`Invalid block balance: inputs sum '${sumOfInputsAmount}', outputs sum '${sumOfOutputsAmount}'`);
            throw new BlockAssertionError(`Invalid block balance: inputs sum '${sumOfInputsAmount}', outputs sum '${sumOfOutputsAmount}'`, { sumOfInputsAmount, sumOfOutputsAmount });
        }

        // Check if there is double spending
        let listOfTransactionIndexInputs = R.flatten(R.map(R.compose(R.map(R.compose(R.join('|'), R.props(['transaction', 'index']))), R.prop('inputs'), R.prop('data')), newBlock.transactions));
        let doubleSpendingList = R.filter((x) => x >= 2, R.map(R.length, R.groupBy(x => x)(listOfTransactionIndexInputs)));

        if (R.keys(doubleSpendingList).length) {
            console.error(`There are unspent output transactions being used more than once: unspent output transaction: '${R.keys(doubleSpendingList).join(', ')}'`);
            throw new BlockAssertionError(`There are unspent output transactions being used more than once: unspent output transaction: '${R.keys(doubleSpendingList).join(', ')}'`);
        }

        // Check if there is only 1 fee transaction and 1 reward transaction;
        let transactionsByType = R.countBy(R.prop('type'), newBlock.transactions);
        if (transactionsByType.fee && transactionsByType.fee > 1) {
            console.error(`Invalid fee transaction count: expected '1' got '${transactionsByType.fee}'`);
            throw new BlockAssertionError(`Invalid fee transaction count: expected '1' got '${transactionsByType.fee}'`);
        }

        if (transactionsByType.reward && transactionsByType.reward > 1) {
            console.error(`Invalid reward transaction count: expected '1' got '${transactionsByType.reward}'`);
            throw new BlockAssertionError(`Invalid reward transaction count: expected '1' got '${transactionsByType.reward}'`);
        }

        return true;
    }
Example #6
0
  return $c('td.summarytitle').map((i, el) => {
    el = $c(el);

    const items_json = el.parent().find('table.summaryinner').map((j, table) => {
      table = $c(table);
      const rows = table.children('tr');
      const item_name_row = $c(rows[0]);
      const win_rates = $c(rows[1]).find('td.win.summarystats');
      const pick_rates = $c(rows[2]).find('td.popularity.summarystats');

      return item_name_row.find('h1').map((idx, item_name) => {
        const item_title = $c(item_name).text();
        const win_rate = parseFloat($c(win_rates[idx]).text());
        const pick_rate = parseFloat($c(pick_rates[idx]).text());

        return {
          name: item_title,
          win: win_rate,
          pick: pick_rate
        };
      });
    }).get();

    return {
      title: el.text(), //  name of the section
      json: R.flatten(items_json)  //  json object w/ name, win, & pick values
    };
  }).get();
Example #7
0
function parseSkillsData($c) {
  let skill_sections = $c('td.summarytitle').map((i, el) => {
    el = $c(el);
    if (el.text() === 'Abilities') return el.parent().find('table.summaryskillstable').find('tr').map((idx, row) => {
      row = $c(row);
      if (idx === 0) return; // Skip the header row

      const skill_order = row.find('td.summaryskills > div.summaryspellkey').text().split('').join('.');
      const win_rate = parseFloat(row.find('td.win').text());
      const pick_rate = parseFloat(row.find('td.popularity').text());

      return {
        skills: skill_order,
        win: win_rate,
        pick: pick_rate
      };
    });
  }).get();

  skill_sections = R.reject(R.isNil, R.flatten(skill_sections));

  let highest_win_skills = R.reverse(sortByWinRate(skill_sections))[0];
  let most_freq_skills = R.reverse(sortByPickRate(skill_sections))[0];
  const shorthand_bool = store.get('settings').skillsformat;

  return {
    most_freq: shorthand_bool ? shorthandSkills(most_freq_skills.skills.split('.')) : most_freq_skills.skills,
    highest_win: shorthand_bool ? shorthandSkills(highest_win_skills.skills.split('.')) : highest_win_skills.skills
  };
}
Example #8
0
  report({ addedComponents, warnings }: AddActionResults): string {
    const paintWarning = () => {
      if (warnings) {
        const warn = Object.keys(warnings)
          .map(key =>
            chalk.yellow(`warning: files ${chalk.bold(warnings[key].join(', '))} already used by component: ${key}`)
          )
          .filter(x => x)
          .join('\n');
        if (!R.isEmpty(warn)) return `${warn}\n`;
      }
      return '';
    };

    if (addedComponents.length > 1) {
      return paintWarning() + chalk.green(`tracking ${addedComponents.length} new components`);
    }

    return (
      paintWarning() +
      R.flatten(
        addedComponents.map((result: AddResult) => {
          if (result.files.length === 0) {
            return chalk.underline.red(`could not track component ${chalk.bold(result.id)}: no files to track`);
          }
          const title = chalk.underline(`tracking component ${chalk.bold(result.id)}:\n`);
          const files = result.files.map(file => chalk.green(`added ${file.relativePath}`));
          return title + files.join('\n');
        })
      ).join('\n\n')
    );
  }
Example #9
0
    checkTransaction(transaction, referenceBlockchain = this.blocks) {

        // Check the transaction
        transaction.check(transaction);

        // Verify if the transaction isn't already in the blockchain
        let isNotInBlockchain = R.all((block) => {
            return R.none(R.propEq('id', transaction.id), block.transactions);
        }, referenceBlockchain);

        if (!isNotInBlockchain) {
            console.error(`Transaction '${transaction.id}' is already in the blockchain`);
            throw new TransactionAssertionError(`Transaction '${transaction.id}' is already in the blockchain`, transaction);
        }

        // Verify if all input transactions are unspent in the blockchain
        let isInputTransactionsUnspent = R.all(R.equals(false), R.flatten(R.map((txInput) => {
            return R.map(
                R.pipe(
                    R.prop('transactions'),
                    R.map(R.pipe(
                        R.path(['data', 'inputs']),
                        R.contains({ transaction: txInput.transaction, index: txInput.index })
                    ))
                ), referenceBlockchain);
        }, transaction.data.inputs)));

        if (!isInputTransactionsUnspent) {
            console.error(`Not all inputs are unspent for transaction '${transaction.id}'`);
            throw new TransactionAssertionError(`Not all inputs are unspent for transaction '${transaction.id}'`, transaction.data.inputs);
        }

        return true;
    }
function mkQuery (edges) {
  // ?n1 ?n2 ...
  var nstr = R.pipe(
    R.flatten(),
    R.uniq(),
    R.map(n => `?n${n}`),
    R.join(' ')
  )(edges)

  // ?e1 ?e2 ...
  var estr = R.pipe(
    R.mapObjIndexed((edge, i) => `?e${i + 1}`),
    R.values(),
    R.join(' ')
  )(edges)

  // [?e1 "s" ?n1] [?e1 "t" ?n2] ...
  var topostr = R.pipe(
    R.mapObjIndexed(function (edge, idx) {
      var s = edge[0]
      var t = edge[1]
      var i = idx + 1
      return `[?e${i} "s" ?n${s}] [?e${i} "t" ?n${t}] `
    }),
    R.values(),
    R.join(' ')
  )(edges)
  return `[:find ${nstr} ${estr} :in $ :where ${topostr}]`
}
Example #11
0
// E.g. !help useful
function helpCategory(client, evt, category, lang = 'en') {
  let methods;
  if (category === 'all') {
    methods = R.flatten(R.values(categories)).sort();
  } else {
    methods = categories[category].sort();
  }

  const text = R.map(name => {
    const translation = T(name, lang);
    if (!translation && category !== 'other' && !R.contains(name, categories.other)) return;

    let parameters;
    if (help_parameters[name] && help_parameters[name].parameters) {
      parameters = !R.is(String, help_parameters[name].parameters) ? R.join(' ', help_parameters[name].parameters || []) : help_parameters[name].parameters;
    }
    let text = `**\`${nconf.get('PREFIX')}${name}\`**`;
    if (parameters) text += ` \`${parameters}\``;
    if (translation) text += `\n\t\t${translation}`;

    return text;
  }, methods);

  if (category === 'all') {
    R.forEach(commands_text => {
      return client.Users.get(evt.message.author.id).openDM().then(dm => dm.sendMessage(R.join('\n', R.reject(R.isNil, commands_text))));
    }, R.splitEvery(10)(text));
  } else {
    return Promise.resolve(R.join('\n', R.reject(R.isNil, text)));
  }
}
 .then(instagram=>{
     return R.flatten(instagram.map(i=>{
         return i.instagram_photos.map(photo=>{
             return Object.assign({facebook_place_id:i.id},photo)
         })
     }))
 })
Example #13
0
    return this.chain(x => {
        var res = fn(this.value);
        var nextValue = res.value;
        var nextLog = res.log ? R.flatten(this.log.concat(res.log)) : this.log;

        return this.of(nextValue, nextLog);
    });
 .then((ids) => {
   ids = flatten(ids)
   return Promise.all(products.map((product, i) => {
     const prod = { resourceTypeId: ids[i], supplierAgentId: supplierId }
     return knex('products').insert(prod).returning('id')
   }))
 })
Example #15
0
Righter.prototype.chain = function(fn) {
    var res = fn(this.value);
    var nextValue = res.value;
    var nextLog = res.log ? R.flatten(this.log.concat(res.log)) : this.log;

    return res instanceof Righter ? this.of(nextValue, nextLog) : res;
};
Example #16
0
// E.g. !help useful
function helpCategory(bot, msg, category, lang = 'en') {
  let methods, channel;
  if (category === 'all') {
    channel = msg.author;
    methods = R.flatten(R.values(categories)).sort();
  } else {
    channel = msg.channel;
    methods = categories[category].sort();
  }

  const text = R.map(name => {
    const translation = T(name, lang);
    if (!translation && category !== 'other' && !R.contains(name, categories.other)) return;

    let parameters;
    if (help_parameters[name] && help_parameters[name].parameters) {
      parameters = !R.is(String, help_parameters[name].parameters) ? R.join(' ', help_parameters[name].parameters || []) : help_parameters[name].parameters;
    }
    let text = `**\`${nconf.get('PREFIX')}${name}\`**`;
    if (parameters) text += ` \`${parameters}\``;
    if (translation) text += `\n\t\t${translation}`;

    return text;
  }, methods);

  if (category === 'all') {
    R.forEach(commands_text => {
      return bot.sendMessage(channel, R.join('\n', R.reject(R.isNil, commands_text)));
    }, R.splitEvery(10)(text));
  } else {
    return bot.sendMessage(channel, R.join('\n', R.reject(R.isNil, text)));
  }
}
Example #17
0
function processChampData(champ, lm_position, data) {
  if (!data || !data.buildTree) return;

  const item_ids = R.flatten(pickIDs(data.buildTree.main));
  if (data.boots[0] && data.boots[0].id) item_ids.splice(1, 0, data.boots[0].id.toString()); // Add boots as second item

  const items = R.map(id => ({
    id,
    count: 1
  }), item_ids);

  const riot_json = R.merge(default_schema, {
    champion: champ,
    title: `LM ${store.get('lolmasters_ver')} ${positions[lm_position]}`,
    blocks: trinksCon([{
      type: positions[lm_position],
      items
    }])
  });

  return {
    champ,
    file_prefix: positions[lm_position],
    riot_json,
    source: 'lolmasters'
  };
}
Example #18
0
export const podcasts = (state = initialState, {type, payload}) => {
    switch (type) {
        case 'LOAD_PODCASTS':
            return {
                ...state,
                fetching: true,
            };

        case 'LOAD_PODCASTS_SUCCESS':
            return {
                ...state,
                fetching: false,
                allPodcasts: flatten(payload.map(episodes => episodes.map(toPodcast))),
            };

        case 'SELECT_PODCAST':
            return {
                ...state,
                selectedId: payload.id,
            };

        default:
            return state;
    }
};
Example #19
0
 .then(() => {
   const results = R.flatten(store.get('sr_itemsets'));
   if (process.env.BUILD_FIXTURES === 'true') {
     fs.writeFileSync(path.join(__dirname, `fixtures/lolmasters/results/${fixture}.json`), JSON.stringify(results, null, 2), 'utf8');
   }
   should.exist(results);
   results.should.eql(RESULTS_FIXTURES[fixture]);
 });
Example #20
0
export const arpeggiatedScale = ({
  arpeggiatorPatterns,
  scale,
  controlPad: {arpeggiatorOctaves, selectedArpeggiatorPattern}
}) => arpeggiatorPatterns[selectedArpeggiatorPattern](flatten(map(
  x => map(compose(add(x), flip(nth)(currentScale(scale))), [0, 2, 4]),
  map(multiply(12), range(0, arpeggiatorOctaves)))
))
Example #21
0
 children3D() {
     let children = React.Children.map(this.props.children || [], child => child);
     if (this.props.onChildren3D) {
         children = this.props.onChildren3D(children);
         children = RenderObject.uniqueKey(R.flatten(children));
     }
     return children;
 }
 get docs(): ?(Doclet[]) {
   if (!this._docs) {
     this._docs = this.files
       ? R.flatten(this.files.map(file => docsParser(file.contents.toString(), file.relative)))
       : [];
   }
   return this._docs;
 }
Example #23
0
 (err, errorMessages) => {
   if (err) { return next(err); }
   const realErrors = R.flatten(errorMessages).filter(message => message);
   if (realErrors.length === 0) {
     return activitySubmitted(req, res, next);
   }
   return res.render('../../../views/errorPages/validationError', {errors: realErrors});
 }
 .then((ids) => {
   ids = flatten(ids)
   // insert person profiles
   return Promise.all(agents.map((agent, i) => {
     const profile = merge(pick(['name', 'description', 'avatar'], agent), { agentId: ids[i] })
     return knex('profiles').insert(profile).returning('agentId')
   }))
 })
Example #25
0
export function parseAddresses (addresses = []) {
  return flatten([].concat(addresses).map((address) => {
    if (address && address.address) {
      address = convertAddresses(address)
    }
    return parseAddress(address)
  }))
}
 .then((ids) => {
   ids = flatten(ids)
   return Promise.all(products.map((product, i) => {
     return Promise.all(product.priceSpecs.map((priceSpec) => {
       const pSpec = merge(pick(['minimum', 'price', 'currency'], priceSpec), { productId: ids[i] })
       return knex('priceSpecs').insert(pSpec).returning('id')
     }))
   }))
 })
Example #27
0
      it("should return the board with the proper structure", function() {
        let columns = 4
        let rows = 3
        let result = makeRandomBoard(columns, rows)
        let cells = R.flatten(result)

        // expect list of lists
        chai.expect(R.all(c => R.type(R.prop("value", c)) == "String" && R.type(R.prop("status", c)), cells)).to.be.true
      })
Example #28
0
export function solveEquation(equation) {
  const solution = R.flatten(solve(equation)); // flatten single column matrix into array

  if (R.any(isNaN, solution)) {
    throw new Error('Solution contained NaNs');
  }

  return solution;
}
function identifiers(x) {
  function add(name) {
    if (stack.length > 0) {
      stack[stack.length - 1].uses.push(name);
    }
  }
  switch (type(x)) {
    case 'Program':
      return R.flatten(x.body.map(identifiers));
    case 'BlockStatement':
      return R.flatten(x.body.map(identifiers));
    case 'FunctionDeclaration':
      stack.push({ name: x.id.name, uses: [], params: x.params.map(name) })
      return identifiers(x.body);
    case 'FunctionExpression':
      stack.push({ name: x.id.name, uses: [], params: x.params.map(name) })
      return identifiers(x.body);
    case 'Identifier':
      add(x.name);
      return [x.name];
    case 'ExpressionStatement':
      return identifiers(x.expression);
    case 'VariableDeclaration':
      x.declarations.forEach(function (x) {
        add(R.path(['init','name'])(x));
      });
      return x.declarations.map(R.path(['init','name']));
    case 'UpdateExpression':
      return [identifiers(x.argument)];
    case 'CallExpression':
      var calleeName = identifiers(x.callee);
      return [calleeName].concat(x.arguments.map(identifiers));
    case 'MemberExpression':
      return [identifiers(x.object)];
    case 'BinaryExpression':
      return identifiers(x.left).concat(identifiers(x.right));
    case 'VariableDeclaration':
      return x.declarations.map(R.path(['init','name']));
    default:
      console.log('do nothing for', type(x), x);
      return [];
  }
}
 .then((ids) => {
   ids = flatten(ids)
   groupId = ids[0]
   supplierId = ids[1]
   // insert group profiles
   return Promise.all(groups.map((group, i) => {
     const profile = merge(group, { agentId: ids[i] })
     return knex('profiles').insert(profile).returning('agentId')
   }))
 })