Example #1
0
    def __init__(self):
        with open('config.json', 'r') as f:
            config = json.load(f)
        with open('page_templates/index.html', 'r') as f:
            template = BeautifulSoup(f.read(), 'html.parser')

        self.host = config['auth_info']['host']
        self.project = config['auth_info']['project']
        user_name = config['auth_info']['user_name']
        secret_key = config['auth_info']['secret_key']
        url = self.host + '/projects/' + self.project + '/cards/'
        self.template = template
        self.key_status = config['query_info']['key_status']
        self.status = config['query_info']['status']
        self.query_cards_in = config['query_info']['query_cards_in']
        self.calculate_days_for = config['query_info']['calculate_days_for']
        self.calculate_steps_for = config['query_info']['calculate_steps_for']
        self.time_zone = config['query_info']['time_zone']
        self.oldest_date = datetime.now()
        self.progress = 0

        self.requester = Requester(self.host, self.project, user_name,
                                   secret_key)
        self.formatter = Formatter(self.template, self.status, self.key_status,
                                   url)
Example #2
0
    def test_subscript_operations(self):
        '''
        Test subscripting operations are formatted properly
        :return:
        '''
        format = Formatter()._format_node

        containers = tuple(map(Variable, ('x', 'y', 'z')))

        indexes = map(lambda x: Index(LiteralNumber(x)), range(0, 20))
        for container, index in product(containers, indexes):
            self.assertEqual(format(SubscriptOperation(container, index)), container.id+enclose(repr(index.value.n),'[]'))

        container = Variable('x')
        for start, stop, step in product(map(LiteralNumber, range(0, 3)), repeat=3):
            self.assertEqual(
                format(SubscriptOperation(container, Slice(start, stop, step))),
                container.id+enclose(slice_to_str(slice(start.n, stop.n, step.n)), '[]'))

        container = Variable('x')
        for a, b in product(map(lambda x: Index(LiteralNumber(x)), range(0, 3)), repeat=2):
            indexes = (a, b)
            self.assertEqual(
                format(SubscriptOperation(container, ExtendedSlice(*indexes))),
                container.id+enclose(', '.join(map(lambda index: repr(index.value.n), indexes)), '[]'))
Example #3
0
 def test_compare_operations(self):
     '''
     Test compare operations are formatted correctly
     '''
     format = Formatter()._format_node
     operands = tuple(map(Variable, ('x', 'y', 'z')))
     for left, operator, right in product(operands, compare_operators, operands):
         self.assertEqual(format(CompareOperation(left, operator, right)), ' '.join([left.id, operator.symbol, right.id]))
Example #4
0
 def test_unary_operations(self):
     '''
     Test unary operations are formatted correctly
     '''
     format = Formatter()._format_node
     operands = tuple(map(Variable, ('x', 'y', 'z')))
     for operator, operand in product(unary_operators, operands):
         self.assertEqual(format(UnaryOperation(operator, operand)), operator.symbol + operand.id)
Example #5
0
    def test_operators(self):
        '''
        Test operators are formatted correctly
        '''
        format = Formatter()._format_node

        for operator in operators:
            self.assertEqual(format(operator), operator.symbol)
Example #6
0
    def test_variables(self):
        '''
        Test variables are formatted correctly
        :return:
        '''
        format = Formatter()._format_node

        self.assertEqual(format(Variable('x')), 'x')
        self.assertEqual(format(Variable('y')), 'y')
        self.assertEqual(format(Variable('z')), 'z')
Example #7
0
 def test_call_operations(self):
     '''
     Test calling operations are formatted properly
     '''
     format = Formatter()._format_node
     containers = tuple(map(Variable, ('x', 'y', 'z')))
     for container, args in product(containers, product(map(LiteralNumber, range(0, 3)),repeat=3)):
         self.assertEqual(
             format(CallOperation(container, *args)),
             container.id + enclose(', '.join(map(lambda arg: repr(arg.n), args)),'()'))
Example #8
0
    def test_getattr_operations(self):
        '''
        Test get attribute operations are formatted properly
        '''
        format = Formatter()._format_node

        attrs = tuple(map(chr, range(ord('a'), ord('z')+1)))
        containers = tuple(map(Variable, ('x', 'y', 'z')))

        for container, attr in product(containers, attrs):
            self.assertEqual(format(AttributeOperation(container, attr)), container.id+'.'+attr)
