The execution context for rowprocessors and row-generating notebooks and functions.
544519
def env(self):
        
        from copy import copy

        env = copy(self.doc.env)

        assert env is not None, 'Got a null execution context'

        env.update(self._envvar_env)

        env.update(self.all_props)

        return env
268428
private Iterator<Row<ByteBuffer, DeltaKey>> rowScan(final DeltaPlacement placement,
                                                        final ByteBufferRange rowRange,
                                                        final ByteBufferRange columnRange,
                                                        final LimitCounter limit,
                                                        final ReadConsistency consistency) {
        return rowScan(placement, placement.getBlockedDeltaColumnFamily(), rowRange, columnRange, limit, consistency);
    }
150973
@SuppressWarnings("unchecked")
    void initThreadContext(WSContextService contextSvc, Map<String, String> execProps) {
        threadContext = contextSvc.captureThreadContext(execProps);
    }
225278
def make_row_processors(bundle, source_headers, dest_table, env):
    

    dest_headers = [c.name for c in dest_table.columns]

    row_processors = []

    out = [file_header]

    transforms = list(dest_table.transforms)
    column_names = []
    column_types = []
    for i, segments in enumerate(transforms):

        seg_funcs = []

        for col_num, (segment, column) in enumerate(zip(segments, dest_table.columns), 1):

            if not segment:
                seg_funcs.append('row[{}]'.format(col_num - 1))
                continue

            assert column
            assert column.name == segment['column'].name
            col_name = column.name
            preamble, try_lines, exception = make_stack(env, i, segment)

            assert col_num == column.sequence_id, (dest_table.name, col_num, column.sequence_id)

            column_names.append(col_name)
            column_types.append(column.datatype)

            f_name = "{table_name}_{column_name}_{stage}".format(
                table_name=dest_table.name,
                column_name=col_name,
                stage=i
            )

            exception = (exception if exception else
                                  ('raise ValueError("Failed to cast column \'{}\', in '
                                   'function {}, value \'{}\': {}".format(header_d,"') + f_name +
                                  '", v.encode(\'ascii\', \'replace\'), exc) ) ')

            try:
                i_s = source_headers.index(column.name)
                header_s = column.name
                v = 'row[{}]'.format(i_s)

            except ValueError as e:

                i_s = 'None'
                header_s = None
                v = 'None' if col_num > 1 else 'row_n' # Give the id column the row number


            i_d = column.sequence_id - 1

            header_d = column.name

            template_args = dict(
                f_name=f_name,
                table_name=dest_table.name,
                column_name=col_name,
                stage=i,
                i_s=i_s,
                i_d=i_d,
                header_s=header_s,
                header_d=header_d,
                v=v,
                exception=indent + exception,
                stack='\n'.join(indent + l for l in try_lines),
                col_args = '# col_args not implemented yet'
            )

            seg_funcs.append(f_name
                             + ('({v}, {i_s}, {i_d}, {header_s}, \'{header_d}\', '
                                'row, row_n, errors, scratch, accumulator, pipe, bundle, source)')
                             .format(v=v, i_s=i_s, i_d=i_d, header_s="'" + header_s + "'" if header_s else 'None',
                                     header_d=header_d))

            out.append('\n'.join(preamble))

            out.append(column_template.format(**template_args))

        source_headers = dest_headers

        stack = '\n'.join("{}{}, # {}".format(indent,l,cn)
                          for l,cn, dt in zip(seg_funcs, column_names, column_types))

        out.append(row_template.format(
            table=dest_table.name,
            stage=i,
            stack=stack
        ))

        row_processors.append('row_{table}_{stage}'.format(stage=i, table=dest_table.name))

    # Add the final datatype cast, which is done seperately to avoid an unecessary function call.

    stack = '\n'.join("{}cast_{}(row[{}], '{}', errors),".format(indent, c.datatype, i, c.name)
                      for i, c in enumerate(dest_table.columns) )

    out.append(row_template.format(
        table=dest_table.name,
        stage=len(transforms),
        stack=stack
    ))

    row_processors.append('row_{table}_{stage}'.format(stage=len(transforms), table=dest_table.name))

    out.append('row_processors = [{}]'.format(','.join(row_processors)))

    return '\n'.join(out)
