def execute_input(input_array):
    input_parser = InputParser(input_array)
    board, statement = input_parser.get_board(), input_parser.get_statement()

    if statement == "occupied?":
        point = input_parser.get_point()
        return board.occupied(point)

    elif statement == "occupies?":
        stone_type, point = input_parser.get_stone_and_point()
        return board.occupies(stone_type, point)

    elif statement == "reachable?":
        point, stone_type = input_parser.get_point_and_stone()
        return board.reachable(point, stone_type)

    elif statement == "place":
        stone_type, point = input_parser.get_stone_and_point()
        return format_board_if_valid(board.place_stone(stone_type, point))

    elif statement == "remove":
        stone_type, point = input_parser.get_stone_and_point()
        return format_board_if_valid(board.remove_stone(stone_type, point))

    elif statement == "get-points":
        stone_type = input_parser.get_stone()
        return format_points(board.get_points(stone_type))
示例#2
0
def main():

    f = Figlet(font='slant')
    print(f.renderText('        '))
    print(f.renderText(' openAA:'))
    print("         'h' for help, 'q' to quit  \n")
    print(f.renderText('         '))
    openAA = OpenAA()
    inputparser = InputParser(openAA)

    while True:
        cmd = input('$$$: ')

        if cmd == "q":
            break
        elif cmd == "h":
            print("\n -List of commands: -----------\n")
            print("1. load_data   (load datasets)")
            print("2. load_json   (load settings from json file)")
            print("3. setup_model (set GANN and training parameters)")
            print("4. visualize   (set visualization modes)")
            print("5. run_model   (build the GANN and train it)")
            print("6. view_model  (view GANN and training paramters)")
            print(
                "7. predict     (run some cases through the trained GANN and look at the predictions)"
            )
            print(
                "\n For now you will have to read through the code to see how these are used.\n Might add DOCS and better help-instructions here later"
            )
        elif cmd == "":
            continue
        else:
            inputparser.evaluator(cmd)
示例#3
0
def fit_linear(file_path):
    input_parser = InputParser(file_path=file_path)
    file_input = input_parser.start()
    linear_calc = FitLinearCalculator(file_input)
    linear_calc.calculate()
    linear_calc.print_output()
    linear_calc.plot(save_plot_name=config.LINEAR_PLOT_FILE_NAME)
示例#4
0
 def test_relative_time(self):  # test开头的方法会被自动调用
     test_cases = [
         # N minutes
         ("0m abc", (time.mktime(time.localtime()) + 60 * 0, "abc")),
         ("5m 中文", (time.mktime(time.localtime()) + 60 * 5, "中文")),
         ("5 onlynum中文", (time.mktime(time.localtime()) + 60 * 5,
                          "onlynum中文")),
         (
             "5",  # 匿名事件
             (time.mktime(time.localtime()) + 60 * 5, "")),
         (
             "abc 99m",  # 顺序
             (time.mktime(time.localtime()) + 60 * 99, "abc")),
         ("中文 空格 99m", (time.mktime(time.localtime()) + 60 * 99, "中文 空格")),
         # N days
         ("0d abc space", (time.mktime(time.localtime()) + 24 * 60 * 60 * 0,
                           "abc space")),
         ("9d abc", (time.mktime(time.localtime()) + 24 * 60 * 60 * 9,
                     "abc")),
         ("100d abc", (time.mktime(time.localtime()) + 24 * 60 * 60 * 100,
                       "abc")),
         ("100day abc", (time.mktime(time.localtime()) + 24 * 60 * 60 * 100,
                         "abc")),
         ("100days abc",
          (time.mktime(time.localtime()) + 24 * 60 * 60 * 100, "abc")),
         ("abc 100day", (time.mktime(time.localtime()) + 24 * 60 * 60 * 100,
                         "abc"))
     ]
     parser = InputParser()
     for test_case in test_cases:
         (due_timestamp, thing) = parser.parse_textline(test_case[0])
         self.assertEqual(test_case[1], (due_timestamp, thing))
示例#5
0
 def add_flow_chart(self, path, x, y):
     y += self.tm
     flow_chart = FlowChart("RGB", (x, y), color="white")
     with open(path) as file:
         input_parser = InputParser(file)
         input_parser.instruct(flow_chart)
     self.im.paste(flow_chart.im, (0, self.tm))
