#!/usr/bin/env python

# DSP
# Phil Bordelon

import os
import sys

DEBUG = os.getenv("DEBUG", False)

# <rant>
# Note that this solution is not the 'main' solution, and as such does dirty
# dirty scripting language tricks (namely the use of exec()) to get around
# having to write a parser for the functions.  This is NOT A VALID PRACTICE
# for actual contest solutions.  Of course, Python isn't a valid practice in
# the first place, so I suppose this is really just once again showing why a
# well-organised Python team could probably stomp all over teams forced to
# use C/C++/Java.  Yeah.
# </rant>

# Structs?  In my Python?  It's more likely than you think.
class Struct(object):
   pass

####
# printFilterRepresentation prints a representation of a given filter.
# It's for debugging purposes.
def printFilterRepresentation(filter):

   to_print = "%s: " % (filter.name)
   for bit in filter.equation:
      if bit.type == "n":
         to_print += bit.string
      else:
         to_print += "%s[%d]" % (bit.input, bit.offset)

   print(to_print)

####
# addElementToNetwork adds a new element, be it a raw stream or a filter,
# to the network.  It does the requisite parsing and breakdown into a
# filter object.  Internally, even raw streams are turned into filters
# with predetermined outputs for simplicity.
def addElementToNetwork(network, element_repr):

   # New filter object.
   filter = Struct()

   filter.name = element_repr[0]

   # See if this is a raw stream or a real filter.
   if element_repr[2] == "%":

      # Raw stream.  Easy!  Set the output and note the lack of inputs.
      values = element_repr.split("%")[1].strip()
      filter.output = [int(x) for x in values.split(" ")]
      filter.equation = []
      filter.inputs = None
   
   else:

      # Guh, this is a real filter.  For now, there is no output from this.
      filter.output = None
      filter.equation = []
      filter.inputs = []

      # Now we need to break down the equation.  The way we do this is simple;
      # as concerns our use of Python's eval() function, the only thing we
      # care about breaking out of the function are the "variables."  So we'll
      # build a list of elements in the equation, using a two-state FSM to
      # manage what we're building.
      equation = element_repr[4:]

      # We append a space at the end so that we force a flush of a terminal
      # variable.
      equation += " "

      bit_string = ""
      in_variable = False
      for i in range(len(equation)):
         curr_char = equation[i]
         if in_variable:

            # Variables end with whitespace.  If we're not there yet ...
            if curr_char != " ":

               # Just keep building the variable string.
               bit_string += curr_char
            else:

               # Okay.  We need to convert this variable to something more
               # useful.  Variables are of the form C[N] where C is a letter
               # representing an input and N as some integer representing the
               # offset.
               bit = Struct()
               bit.type = "v"
               bit.input = bit_string[0]
               bit.offset = int(bit_string[2:-1])
               bit.string = bit_string

               # Add to the equation list.  Also note the input.
               filter.equation.append(bit)
               if bit.input not in filter.inputs:
                  filter.inputs.append(bit.input)

               # Switch states and store that space.
               in_variable = False
               bit_string = curr_char

         else:
            if not curr_char.isalpha():
               bit_string += curr_char
            else:

               # Start of a variable.  Save off this text into a struct and make
               # it part of the equation list.
               bit = Struct()
               bit.type = "n"
               bit.string = bit_string

               filter.equation.append(bit)

               # Now, switch state to the 'variable' state.
               in_variable = True
               bit_string = curr_char

      # We need to add the very last non-variable bit; we're guaranteed that the
      # end of it /is/ non-variable thanks to our extra space at the end.
      bit = Struct()
      bit.type = "n"
      bit.string = bit_string

      filter.equation.append(bit)

      # Phew.
   
   if DEBUG:
      printFilterRepresentation(filter)

   # Add this filter to the network.
   network.filters[filter.name] = filter

####
# calculate calculates the output of a given filter.
def calculate(network, filter):

   # Get the actual filter.
   actual_filter = network.filters[filter]

   output = []
   # We want to loop through every sample number.
   for i in range(network.sample_count):

      # All right.  We need to build the string that we're going to eval().
      # This is done by combining together the bits of the equation; if it's
      # a non-variable, we just add it to the string.  If it's a variable,
      # we need to actually get the requisite value.
      string_bits = []
      for bit in actual_filter.equation:
         if bit.type == "n":
            string_bits.append(bit.string)
         else:

            # Okay.  We need to get the value required.
            input = network.filters[bit.input]
            offset = bit.offset

            source_loc = i + offset

            # If the source is out of range (before 0 or after the sample
            # total), it's gonna be zero.
            if source_loc < 0 or source_loc >= network.sample_count:
               value = 0
            else:

               # Retrieve the value.
               value = input.output[source_loc]

            # Now that we have the value, we want to add it to the equation.
            string_bits.append(repr(value))

      if DEBUG:
         print("Filter %s: Evaluating %s" % (filter, " ".join(string_bits)))

      # Evaluate!  (This is sleazy.
      result = eval(" ".join(string_bits))

      # Okay.  If this is below zero or above 255, normalize.
      if result < 0:
         result = 0
      elif result > 255:
         result = 255

      # Lastly, round down to the nearest integer.
      result = int(result)

      # Add it to the output stream.
      output.append(result)

   # Now that all of that's done, set the filter's output to the output.
   actual_filter.output = output

####
# simulate does the actual network simulation work.
def simulate(network):

   # Okay.  We're going to loop until nothing happens, and we're going to set
   # every filter that doesn't start with input to 'unhandled'.  Each 'pass',
   # we're guaranteed that one unhandled filter will suddenly have all of its
   # inputs ready, otherwise we have a feedback loop which is Not Allowed.
   # So then we calculate!

   unhandled_filters = []
   for filter in network.filters:
      if not network.filters[filter].output:
         unhandled_filters.append(filter)

   while len(unhandled_filters) > 0:

      for filter in unhandled_filters:
         real_filter = network.filters[filter]

         # Let's see if all of its inputs are ready.
         ready_to_run = True
         for input in real_filter.inputs:
            if input in unhandled_filters:
               ready_to_run = False

         if ready_to_run:

            # Woo!  Time to calculate.
            calculate(network, filter)

            # We can axe this filter from the unhandled list.
            unhandled_filters.remove(filter)

####
# printOutputs prints the outputs of each element in the network.
def printOutputs(network):

   # Get the list of actual filters in the network and sort them.
   filter_names = network.filters.keys()
   filter_names.sort()

   # Loop through them, printing.
   for filter in filter_names:
      
      # We only print actual filters.
      if len(network.filters[filter].equation) > 0:

         to_print = "%s %% " % filter
         output = network.filters[filter].output
         if not output:
            to_print += "NO OUTPUT"
         else:
            output_strings = [repr(x) for x in output]
            to_print += " ".join(output_strings)
         print(to_print)

def main():

   dataset_count = int(sys.stdin.readline())
   for dataset_loop in range(dataset_count):

      print("DATA SET #%d" % (dataset_loop + 1))

      # A new network.
      network = Struct()
      network.filters = {}

      # Get the number of elements and how many samples the streams have.
      network.size = int(sys.stdin.readline())
      network.sample_count = int(sys.stdin.readline())

      # Read in the elements ...
      for element_loop in range(network.size):
         element_repr = sys.stdin.readline().strip()
         addElementToNetwork(network, element_repr)

      # ... and simulate.
      simulate(network)

      # Lastly, print out the outputs.
      printOutputs(network)

if "__main__" == __name__:
   main()