1079149
function ExecutionContext () {
  var self = this
  this.event = new EventManager()

  var executionContext = null

  this.blockGasLimitDefault = 4300000
  this.blockGasLimit = this.blockGasLimitDefault
  this.customNetWorks = {}

  this.init = function (config) {
    if (config.get('settings/always-use-vm')) {
      executionContext = 'vm'
    } else {
      executionContext = injectedProvider ? 'injected' : 'vm'
    }
  }

  this.getProvider = function () {
    return executionContext
  }

  this.isVM = function () {
    return executionContext === 'vm'
  }

  this.web3 = function () {
    return this.isVM() ? web3VM : web3
  }

  this.detectNetwork = function (callback) {
    if (this.isVM()) {
      callback(null, { id: '-', name: 'VM' })
    } else {
      this.web3().version.getNetwork((err, id) => {
        var name = null
        if (err) name = 'Unknown'
        // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md
        else if (id === '1') name = 'Main'
        else if (id === '2') name = 'Morden (deprecated)'
        else if (id === '3') name = 'Ropsten'
        else if (id === '4') name = 'Rinkeby'
        else if (id === '42') name = 'Kovan'
        else if (id === '237') name = 'DEXON'
        else if (id === '238') name = 'DEXON Testnet'
        else name = 'Custom'

        if (id === '1') {
          this.web3().eth.getBlock(0, (error, block) => {
            if (error) console.log('cant query first block')
            if (block && block.hash !== mainNetGenesisHash) name = 'Custom'
            callback(err, { id, name })
          })
        } else {
          callback(err, { id, name })
        }
      })
    }
  }

  this.removeProvider = function (name) {
    if (name && this.customNetWorks[name]) {
      delete this.customNetWorks[name]
      self.event.trigger('removeProvider', [name])
    }
  }

  this.addProvider = function (network) {
    if (network && network.name && network.url) {
      this.customNetWorks[network.name] = network
      self.event.trigger('addProvider', [network])
    }
  }

  this.internalWeb3 = function () {
    return web3
  }

  this.blankWeb3 = function () {
    return blankWeb3
  }

  this.vm = function () {
    return vm
  }

  this.setContext = function (context, endPointUrl, confirmCb, infoCb) {
    executionContext = context
    this.executionContextChange(context, endPointUrl, confirmCb, infoCb)
  }

  this.executionContextChange = function (context, endPointUrl, confirmCb, infoCb, cb) {
    if (!cb) cb = () => {}

    if (context === 'vm') {
      executionContext = context
      vm.stateManager.revert(function () {
        vm.stateManager.checkpoint()
      })
      self.event.trigger('contextChanged', ['vm'])
      return cb()
    }

    if (context === 'injected') {
      if (injectedProvider === undefined) {
        var alertMsg = 'No injected Web3 provider found. '
        alertMsg += 'Make sure your provider (e.g. MetaMask) is active and running '
        alertMsg += '(when recently activated you may have to reload the page).'
        infoCb(alertMsg)
        return cb()
      } else {
        executionContext = context
        web3.setProvider(injectedProvider)
        self._updateBlockGasLimit()
        self.event.trigger('contextChanged', ['injected'])
        return cb()
      }
    }

    if (context === 'web3') {
      confirmCb(cb)
    }

    if (this.customNetWorks[context]) {
      var provider = this.customNetWorks[context]
      setProviderFromEndpoint(provider.url, provider.name, () => { cb() })
    }
  }

  this.currentblockGasLimit = function () {
    return this.blockGasLimit
  }

  this.stopListenOnLastBlock = function () {
    if (this.listenOnLastBlockId) clearInterval(this.listenOnLastBlockId)
    this.listenOnLastBlockId = null
  }

  this._updateBlockGasLimit = function () {
    if (this.getProvider() !== 'vm') {
      web3.eth.getBlock('latest', (err, block) => {
        if (!err) {
          // we can't use the blockGasLimit cause the next blocks could have a lower limit : https://github.com/dexon-foundation/remix/issues/506
          this.blockGasLimit = (block && block.gasLimit) ? Math.floor(block.gasLimit - (5 * block.gasLimit) / 1024) : this.blockGasLimitDefault
        } else {
          this.blockGasLimit = this.blockGasLimitDefault
        }
      })
    }
  }

  this.listenOnLastBlock = function () {
    this.listenOnLastBlockId = setInterval(() => {
      this._updateBlockGasLimit()
    }, 15000)
  }

  // TODO: not used here anymore and needs to be moved
  function setProviderFromEndpoint (endpoint, context, cb) {
    var oldProvider = web3.currentProvider

    if (endpoint === 'ipc') {
      web3.setProvider(new web3.providers.IpcProvider())
    } else {
      web3.setProvider(new web3.providers.HttpProvider(endpoint))
    }
    if (web3.isConnected()) {
      executionContext = context
      self._updateBlockGasLimit()
      self.event.trigger('contextChanged', ['web3'])
      self.event.trigger('web3EndpointChanged')
      cb()
    } else {
      web3.setProvider(oldProvider)
      var alertMsg = 'Not possible to connect to the Web3 provider. '
      alertMsg += 'Make sure the provider is running and a connection is open (via IPC or RPC).'
      cb(alertMsg)
    }
  }
  this.setProviderFromEndpoint = setProviderFromEndpoint

  this.txDetailsLink = function (network, hash) {
    if (transactionDetailsLinks[network]) {
      return transactionDetailsLinks[network] + hash
    }
  }
}
891673
def run(instruction)
      @inst = instruction
      measurements = []

      # run pre_build hooks
      if @inst.respond_to? :pre_hooks
        measurements << Benchmark.measure('pre build:') do
          @inst.pre_hooks.each(&:call)
        end
      end

      # process the rows
      measurements << Benchmark.measure('process rows:') do
        @inst.options[:parallel] ? pprocess_rows : process_rows
      end

      # build
      measurements << Benchmark.measure('build:') do
        build @inst.consumers
      end

      # run post_build hooks
      if @inst.respond_to? :post_hooks
        measurements << Benchmark.measure('post build:') do
          @inst.post_hooks.each(&:call)
        end
      end
      report measurements if @inst.options[:benchmark]
    end