示例#6
0
def search_best_parameter(file_path):
    input_parser = InputParser(file_path=file_path, contains_ab_values=True)
    file_input = input_parser.start()
    linear_calc = FitLinearCalculator(file_input)
    linear_calc.calculate(chose_ab=True)
    linear_calc.print_output()
    linear_calc.plot(save_plot_name=config.LINEAR_PLOT_FILE_NAME)
    linear_calc.create_and_plot_a_chosing_plot(
        save_plot_name=config.A_PLOT_FILE_NAME)
示例#7
0
 def __init__(self):
     self.musicdata = []
     self.ydl_options = {
         'format': 'bestaudio',
         'postprocessors': [{
             'key': 'FFmpegExtractAudio',
         }]
     }
     self.dataparser = InputParser()
示例#8
0
    def test_parse_tracks_from_video(self):
        ip = InputParser()
        url = 'https://www.youtube.com/watch?v=ldwg3eXiISM'
        vdata = ip.get_video_info(url)
        tracks = ip.get_track_list(vdata)
        self.assertEqual(False, tracks is None)

        parsed = ip.parse_tracks_from_video(tracks)
        with open('test_data\\parsed_tracks.json', 'r') as f:
            expected = json.load(f)

        self.assertListEqual(expected, parsed)
示例#9
0
def main():
    flow_chart = FlowChart("RGB", (2480, 3508), color="white")
    try:
        fp = sys.stdin
        if "-f" in sys.argv:
            file_path = sys.argv[sys.argv.index("-f")+1]
            fp = open(file_path)
        input_parser = InputParser(fp)
        input_parser.instruct(flow_chart)
    finally:
        fp.close()
    return flow_chart
示例#10
0
 def test_parse_user_tracks(self):
     tracklist = [
         {
             'name': 'Track 1',
             'start': '00:00'
         },
         {
             'name': 'Track 2',
             'start': '01:00'
         },
         {
             'name': 'Track 3',
             'start': '05:30'
         },
     ]
     parsed = InputParser().parse_user_tracks(tracklist)
     expected = [{
         'name': 'Track 1',
         'start': '00:00',
         'duration': '0:01:00'
     }, {
         'name': 'Track 2',
         'start': '01:00',
         'duration': '0:04:30'
     }, {
         'name': 'Track 3',
         'start': '05:30',
         'duration': None
     }]
     self.assertListEqual(expected, parsed)
示例#11
0
    def analyze(field, parser: InputParser):
        available = {1, 2, 3, 4, 5, 6, 7, 8, 9}
        scores = dict()
        for i, y in enumerate(field):
            row = parser.row(i)
            for x in y:
                if x == 0:
                    col = parser.col(x, y.index(x))
                    scores[i, x] = (row | col)
                elif x in available:
                    available.remove(x)

        # ! ----------------------------------------

        for i, x in scores:
            scores[i, x] = available.difference(scores[i, x])

        return scores
示例#12
0
    def test_parse_input(self):
        with open('test_data/input.json') as f:
            input_data = json.load(f)

        with open('test_data/output.json', 'r') as f:
            expected = json.load(f)

        parsed = InputParser().parse_input([input_data])[0]
        self.assertDictEqual(expected, parsed)
示例#13
0
    def analyze(field, parser: InputParser, row_section, col_section):
        available = {1, 2, 3, 4, 5, 6, 7, 8, 9}
        scores = dict()
        for i, y in enumerate(field):
            row = parser.row(row_section + i)
            for j, x in enumerate(y):
                if x == 0:
                    col = parser.col(col_section + j)
                    scores[i, j] = (row | col)
                elif x in available:
                    available.remove(x)

        # ! ----------------------------------------

        for i, x in scores:
            scores[i, x] = available.difference(scores[i, x])

        return scores
示例#14
0
def start_process(input_file, output_file):
    handler = FileHandler(input_file, output_file)

    info = handler.read_file()
    error_msgs = info['error_msgs']

    if len(info['ref_words']) > 0:
        parser = InputParser(DEFAULT_ANSWER)

        result = parser.process_info(info['ref_words'], info['price_msgs'])
        if result:
            error_msgs.extend(result)

        answers = parser.answer_questions(info['questions'])

        handler.write_file(answers, error_msgs)

    else:
        handler.error_output("No correct inputs found.")
