Move chuck to wafer map chip index
519818
def get_die(self):
        ''' '''
        reply = self._intf.query('ReadMapPosition')
        values = reply[2:].split(' ')
        return (int(values[0]), int(values[1]))
452067
private void updateIndex(
			long key,
			int hashCode,
			long address,
			int size,
			MemorySegment dataSegment,
			int currentPositionInSegment) throws IOException {
		assert (numKeys <= numBuckets / 2);
		int bucketId = hashCode & numBucketsMask;

		// each bucket occupied 16 bytes (long key + long pointer to data address)
		int bucketOffset = bucketId * SPARSE_BUCKET_ELEMENT_SIZE_IN_BYTES;
		MemorySegment segment = buckets[bucketOffset >>> segmentSizeBits];
		int segOffset = bucketOffset & segmentSizeMask;
		long currAddress;

		while (true) {
			currAddress = segment.getLong(segOffset + 8);
			if (segment.getLong(segOffset) != key && currAddress != INVALID_ADDRESS) {
				// hash conflicts, the bucket is occupied by another key

				// TODO test Conflict resolution:
				// now:    +1 +1 +1... cache friendly but more conflict, so we set factor to 0.5
				// other1: +1 +2 +3... less conflict, factor can be 0.75
				// other2: Secondary hashCode... less and less conflict, but need compute hash again
				bucketId = (bucketId + 1) & numBucketsMask;
				if (segOffset + SPARSE_BUCKET_ELEMENT_SIZE_IN_BYTES < segmentSize) {
					// if the new bucket still in current segment, we only need to update offset
					// within this segment
					segOffset += SPARSE_BUCKET_ELEMENT_SIZE_IN_BYTES;
				} else {
					// otherwise, we should re-calculate segment and offset
					bucketOffset = bucketId * 16;
					segment = buckets[bucketOffset >>> segmentSizeBits];
					segOffset = bucketOffset & segmentSizeMask;
				}
			} else {
				break;
			}
		}
		if (currAddress == INVALID_ADDRESS) {
			// this is the first value for this key, put the address in array.
			segment.putLong(segOffset, key);
			segment.putLong(segOffset + 8, address);
			numKeys += 1;
			// dataSegment may be null if we only have to rehash bucket area
			if (dataSegment != null) {
				dataSegment.putLong(currentPositionInSegment, toAddrAndLen(INVALID_ADDRESS, size));
			}
			if (numKeys * 2 > numBuckets) {
				resize();
			}
		} else {
			// there are some values for this key, put the address in the front of them.
			dataSegment.putLong(currentPositionInSegment, toAddrAndLen(currAddress, size));
			segment.putLong(segOffset + 8, address);
		}
	}
359171
def _map_block_index_to_location(ir_blocks):
    """"""
    block_index_to_location = {}
    # MarkLocation blocks occur after the blocks related to that location.
    # The core approach here is to buffer blocks until their MarkLocation is encountered
    # after which all buffered blocks can be associated with the encountered MarkLocation.location.
    current_block_ixs = []
    for num, ir_block in enumerate(ir_blocks):
        if isinstance(ir_block, blocks.GlobalOperationsStart):
            if len(current_block_ixs) > 0:
                unassociated_blocks = [ir_blocks[ix] for ix in current_block_ixs]
                raise AssertionError(
                    u'Unexpectedly encountered global operations before mapping blocks '
                    u'{} to their respective locations.'.format(unassociated_blocks))
            break
        current_block_ixs.append(num)
        if isinstance(ir_block, blocks.MarkLocation):
            for ix in current_block_ixs:
                block_index_to_location[ix] = ir_block.location
            current_block_ixs = []
    return block_index_to_location
187872
private int indexToOutputIndex(int parameterIndex) throws SQLException {
    try {
      if (outputParameterMapper[parameterIndex - 1] == -1) {
        //this is not an outputParameter
        throw new SQLException("Parameter in index '" + parameterIndex
            + "' is not declared as output parameter with method registerOutParameter");
      }
      return outputParameterMapper[parameterIndex - 1];
    } catch (ArrayIndexOutOfBoundsException arrayIndexOutOfBoundsException) {
      if (parameterIndex < 1) {
        throw new SQLException("Index " + parameterIndex + " must at minimum be 1");
      }
      throw new SQLException("Index value '" + parameterIndex
          + "' is incorrect. Maximum value is " + params.size());
    }
  }
967529
def merge_specific_instructions(chunks, join_preamble=True, join_raster=True):
    
    new_instructions = []
    last_opcode = None
    instruction_buffer = b''
    for instruction in chunks:
        opcode = match_opcode(instruction)
        if   join_preamble and OPCODES[opcode][0] == 'preamble' and last_opcode == 'preamble':
            instruction_buffer += instruction
        elif join_raster   and 'raster' in OPCODES[opcode][0] and 'raster' in last_opcode:
            instruction_buffer += instruction
        else:
            if instruction_buffer:
                new_instructions.append(instruction_buffer)
            instruction_buffer = instruction
        last_opcode = OPCODES[opcode][0]
    if instruction_buffer:
        new_instructions.append(instruction_buffer)
    return new_instructions