454254
function callProcessor(eventType, data, callback) {
    var p = processors[eventType];
    // no processors
    if (p===undefined || p.length==0) {
      if (callback!==undefined) callback(data);
      return;
    }
    // now go through all processors
    var n = 0;
    var cbCalled = false;
    var cb = function(inData) {
      if (cbCalled) throw new Error("Internal error in "+eventType+" processor. Callback is called TWICE.");
      cbCalled = true;
      if (n < p.length) {
        cbCalled = false;
        p[n++](inData, cb);
      } else {
        if (callback!==undefined) callback(inData);
      }
    };
    cb(data);
  }
1217398
function runStep(step) 
{
  switch (step) {
    case 1 : 
      trace("-- Beginning benchmark --");
      initializeDB();
      initializeUnique();
      setTimeout(function() { runStep(2); }, 100);
      break;
    case 2 : 
      benchGet();
      setTimeout(function() { runStep(3); }, 100);
      break;
    case 3 :
      benchUniquePerf();
      setTimeout(function() { runStep(4); }, 100);
      trace("");
      trace("-- Benchmarking query on non-indexed column --");
      break;
    case 4 : 
      benchFind();	// find benchmark on unindexed customid field
      setTimeout(function() { runStep(5); }, 100);
      break;
    case 5 : 
      benchRS(); // resultset find benchmark on unindexed customid field
      setTimeout(function() { runStep(6); }, 100);
      break;
    case 6 : 
      benchDV();
      setTimeout(function() { runStep(7); }, 100);
      trace("");
      trace("-- Adding Binary Index to query column and repeating benchmarks --");
      break;
    case 7 : 
      samplecoll.ensureIndex("customId");
      setTimeout(function() { runStep(8); }, 100);
      break;
    case 8 : 
      benchFind(20);
      setTimeout(function() { runStep(9); }, 100);
      break;
    case 9 : 
      benchRS(15);
      setTimeout(function() { runStep(10); }, 100);
      break;
    case 10 : 
      benchDV(15);
      trace("");
      trace("done.");
      break;
  }
}
137125
private void executeRow(Example valuesRow, Example headers, Fixture rowFixtureAdapter)
    {
        valuesRow.annotate( Annotations.right() );

        Statistics rowStats = new Statistics();

        for (int i = 0; i != valuesRow.remainings(); ++i)
        {
            Example cell = valuesRow.at( i );

            if (i < headers.remainings())
            {
                // We can do the cast because #parseColumn returns an ExpectedColumn
                ExpectedColumn column = (ExpectedColumn) columns[i];

                try
                {
                    chekOneCell(rowFixtureAdapter, rowStats, cell, column);
                }
                catch (Exception e)
                {
                    cell.annotate( exception( e ) );
                    stats.exception();
                }
            }
            else
            {
                cell.annotate( ignored( cell.getContent() ) );
            }
        }
        applyRowStatistic(rowStats);
    }