示例#15
0
def parse_input(options):
    """ validate and parse input high-level description file"""
    from input_parser import InputParser
    if options.createmud:
        log.info("Create MUD file(s) from flow rules in path: %s" %
                 (options.createmud[0]))
        try:
            InputParser().create_mud_files(options.createmud[0])
        except BaseException, e:
            log.error('%s' % e.message)
    def __init__(self, config=None):
        """ Sets up the Aribtary Solar System

        Args:
            config - config file which contains information about planets
        """
        self.planets = {}
        if config:
            ip = InputParser(config)
            try:
                planets = ip.get_objects()
                for planet in planets:
                    logging.info('planet info: ', planet)
                    p = Planet(planet['name'], planet['theta'], planet['radius'],
                            planet['period'])
                    self.planets[planet['name']] = p
            except IOError as e:
                raise AlignmentInputError("Failed to parse config file")
        else:
            logging.warning('No configuration for AribtarySolar System')
示例#17
0
def main():
    # YOUR MAIN CODE GOES HERE
    st_dict = {}
    exist_node = {}
    # sample code to read from stdin.
    # make sure to remove all spurious print statements as required
    # by the assignment
    while True:
        line = sys.stdin.readline()
        if line.rstrip().strip() == '':
            break
        else:
            #print('read a line:', line)
            # parse the input line
            i_p = InputParser(line, st_dict, exist_node)
            i_p.parseInput()

    #print('Finished reading input')

    # return exit code 0 on successful termination
    sys.exit(0)
示例#18
0
    def test_absolute_time_without_date(self):
        year = time.localtime().tm_year
        month = time.localtime().tm_mon
        day = time.localtime().tm_mday
        today_timestamp = time.mktime(
            time.strptime(str(year) + str(month) + str(day), "%Y%m%d"))
        tomorrow_timestamp = time.mktime(
            time.strptime(str(year) + str(month) + str(day + 1), "%Y%m%d"))

        # 如果现在过了2点,那么指的是第二天的2点,否则指的是今天的2点
        if time.localtime().tm_hour > 2 or (time.localtime().tm_hour == 2 and
                                            time.localtime().tm_minute > 0):
            timestamp_for_2 = tomorrow_timestamp
        else:
            timestamp_for_2 = today_timestamp
        # 如果现在过了23点,那么指的是第二天的23点,否则指的是今天的23点
        if time.localtime().tm_hour > 23 or (time.localtime().tm_hour == 23 and
                                             time.localtime().tm_minute > 0):
            timestamp_for_23 = tomorrow_timestamp
        else:
            timestamp_for_23 = today_timestamp

        test_cases = [
            ("23:00 中文", (timestamp_for_23 + 23 * 60 * 60, "中文")),
            ("23am 中文", (timestamp_for_23 + 23 * 60 * 60, "中文")),
            ("11pm 中文", (timestamp_for_23 + 23 * 60 * 60, "中文")),
            ("2am 中文", (timestamp_for_2 + 2 * 60 * 60, "中文"))
            # failed now
            #(
            #    "中文abc 2:00 中文",
            #    (timestamp_for_2+2*60*60, "中文abc 中文")
            #)
        ]
        parser = InputParser()
        for test_case in test_cases:
            (due_timestamp, thing) = parser.parse_textline(test_case[0])
            #tmp = parser.parse_textline(test_case[0])
            #print tmp
            self.assertEqual(test_case[1], (due_timestamp, thing))
示例#19
0
 def test_absolute_time_with_date(self):
     year = time.localtime().tm_year
     month = time.localtime().tm_mon
     day = time.localtime().tm_mday
     today_timestamp = time.mktime(
         time.strptime(str(year) + str(month) + str(day), "%Y%m%d"))
     test_cases = [
         (
             "2014-11-1 abc1",  # 默认是早上8点提醒
             (1414800000.0, "abc1")),
         ("11-1 abc", (1414800000.0, "abc")),
         ("abc 11-1", (1414800000.0, "abc")),
         ("2014-11-1 16:30 中文", (1414830600.0, "中文")),
         ("11-1 16:30 中文", (1414830600.0, "中文")),
         ("中文 11-1 11pm", (1414854000.0, "中文")),
         ("中文 11-1 23am", (1414854000.0, "中文")),
         ("中文 11-1 2am", (1414778400.0, "中文"))
     ]
     parser = InputParser()
     for test_case in test_cases:
         (due_timestamp, thing) = parser.parse_textline(test_case[0])
         self.assertEqual(test_case[1], (due_timestamp, thing))
示例#20
0
    def test04(self):
        '''
        购买的“买二送一”商品未达到赠送条件
        '''
        receipt = InputParser.parse(r'input\input04.json')
        rp = ReceiptPrinter(receipt)
        act = rp.print_receipt()
        dst = '''***<没钱赚商店>购物清单***
名称:羽毛球,数量:2个,单价:1.00(元),小计:2.00(元)
----------------------
总计:2.00(元)
**********************
'''
        self.assertEquals(act, dst)
