def _GenerateRandomRasks(specs):
    """Generate a task that has random values.

  Args:
    specs: A list of spec from which the flag set is created.

  Returns:
    A set containing a task that has random values.
  """

    flag_set = []

    for spec in specs:
        numeric_flag_match = flags.Search(spec)
        if numeric_flag_match:
            # Numeric flags.
            start = int(numeric_flag_match.group('start'))
            end = int(numeric_flag_match.group('end'))

            value = random.randint(start - 1, end - 1)
            if value != start - 1:
                # If the value falls in the range, this flag is enabled.
                flag_set.append(Flag(spec, value))
        else:
            # Boolean flags.
            if random.randint(0, 1):
                flag_set.append(Flag(spec))

    return set([Task(FlagSet(flag_set))])
Ejemplo n.º 2
0
    def __init__(self):
        self.lineNumberCounter = LineNumberCounter()
        self.emptyLineCounter = EmptyLineCounter()
        self.re_emptyLine = re.compile(self.re_match_emptyLine)
        self.re_tailingeWhiteSpaces = re.compile(
            self.re_match_tailingWhiteSpaces)
        self.re_header = re.compile(self.re_match_header)
        self.re_codeblock = re.compile(self.re_match_codeblock)

        self.codeblockFlag = Flag()
Ejemplo n.º 3
0
def RandomMutate(specs, flag_set, mutation_rate):
    """Randomly mutate the content of a task.

  Args:
    specs: A list of spec from which the flag set is created.
    flag_set: The current flag set being mutated
    mutation_rate: What fraction of genes to mutate.

  Returns:
    A Genetic Task constructed by randomly mutating the input flag set.
  """

    results_flags = []

    for spec in specs:
        # Randomly choose whether this flag should be mutated.
        if random.randint(0, int(1 / mutation_rate)):
            continue

        # If the flag is not already in the flag set, it is added.
        if spec not in flag_set:
            results_flags.append(Flag(spec))
            continue

        # If the flag is already in the flag set, it is mutated.
        numeric_flag_match = flags.Search(spec)

        # The value of a numeric flag will be changed, and a boolean flag will be
        # dropped.
        if not numeric_flag_match:
            continue

        value = flag_set[spec].GetValue()

        # Randomly select a nearby value of the current value of the flag.
        rand_arr = [value]
        if value + 1 < int(numeric_flag_match.group('end')):
            rand_arr.append(value + 1)

        rand_arr.append(value - 1)
        value = random.sample(rand_arr, 1)[0]

        # If the value is smaller than the start of the spec, this flag will be
        # dropped.
        if value != int(numeric_flag_match.group('start')) - 1:
            results_flags.append(Flag(spec, value))

    return GATask(FlagSet(results_flags))
def _GenerateAllFlagsTasks(specs):
    """Generate a task that all the flags are enable.

  All the boolean flags in the specs will be enabled and all the numeric flag
  with have the largest legal value.

  Args:
    specs: A list of spec from which the flag set is created.

  Returns:
    A set containing a task that has all flags enabled.
  """

    flag_set = []

    for spec in specs:
        numeric_flag_match = flags.Search(spec)

        if numeric_flag_match:
            value = (int(numeric_flag_match.group('end')) - 1)
        else:
            value = -1
        flag_set.append(Flag(spec, value))

    return set([Task(FlagSet(flag_set))])
def GenerateRandomGATasks(specs, num_tasks, num_trials):
    """Generate a set of tasks for the Genetic Algorithm.

  Args:
    specs: A list of spec from which the flag set is created.
    num_tasks: number of tasks that should be generated.
    num_trials: the maximum number of tries should be attempted to generate the
      set of tasks.

  Returns:
    A set of randomly generated tasks.
  """

    tasks = set([])

    total_trials = 0
    while len(tasks) < num_tasks and total_trials < num_trials:
        new_flag = FlagSet(
            [Flag(spec) for spec in specs if random.randint(0, 1)])
        new_task = GATask(new_flag)

        if new_task in tasks:
            total_trials += 1
        else:
            tasks.add(new_task)
            total_trials = 0

    return tasks
  def testEqual(self):
    """Test the equal operator (==) of the flag.

    Two flags are equal if and only if their spec and value are equal.
    """

    tests = range(NUM_TESTS)

    # Two tasks having the same spec and value should be equivalent.
    for test in tests:
      assert Flag(str(test), test) == Flag(str(test), test)

    # Two tasks having different flag set should be different.
    for test in tests:
      flag = Flag(str(test), test)
      other_flag_sets = [other for other in tests if test != other]
      for other_test in other_flag_sets:
        assert flag != Flag(str(other_test), other_test)