1067206
public final void fiadd(Mem src)
  {
    assert(src.size() == 2 || src.size() == 4);
    emitX86(INST_FIADD, src);
  }
243399
def read_chip_sn(self):
    '''
    '''
    commands = []
    commands.extend(self.register.get_commands("ConfMode"))
    self.register_utils.send_commands(commands)
    with self.readout(fill_buffer=True, callback=None, errback=None):
        if self.register.fei4b:
            commands = []
            self.register.set_global_register_value('Efuse_Sense', 1)
            commands.extend(self.register.get_commands("WrRegister", name=['Efuse_Sense']))
            commands.extend(self.register.get_commands("GlobalPulse", Width=0))
            self.register.set_global_register_value('Efuse_Sense', 0)
            commands.extend(self.register.get_commands("WrRegister", name=['Efuse_Sense']))
            self.register_utils.send_commands(commands)
        commands = []
        self.register.set_global_register_value('Conf_AddrEnable', 1)
        commands.extend(self.register.get_commands("WrRegister", name=['Conf_AddrEnable']))
        chip_sn_address = self.register.get_global_register_attributes("addresses", name="Chip_SN")
        commands.extend(self.register.get_commands("RdRegister", addresses=chip_sn_address))
        self.register_utils.send_commands(commands)
    data = self.read_data()

    if data.shape[0] == 0:
        logging.error('Chip S/N: No data')
        return
    read_values = []
    for index, word in enumerate(np.nditer(data)):
        fei4_data_word = FEI4Record(word, self.register.chip_flavor)
        if fei4_data_word == 'AR':
            fei4_next_data_word = FEI4Record(data[index + 1], self.register.chip_flavor)
            if fei4_next_data_word == 'VR':
                read_value = fei4_next_data_word['value']
                read_values.append(read_value)

#     commands = []
#     commands.extend(self.register.get_commands("RunMode"))
#     self.register_utils.send_commands(commands)

    if len(read_values) == 0:
        logging.error('No Chip S/N was found')
    elif len(read_values) == 1:
        logging.info('Chip S/N: %d', read_values[0])
    else:
        logging.warning('Ambiguous Chip S/N: %s', read_values)
984869
protected int[] getFringeIndexes (int bits)
    {
        int index = BITS_TO_INDEX[bits];
        if (index != -1) {
            int[] ret = new int[1];
            ret[0] = index;
            return ret;
        }

        // otherwise, split the bits into contiguous components

        // look for a zero and start our first split
        int start = 0;
        while ((((1 << start) & bits) != 0) && (start < NUM_FRINGEBITS)) {
            start++;
        }

        if (start == NUM_FRINGEBITS) {
            // we never found an empty fringebit, and since index (above)
            // was already -1, we have no fringe tile for these bits.. sad.
            return new int[0];
        }

        ArrayList<Integer> indexes = Lists.newArrayList();
        int weebits = 0;
        for (int ii = (start + 1) % NUM_FRINGEBITS; ii != start; ii = (ii + 1) % NUM_FRINGEBITS) {

            if (((1 << ii) & bits) != 0) {
                weebits |= (1 << ii);
            } else if (weebits != 0) {
                index = BITS_TO_INDEX[weebits];
                if (index != -1) {
                    indexes.add(index);
                }
                weebits = 0;
            }
        }
        if (weebits != 0) {
            index = BITS_TO_INDEX[weebits];
            if (index != -1) {
                indexes.add(index);
            }
        }

        int[] ret = new int[indexes.size()];
        for (int ii = 0; ii < ret.length; ii++) {
            ret[ii] = indexes.get(ii);
        }
        return ret;
    }
562718
def swapper_map(index)
      array = (0..9).to_a
      10.times.collect.with_index do |i|
        array.rotate!(index + i ^ spin).pop
      end
    end
325313
private LinkedHashMapSegment<K, V> segmentFor(int hash) {
        int h = hash(hash);
        return segments[(h >>> segmentShift) & segmentMask];
    }