示例#21
0
    def test03(self):
        '''
        仅仅单种不参加活动的商品
        '''
        receipt = InputParser.parse(r'input\input03.json')
        rp = ReceiptPrinter(receipt)
        act = rp.print_receipt()
        dst = '''***<没钱赚商店>购物清单***
名称:手表,数量:2块,单价:30000000.00(元),小计:60000000.00(元)
----------------------
总计:60000000.00(元)
**********************
'''
        self.assertEquals(act, dst)
示例#22
0
    def __init__(self, parent=None):
        super(CaminoProgrammer, self).__init__(parent)
        self.setupUi(self)
        self.actionExit.triggered.connect(QtGui.qApp.quit)
        self.actionConnect.triggered.connect(self.connectCamino)
        self.actionDisconnect.triggered.connect(self.disconnectCamino)
        self.pushButtonConfigureDevice.clicked.connect(self.programCamino)
        self.pushButtonReadDevice.clicked.connect(self.readCamino)

        self.inputParser = InputParser(self)

        # Instance of the settings device
        self.settings = Settings(self)
        self.actionSettings.triggered.connect(self.settings.show)
示例#23
0
    def test02(self):
        receipt = InputParser.parse(r'input\input02.json')
        rp = ReceiptPrinter(receipt)
        act = rp.print_receipt()
        dst = '''***<没钱赚商店>购物清单***
名称:羽毛球,数量:6个,单价:1.00(元),小计:4.00(元)
----------------------
买二赠一商品:
名称:羽毛球,数量:2个
----------------------
总计:4.00(元)
节省:2.00(元)
**********************
'''
        self.assertEquals(act, dst)
示例#24
0
    def encrypt_sentence(self, sentence):
        '''
        encrypt the whole sentence
        '''
        words = InputParser().parse(sentence)

        if self.log_steps:
            print(f'Phrase: {" ".join([word for word in words])}')

        encrypted_words = self.encrypt_words(words)

        if self.log_steps:
            print(f"Encrypted pass 1: {' '.join(str(w) for w in encrypted_words)}")

        return self.distil_sentence(encrypted_words, 2)
示例#25
0
    def test01(self):
        receipt = InputParser.parse()
        rp = ReceiptPrinter(receipt)
        act = rp.print_receipt()
        dst = '''***<没钱赚商店>购物清单***
名称:可口可乐,数量:3瓶,单价:3.00(元),小计:6.00(元)
名称:苹果,数量:2斤,单价:5.50(元),小计:10.45(元),节省0.55(元)
名称:羽毛球,数量:6个,单价:1.00(元),小计:4.00(元)
----------------------
买二赠一商品:
名称:可口可乐,数量:1瓶
名称:羽毛球,数量:2个
----------------------
总计:20.45(元)
节省:5.55(元)
**********************
'''
        self.assertEquals(act, dst)
示例#26
0
    def test05(self):
        '''
        购买的“买二送一”商品达到赠送条件后,又多买了1个
        '''
        receipt = InputParser.parse(r'input\input05.json')
        rp = ReceiptPrinter(receipt)
        act = rp.print_receipt()
        dst = '''***<没钱赚商店>购物清单***
名称:羽毛球,数量:4个,单价:1.00(元),小计:3.00(元)
----------------------
买二赠一商品:
名称:羽毛球,数量:1个
----------------------
总计:3.00(元)
节省:1.00(元)
**********************
'''
        self.assertEquals(act, dst)
示例#27
0
    def test_parse_video(self):
        self.maxDiff = None
        video = {
            "url":
            "https://www.youtube.com/watch?v=ldwg3eXiISM",
            "tracklist": [{
                "name": "ALEX - Insert Soul",
                "start": "00:00"
            }, {
                "name": "Tokyo Rose - The Pact (feat. WVLFPAKT)",
                "start": "01:47"
            }, {
                "name": "ALEX - Ritual",
                "start": "05:16"
            }]
        }

        parsed = InputParser().parse_video(video)
        expected = {
            'url':
            'https://www.youtube.com/watch?v=ldwg3eXiISM',
            'filename':
            'ALEX & Tokyo Rose - AKUMA [Full Album] 2017-ldwg3eXiISM',
            'output_dir':
            'ALEX & Tokyo Rose - AKUMA [Full Album] 2017',
            'tracklist': [{
                'name': 'ALEX - Insert Soul',
                'start': '00:00',
                'duration': '0:01:47'
            }, {
                'name': 'Tokyo Rose - The Pact (feat. WVLFPAKT)',
                'start': '01:47',
                'duration': '0:03:29'
            }, {
                'name': 'ALEX - Ritual',
                'start': '05:16',
                'duration': None
            }]
        }
        self.assertDictEqual(expected, parsed)