Ejemplo n.º 7
0
 def post(self):
     task = {}
     task['task_name'] = request.form['task_name']
     task['task_description'] = request.form['task_description']
     task['points'] = request.form['points']
     task['flag'] = Flag().create_flag()
     task['task_id'] = mongo.db.tasks.find().count() + 1
     print(task)
     mongo.db.tasks.insert(task)
     return redirect(url_for('tasks'))
  def testInit(self):
    """The value generated should fall within start and end of the spec.

    If the value is not specified, the value generated should fall within start
    and end of the spec.
    """

    for _ in range(NUM_TESTS):
      start = random.randint(1, sys.maxint - 1)
      end = random.randint(start + 1, sys.maxint)

      spec = 'flag=[%s-%s]' % (start, end)

      test_flag = Flag(spec)

      value = test_flag.GetValue()

      # If the value is not specified when the flag is constructed, a random
      # value is chosen. This value should fall within start and end of the
      # spec.
      assert start <= value and value < end
  def testFormattedForUse(self):
    """Test the FormattedForUse method of the flag.

    The FormattedForUse replaces the string within the [] with the actual value.
    """

    for _ in range(NUM_TESTS):
      start = random.randint(1, sys.maxint - 1)
      end = random.randint(start + 1, sys.maxint)
      value = random.randint(start, end - 1)

      spec = 'flag=[%s-%s]' % (start, end)

      test_flag = Flag(spec, value)

      # For numeric flag, the FormattedForUse replaces the string within the []
      # with the actual value.
      test_value = test_flag.FormattedForUse()
      actual_value = 'flag=%s' % value

      assert test_value == actual_value

    for _ in range(NUM_TESTS):
      value = random.randint(1, sys.maxint - 1)

      test_flag = Flag('flag', value)

      # For boolean flag, the FormattedForUse returns the spec.
      test_value = test_flag.FormattedForUse()
      actual_value = 'flag'
      assert test_value == actual_value
  def testEqual(self):
    """Test the equal method of the Class FlagSet.

    Two FlagSet instances are equal if all their flags are equal.
    """

    flag_names = range(NUM_TESTS)

    # Two flag sets having the same flags should be equivalent.
    for flag_name in flag_names:
      spec = '%s' % flag_name

      assert FlagSet([Flag(spec)]) == FlagSet([Flag(spec)])

    # Two flag sets having different flags should be different.
    for flag_name in flag_names:
      spec = '%s' % flag_name
      flag_set = FlagSet([Flag(spec)])
      other_flag_sets = [other for other in flag_names if flag_name != other]
      for other_name in other_flag_sets:
        other_spec = '%s' % other_name
        assert flag_set != FlagSet([Flag(other_spec)])
  def testContain(self):
    """Test the contain method of the Class FlagSet.

    The flag set is also indexed by the specs. The flag set should return true
    for spec if it contains a flag containing spec.
    """

    true_tests = range(NUM_TESTS)
    false_tests = range(NUM_TESTS, NUM_TESTS * 2)

    specs = [str(spec) for spec in true_tests]

    flag_set = FlagSet([Flag(spec) for spec in specs])

    for spec in specs:
      assert spec in flag_set

    for spec in false_tests:
      assert spec not in flag_set
  def testGetItem(self):
    """Test the get item method of the Class FlagSet.

    The flag set is also indexed by the specs. The flag set should return the
    appropriate flag given the spec.
    """

    tests = range(NUM_TESTS)

    specs = [str(spec) for spec in tests]
    flag_array = [Flag(spec) for spec in specs]

    flag_set = FlagSet(flag_array)

    # Created a dictionary of spec and flag, the flag set should return the flag
    # the same as this dictionary.
    spec_flag = dict(zip(specs, flag_array))

    for spec in spec_flag:
      assert flag_set[spec] == spec_flag[spec]
  def testFormattedForUse(self):
    """Test the FormattedForUse method of the Class FlagSet.

    The output should be a sorted list of strings.
    """

    flag_names = range(NUM_TESTS)
    flag_names.reverse()
    flags = []
    result = []

    # Construct the flag set.
    for flag_name in flag_names:
      spec = '%s' % flag_name
      flags.append(Flag(spec))
      result.append(spec)

    flag_set = FlagSet(flags)

    # The results string should be sorted.
    assert sorted(result) == flag_set.FormattedForUse()