1333140
def _decompose(net, wv_map, mems, block_out):
    

    def arg(x, i):
        # return the mapped wire vector for argument x, wire number i
        return wv_map[(net.args[x], i)]

    def destlen():
        # return iterator over length of the destination in bits
        return range(len(net.dests[0]))

    def assign_dest(i, v):
        # assign v to the wiremap for dest[0], wire i
        wv_map[(net.dests[0], i)] <<= v

    one_var_ops = {
        'w': lambda w: w,
        '~': lambda w: ~w,
    }
    c_two_var_ops = {
        '&': lambda l, r: l & r,
        '|': lambda l, r: l | r,
        '^': lambda l, r: l ^ r,
        'n': lambda l, r: l.nand(r),
    }

    if net.op in one_var_ops:
        for i in destlen():
            assign_dest(i, one_var_ops[net.op](arg(0, i)))
    elif net.op in c_two_var_ops:
        for i in destlen():
            assign_dest(i, c_two_var_ops[net.op](arg(0, i), arg(1, i)))
    elif net.op == 's':
        for i in destlen():
            selected_bit = arg(0, net.op_param[i])
            assign_dest(i, selected_bit)
    elif net.op == 'c':
        arg_wirelist = []
        # generate list of wires for vectors being concatenated
        for arg_vector in net.args:
            arg_vector_as_list = [wv_map[(arg_vector, i)] for i in range(len(arg_vector))]
            arg_wirelist = arg_vector_as_list + arg_wirelist
        for i in destlen():
            assign_dest(i, arg_wirelist[i])
    elif net.op == 'r':
        for i in destlen():
            args = (arg(0, i),)
            dests = (wv_map[(net.dests[0], i)],)
            new_net = LogicNet('r', None, args=args, dests=dests)
            block_out.add_net(new_net)
    elif net.op == 'm':
        arg0list = [arg(0, i) for i in range(len(net.args[0]))]
        addr = concat_list(arg0list)
        new_mem = _get_new_block_mem_instance(net.op_param, mems, block_out)[1]
        data = as_wires(new_mem[addr])
        for i in destlen():
            assign_dest(i, data[i])
    elif net.op == '@':
        addrlist = [arg(0, i) for i in range(len(net.args[0]))]
        addr = concat_list(addrlist)
        datalist = [arg(1, i) for i in range(len(net.args[1]))]
        data = concat_list(datalist)
        enable = arg(2, 0)
        new_mem = _get_new_block_mem_instance(net.op_param, mems, block_out)[1]
        new_mem[addr] <<= MemBlock.EnabledWrite(data=data, enable=enable)
    else:
        raise PyrtlInternalError('Unable to synthesize the following net '
                                 'due to unimplemented op :\n%s' % str(net))
    return
935947
private int mapIndexToAction(int index) {
    if (index < buttonCount) {
      int count = -1;
      for (int x = 0; x < MAX_BUTTON_COUNT; x++) {
        if (fields[x]) {
          count++;
        }
        if (count == index) {
          return x;
        }
      }
    }
    return -1;
  }
679027
private long move(long fromBaseAddress, long capacity, MemoryAllocator fromMalloc, MemoryAllocator toMalloc) {
        final long allocatedSize = HEADER_SIZE + capacity * slotLength;
        final long toBaseAddress = toMalloc.allocate(allocatedSize) + HEADER_SIZE;
        mem.copyMemory(fromBaseAddress - HEADER_SIZE, toBaseAddress - HEADER_SIZE, allocatedSize);
        fromMalloc.free(fromBaseAddress - HEADER_SIZE, allocatedSize);
        return toBaseAddress;
    }
682429
def move_to_next_bit_address(self):
        """"""
        self._current_bit_address = self.next_bit_address()
        self.mark_address(self._current_bit_address.split('.')[0], self._size_of_current_register_address)
1257903
private int nextSetBit(int fromIndex) {
      if (fromIndex < 0)
         throw new IndexOutOfBoundsException("fromIndex < 0: " + fromIndex);

      int u = intIndex(fromIndex);
      int arrayLength = array.length();
      if (u >= arrayLength)
         return -1;

      int possible = array.get(u) & (INT_MASK << fromIndex);

      while (true) {
         if (possible != 0) {
            return (u << ADDRESS_BITS_PER_INT) + Integer.numberOfTrailingZeros(possible);
         }
         if (++u == arrayLength) {
            return -1;
         }
         possible = array.get(u);
      }
   }
536145
def macro2micro(self, macro_indices):
        
        def from_partition(partition, macro_indices):
            micro_indices = itertools.chain.from_iterable(
                partition[i] for i in macro_indices)
            return tuple(sorted(micro_indices))

        if self.blackbox and self.coarse_grain:
            cg_micro_indices = from_partition(self.coarse_grain.partition,
                                              macro_indices)
            return from_partition(self.blackbox.partition,
                                  reindex(cg_micro_indices))
        elif self.blackbox:
            return from_partition(self.blackbox.partition, macro_indices)
        elif self.coarse_grain:
            return from_partition(self.coarse_grain.partition, macro_indices)
        return macro_indices
783513
def _run_chunk(self, chunk, kernel_options, device_options, tuning_options):
        """"""

        #detect language and create high-level device interface
        self.dev = DeviceInterface(kernel_options.kernel_string, iterations=tuning_options.iterations, **device_options)

        #move data to the GPU
        gpu_args = self.dev.ready_argument_list(kernel_options.arguments)

        results = []

        for element in chunk:
            params = dict(OrderedDict(zip(tuning_options.tune_params.keys(), element)))

            try:
                time = self.dev.compile_and_benchmark(gpu_args, params, kernel_options, tuning_options)

                params['time'] = time
                results.append(params)
            except Exception:
                params['time'] = None
                results.append(params)

        return results