Example #9
0
 def test_literals(self):
     '''
     Test literals are formatted correctly
     :return:
     '''
     format = Formatter()._format_node
     self.assertEqual(format(LiteralNumber(10)), repr(10))
     self.assertEqual(format(LiteralEllipsis()), '...')
     self.assertEqual(format(LiteralStr('Hello World')), 'Hello World')
     self.assertEqual(format(LiteralBytes(b'Hello World')), str(b'Hello World'))
     self.assertEqual(format(LiteralBool(True)), str(True))
     self.assertEqual(format(LiteralBool(False)), str(False))
     self.assertEqual(format(LiteralNone()), str(None))
    def __init__(self, parent=None):
        """ setup the application """
        QtGui.QWidget.__init__(self, parent)

        # parser setup
        self.line_parser = ParserLine(LanguageMathematica())
        self.text_parser = ParserText(LanguageMathematica())
        self.formatter = Formatter(LanguagePython(int2float=True))

        # Quit Button
        quitButton = QtGui.QPushButton("Close", self)
        self.connect(quitButton, QtCore.SIGNAL("clicked()"), QtGui.qApp,
                     QtCore.SLOT("quit()"))
        convertButton = QtGui.QPushButton("Convert", self)
        self.connect(convertButton, QtCore.SIGNAL("clicked()"), self.onChanged)

        # Widgets
        self.matLabel = QtGui.QLabel("Mathematica Code:")
        self.matEdit = QtGui.QTextEdit()
        self.pyLabel = QtGui.QLabel("Python Code:")
        self.pyEdit = QtGui.QTextEdit()
        self.connect(self.matEdit, QtCore.SIGNAL("textChanged()"),
                     self.onChanged)
        self.multilineCb = QtGui.QCheckBox("Support Multiple Lines", self)
        self.connect(
            self.multilineCb,
            QtCore.SIGNAL("stateChanged(int)"),
            lambda i: self.onChanged(),
        )

        # Bottom Row
        bottomRow = QtGui.QHBoxLayout()
        bottomRow.addWidget(self.multilineCb)
        bottomRow.addStretch(1)
        bottomRow.addWidget(convertButton)
        bottomRow.addWidget(quitButton)

        # Complete Layout
        vbox = QtGui.QVBoxLayout()
        vbox.addWidget(self.matLabel)
        vbox.addWidget(self.matEdit)
        vbox.addWidget(self.pyLabel)
        vbox.addWidget(self.pyEdit)
        vbox.addLayout(bottomRow)

        # set layout
        self.setLayout(vbox)
        self.setWindowTitle("Mathematica to Python Converter")
        self.resize(500, 350)
Example #11
0
    def __init__(self):
        """ setup the application """
        super().__init__()

        # parser setup
        self.line_parser = ParserLine(LanguageMathematica())
        self.text_parser = ParserText(LanguageMathematica())
        self.formatter = Formatter(LanguagePython(int2float=True))

        # Quit Button
        quitButton = QtWidgets.QPushButton("Close", self)
        quitButton.clicked.connect(QtWidgets.qApp.quit)
        convertButton = QtWidgets.QPushButton("Convert", self)
        convertButton.clicked.connect(self.onChanged)

        # Widgets
        self.matLabel = QtWidgets.QLabel("Mathematica Code:")
        self.matEdit = QtWidgets.QTextEdit()
        self.matEdit.textChanged.connect(self.onChanged)
        self.pyLabel = QtWidgets.QLabel("Python Code:")
        self.pyEdit = QtWidgets.QTextEdit()
        self.pyEdit.setReadOnly(True)

        self.multilineCb = QtWidgets.QCheckBox("Support Multiple Lines", self)
        self.multilineCb.stateChanged.connect(self.onChanged)

        # Bottom Row
        bottomRow = QtWidgets.QHBoxLayout()
        bottomRow.addWidget(self.multilineCb)
        bottomRow.addStretch(1)
        bottomRow.addWidget(convertButton)
        bottomRow.addWidget(quitButton)

        # Complete Layout
        vbox = QtWidgets.QVBoxLayout()
        vbox.addWidget(self.matLabel)
        vbox.addWidget(self.matEdit)
        vbox.addWidget(self.pyLabel)
        vbox.addWidget(self.pyEdit)
        vbox.addLayout(bottomRow)

        # set layout
        self.setLayout(vbox)
        self.setWindowTitle("Mathematica to Python Converter")
        self.resize(500, 350)