1220693
void createRowElementLinkedLists( int leftmost[] , int w[]) {
        for (int k = 0; k < n; k++) {
            w[head+k] = -1; w[tail+k] = -1;  w[nque+k] = 0;
        }

        // scan rows in reverse order creating a linked list of nz element indexes in each row
        for (int i = m-1; i >= 0; i--) {
            int k = leftmost[i];      // 'k' = left most column in row 'i'
            if( k == -1 )             // row 'i' is empty
                continue;
            if( w[nque+k]++ == 0 )
                w[tail+k] = i;
            w[next+i] = w[head+k];
            w[head+k] = i;
        }
    }
39092
def ctx(self):
        '''
        
        '''
        if six.PY2:
            return contextlib.nested(
                self.functions.context_dict.clone(),
                self.returners.context_dict.clone(),
                self.executors.context_dict.clone(),
            )
        else:
            exitstack = contextlib.ExitStack()
            exitstack.enter_context(self.functions.context_dict.clone())
            exitstack.enter_context(self.returners.context_dict.clone())
            exitstack.enter_context(self.executors.context_dict.clone())
            return exitstack
612504
public void each(MatrixProcedure procedure) {
        MatrixIterator it = iterator();

        while (it.hasNext()) {
            double x = it.next();
            int i = it.rowIndex();
            int j = it.columnIndex();
            procedure.apply(i, j, x);
        }
    }
753453
async function* run_table_cases(worker, data, test) {
    console.log(`Benchmarking \`${test}\``);
    try {
        for (let x = 0; x < ITERATIONS + TOSS_ITERATIONS; x++) {
            const start = performance.now();
            const table = worker.table(data.slice ? data.slice() : data);
            await table.size();
            if (x >= TOSS_ITERATIONS) {
                yield {
                    test,
                    time: performance.now() - start,
                    method: test,
                    row_pivots: "n/a",
                    column_pivots: "n/a",
                    aggregate: "n/a"
                };
            }
            await table.delete();
        }
    } catch (e) {
        console.error(`Benchmark ${test} failed`, e);
    }
}
593069
function main() {
	var len;
	var min;
	var max;
	var f;
	var i;

	min = 1; // 10^min
	max = 6; // 10^max

	for ( i = min; i <= max; i++ ) {
		len = pow( 10, i );
		f = createBenchmark( len );
		bench( pkg+':len='+len, f );
	}
}
620175
protected void processGrid( int cols, int rows, boolean ignoreBorder, Calculator calculator ) throws Exception {
        ExecutionPlanner planner = createDefaultPlanner();
        planner.setNumberOfTasks(rows * cols);

        int startC = 0;
        int startR = 0;
        int endC = cols;
        int endR = rows;
        if (ignoreBorder) {
            startC = 1;
            startR = 1;
            endC = cols - 1;
            endR = rows - 1;
        }
        for( int r = startR; r < endR; r++ ) {
            for( int c = startC; c < endC; c++ ) {
                int _c = c, _r = r;
                planner.submit(() -> {
                    if (!pm.isCanceled()) {
                        calculator.calculate(_c, _r);
                    }
                });
            }
        }
        planner.join();
    }
469363
def row(self, data):
        """"""
        for column in self.column_funcs:
            if callable(column):
                yield column(data)
            else:
                yield utils.lookup(data, *column)
938957
function () {
		var prepData, supportDesc;
		for ( var instanceNo in this.workerDescription.workerSupports ) {

			supportDesc = this.workerDescription.workerSupports[ instanceNo ];
			if ( ! supportDesc.inUse ) {

				if ( this.instructionQueuePointer < this.instructionQueue.length ) {

					prepData = this.instructionQueue[ this.instructionQueuePointer ];
					this._kickWorkerRun( prepData, supportDesc );
					this.instructionQueuePointer++;

				} else {

					this._deregister( supportDesc );

				}

			}

		}

		if ( ! this.isRunning() && this.callbackOnFinishedProcessing !== null ) {

			this.callbackOnFinishedProcessing();
			this.callbackOnFinishedProcessing = null;

		}
	}