class RPNCalculator:
    def __init__(self):
        self.parser = InputParser()
        self.processor = RPNProcessor()

    def to_rpn(self, expression):
        try:
            return self.parser.to_rpn(expression)
        except ValueError:
            raise

    def calculate(self, expression, value=0):
        try:
            rpn = self.to_rpn(expression)
            return self.processor.evaluate_rpn(rpn, value)
        except ValueError:
            print("Your expression is invalid")
        except ZeroDivisionError:
            print("Can't divide by zero.")

    def evaluate(self, expression, value):
        return self.calculate(expression, value)
示例#29
0
class Main(Wox):
    """Class that works with the Wox API."""

    parser = InputParser()
    generator = ResultGenerator()
    manager = VolumeManager()

    def query(self, parameters):
        """
        Returns list of results based on provided parameters.

        Parameters are provided as string stripped from plugin keyword, if any.
        For instance, input of "v 50 whatever" (assuming plugin keyword is v)
        will set parameters to "50 whatever".
        """
        if not self.manager.init_success:
            return [
                self.generator.generate_error(),
            ]

        value = self.parser.parse(parameters)
        if value is None:
            return []
        result = self.generator.generate_valid_result(value)
        return [
            result,
        ]

    def perform_action(self, value):
        """Method that reroutes user-defined value to VolumeManager."""
        self.manager.perform_action(value)

    def open_url(self, url):
        """Opens provided URL as a new tab in default browser."""
        # new=2 is a way of saying "new tab please, um, if that's possible"
        webbrowser.open(url, new=2)
示例#30
0
 def testParse01(self):
     receipt = InputParser.parse()
     print "合并输入后打印:"
     print receipt
示例#31
0
# coding: GBK
'''
Created on 2016Äê3ÔÂ8ÈÕ

@author: Administrator
'''
import cash_register
from input_parser import InputParser
from receipt_printer import ReceiptPrinter


if __name__ == '__main__':
    receipt = InputParser.parse()
    rp = ReceiptPrinter(receipt)
    rp.print_receipt()
示例#32
0
def parse_input(options):
    """ validate and parse input high-level description file"""
    from input_parser import InputParser
    if options.createmud:
        log.info("Create MUD file(s) from flow rules in path: %s" %
                 (options.createmud[0]))
        try:
            InputParser().create_mud_files(options.createmud[0])
        except BaseException, e:
            log.error('%s' % e.message)

    if options.checkmud:
        log.info("Check MUD file consistency using metagraphs")
        try:
            InputParser().check_mud_consistency(options.checkmud[0])
        except BaseException, e:
            log.error('%s' % e.message)

    if options.bpcompare:
        log.info("Check best practice compliance of MUD policy: %s" %
                 (options.bpcompare[0]))
        try:
            InputParser().check_bp_compliance(options.bpcompare[0])
        except BaseException, e:
            log.error('%s' % e.message)


# !! The main function are only here for debug. The real compiler don't need this`!!
if __name__ == '__main__':
    import sys
示例#33
0
available_options = ['-swn', '-qe', '-uid', '-cap', '-bow', '-r', '-rt', '-emoji']

options = available_options 

if len(sys.argv) > 1:
  options = sys.argv[1:]

if '-t' in options:
  filename = '../res/one_tenth_semeval_twitter_data.txt'
else:
  filename = '../res/semeval_twitter_data.txt'

if '-a' in options:
  options = available_options

parser = InputParser(filename)
tweet_list = parser.parse()

#All preprocessing necessary
print('Started preprocessing')

analyzer = Analyzer(constants.ESCAPE_SEQUENCE)
uFeatureParser = UnigramSWNFeatureParser()

for data in tweet_list:
  tokens = analyzer.analyze(data.tweet_string)

  for term in tokens:
    term = term.encode('utf_8').decode('ascii', 'ignore')
      
  data.set_tokens(tokens)
示例#34
0
文件: client.py 项目: lsc36/cn-14fall
def read_data():
    input_file = open(sys.argv[1])
    parser = InputParser()
    data = parser.parse_all(input_file.read())
    input_file.close()
    return data