Example #12
0
    pretty.pprint("")
    pretty.pprint(". . . level")
    for key in data.keys():
        pretty.pprint("")
        pretty.pprint("item")
        key_p = "key: " + key + "end"
        pretty.pprint(key_p)
        val_p = "val: " + str(data[key]) + "endval"
        pretty.pprint(val_p)
        r_dict(i + 12, data[key])


with open('user_variables.json') as data_file:
    data = json.load(data_file)

    pretty = Formatter()
    print(pretty(data))

#    r_dict(9,data)
#    for val in data.values():
#        print(val)

#    pprint(data.items())
#    print(data.items())
#    print(type(data))
#    print(dir(data))

#    for thing in data.items():
#        print(type(thing))
#        print('keys')
#        for key in thing:
 def setUp(self):
     self.parser = ParserLine(LanguagePython(int2float=False))
     self.formatter = Formatter(LanguagePython())
Example #14
0
class GetMingle:
    def __init__(self):
        with open('config.json', 'r') as f:
            config = json.load(f)
        with open('page_templates/index.html', 'r') as f:
            template = BeautifulSoup(f.read(), 'html.parser')

        self.host = config['auth_info']['host']
        self.project = config['auth_info']['project']
        user_name = config['auth_info']['user_name']
        secret_key = config['auth_info']['secret_key']
        url = self.host + '/projects/' + self.project + '/cards/'
        self.template = template
        self.key_status = config['query_info']['key_status']
        self.status = config['query_info']['status']
        self.query_cards_in = config['query_info']['query_cards_in']
        self.calculate_days_for = config['query_info']['calculate_days_for']
        self.calculate_steps_for = config['query_info']['calculate_steps_for']
        self.time_zone = config['query_info']['time_zone']
        self.oldest_date = datetime.now()
        self.progress = 0

        self.requester = Requester(self.host, self.project, user_name,
                                   secret_key)
        self.formatter = Formatter(self.template, self.status, self.key_status,
                                   url)

    def get_iteration(self, name):
        mql = f"SELECT Number,Name,'Start date','End Date' where Name = '{name}'"
        xml = self.requester.get_cards_by_mql(mql)
        if xml == b'Incorrect username or password.\n':
            raise RuntimeError('Incorrect username or password.')
        soup = BeautifulSoup(xml, 'xml')
        result = soup.find('result')
        if not result:
            raise RuntimeError('No iteration found by this name.')
        start_date = datetime.strptime(
            result.find('start_date').string, '%Y-%m-%d')
        end_date = datetime.strptime(
            result.find('end_date').string, '%Y-%m-%d')

        return Iteration(name, start_date, end_date, self.calculate_days_for,
                         self.calculate_steps_for)

    def get_cards_by_iteration(self, iteration: Iteration):
        self.progress = 1
        query_status = '(' + str(self.query_cards_in)[1:-1] + ')'
        xml = self.requester.get_cards_by_mql(
            "SELECT Number,Name,'Estimated Points','Created On' " +
            "where Status in " + query_status + " and Iteration = '" +
            iteration.title + "'")
        return self.get_cards_from_xml(xml)

    def get_cards_by_properties(self, properties):
        mql = "SELECT Number,Name,'Estimated Points','Created On' where "
        xml = self.requester.get_cards_by_mql(mql + " and ".join(properties))
        return self.get_cards_from_xml(xml)

    def get_cards_from_xml(self, xml):
        if xml == b'Incorrect username or password.\n':
            raise RuntimeError('Incorrect username or password.')
        soup = BeautifulSoup(xml, 'xml')
        cards = []
        for result in soup.find_all('result'):
            number = result.find('number').string
            title = result.find('name').string
            points = result.find('estimated_points').string
            this_date = datetime.strptime(
                result.find('created_on').string, '%Y-%m-%d')
            self.oldest_date = this_date if this_date < self.oldest_date else self.oldest_date
            cards.append(
                Card(number, title, points, self.status, self.key_status,
                     self.requester, self.time_zone))
        return cards

    def get_info_of_iteration_and_cards(self, iteration, cards):
        not_finished_cards = {card.number: card for card in cards}
        not_finished_iteration = not not iteration
        next_page = None
        start_time = datetime.now()
        while not_finished_cards or not_finished_iteration:
            xml = self.requester.get_events(next_page)
            if xml == b'Incorrect username or password.\n':
                raise RuntimeError('Incorrect username or password.')
            soup = BeautifulSoup(xml, 'xml')
            next_page = soup.find('link', rel='next')['href']
            entries = soup.find_all('entry')

            for entry in entries:
                if not (not_finished_cards or not_finished_iteration):
                    break

                update_time = datetime.strptime(
                    entry.updated.string, '%Y-%m-%dT%H:%M:%SZ') + timedelta(
                        hours=int(self.time_zone))
                self.progress = (start_time - update_time) / (
                    start_time - self.oldest_date) * 100
                self.progress = self.progress if self.progress > 1 else 1
                print('\rCalling the api %.2f%% ' % self.progress, end='')
                entry.updated.string = update_time.strftime(
                    '%Y-%m-%dT%H:%M:%SZ')
                if not_finished_iteration:
                    not_finished_iteration = self.modify_iteration_from_entry(
                        entry, update_time, iteration)

                if not_finished_cards:
                    self.modify_cards_from_entry(entry, not_finished_cards)
        if iteration:
            iteration.cards = cards
            iteration.init()

    @staticmethod
    def modify_iteration_from_entry(entry, update_time, iteration):
        if iteration.start_date < update_time <= iteration.end_date:
            iteration.changes.append(entry)
        elif update_time < iteration.start_date:
            iteration.changes.reverse()
            return False
        return True

    @staticmethod
    def modify_cards_from_entry(entry, not_finished_cards):
        card_title = entry.title.string
        number_mark = card_title.find('#') + 1
        card_number = card_title[number_mark:card_title.find(' ', number_mark)]
        if card_number in not_finished_cards:
            card = not_finished_cards[card_number]
            card.changes.append(entry)
            if entry.find('change', type='card-creation'):
                card.changes.reverse()
                card.init()
                not_finished_cards.pop(card_number)

    def format_index(self, iteration, cards):
        if iteration:
            self.formatter.format_iteration_data(iteration)
            self.formatter.format_iteration_chart(iteration)
        else:
            self.formatter.remove_iteration_summary_section()
        self.formatter.format_unusual_cards(cards)
        self.formatter.format_status_toggles()
        self.formatter.format_card_durations_chart(cards)
        self.formatter.format_card_durations_data(cards)

    def save_result(self, name=''):
        self.progress = 100
        directory_name = datetime.now().strftime('result/%Y%m%d-%H%M%S')
        os.mkdir(directory_name)
        with codecs.open(directory_name + '/' + name + '.html',
                         'w',
                         encoding='utf8') as f:
            f.write(str(self.template))
Example #15
0
#!/usr/bin/env python

import sys
sys.path.append('..')

from src.parser_line import ParserLine
from src.language import LanguagePython, LanguageMathematica
from src.parser_text import ParserText
from src.formatter import Formatter

parser_python = ParserLine(LanguagePython())
parser_mathematica = ParserLine(LanguageMathematica())
parser_text = ParserText(LanguageMathematica())
formatter = Formatter(LanguagePython())


def parse_line(s, style='python'):
    if style == 'python':
        parser = parser_python
    else:
        parser = parser_mathematica
    parser.parse_string(s)
    print('parse: %r' % parser.result_parse)
    print('stack: %r' % parser.result_stack)
    print('nested: %r' % parser.result_nested)
    print(formatter(parser))
    print(s)


def parse_text(s, optimize=True):
    parser_text.parse_text(s)
 def setUp(self):
     self.parser = ParserLine(LanguageMathematica())
     self.formatter = Formatter(LanguagePython())