def ClimbNext(flags_dict, climb_spec):
    """Get the flags that are different from |flags_dict| by |climb_spec|.

  Given a set of flags, |flags_dict|, return a new set of flags that are
  adjacent along the flag spec |climb_spec|.

  An example flags_dict is {foo=[1-9]:foo=5, bar=[1-5]:bar=2} and climb_spec is
  bar=[1-5]. This method changes the flag that contains the spec bar=[1-5]. The
  results are its neighbors dictionaries, i.e., {foo=[1-9]:foo=5,
  bar=[1-5]:bar=1} and {foo=[1-9]:foo=5, bar=[1-5]:bar=3}.

  Args:
    flags_dict: The dictionary containing the original flags whose neighbors are
      to be explored.
    climb_spec: The spec in the flags_dict is to be changed. The spec is a
      definition in the little language, a string with escaped sequences of the
      form [<start>-<end>] where start and end is an positive integer for a
      fillable value. An example of a spec is "foo[0-9]".

  Returns:
    List of dictionaries of neighbor flags.
  """

    # This method searches for a pattern [start-end] in the spec. If the spec
    # contains this pattern, it is a numeric flag. Otherwise it is a boolean flag.
    # For example, -finline-limit=[1-1000] is a numeric flag and -falign-jumps is
    # a boolean flag.
    numeric_flag_match = flags.Search(climb_spec)

    # If the flags do not contain the spec.
    if climb_spec not in flags_dict:
        results = flags_dict.copy()

        if numeric_flag_match:
            # Numeric flags.
            results[climb_spec] = Flag(climb_spec,
                                       int(numeric_flag_match.group('start')))
        else:
            # Boolean flags.
            results[climb_spec] = Flag(climb_spec)

        return [results]

    # The flags contain the spec.
    if not numeric_flag_match:
        # Boolean flags.
        results = flags_dict.copy()

        # Turn off the flag. A flag is turned off if it is not presented in the
        # flags_dict.
        del results[climb_spec]
        return [results]

    # Numeric flags.
    flag = flags_dict[climb_spec]

    # The value of the flag having spec.
    value = flag.GetValue()
    results = []

    if value + 1 < int(numeric_flag_match.group('end')):
        # If the value is not the end value, explore the value that is 1 larger than
        # the current value.
        neighbor = flags_dict.copy()
        neighbor[climb_spec] = Flag(climb_spec, value + 1)
        results.append(neighbor)

    if value > int(numeric_flag_match.group('start')):
        # If the value is not the start value, explore the value that is 1 lesser
        # than the current value.
        neighbor = flags_dict.copy()
        neighbor[climb_spec] = Flag(climb_spec, value - 1)
        results.append(neighbor)
    else:
        # Delete the value, i.e., turn off the flag. A flag is turned off if it is
        # not presented in the flags_dict.
        neighbor = flags_dict.copy()
        del neighbor[climb_spec]
        results.append(neighbor)

    return results
Ejemplo n.º 15
0
class Scanner:

    re_match_emptyLine = "^\s*$"
    re_match_tailingWhiteSpaces = "[\t\f\v ]$"
    re_match_header = "^#+ "
    re_match_codeblock = "^```"

    def __init__(self):
        self.lineNumberCounter = LineNumberCounter()
        self.emptyLineCounter = EmptyLineCounter()
        self.re_emptyLine = re.compile(self.re_match_emptyLine)
        self.re_tailingeWhiteSpaces = re.compile(
            self.re_match_tailingWhiteSpaces)
        self.re_header = re.compile(self.re_match_header)
        self.re_codeblock = re.compile(self.re_match_codeblock)

        self.codeblockFlag = Flag()

    def scan(self, filename):
        with open(filename, "r") as txt:
            for line in txt:
                self.lineNumberCounter.next()
                self.analyseLine(line)
        print("Scanned " + str(self.lineNumberCounter.get()) + " lines")

    def isEmptyLine(self, line):
        return self.re_emptyLine.search(line)

    def hasTailingWhiteSpaces(self, line):
        return self.re_tailingeWhiteSpaces.search(line)

    def isHeader(self, line):
        return self.re_header.search(line)

    def isCodeblock(self, line):
        return self.re_codeblock.search(line)

    def analyseLine(self, line):
        flagNonEmptyLine = False
        if self.isEmptyLine(line):
            self.emptyLineCounter.next()
        else:
            flagNonEmptyLine = True

        if self.hasTailingWhiteSpaces(line):
            print(str(self.lineNumberCounter) + "has tailing whitespaces!")

        if self.isCodeblock(line):
            self.codeblockFlag.toggle()

        if self.isHeader(line) and self.codeblockFlag.isNotSet():
            warningstr = ""
            if self.emptyLineCounter.get() < 2:
                if self.emptyLineCounter.get() < 1:
                    warningstr = "no"
                else:
                    warningstr = "only one"
                warningstr = warningstr + " blank line"
            else:
                if self.emptyLineCounter.get() > 2:
                    warningstr = "more than two blank lines"
            if warningstr != "":
                warningstr = "has " + warningstr + "before header, should be two!"
                print(str(self.lineNumberCounter) + warningstr)

        if flagNonEmptyLine:
            self.emptyLineCounter.reset()
Ejemplo n.º 16
0
# states.py
from flags import Flag
import time

# Set up the flags
flag = Flag()


class State(object):
    """
    Generic state class that can run code and move into the next state.
    """
    def run(self):
        raise NotImplementedError

    def __str__(self):
        return self.state_string

    def event(self, event):
        pass


class Idle(State):
    """
    Idle State

    - Robot will idle.
    - If the person flag is set then move to the WatchingGreeting state.
    - Otherwise remain in this state.
    """
    def run(self):