prompt
large_stringlengths
72
9.34k
completion
large_stringlengths
0
7.61k
<|file_name|>testing.py<|end_file_name|><|fim▁begin|>""" .15925 Editor Copyright 2014 TechInvestLab.ru [email protected] .15925 Editor is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3.0 of the License, or (at your option) any later version. .15925 Editor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with .15925 Editor. """ from iso15926.tools.environment import EnvironmentContext from PySide.QtCore import * from PySide.QtGui import * import os from framework.dialogs import Choice class TestWindow(QDialog): <|fim_middle|> if os.path.exists(TestWindow.tests_dir): @public('workbench.menu.help') class xTestMenu: vis_label = tm.main.menu_tests @classmethod def Do(cls): TestWindow() <|fim▁end|>
vis_label = tm.main.tests_title tests_dir = 'tests' def __init__(self): QDialog.__init__(self, appdata.topwindow, Qt.WindowSystemMenuHint | Qt.WindowTitleHint) self.setWindowTitle(self.vis_label) layout = QVBoxLayout(self) box = QGroupBox(tm.main.tests_field, self) self.tests_list = QListWidget(box) boxlayout = QHBoxLayout(box) boxlayout.addWidget(self.tests_list) layout.addWidget(box) for n in os.listdir(self.tests_dir): if n.startswith(".") or not n.endswith('.py'): continue sp = os.path.splitext(n) item = QListWidgetItem(sp[0], self.tests_list) item.setCheckState(Qt.Unchecked) self.btn_prepare = QPushButton(tm.main.prepare, self) self.btn_prepare.setToolTip(tm.main.prepare_selected_tests) self.btn_prepare.clicked.connect(self.OnPrepare) self.btn_run = QPushButton(tm.main.run, self) self.btn_run.setToolTip(tm.main.run_selected_tests) self.btn_run.clicked.connect(self.OnRun) self.btn_sel_all = QPushButton(tm.main.select_all, self) self.btn_sel_all.clicked.connect(self.SelectAll) self.btn_unsel_all = QPushButton(tm.main.unselect_all, self) self.btn_unsel_all.clicked.connect(self.UnselectAll) self.btn_cancel = QPushButton(tm.main.cancel, self) self.btn_cancel.clicked.connect(self.reject) btnlayout = QHBoxLayout() btnlayout.addWidget(self.btn_sel_all) btnlayout.addWidget(self.btn_unsel_all) btnlayout.addStretch() btnlayout.addWidget(self.btn_prepare) btnlayout.addWidget(self.btn_run) btnlayout.addWidget(self.btn_cancel) layout.addLayout(btnlayout) box = QGroupBox(tm.main.tests_result_field, self) self.report = QPlainTextEdit(self) boxlayout = QHBoxLayout(box) boxlayout.addWidget(self.report) layout.addWidget(box) self.exec_() def SelectAll(self): self.tests_list.SetChecked([x for x in xrange(self.tests_list.Count)]) def UnselectAll(self): self.tests_list.SetChecked([]) def OnPrepare(self): if Choice(tm.main.tests_prepare_warning): for k in self.tests_list.CheckedStrings: self.report.AppendText(tm.main.tests_preparing.format(k)) locals = {'mode': 'prepare'} ec = EnvironmentContext(None, locals) ec.ExecutePythonFile(os.path.join(self.tests_dir, k + '.py')) self.report.AppendText(tm.main.tests_preparing_done) def OnRun(self): all_passed = True self.report.appendPlainText(tm.main.tests_running) count = 0 passed = 0 for i in xrange(self.tests_list.count()): item = self.tests_list.item(i) name = item.text() if not item.checkState() == Qt.Checked: continue count += 1 locals = {'mode': 'run', 'passed': False} ec = EnvironmentContext(None, locals) ec.ExecutePythonFile(os.path.join(self.tests_dir, name + '.py')) if locals['passed']: passed += 1 self.report.appendPlainText(tm.main.test_passed.format(name)) else: self.report.appendPlainText(tm.main.test_failed.format(name)) self.report.appendPlainText(tm.main.tests_result) self.report.appendPlainText(tm.main.tests_result_info.format(passed, count))
<|file_name|>testing.py<|end_file_name|><|fim▁begin|>""" .15925 Editor Copyright 2014 TechInvestLab.ru [email protected] .15925 Editor is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3.0 of the License, or (at your option) any later version. .15925 Editor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with .15925 Editor. """ from iso15926.tools.environment import EnvironmentContext from PySide.QtCore import * from PySide.QtGui import * import os from framework.dialogs import Choice class TestWindow(QDialog): vis_label = tm.main.tests_title tests_dir = 'tests' def __init__(self): <|fim_middle|> def SelectAll(self): self.tests_list.SetChecked([x for x in xrange(self.tests_list.Count)]) def UnselectAll(self): self.tests_list.SetChecked([]) def OnPrepare(self): if Choice(tm.main.tests_prepare_warning): for k in self.tests_list.CheckedStrings: self.report.AppendText(tm.main.tests_preparing.format(k)) locals = {'mode': 'prepare'} ec = EnvironmentContext(None, locals) ec.ExecutePythonFile(os.path.join(self.tests_dir, k + '.py')) self.report.AppendText(tm.main.tests_preparing_done) def OnRun(self): all_passed = True self.report.appendPlainText(tm.main.tests_running) count = 0 passed = 0 for i in xrange(self.tests_list.count()): item = self.tests_list.item(i) name = item.text() if not item.checkState() == Qt.Checked: continue count += 1 locals = {'mode': 'run', 'passed': False} ec = EnvironmentContext(None, locals) ec.ExecutePythonFile(os.path.join(self.tests_dir, name + '.py')) if locals['passed']: passed += 1 self.report.appendPlainText(tm.main.test_passed.format(name)) else: self.report.appendPlainText(tm.main.test_failed.format(name)) self.report.appendPlainText(tm.main.tests_result) self.report.appendPlainText(tm.main.tests_result_info.format(passed, count)) if os.path.exists(TestWindow.tests_dir): @public('workbench.menu.help') class xTestMenu: vis_label = tm.main.menu_tests @classmethod def Do(cls): TestWindow() <|fim▁end|>
QDialog.__init__(self, appdata.topwindow, Qt.WindowSystemMenuHint | Qt.WindowTitleHint) self.setWindowTitle(self.vis_label) layout = QVBoxLayout(self) box = QGroupBox(tm.main.tests_field, self) self.tests_list = QListWidget(box) boxlayout = QHBoxLayout(box) boxlayout.addWidget(self.tests_list) layout.addWidget(box) for n in os.listdir(self.tests_dir): if n.startswith(".") or not n.endswith('.py'): continue sp = os.path.splitext(n) item = QListWidgetItem(sp[0], self.tests_list) item.setCheckState(Qt.Unchecked) self.btn_prepare = QPushButton(tm.main.prepare, self) self.btn_prepare.setToolTip(tm.main.prepare_selected_tests) self.btn_prepare.clicked.connect(self.OnPrepare) self.btn_run = QPushButton(tm.main.run, self) self.btn_run.setToolTip(tm.main.run_selected_tests) self.btn_run.clicked.connect(self.OnRun) self.btn_sel_all = QPushButton(tm.main.select_all, self) self.btn_sel_all.clicked.connect(self.SelectAll) self.btn_unsel_all = QPushButton(tm.main.unselect_all, self) self.btn_unsel_all.clicked.connect(self.UnselectAll) self.btn_cancel = QPushButton(tm.main.cancel, self) self.btn_cancel.clicked.connect(self.reject) btnlayout = QHBoxLayout() btnlayout.addWidget(self.btn_sel_all) btnlayout.addWidget(self.btn_unsel_all) btnlayout.addStretch() btnlayout.addWidget(self.btn_prepare) btnlayout.addWidget(self.btn_run) btnlayout.addWidget(self.btn_cancel) layout.addLayout(btnlayout) box = QGroupBox(tm.main.tests_result_field, self) self.report = QPlainTextEdit(self) boxlayout = QHBoxLayout(box) boxlayout.addWidget(self.report) layout.addWidget(box) self.exec_()
<|file_name|>testing.py<|end_file_name|><|fim▁begin|>""" .15925 Editor Copyright 2014 TechInvestLab.ru [email protected] .15925 Editor is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3.0 of the License, or (at your option) any later version. .15925 Editor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with .15925 Editor. """ from iso15926.tools.environment import EnvironmentContext from PySide.QtCore import * from PySide.QtGui import * import os from framework.dialogs import Choice class TestWindow(QDialog): vis_label = tm.main.tests_title tests_dir = 'tests' def __init__(self): QDialog.__init__(self, appdata.topwindow, Qt.WindowSystemMenuHint | Qt.WindowTitleHint) self.setWindowTitle(self.vis_label) layout = QVBoxLayout(self) box = QGroupBox(tm.main.tests_field, self) self.tests_list = QListWidget(box) boxlayout = QHBoxLayout(box) boxlayout.addWidget(self.tests_list) layout.addWidget(box) for n in os.listdir(self.tests_dir): if n.startswith(".") or not n.endswith('.py'): continue sp = os.path.splitext(n) item = QListWidgetItem(sp[0], self.tests_list) item.setCheckState(Qt.Unchecked) self.btn_prepare = QPushButton(tm.main.prepare, self) self.btn_prepare.setToolTip(tm.main.prepare_selected_tests) self.btn_prepare.clicked.connect(self.OnPrepare) self.btn_run = QPushButton(tm.main.run, self) self.btn_run.setToolTip(tm.main.run_selected_tests) self.btn_run.clicked.connect(self.OnRun) self.btn_sel_all = QPushButton(tm.main.select_all, self) self.btn_sel_all.clicked.connect(self.SelectAll) self.btn_unsel_all = QPushButton(tm.main.unselect_all, self) self.btn_unsel_all.clicked.connect(self.UnselectAll) self.btn_cancel = QPushButton(tm.main.cancel, self) self.btn_cancel.clicked.connect(self.reject) btnlayout = QHBoxLayout() btnlayout.addWidget(self.btn_sel_all) btnlayout.addWidget(self.btn_unsel_all) btnlayout.addStretch() btnlayout.addWidget(self.btn_prepare) btnlayout.addWidget(self.btn_run) btnlayout.addWidget(self.btn_cancel) layout.addLayout(btnlayout) box = QGroupBox(tm.main.tests_result_field, self) self.report = QPlainTextEdit(self) boxlayout = QHBoxLayout(box) boxlayout.addWidget(self.report) layout.addWidget(box) self.exec_() def SelectAll(self): <|fim_middle|> def UnselectAll(self): self.tests_list.SetChecked([]) def OnPrepare(self): if Choice(tm.main.tests_prepare_warning): for k in self.tests_list.CheckedStrings: self.report.AppendText(tm.main.tests_preparing.format(k)) locals = {'mode': 'prepare'} ec = EnvironmentContext(None, locals) ec.ExecutePythonFile(os.path.join(self.tests_dir, k + '.py')) self.report.AppendText(tm.main.tests_preparing_done) def OnRun(self): all_passed = True self.report.appendPlainText(tm.main.tests_running) count = 0 passed = 0 for i in xrange(self.tests_list.count()): item = self.tests_list.item(i) name = item.text() if not item.checkState() == Qt.Checked: continue count += 1 locals = {'mode': 'run', 'passed': False} ec = EnvironmentContext(None, locals) ec.ExecutePythonFile(os.path.join(self.tests_dir, name + '.py')) if locals['passed']: passed += 1 self.report.appendPlainText(tm.main.test_passed.format(name)) else: self.report.appendPlainText(tm.main.test_failed.format(name)) self.report.appendPlainText(tm.main.tests_result) self.report.appendPlainText(tm.main.tests_result_info.format(passed, count)) if os.path.exists(TestWindow.tests_dir): @public('workbench.menu.help') class xTestMenu: vis_label = tm.main.menu_tests @classmethod def Do(cls): TestWindow() <|fim▁end|>
self.tests_list.SetChecked([x for x in xrange(self.tests_list.Count)])
<|file_name|>testing.py<|end_file_name|><|fim▁begin|>""" .15925 Editor Copyright 2014 TechInvestLab.ru [email protected] .15925 Editor is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3.0 of the License, or (at your option) any later version. .15925 Editor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with .15925 Editor. """ from iso15926.tools.environment import EnvironmentContext from PySide.QtCore import * from PySide.QtGui import * import os from framework.dialogs import Choice class TestWindow(QDialog): vis_label = tm.main.tests_title tests_dir = 'tests' def __init__(self): QDialog.__init__(self, appdata.topwindow, Qt.WindowSystemMenuHint | Qt.WindowTitleHint) self.setWindowTitle(self.vis_label) layout = QVBoxLayout(self) box = QGroupBox(tm.main.tests_field, self) self.tests_list = QListWidget(box) boxlayout = QHBoxLayout(box) boxlayout.addWidget(self.tests_list) layout.addWidget(box) for n in os.listdir(self.tests_dir): if n.startswith(".") or not n.endswith('.py'): continue sp = os.path.splitext(n) item = QListWidgetItem(sp[0], self.tests_list) item.setCheckState(Qt.Unchecked) self.btn_prepare = QPushButton(tm.main.prepare, self) self.btn_prepare.setToolTip(tm.main.prepare_selected_tests) self.btn_prepare.clicked.connect(self.OnPrepare) self.btn_run = QPushButton(tm.main.run, self) self.btn_run.setToolTip(tm.main.run_selected_tests) self.btn_run.clicked.connect(self.OnRun) self.btn_sel_all = QPushButton(tm.main.select_all, self) self.btn_sel_all.clicked.connect(self.SelectAll) self.btn_unsel_all = QPushButton(tm.main.unselect_all, self) self.btn_unsel_all.clicked.connect(self.UnselectAll) self.btn_cancel = QPushButton(tm.main.cancel, self) self.btn_cancel.clicked.connect(self.reject) btnlayout = QHBoxLayout() btnlayout.addWidget(self.btn_sel_all) btnlayout.addWidget(self.btn_unsel_all) btnlayout.addStretch() btnlayout.addWidget(self.btn_prepare) btnlayout.addWidget(self.btn_run) btnlayout.addWidget(self.btn_cancel) layout.addLayout(btnlayout) box = QGroupBox(tm.main.tests_result_field, self) self.report = QPlainTextEdit(self) boxlayout = QHBoxLayout(box) boxlayout.addWidget(self.report) layout.addWidget(box) self.exec_() def SelectAll(self): self.tests_list.SetChecked([x for x in xrange(self.tests_list.Count)]) def UnselectAll(self): <|fim_middle|> def OnPrepare(self): if Choice(tm.main.tests_prepare_warning): for k in self.tests_list.CheckedStrings: self.report.AppendText(tm.main.tests_preparing.format(k)) locals = {'mode': 'prepare'} ec = EnvironmentContext(None, locals) ec.ExecutePythonFile(os.path.join(self.tests_dir, k + '.py')) self.report.AppendText(tm.main.tests_preparing_done) def OnRun(self): all_passed = True self.report.appendPlainText(tm.main.tests_running) count = 0 passed = 0 for i in xrange(self.tests_list.count()): item = self.tests_list.item(i) name = item.text() if not item.checkState() == Qt.Checked: continue count += 1 locals = {'mode': 'run', 'passed': False} ec = EnvironmentContext(None, locals) ec.ExecutePythonFile(os.path.join(self.tests_dir, name + '.py')) if locals['passed']: passed += 1 self.report.appendPlainText(tm.main.test_passed.format(name)) else: self.report.appendPlainText(tm.main.test_failed.format(name)) self.report.appendPlainText(tm.main.tests_result) self.report.appendPlainText(tm.main.tests_result_info.format(passed, count)) if os.path.exists(TestWindow.tests_dir): @public('workbench.menu.help') class xTestMenu: vis_label = tm.main.menu_tests @classmethod def Do(cls): TestWindow() <|fim▁end|>
self.tests_list.SetChecked([])
<|file_name|>testing.py<|end_file_name|><|fim▁begin|>""" .15925 Editor Copyright 2014 TechInvestLab.ru [email protected] .15925 Editor is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3.0 of the License, or (at your option) any later version. .15925 Editor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with .15925 Editor. """ from iso15926.tools.environment import EnvironmentContext from PySide.QtCore import * from PySide.QtGui import * import os from framework.dialogs import Choice class TestWindow(QDialog): vis_label = tm.main.tests_title tests_dir = 'tests' def __init__(self): QDialog.__init__(self, appdata.topwindow, Qt.WindowSystemMenuHint | Qt.WindowTitleHint) self.setWindowTitle(self.vis_label) layout = QVBoxLayout(self) box = QGroupBox(tm.main.tests_field, self) self.tests_list = QListWidget(box) boxlayout = QHBoxLayout(box) boxlayout.addWidget(self.tests_list) layout.addWidget(box) for n in os.listdir(self.tests_dir): if n.startswith(".") or not n.endswith('.py'): continue sp = os.path.splitext(n) item = QListWidgetItem(sp[0], self.tests_list) item.setCheckState(Qt.Unchecked) self.btn_prepare = QPushButton(tm.main.prepare, self) self.btn_prepare.setToolTip(tm.main.prepare_selected_tests) self.btn_prepare.clicked.connect(self.OnPrepare) self.btn_run = QPushButton(tm.main.run, self) self.btn_run.setToolTip(tm.main.run_selected_tests) self.btn_run.clicked.connect(self.OnRun) self.btn_sel_all = QPushButton(tm.main.select_all, self) self.btn_sel_all.clicked.connect(self.SelectAll) self.btn_unsel_all = QPushButton(tm.main.unselect_all, self) self.btn_unsel_all.clicked.connect(self.UnselectAll) self.btn_cancel = QPushButton(tm.main.cancel, self) self.btn_cancel.clicked.connect(self.reject) btnlayout = QHBoxLayout() btnlayout.addWidget(self.btn_sel_all) btnlayout.addWidget(self.btn_unsel_all) btnlayout.addStretch() btnlayout.addWidget(self.btn_prepare) btnlayout.addWidget(self.btn_run) btnlayout.addWidget(self.btn_cancel) layout.addLayout(btnlayout) box = QGroupBox(tm.main.tests_result_field, self) self.report = QPlainTextEdit(self) boxlayout = QHBoxLayout(box) boxlayout.addWidget(self.report) layout.addWidget(box) self.exec_() def SelectAll(self): self.tests_list.SetChecked([x for x in xrange(self.tests_list.Count)]) def UnselectAll(self): self.tests_list.SetChecked([]) def OnPrepare(self): <|fim_middle|> def OnRun(self): all_passed = True self.report.appendPlainText(tm.main.tests_running) count = 0 passed = 0 for i in xrange(self.tests_list.count()): item = self.tests_list.item(i) name = item.text() if not item.checkState() == Qt.Checked: continue count += 1 locals = {'mode': 'run', 'passed': False} ec = EnvironmentContext(None, locals) ec.ExecutePythonFile(os.path.join(self.tests_dir, name + '.py')) if locals['passed']: passed += 1 self.report.appendPlainText(tm.main.test_passed.format(name)) else: self.report.appendPlainText(tm.main.test_failed.format(name)) self.report.appendPlainText(tm.main.tests_result) self.report.appendPlainText(tm.main.tests_result_info.format(passed, count)) if os.path.exists(TestWindow.tests_dir): @public('workbench.menu.help') class xTestMenu: vis_label = tm.main.menu_tests @classmethod def Do(cls): TestWindow() <|fim▁end|>
if Choice(tm.main.tests_prepare_warning): for k in self.tests_list.CheckedStrings: self.report.AppendText(tm.main.tests_preparing.format(k)) locals = {'mode': 'prepare'} ec = EnvironmentContext(None, locals) ec.ExecutePythonFile(os.path.join(self.tests_dir, k + '.py')) self.report.AppendText(tm.main.tests_preparing_done)
<|file_name|>testing.py<|end_file_name|><|fim▁begin|>""" .15925 Editor Copyright 2014 TechInvestLab.ru [email protected] .15925 Editor is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3.0 of the License, or (at your option) any later version. .15925 Editor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with .15925 Editor. """ from iso15926.tools.environment import EnvironmentContext from PySide.QtCore import * from PySide.QtGui import * import os from framework.dialogs import Choice class TestWindow(QDialog): vis_label = tm.main.tests_title tests_dir = 'tests' def __init__(self): QDialog.__init__(self, appdata.topwindow, Qt.WindowSystemMenuHint | Qt.WindowTitleHint) self.setWindowTitle(self.vis_label) layout = QVBoxLayout(self) box = QGroupBox(tm.main.tests_field, self) self.tests_list = QListWidget(box) boxlayout = QHBoxLayout(box) boxlayout.addWidget(self.tests_list) layout.addWidget(box) for n in os.listdir(self.tests_dir): if n.startswith(".") or not n.endswith('.py'): continue sp = os.path.splitext(n) item = QListWidgetItem(sp[0], self.tests_list) item.setCheckState(Qt.Unchecked) self.btn_prepare = QPushButton(tm.main.prepare, self) self.btn_prepare.setToolTip(tm.main.prepare_selected_tests) self.btn_prepare.clicked.connect(self.OnPrepare) self.btn_run = QPushButton(tm.main.run, self) self.btn_run.setToolTip(tm.main.run_selected_tests) self.btn_run.clicked.connect(self.OnRun) self.btn_sel_all = QPushButton(tm.main.select_all, self) self.btn_sel_all.clicked.connect(self.SelectAll) self.btn_unsel_all = QPushButton(tm.main.unselect_all, self) self.btn_unsel_all.clicked.connect(self.UnselectAll) self.btn_cancel = QPushButton(tm.main.cancel, self) self.btn_cancel.clicked.connect(self.reject) btnlayout = QHBoxLayout() btnlayout.addWidget(self.btn_sel_all) btnlayout.addWidget(self.btn_unsel_all) btnlayout.addStretch() btnlayout.addWidget(self.btn_prepare) btnlayout.addWidget(self.btn_run) btnlayout.addWidget(self.btn_cancel) layout.addLayout(btnlayout) box = QGroupBox(tm.main.tests_result_field, self) self.report = QPlainTextEdit(self) boxlayout = QHBoxLayout(box) boxlayout.addWidget(self.report) layout.addWidget(box) self.exec_() def SelectAll(self): self.tests_list.SetChecked([x for x in xrange(self.tests_list.Count)]) def UnselectAll(self): self.tests_list.SetChecked([]) def OnPrepare(self): if Choice(tm.main.tests_prepare_warning): for k in self.tests_list.CheckedStrings: self.report.AppendText(tm.main.tests_preparing.format(k)) locals = {'mode': 'prepare'} ec = EnvironmentContext(None, locals) ec.ExecutePythonFile(os.path.join(self.tests_dir, k + '.py')) self.report.AppendText(tm.main.tests_preparing_done) def OnRun(self): <|fim_middle|> if os.path.exists(TestWindow.tests_dir): @public('workbench.menu.help') class xTestMenu: vis_label = tm.main.menu_tests @classmethod def Do(cls): TestWindow() <|fim▁end|>
all_passed = True self.report.appendPlainText(tm.main.tests_running) count = 0 passed = 0 for i in xrange(self.tests_list.count()): item = self.tests_list.item(i) name = item.text() if not item.checkState() == Qt.Checked: continue count += 1 locals = {'mode': 'run', 'passed': False} ec = EnvironmentContext(None, locals) ec.ExecutePythonFile(os.path.join(self.tests_dir, name + '.py')) if locals['passed']: passed += 1 self.report.appendPlainText(tm.main.test_passed.format(name)) else: self.report.appendPlainText(tm.main.test_failed.format(name)) self.report.appendPlainText(tm.main.tests_result) self.report.appendPlainText(tm.main.tests_result_info.format(passed, count))
<|file_name|>testing.py<|end_file_name|><|fim▁begin|>""" .15925 Editor Copyright 2014 TechInvestLab.ru [email protected] .15925 Editor is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3.0 of the License, or (at your option) any later version. .15925 Editor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with .15925 Editor. """ from iso15926.tools.environment import EnvironmentContext from PySide.QtCore import * from PySide.QtGui import * import os from framework.dialogs import Choice class TestWindow(QDialog): vis_label = tm.main.tests_title tests_dir = 'tests' def __init__(self): QDialog.__init__(self, appdata.topwindow, Qt.WindowSystemMenuHint | Qt.WindowTitleHint) self.setWindowTitle(self.vis_label) layout = QVBoxLayout(self) box = QGroupBox(tm.main.tests_field, self) self.tests_list = QListWidget(box) boxlayout = QHBoxLayout(box) boxlayout.addWidget(self.tests_list) layout.addWidget(box) for n in os.listdir(self.tests_dir): if n.startswith(".") or not n.endswith('.py'): continue sp = os.path.splitext(n) item = QListWidgetItem(sp[0], self.tests_list) item.setCheckState(Qt.Unchecked) self.btn_prepare = QPushButton(tm.main.prepare, self) self.btn_prepare.setToolTip(tm.main.prepare_selected_tests) self.btn_prepare.clicked.connect(self.OnPrepare) self.btn_run = QPushButton(tm.main.run, self) self.btn_run.setToolTip(tm.main.run_selected_tests) self.btn_run.clicked.connect(self.OnRun) self.btn_sel_all = QPushButton(tm.main.select_all, self) self.btn_sel_all.clicked.connect(self.SelectAll) self.btn_unsel_all = QPushButton(tm.main.unselect_all, self) self.btn_unsel_all.clicked.connect(self.UnselectAll) self.btn_cancel = QPushButton(tm.main.cancel, self) self.btn_cancel.clicked.connect(self.reject) btnlayout = QHBoxLayout() btnlayout.addWidget(self.btn_sel_all) btnlayout.addWidget(self.btn_unsel_all) btnlayout.addStretch() btnlayout.addWidget(self.btn_prepare) btnlayout.addWidget(self.btn_run) btnlayout.addWidget(self.btn_cancel) layout.addLayout(btnlayout) box = QGroupBox(tm.main.tests_result_field, self) self.report = QPlainTextEdit(self) boxlayout = QHBoxLayout(box) boxlayout.addWidget(self.report) layout.addWidget(box) self.exec_() def SelectAll(self): self.tests_list.SetChecked([x for x in xrange(self.tests_list.Count)]) def UnselectAll(self): self.tests_list.SetChecked([]) def OnPrepare(self): if Choice(tm.main.tests_prepare_warning): for k in self.tests_list.CheckedStrings: self.report.AppendText(tm.main.tests_preparing.format(k)) locals = {'mode': 'prepare'} ec = EnvironmentContext(None, locals) ec.ExecutePythonFile(os.path.join(self.tests_dir, k + '.py')) self.report.AppendText(tm.main.tests_preparing_done) def OnRun(self): all_passed = True self.report.appendPlainText(tm.main.tests_running) count = 0 passed = 0 for i in xrange(self.tests_list.count()): item = self.tests_list.item(i) name = item.text() if not item.checkState() == Qt.Checked: continue count += 1 locals = {'mode': 'run', 'passed': False} ec = EnvironmentContext(None, locals) ec.ExecutePythonFile(os.path.join(self.tests_dir, name + '.py')) if locals['passed']: passed += 1 self.report.appendPlainText(tm.main.test_passed.format(name)) else: self.report.appendPlainText(tm.main.test_failed.format(name)) self.report.appendPlainText(tm.main.tests_result) self.report.appendPlainText(tm.main.tests_result_info.format(passed, count)) if os.path.exists(TestWindow.tests_dir): @public('workbench.menu.help') class xTestMenu: <|fim_middle|> <|fim▁end|>
vis_label = tm.main.menu_tests @classmethod def Do(cls): TestWindow()
<|file_name|>testing.py<|end_file_name|><|fim▁begin|>""" .15925 Editor Copyright 2014 TechInvestLab.ru [email protected] .15925 Editor is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3.0 of the License, or (at your option) any later version. .15925 Editor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with .15925 Editor. """ from iso15926.tools.environment import EnvironmentContext from PySide.QtCore import * from PySide.QtGui import * import os from framework.dialogs import Choice class TestWindow(QDialog): vis_label = tm.main.tests_title tests_dir = 'tests' def __init__(self): QDialog.__init__(self, appdata.topwindow, Qt.WindowSystemMenuHint | Qt.WindowTitleHint) self.setWindowTitle(self.vis_label) layout = QVBoxLayout(self) box = QGroupBox(tm.main.tests_field, self) self.tests_list = QListWidget(box) boxlayout = QHBoxLayout(box) boxlayout.addWidget(self.tests_list) layout.addWidget(box) for n in os.listdir(self.tests_dir): if n.startswith(".") or not n.endswith('.py'): continue sp = os.path.splitext(n) item = QListWidgetItem(sp[0], self.tests_list) item.setCheckState(Qt.Unchecked) self.btn_prepare = QPushButton(tm.main.prepare, self) self.btn_prepare.setToolTip(tm.main.prepare_selected_tests) self.btn_prepare.clicked.connect(self.OnPrepare) self.btn_run = QPushButton(tm.main.run, self) self.btn_run.setToolTip(tm.main.run_selected_tests) self.btn_run.clicked.connect(self.OnRun) self.btn_sel_all = QPushButton(tm.main.select_all, self) self.btn_sel_all.clicked.connect(self.SelectAll) self.btn_unsel_all = QPushButton(tm.main.unselect_all, self) self.btn_unsel_all.clicked.connect(self.UnselectAll) self.btn_cancel = QPushButton(tm.main.cancel, self) self.btn_cancel.clicked.connect(self.reject) btnlayout = QHBoxLayout() btnlayout.addWidget(self.btn_sel_all) btnlayout.addWidget(self.btn_unsel_all) btnlayout.addStretch() btnlayout.addWidget(self.btn_prepare) btnlayout.addWidget(self.btn_run) btnlayout.addWidget(self.btn_cancel) layout.addLayout(btnlayout) box = QGroupBox(tm.main.tests_result_field, self) self.report = QPlainTextEdit(self) boxlayout = QHBoxLayout(box) boxlayout.addWidget(self.report) layout.addWidget(box) self.exec_() def SelectAll(self): self.tests_list.SetChecked([x for x in xrange(self.tests_list.Count)]) def UnselectAll(self): self.tests_list.SetChecked([]) def OnPrepare(self): if Choice(tm.main.tests_prepare_warning): for k in self.tests_list.CheckedStrings: self.report.AppendText(tm.main.tests_preparing.format(k)) locals = {'mode': 'prepare'} ec = EnvironmentContext(None, locals) ec.ExecutePythonFile(os.path.join(self.tests_dir, k + '.py')) self.report.AppendText(tm.main.tests_preparing_done) def OnRun(self): all_passed = True self.report.appendPlainText(tm.main.tests_running) count = 0 passed = 0 for i in xrange(self.tests_list.count()): item = self.tests_list.item(i) name = item.text() if not item.checkState() == Qt.Checked: continue count += 1 locals = {'mode': 'run', 'passed': False} ec = EnvironmentContext(None, locals) ec.ExecutePythonFile(os.path.join(self.tests_dir, name + '.py')) if locals['passed']: passed += 1 self.report.appendPlainText(tm.main.test_passed.format(name)) else: self.report.appendPlainText(tm.main.test_failed.format(name)) self.report.appendPlainText(tm.main.tests_result) self.report.appendPlainText(tm.main.tests_result_info.format(passed, count)) if os.path.exists(TestWindow.tests_dir): @public('workbench.menu.help') class xTestMenu: vis_label = tm.main.menu_tests @classmethod def Do(cls): <|fim_middle|> <|fim▁end|>
TestWindow()
<|file_name|>testing.py<|end_file_name|><|fim▁begin|>""" .15925 Editor Copyright 2014 TechInvestLab.ru [email protected] .15925 Editor is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3.0 of the License, or (at your option) any later version. .15925 Editor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with .15925 Editor. """ from iso15926.tools.environment import EnvironmentContext from PySide.QtCore import * from PySide.QtGui import * import os from framework.dialogs import Choice class TestWindow(QDialog): vis_label = tm.main.tests_title tests_dir = 'tests' def __init__(self): QDialog.__init__(self, appdata.topwindow, Qt.WindowSystemMenuHint | Qt.WindowTitleHint) self.setWindowTitle(self.vis_label) layout = QVBoxLayout(self) box = QGroupBox(tm.main.tests_field, self) self.tests_list = QListWidget(box) boxlayout = QHBoxLayout(box) boxlayout.addWidget(self.tests_list) layout.addWidget(box) for n in os.listdir(self.tests_dir): if n.startswith(".") or not n.endswith('.py'): <|fim_middle|> sp = os.path.splitext(n) item = QListWidgetItem(sp[0], self.tests_list) item.setCheckState(Qt.Unchecked) self.btn_prepare = QPushButton(tm.main.prepare, self) self.btn_prepare.setToolTip(tm.main.prepare_selected_tests) self.btn_prepare.clicked.connect(self.OnPrepare) self.btn_run = QPushButton(tm.main.run, self) self.btn_run.setToolTip(tm.main.run_selected_tests) self.btn_run.clicked.connect(self.OnRun) self.btn_sel_all = QPushButton(tm.main.select_all, self) self.btn_sel_all.clicked.connect(self.SelectAll) self.btn_unsel_all = QPushButton(tm.main.unselect_all, self) self.btn_unsel_all.clicked.connect(self.UnselectAll) self.btn_cancel = QPushButton(tm.main.cancel, self) self.btn_cancel.clicked.connect(self.reject) btnlayout = QHBoxLayout() btnlayout.addWidget(self.btn_sel_all) btnlayout.addWidget(self.btn_unsel_all) btnlayout.addStretch() btnlayout.addWidget(self.btn_prepare) btnlayout.addWidget(self.btn_run) btnlayout.addWidget(self.btn_cancel) layout.addLayout(btnlayout) box = QGroupBox(tm.main.tests_result_field, self) self.report = QPlainTextEdit(self) boxlayout = QHBoxLayout(box) boxlayout.addWidget(self.report) layout.addWidget(box) self.exec_() def SelectAll(self): self.tests_list.SetChecked([x for x in xrange(self.tests_list.Count)]) def UnselectAll(self): self.tests_list.SetChecked([]) def OnPrepare(self): if Choice(tm.main.tests_prepare_warning): for k in self.tests_list.CheckedStrings: self.report.AppendText(tm.main.tests_preparing.format(k)) locals = {'mode': 'prepare'} ec = EnvironmentContext(None, locals) ec.ExecutePythonFile(os.path.join(self.tests_dir, k + '.py')) self.report.AppendText(tm.main.tests_preparing_done) def OnRun(self): all_passed = True self.report.appendPlainText(tm.main.tests_running) count = 0 passed = 0 for i in xrange(self.tests_list.count()): item = self.tests_list.item(i) name = item.text() if not item.checkState() == Qt.Checked: continue count += 1 locals = {'mode': 'run', 'passed': False} ec = EnvironmentContext(None, locals) ec.ExecutePythonFile(os.path.join(self.tests_dir, name + '.py')) if locals['passed']: passed += 1 self.report.appendPlainText(tm.main.test_passed.format(name)) else: self.report.appendPlainText(tm.main.test_failed.format(name)) self.report.appendPlainText(tm.main.tests_result) self.report.appendPlainText(tm.main.tests_result_info.format(passed, count)) if os.path.exists(TestWindow.tests_dir): @public('workbench.menu.help') class xTestMenu: vis_label = tm.main.menu_tests @classmethod def Do(cls): TestWindow() <|fim▁end|>
continue
<|file_name|>testing.py<|end_file_name|><|fim▁begin|>""" .15925 Editor Copyright 2014 TechInvestLab.ru [email protected] .15925 Editor is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3.0 of the License, or (at your option) any later version. .15925 Editor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with .15925 Editor. """ from iso15926.tools.environment import EnvironmentContext from PySide.QtCore import * from PySide.QtGui import * import os from framework.dialogs import Choice class TestWindow(QDialog): vis_label = tm.main.tests_title tests_dir = 'tests' def __init__(self): QDialog.__init__(self, appdata.topwindow, Qt.WindowSystemMenuHint | Qt.WindowTitleHint) self.setWindowTitle(self.vis_label) layout = QVBoxLayout(self) box = QGroupBox(tm.main.tests_field, self) self.tests_list = QListWidget(box) boxlayout = QHBoxLayout(box) boxlayout.addWidget(self.tests_list) layout.addWidget(box) for n in os.listdir(self.tests_dir): if n.startswith(".") or not n.endswith('.py'): continue sp = os.path.splitext(n) item = QListWidgetItem(sp[0], self.tests_list) item.setCheckState(Qt.Unchecked) self.btn_prepare = QPushButton(tm.main.prepare, self) self.btn_prepare.setToolTip(tm.main.prepare_selected_tests) self.btn_prepare.clicked.connect(self.OnPrepare) self.btn_run = QPushButton(tm.main.run, self) self.btn_run.setToolTip(tm.main.run_selected_tests) self.btn_run.clicked.connect(self.OnRun) self.btn_sel_all = QPushButton(tm.main.select_all, self) self.btn_sel_all.clicked.connect(self.SelectAll) self.btn_unsel_all = QPushButton(tm.main.unselect_all, self) self.btn_unsel_all.clicked.connect(self.UnselectAll) self.btn_cancel = QPushButton(tm.main.cancel, self) self.btn_cancel.clicked.connect(self.reject) btnlayout = QHBoxLayout() btnlayout.addWidget(self.btn_sel_all) btnlayout.addWidget(self.btn_unsel_all) btnlayout.addStretch() btnlayout.addWidget(self.btn_prepare) btnlayout.addWidget(self.btn_run) btnlayout.addWidget(self.btn_cancel) layout.addLayout(btnlayout) box = QGroupBox(tm.main.tests_result_field, self) self.report = QPlainTextEdit(self) boxlayout = QHBoxLayout(box) boxlayout.addWidget(self.report) layout.addWidget(box) self.exec_() def SelectAll(self): self.tests_list.SetChecked([x for x in xrange(self.tests_list.Count)]) def UnselectAll(self): self.tests_list.SetChecked([]) def OnPrepare(self): if Choice(tm.main.tests_prepare_warning): <|fim_middle|> def OnRun(self): all_passed = True self.report.appendPlainText(tm.main.tests_running) count = 0 passed = 0 for i in xrange(self.tests_list.count()): item = self.tests_list.item(i) name = item.text() if not item.checkState() == Qt.Checked: continue count += 1 locals = {'mode': 'run', 'passed': False} ec = EnvironmentContext(None, locals) ec.ExecutePythonFile(os.path.join(self.tests_dir, name + '.py')) if locals['passed']: passed += 1 self.report.appendPlainText(tm.main.test_passed.format(name)) else: self.report.appendPlainText(tm.main.test_failed.format(name)) self.report.appendPlainText(tm.main.tests_result) self.report.appendPlainText(tm.main.tests_result_info.format(passed, count)) if os.path.exists(TestWindow.tests_dir): @public('workbench.menu.help') class xTestMenu: vis_label = tm.main.menu_tests @classmethod def Do(cls): TestWindow() <|fim▁end|>
for k in self.tests_list.CheckedStrings: self.report.AppendText(tm.main.tests_preparing.format(k)) locals = {'mode': 'prepare'} ec = EnvironmentContext(None, locals) ec.ExecutePythonFile(os.path.join(self.tests_dir, k + '.py')) self.report.AppendText(tm.main.tests_preparing_done)
<|file_name|>testing.py<|end_file_name|><|fim▁begin|>""" .15925 Editor Copyright 2014 TechInvestLab.ru [email protected] .15925 Editor is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3.0 of the License, or (at your option) any later version. .15925 Editor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with .15925 Editor. """ from iso15926.tools.environment import EnvironmentContext from PySide.QtCore import * from PySide.QtGui import * import os from framework.dialogs import Choice class TestWindow(QDialog): vis_label = tm.main.tests_title tests_dir = 'tests' def __init__(self): QDialog.__init__(self, appdata.topwindow, Qt.WindowSystemMenuHint | Qt.WindowTitleHint) self.setWindowTitle(self.vis_label) layout = QVBoxLayout(self) box = QGroupBox(tm.main.tests_field, self) self.tests_list = QListWidget(box) boxlayout = QHBoxLayout(box) boxlayout.addWidget(self.tests_list) layout.addWidget(box) for n in os.listdir(self.tests_dir): if n.startswith(".") or not n.endswith('.py'): continue sp = os.path.splitext(n) item = QListWidgetItem(sp[0], self.tests_list) item.setCheckState(Qt.Unchecked) self.btn_prepare = QPushButton(tm.main.prepare, self) self.btn_prepare.setToolTip(tm.main.prepare_selected_tests) self.btn_prepare.clicked.connect(self.OnPrepare) self.btn_run = QPushButton(tm.main.run, self) self.btn_run.setToolTip(tm.main.run_selected_tests) self.btn_run.clicked.connect(self.OnRun) self.btn_sel_all = QPushButton(tm.main.select_all, self) self.btn_sel_all.clicked.connect(self.SelectAll) self.btn_unsel_all = QPushButton(tm.main.unselect_all, self) self.btn_unsel_all.clicked.connect(self.UnselectAll) self.btn_cancel = QPushButton(tm.main.cancel, self) self.btn_cancel.clicked.connect(self.reject) btnlayout = QHBoxLayout() btnlayout.addWidget(self.btn_sel_all) btnlayout.addWidget(self.btn_unsel_all) btnlayout.addStretch() btnlayout.addWidget(self.btn_prepare) btnlayout.addWidget(self.btn_run) btnlayout.addWidget(self.btn_cancel) layout.addLayout(btnlayout) box = QGroupBox(tm.main.tests_result_field, self) self.report = QPlainTextEdit(self) boxlayout = QHBoxLayout(box) boxlayout.addWidget(self.report) layout.addWidget(box) self.exec_() def SelectAll(self): self.tests_list.SetChecked([x for x in xrange(self.tests_list.Count)]) def UnselectAll(self): self.tests_list.SetChecked([]) def OnPrepare(self): if Choice(tm.main.tests_prepare_warning): for k in self.tests_list.CheckedStrings: self.report.AppendText(tm.main.tests_preparing.format(k)) locals = {'mode': 'prepare'} ec = EnvironmentContext(None, locals) ec.ExecutePythonFile(os.path.join(self.tests_dir, k + '.py')) self.report.AppendText(tm.main.tests_preparing_done) def OnRun(self): all_passed = True self.report.appendPlainText(tm.main.tests_running) count = 0 passed = 0 for i in xrange(self.tests_list.count()): item = self.tests_list.item(i) name = item.text() if not item.checkState() == Qt.Checked: <|fim_middle|> count += 1 locals = {'mode': 'run', 'passed': False} ec = EnvironmentContext(None, locals) ec.ExecutePythonFile(os.path.join(self.tests_dir, name + '.py')) if locals['passed']: passed += 1 self.report.appendPlainText(tm.main.test_passed.format(name)) else: self.report.appendPlainText(tm.main.test_failed.format(name)) self.report.appendPlainText(tm.main.tests_result) self.report.appendPlainText(tm.main.tests_result_info.format(passed, count)) if os.path.exists(TestWindow.tests_dir): @public('workbench.menu.help') class xTestMenu: vis_label = tm.main.menu_tests @classmethod def Do(cls): TestWindow() <|fim▁end|>
continue
<|file_name|>testing.py<|end_file_name|><|fim▁begin|>""" .15925 Editor Copyright 2014 TechInvestLab.ru [email protected] .15925 Editor is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3.0 of the License, or (at your option) any later version. .15925 Editor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with .15925 Editor. """ from iso15926.tools.environment import EnvironmentContext from PySide.QtCore import * from PySide.QtGui import * import os from framework.dialogs import Choice class TestWindow(QDialog): vis_label = tm.main.tests_title tests_dir = 'tests' def __init__(self): QDialog.__init__(self, appdata.topwindow, Qt.WindowSystemMenuHint | Qt.WindowTitleHint) self.setWindowTitle(self.vis_label) layout = QVBoxLayout(self) box = QGroupBox(tm.main.tests_field, self) self.tests_list = QListWidget(box) boxlayout = QHBoxLayout(box) boxlayout.addWidget(self.tests_list) layout.addWidget(box) for n in os.listdir(self.tests_dir): if n.startswith(".") or not n.endswith('.py'): continue sp = os.path.splitext(n) item = QListWidgetItem(sp[0], self.tests_list) item.setCheckState(Qt.Unchecked) self.btn_prepare = QPushButton(tm.main.prepare, self) self.btn_prepare.setToolTip(tm.main.prepare_selected_tests) self.btn_prepare.clicked.connect(self.OnPrepare) self.btn_run = QPushButton(tm.main.run, self) self.btn_run.setToolTip(tm.main.run_selected_tests) self.btn_run.clicked.connect(self.OnRun) self.btn_sel_all = QPushButton(tm.main.select_all, self) self.btn_sel_all.clicked.connect(self.SelectAll) self.btn_unsel_all = QPushButton(tm.main.unselect_all, self) self.btn_unsel_all.clicked.connect(self.UnselectAll) self.btn_cancel = QPushButton(tm.main.cancel, self) self.btn_cancel.clicked.connect(self.reject) btnlayout = QHBoxLayout() btnlayout.addWidget(self.btn_sel_all) btnlayout.addWidget(self.btn_unsel_all) btnlayout.addStretch() btnlayout.addWidget(self.btn_prepare) btnlayout.addWidget(self.btn_run) btnlayout.addWidget(self.btn_cancel) layout.addLayout(btnlayout) box = QGroupBox(tm.main.tests_result_field, self) self.report = QPlainTextEdit(self) boxlayout = QHBoxLayout(box) boxlayout.addWidget(self.report) layout.addWidget(box) self.exec_() def SelectAll(self): self.tests_list.SetChecked([x for x in xrange(self.tests_list.Count)]) def UnselectAll(self): self.tests_list.SetChecked([]) def OnPrepare(self): if Choice(tm.main.tests_prepare_warning): for k in self.tests_list.CheckedStrings: self.report.AppendText(tm.main.tests_preparing.format(k)) locals = {'mode': 'prepare'} ec = EnvironmentContext(None, locals) ec.ExecutePythonFile(os.path.join(self.tests_dir, k + '.py')) self.report.AppendText(tm.main.tests_preparing_done) def OnRun(self): all_passed = True self.report.appendPlainText(tm.main.tests_running) count = 0 passed = 0 for i in xrange(self.tests_list.count()): item = self.tests_list.item(i) name = item.text() if not item.checkState() == Qt.Checked: continue count += 1 locals = {'mode': 'run', 'passed': False} ec = EnvironmentContext(None, locals) ec.ExecutePythonFile(os.path.join(self.tests_dir, name + '.py')) if locals['passed']: <|fim_middle|> else: self.report.appendPlainText(tm.main.test_failed.format(name)) self.report.appendPlainText(tm.main.tests_result) self.report.appendPlainText(tm.main.tests_result_info.format(passed, count)) if os.path.exists(TestWindow.tests_dir): @public('workbench.menu.help') class xTestMenu: vis_label = tm.main.menu_tests @classmethod def Do(cls): TestWindow() <|fim▁end|>
passed += 1 self.report.appendPlainText(tm.main.test_passed.format(name))
<|file_name|>testing.py<|end_file_name|><|fim▁begin|>""" .15925 Editor Copyright 2014 TechInvestLab.ru [email protected] .15925 Editor is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3.0 of the License, or (at your option) any later version. .15925 Editor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with .15925 Editor. """ from iso15926.tools.environment import EnvironmentContext from PySide.QtCore import * from PySide.QtGui import * import os from framework.dialogs import Choice class TestWindow(QDialog): vis_label = tm.main.tests_title tests_dir = 'tests' def __init__(self): QDialog.__init__(self, appdata.topwindow, Qt.WindowSystemMenuHint | Qt.WindowTitleHint) self.setWindowTitle(self.vis_label) layout = QVBoxLayout(self) box = QGroupBox(tm.main.tests_field, self) self.tests_list = QListWidget(box) boxlayout = QHBoxLayout(box) boxlayout.addWidget(self.tests_list) layout.addWidget(box) for n in os.listdir(self.tests_dir): if n.startswith(".") or not n.endswith('.py'): continue sp = os.path.splitext(n) item = QListWidgetItem(sp[0], self.tests_list) item.setCheckState(Qt.Unchecked) self.btn_prepare = QPushButton(tm.main.prepare, self) self.btn_prepare.setToolTip(tm.main.prepare_selected_tests) self.btn_prepare.clicked.connect(self.OnPrepare) self.btn_run = QPushButton(tm.main.run, self) self.btn_run.setToolTip(tm.main.run_selected_tests) self.btn_run.clicked.connect(self.OnRun) self.btn_sel_all = QPushButton(tm.main.select_all, self) self.btn_sel_all.clicked.connect(self.SelectAll) self.btn_unsel_all = QPushButton(tm.main.unselect_all, self) self.btn_unsel_all.clicked.connect(self.UnselectAll) self.btn_cancel = QPushButton(tm.main.cancel, self) self.btn_cancel.clicked.connect(self.reject) btnlayout = QHBoxLayout() btnlayout.addWidget(self.btn_sel_all) btnlayout.addWidget(self.btn_unsel_all) btnlayout.addStretch() btnlayout.addWidget(self.btn_prepare) btnlayout.addWidget(self.btn_run) btnlayout.addWidget(self.btn_cancel) layout.addLayout(btnlayout) box = QGroupBox(tm.main.tests_result_field, self) self.report = QPlainTextEdit(self) boxlayout = QHBoxLayout(box) boxlayout.addWidget(self.report) layout.addWidget(box) self.exec_() def SelectAll(self): self.tests_list.SetChecked([x for x in xrange(self.tests_list.Count)]) def UnselectAll(self): self.tests_list.SetChecked([]) def OnPrepare(self): if Choice(tm.main.tests_prepare_warning): for k in self.tests_list.CheckedStrings: self.report.AppendText(tm.main.tests_preparing.format(k)) locals = {'mode': 'prepare'} ec = EnvironmentContext(None, locals) ec.ExecutePythonFile(os.path.join(self.tests_dir, k + '.py')) self.report.AppendText(tm.main.tests_preparing_done) def OnRun(self): all_passed = True self.report.appendPlainText(tm.main.tests_running) count = 0 passed = 0 for i in xrange(self.tests_list.count()): item = self.tests_list.item(i) name = item.text() if not item.checkState() == Qt.Checked: continue count += 1 locals = {'mode': 'run', 'passed': False} ec = EnvironmentContext(None, locals) ec.ExecutePythonFile(os.path.join(self.tests_dir, name + '.py')) if locals['passed']: passed += 1 self.report.appendPlainText(tm.main.test_passed.format(name)) else: <|fim_middle|> self.report.appendPlainText(tm.main.tests_result) self.report.appendPlainText(tm.main.tests_result_info.format(passed, count)) if os.path.exists(TestWindow.tests_dir): @public('workbench.menu.help') class xTestMenu: vis_label = tm.main.menu_tests @classmethod def Do(cls): TestWindow() <|fim▁end|>
self.report.appendPlainText(tm.main.test_failed.format(name))
<|file_name|>testing.py<|end_file_name|><|fim▁begin|>""" .15925 Editor Copyright 2014 TechInvestLab.ru [email protected] .15925 Editor is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3.0 of the License, or (at your option) any later version. .15925 Editor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with .15925 Editor. """ from iso15926.tools.environment import EnvironmentContext from PySide.QtCore import * from PySide.QtGui import * import os from framework.dialogs import Choice class TestWindow(QDialog): vis_label = tm.main.tests_title tests_dir = 'tests' def __init__(self): QDialog.__init__(self, appdata.topwindow, Qt.WindowSystemMenuHint | Qt.WindowTitleHint) self.setWindowTitle(self.vis_label) layout = QVBoxLayout(self) box = QGroupBox(tm.main.tests_field, self) self.tests_list = QListWidget(box) boxlayout = QHBoxLayout(box) boxlayout.addWidget(self.tests_list) layout.addWidget(box) for n in os.listdir(self.tests_dir): if n.startswith(".") or not n.endswith('.py'): continue sp = os.path.splitext(n) item = QListWidgetItem(sp[0], self.tests_list) item.setCheckState(Qt.Unchecked) self.btn_prepare = QPushButton(tm.main.prepare, self) self.btn_prepare.setToolTip(tm.main.prepare_selected_tests) self.btn_prepare.clicked.connect(self.OnPrepare) self.btn_run = QPushButton(tm.main.run, self) self.btn_run.setToolTip(tm.main.run_selected_tests) self.btn_run.clicked.connect(self.OnRun) self.btn_sel_all = QPushButton(tm.main.select_all, self) self.btn_sel_all.clicked.connect(self.SelectAll) self.btn_unsel_all = QPushButton(tm.main.unselect_all, self) self.btn_unsel_all.clicked.connect(self.UnselectAll) self.btn_cancel = QPushButton(tm.main.cancel, self) self.btn_cancel.clicked.connect(self.reject) btnlayout = QHBoxLayout() btnlayout.addWidget(self.btn_sel_all) btnlayout.addWidget(self.btn_unsel_all) btnlayout.addStretch() btnlayout.addWidget(self.btn_prepare) btnlayout.addWidget(self.btn_run) btnlayout.addWidget(self.btn_cancel) layout.addLayout(btnlayout) box = QGroupBox(tm.main.tests_result_field, self) self.report = QPlainTextEdit(self) boxlayout = QHBoxLayout(box) boxlayout.addWidget(self.report) layout.addWidget(box) self.exec_() def SelectAll(self): self.tests_list.SetChecked([x for x in xrange(self.tests_list.Count)]) def UnselectAll(self): self.tests_list.SetChecked([]) def OnPrepare(self): if Choice(tm.main.tests_prepare_warning): for k in self.tests_list.CheckedStrings: self.report.AppendText(tm.main.tests_preparing.format(k)) locals = {'mode': 'prepare'} ec = EnvironmentContext(None, locals) ec.ExecutePythonFile(os.path.join(self.tests_dir, k + '.py')) self.report.AppendText(tm.main.tests_preparing_done) def OnRun(self): all_passed = True self.report.appendPlainText(tm.main.tests_running) count = 0 passed = 0 for i in xrange(self.tests_list.count()): item = self.tests_list.item(i) name = item.text() if not item.checkState() == Qt.Checked: continue count += 1 locals = {'mode': 'run', 'passed': False} ec = EnvironmentContext(None, locals) ec.ExecutePythonFile(os.path.join(self.tests_dir, name + '.py')) if locals['passed']: passed += 1 self.report.appendPlainText(tm.main.test_passed.format(name)) else: self.report.appendPlainText(tm.main.test_failed.format(name)) self.report.appendPlainText(tm.main.tests_result) self.report.appendPlainText(tm.main.tests_result_info.format(passed, count)) if os.path.exists(TestWindow.tests_dir): <|fim_middle|> <|fim▁end|>
@public('workbench.menu.help') class xTestMenu: vis_label = tm.main.menu_tests @classmethod def Do(cls): TestWindow()
<|file_name|>testing.py<|end_file_name|><|fim▁begin|>""" .15925 Editor Copyright 2014 TechInvestLab.ru [email protected] .15925 Editor is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3.0 of the License, or (at your option) any later version. .15925 Editor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with .15925 Editor. """ from iso15926.tools.environment import EnvironmentContext from PySide.QtCore import * from PySide.QtGui import * import os from framework.dialogs import Choice class TestWindow(QDialog): vis_label = tm.main.tests_title tests_dir = 'tests' def <|fim_middle|>(self): QDialog.__init__(self, appdata.topwindow, Qt.WindowSystemMenuHint | Qt.WindowTitleHint) self.setWindowTitle(self.vis_label) layout = QVBoxLayout(self) box = QGroupBox(tm.main.tests_field, self) self.tests_list = QListWidget(box) boxlayout = QHBoxLayout(box) boxlayout.addWidget(self.tests_list) layout.addWidget(box) for n in os.listdir(self.tests_dir): if n.startswith(".") or not n.endswith('.py'): continue sp = os.path.splitext(n) item = QListWidgetItem(sp[0], self.tests_list) item.setCheckState(Qt.Unchecked) self.btn_prepare = QPushButton(tm.main.prepare, self) self.btn_prepare.setToolTip(tm.main.prepare_selected_tests) self.btn_prepare.clicked.connect(self.OnPrepare) self.btn_run = QPushButton(tm.main.run, self) self.btn_run.setToolTip(tm.main.run_selected_tests) self.btn_run.clicked.connect(self.OnRun) self.btn_sel_all = QPushButton(tm.main.select_all, self) self.btn_sel_all.clicked.connect(self.SelectAll) self.btn_unsel_all = QPushButton(tm.main.unselect_all, self) self.btn_unsel_all.clicked.connect(self.UnselectAll) self.btn_cancel = QPushButton(tm.main.cancel, self) self.btn_cancel.clicked.connect(self.reject) btnlayout = QHBoxLayout() btnlayout.addWidget(self.btn_sel_all) btnlayout.addWidget(self.btn_unsel_all) btnlayout.addStretch() btnlayout.addWidget(self.btn_prepare) btnlayout.addWidget(self.btn_run) btnlayout.addWidget(self.btn_cancel) layout.addLayout(btnlayout) box = QGroupBox(tm.main.tests_result_field, self) self.report = QPlainTextEdit(self) boxlayout = QHBoxLayout(box) boxlayout.addWidget(self.report) layout.addWidget(box) self.exec_() def SelectAll(self): self.tests_list.SetChecked([x for x in xrange(self.tests_list.Count)]) def UnselectAll(self): self.tests_list.SetChecked([]) def OnPrepare(self): if Choice(tm.main.tests_prepare_warning): for k in self.tests_list.CheckedStrings: self.report.AppendText(tm.main.tests_preparing.format(k)) locals = {'mode': 'prepare'} ec = EnvironmentContext(None, locals) ec.ExecutePythonFile(os.path.join(self.tests_dir, k + '.py')) self.report.AppendText(tm.main.tests_preparing_done) def OnRun(self): all_passed = True self.report.appendPlainText(tm.main.tests_running) count = 0 passed = 0 for i in xrange(self.tests_list.count()): item = self.tests_list.item(i) name = item.text() if not item.checkState() == Qt.Checked: continue count += 1 locals = {'mode': 'run', 'passed': False} ec = EnvironmentContext(None, locals) ec.ExecutePythonFile(os.path.join(self.tests_dir, name + '.py')) if locals['passed']: passed += 1 self.report.appendPlainText(tm.main.test_passed.format(name)) else: self.report.appendPlainText(tm.main.test_failed.format(name)) self.report.appendPlainText(tm.main.tests_result) self.report.appendPlainText(tm.main.tests_result_info.format(passed, count)) if os.path.exists(TestWindow.tests_dir): @public('workbench.menu.help') class xTestMenu: vis_label = tm.main.menu_tests @classmethod def Do(cls): TestWindow() <|fim▁end|>
__init__
<|file_name|>testing.py<|end_file_name|><|fim▁begin|>""" .15925 Editor Copyright 2014 TechInvestLab.ru [email protected] .15925 Editor is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3.0 of the License, or (at your option) any later version. .15925 Editor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with .15925 Editor. """ from iso15926.tools.environment import EnvironmentContext from PySide.QtCore import * from PySide.QtGui import * import os from framework.dialogs import Choice class TestWindow(QDialog): vis_label = tm.main.tests_title tests_dir = 'tests' def __init__(self): QDialog.__init__(self, appdata.topwindow, Qt.WindowSystemMenuHint | Qt.WindowTitleHint) self.setWindowTitle(self.vis_label) layout = QVBoxLayout(self) box = QGroupBox(tm.main.tests_field, self) self.tests_list = QListWidget(box) boxlayout = QHBoxLayout(box) boxlayout.addWidget(self.tests_list) layout.addWidget(box) for n in os.listdir(self.tests_dir): if n.startswith(".") or not n.endswith('.py'): continue sp = os.path.splitext(n) item = QListWidgetItem(sp[0], self.tests_list) item.setCheckState(Qt.Unchecked) self.btn_prepare = QPushButton(tm.main.prepare, self) self.btn_prepare.setToolTip(tm.main.prepare_selected_tests) self.btn_prepare.clicked.connect(self.OnPrepare) self.btn_run = QPushButton(tm.main.run, self) self.btn_run.setToolTip(tm.main.run_selected_tests) self.btn_run.clicked.connect(self.OnRun) self.btn_sel_all = QPushButton(tm.main.select_all, self) self.btn_sel_all.clicked.connect(self.SelectAll) self.btn_unsel_all = QPushButton(tm.main.unselect_all, self) self.btn_unsel_all.clicked.connect(self.UnselectAll) self.btn_cancel = QPushButton(tm.main.cancel, self) self.btn_cancel.clicked.connect(self.reject) btnlayout = QHBoxLayout() btnlayout.addWidget(self.btn_sel_all) btnlayout.addWidget(self.btn_unsel_all) btnlayout.addStretch() btnlayout.addWidget(self.btn_prepare) btnlayout.addWidget(self.btn_run) btnlayout.addWidget(self.btn_cancel) layout.addLayout(btnlayout) box = QGroupBox(tm.main.tests_result_field, self) self.report = QPlainTextEdit(self) boxlayout = QHBoxLayout(box) boxlayout.addWidget(self.report) layout.addWidget(box) self.exec_() def <|fim_middle|>(self): self.tests_list.SetChecked([x for x in xrange(self.tests_list.Count)]) def UnselectAll(self): self.tests_list.SetChecked([]) def OnPrepare(self): if Choice(tm.main.tests_prepare_warning): for k in self.tests_list.CheckedStrings: self.report.AppendText(tm.main.tests_preparing.format(k)) locals = {'mode': 'prepare'} ec = EnvironmentContext(None, locals) ec.ExecutePythonFile(os.path.join(self.tests_dir, k + '.py')) self.report.AppendText(tm.main.tests_preparing_done) def OnRun(self): all_passed = True self.report.appendPlainText(tm.main.tests_running) count = 0 passed = 0 for i in xrange(self.tests_list.count()): item = self.tests_list.item(i) name = item.text() if not item.checkState() == Qt.Checked: continue count += 1 locals = {'mode': 'run', 'passed': False} ec = EnvironmentContext(None, locals) ec.ExecutePythonFile(os.path.join(self.tests_dir, name + '.py')) if locals['passed']: passed += 1 self.report.appendPlainText(tm.main.test_passed.format(name)) else: self.report.appendPlainText(tm.main.test_failed.format(name)) self.report.appendPlainText(tm.main.tests_result) self.report.appendPlainText(tm.main.tests_result_info.format(passed, count)) if os.path.exists(TestWindow.tests_dir): @public('workbench.menu.help') class xTestMenu: vis_label = tm.main.menu_tests @classmethod def Do(cls): TestWindow() <|fim▁end|>
SelectAll
<|file_name|>testing.py<|end_file_name|><|fim▁begin|>""" .15925 Editor Copyright 2014 TechInvestLab.ru [email protected] .15925 Editor is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3.0 of the License, or (at your option) any later version. .15925 Editor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with .15925 Editor. """ from iso15926.tools.environment import EnvironmentContext from PySide.QtCore import * from PySide.QtGui import * import os from framework.dialogs import Choice class TestWindow(QDialog): vis_label = tm.main.tests_title tests_dir = 'tests' def __init__(self): QDialog.__init__(self, appdata.topwindow, Qt.WindowSystemMenuHint | Qt.WindowTitleHint) self.setWindowTitle(self.vis_label) layout = QVBoxLayout(self) box = QGroupBox(tm.main.tests_field, self) self.tests_list = QListWidget(box) boxlayout = QHBoxLayout(box) boxlayout.addWidget(self.tests_list) layout.addWidget(box) for n in os.listdir(self.tests_dir): if n.startswith(".") or not n.endswith('.py'): continue sp = os.path.splitext(n) item = QListWidgetItem(sp[0], self.tests_list) item.setCheckState(Qt.Unchecked) self.btn_prepare = QPushButton(tm.main.prepare, self) self.btn_prepare.setToolTip(tm.main.prepare_selected_tests) self.btn_prepare.clicked.connect(self.OnPrepare) self.btn_run = QPushButton(tm.main.run, self) self.btn_run.setToolTip(tm.main.run_selected_tests) self.btn_run.clicked.connect(self.OnRun) self.btn_sel_all = QPushButton(tm.main.select_all, self) self.btn_sel_all.clicked.connect(self.SelectAll) self.btn_unsel_all = QPushButton(tm.main.unselect_all, self) self.btn_unsel_all.clicked.connect(self.UnselectAll) self.btn_cancel = QPushButton(tm.main.cancel, self) self.btn_cancel.clicked.connect(self.reject) btnlayout = QHBoxLayout() btnlayout.addWidget(self.btn_sel_all) btnlayout.addWidget(self.btn_unsel_all) btnlayout.addStretch() btnlayout.addWidget(self.btn_prepare) btnlayout.addWidget(self.btn_run) btnlayout.addWidget(self.btn_cancel) layout.addLayout(btnlayout) box = QGroupBox(tm.main.tests_result_field, self) self.report = QPlainTextEdit(self) boxlayout = QHBoxLayout(box) boxlayout.addWidget(self.report) layout.addWidget(box) self.exec_() def SelectAll(self): self.tests_list.SetChecked([x for x in xrange(self.tests_list.Count)]) def <|fim_middle|>(self): self.tests_list.SetChecked([]) def OnPrepare(self): if Choice(tm.main.tests_prepare_warning): for k in self.tests_list.CheckedStrings: self.report.AppendText(tm.main.tests_preparing.format(k)) locals = {'mode': 'prepare'} ec = EnvironmentContext(None, locals) ec.ExecutePythonFile(os.path.join(self.tests_dir, k + '.py')) self.report.AppendText(tm.main.tests_preparing_done) def OnRun(self): all_passed = True self.report.appendPlainText(tm.main.tests_running) count = 0 passed = 0 for i in xrange(self.tests_list.count()): item = self.tests_list.item(i) name = item.text() if not item.checkState() == Qt.Checked: continue count += 1 locals = {'mode': 'run', 'passed': False} ec = EnvironmentContext(None, locals) ec.ExecutePythonFile(os.path.join(self.tests_dir, name + '.py')) if locals['passed']: passed += 1 self.report.appendPlainText(tm.main.test_passed.format(name)) else: self.report.appendPlainText(tm.main.test_failed.format(name)) self.report.appendPlainText(tm.main.tests_result) self.report.appendPlainText(tm.main.tests_result_info.format(passed, count)) if os.path.exists(TestWindow.tests_dir): @public('workbench.menu.help') class xTestMenu: vis_label = tm.main.menu_tests @classmethod def Do(cls): TestWindow() <|fim▁end|>
UnselectAll
<|file_name|>testing.py<|end_file_name|><|fim▁begin|>""" .15925 Editor Copyright 2014 TechInvestLab.ru [email protected] .15925 Editor is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3.0 of the License, or (at your option) any later version. .15925 Editor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with .15925 Editor. """ from iso15926.tools.environment import EnvironmentContext from PySide.QtCore import * from PySide.QtGui import * import os from framework.dialogs import Choice class TestWindow(QDialog): vis_label = tm.main.tests_title tests_dir = 'tests' def __init__(self): QDialog.__init__(self, appdata.topwindow, Qt.WindowSystemMenuHint | Qt.WindowTitleHint) self.setWindowTitle(self.vis_label) layout = QVBoxLayout(self) box = QGroupBox(tm.main.tests_field, self) self.tests_list = QListWidget(box) boxlayout = QHBoxLayout(box) boxlayout.addWidget(self.tests_list) layout.addWidget(box) for n in os.listdir(self.tests_dir): if n.startswith(".") or not n.endswith('.py'): continue sp = os.path.splitext(n) item = QListWidgetItem(sp[0], self.tests_list) item.setCheckState(Qt.Unchecked) self.btn_prepare = QPushButton(tm.main.prepare, self) self.btn_prepare.setToolTip(tm.main.prepare_selected_tests) self.btn_prepare.clicked.connect(self.OnPrepare) self.btn_run = QPushButton(tm.main.run, self) self.btn_run.setToolTip(tm.main.run_selected_tests) self.btn_run.clicked.connect(self.OnRun) self.btn_sel_all = QPushButton(tm.main.select_all, self) self.btn_sel_all.clicked.connect(self.SelectAll) self.btn_unsel_all = QPushButton(tm.main.unselect_all, self) self.btn_unsel_all.clicked.connect(self.UnselectAll) self.btn_cancel = QPushButton(tm.main.cancel, self) self.btn_cancel.clicked.connect(self.reject) btnlayout = QHBoxLayout() btnlayout.addWidget(self.btn_sel_all) btnlayout.addWidget(self.btn_unsel_all) btnlayout.addStretch() btnlayout.addWidget(self.btn_prepare) btnlayout.addWidget(self.btn_run) btnlayout.addWidget(self.btn_cancel) layout.addLayout(btnlayout) box = QGroupBox(tm.main.tests_result_field, self) self.report = QPlainTextEdit(self) boxlayout = QHBoxLayout(box) boxlayout.addWidget(self.report) layout.addWidget(box) self.exec_() def SelectAll(self): self.tests_list.SetChecked([x for x in xrange(self.tests_list.Count)]) def UnselectAll(self): self.tests_list.SetChecked([]) def <|fim_middle|>(self): if Choice(tm.main.tests_prepare_warning): for k in self.tests_list.CheckedStrings: self.report.AppendText(tm.main.tests_preparing.format(k)) locals = {'mode': 'prepare'} ec = EnvironmentContext(None, locals) ec.ExecutePythonFile(os.path.join(self.tests_dir, k + '.py')) self.report.AppendText(tm.main.tests_preparing_done) def OnRun(self): all_passed = True self.report.appendPlainText(tm.main.tests_running) count = 0 passed = 0 for i in xrange(self.tests_list.count()): item = self.tests_list.item(i) name = item.text() if not item.checkState() == Qt.Checked: continue count += 1 locals = {'mode': 'run', 'passed': False} ec = EnvironmentContext(None, locals) ec.ExecutePythonFile(os.path.join(self.tests_dir, name + '.py')) if locals['passed']: passed += 1 self.report.appendPlainText(tm.main.test_passed.format(name)) else: self.report.appendPlainText(tm.main.test_failed.format(name)) self.report.appendPlainText(tm.main.tests_result) self.report.appendPlainText(tm.main.tests_result_info.format(passed, count)) if os.path.exists(TestWindow.tests_dir): @public('workbench.menu.help') class xTestMenu: vis_label = tm.main.menu_tests @classmethod def Do(cls): TestWindow() <|fim▁end|>
OnPrepare
<|file_name|>testing.py<|end_file_name|><|fim▁begin|>""" .15925 Editor Copyright 2014 TechInvestLab.ru [email protected] .15925 Editor is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3.0 of the License, or (at your option) any later version. .15925 Editor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with .15925 Editor. """ from iso15926.tools.environment import EnvironmentContext from PySide.QtCore import * from PySide.QtGui import * import os from framework.dialogs import Choice class TestWindow(QDialog): vis_label = tm.main.tests_title tests_dir = 'tests' def __init__(self): QDialog.__init__(self, appdata.topwindow, Qt.WindowSystemMenuHint | Qt.WindowTitleHint) self.setWindowTitle(self.vis_label) layout = QVBoxLayout(self) box = QGroupBox(tm.main.tests_field, self) self.tests_list = QListWidget(box) boxlayout = QHBoxLayout(box) boxlayout.addWidget(self.tests_list) layout.addWidget(box) for n in os.listdir(self.tests_dir): if n.startswith(".") or not n.endswith('.py'): continue sp = os.path.splitext(n) item = QListWidgetItem(sp[0], self.tests_list) item.setCheckState(Qt.Unchecked) self.btn_prepare = QPushButton(tm.main.prepare, self) self.btn_prepare.setToolTip(tm.main.prepare_selected_tests) self.btn_prepare.clicked.connect(self.OnPrepare) self.btn_run = QPushButton(tm.main.run, self) self.btn_run.setToolTip(tm.main.run_selected_tests) self.btn_run.clicked.connect(self.OnRun) self.btn_sel_all = QPushButton(tm.main.select_all, self) self.btn_sel_all.clicked.connect(self.SelectAll) self.btn_unsel_all = QPushButton(tm.main.unselect_all, self) self.btn_unsel_all.clicked.connect(self.UnselectAll) self.btn_cancel = QPushButton(tm.main.cancel, self) self.btn_cancel.clicked.connect(self.reject) btnlayout = QHBoxLayout() btnlayout.addWidget(self.btn_sel_all) btnlayout.addWidget(self.btn_unsel_all) btnlayout.addStretch() btnlayout.addWidget(self.btn_prepare) btnlayout.addWidget(self.btn_run) btnlayout.addWidget(self.btn_cancel) layout.addLayout(btnlayout) box = QGroupBox(tm.main.tests_result_field, self) self.report = QPlainTextEdit(self) boxlayout = QHBoxLayout(box) boxlayout.addWidget(self.report) layout.addWidget(box) self.exec_() def SelectAll(self): self.tests_list.SetChecked([x for x in xrange(self.tests_list.Count)]) def UnselectAll(self): self.tests_list.SetChecked([]) def OnPrepare(self): if Choice(tm.main.tests_prepare_warning): for k in self.tests_list.CheckedStrings: self.report.AppendText(tm.main.tests_preparing.format(k)) locals = {'mode': 'prepare'} ec = EnvironmentContext(None, locals) ec.ExecutePythonFile(os.path.join(self.tests_dir, k + '.py')) self.report.AppendText(tm.main.tests_preparing_done) def <|fim_middle|>(self): all_passed = True self.report.appendPlainText(tm.main.tests_running) count = 0 passed = 0 for i in xrange(self.tests_list.count()): item = self.tests_list.item(i) name = item.text() if not item.checkState() == Qt.Checked: continue count += 1 locals = {'mode': 'run', 'passed': False} ec = EnvironmentContext(None, locals) ec.ExecutePythonFile(os.path.join(self.tests_dir, name + '.py')) if locals['passed']: passed += 1 self.report.appendPlainText(tm.main.test_passed.format(name)) else: self.report.appendPlainText(tm.main.test_failed.format(name)) self.report.appendPlainText(tm.main.tests_result) self.report.appendPlainText(tm.main.tests_result_info.format(passed, count)) if os.path.exists(TestWindow.tests_dir): @public('workbench.menu.help') class xTestMenu: vis_label = tm.main.menu_tests @classmethod def Do(cls): TestWindow() <|fim▁end|>
OnRun
<|file_name|>testing.py<|end_file_name|><|fim▁begin|>""" .15925 Editor Copyright 2014 TechInvestLab.ru [email protected] .15925 Editor is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3.0 of the License, or (at your option) any later version. .15925 Editor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with .15925 Editor. """ from iso15926.tools.environment import EnvironmentContext from PySide.QtCore import * from PySide.QtGui import * import os from framework.dialogs import Choice class TestWindow(QDialog): vis_label = tm.main.tests_title tests_dir = 'tests' def __init__(self): QDialog.__init__(self, appdata.topwindow, Qt.WindowSystemMenuHint | Qt.WindowTitleHint) self.setWindowTitle(self.vis_label) layout = QVBoxLayout(self) box = QGroupBox(tm.main.tests_field, self) self.tests_list = QListWidget(box) boxlayout = QHBoxLayout(box) boxlayout.addWidget(self.tests_list) layout.addWidget(box) for n in os.listdir(self.tests_dir): if n.startswith(".") or not n.endswith('.py'): continue sp = os.path.splitext(n) item = QListWidgetItem(sp[0], self.tests_list) item.setCheckState(Qt.Unchecked) self.btn_prepare = QPushButton(tm.main.prepare, self) self.btn_prepare.setToolTip(tm.main.prepare_selected_tests) self.btn_prepare.clicked.connect(self.OnPrepare) self.btn_run = QPushButton(tm.main.run, self) self.btn_run.setToolTip(tm.main.run_selected_tests) self.btn_run.clicked.connect(self.OnRun) self.btn_sel_all = QPushButton(tm.main.select_all, self) self.btn_sel_all.clicked.connect(self.SelectAll) self.btn_unsel_all = QPushButton(tm.main.unselect_all, self) self.btn_unsel_all.clicked.connect(self.UnselectAll) self.btn_cancel = QPushButton(tm.main.cancel, self) self.btn_cancel.clicked.connect(self.reject) btnlayout = QHBoxLayout() btnlayout.addWidget(self.btn_sel_all) btnlayout.addWidget(self.btn_unsel_all) btnlayout.addStretch() btnlayout.addWidget(self.btn_prepare) btnlayout.addWidget(self.btn_run) btnlayout.addWidget(self.btn_cancel) layout.addLayout(btnlayout) box = QGroupBox(tm.main.tests_result_field, self) self.report = QPlainTextEdit(self) boxlayout = QHBoxLayout(box) boxlayout.addWidget(self.report) layout.addWidget(box) self.exec_() def SelectAll(self): self.tests_list.SetChecked([x for x in xrange(self.tests_list.Count)]) def UnselectAll(self): self.tests_list.SetChecked([]) def OnPrepare(self): if Choice(tm.main.tests_prepare_warning): for k in self.tests_list.CheckedStrings: self.report.AppendText(tm.main.tests_preparing.format(k)) locals = {'mode': 'prepare'} ec = EnvironmentContext(None, locals) ec.ExecutePythonFile(os.path.join(self.tests_dir, k + '.py')) self.report.AppendText(tm.main.tests_preparing_done) def OnRun(self): all_passed = True self.report.appendPlainText(tm.main.tests_running) count = 0 passed = 0 for i in xrange(self.tests_list.count()): item = self.tests_list.item(i) name = item.text() if not item.checkState() == Qt.Checked: continue count += 1 locals = {'mode': 'run', 'passed': False} ec = EnvironmentContext(None, locals) ec.ExecutePythonFile(os.path.join(self.tests_dir, name + '.py')) if locals['passed']: passed += 1 self.report.appendPlainText(tm.main.test_passed.format(name)) else: self.report.appendPlainText(tm.main.test_failed.format(name)) self.report.appendPlainText(tm.main.tests_result) self.report.appendPlainText(tm.main.tests_result_info.format(passed, count)) if os.path.exists(TestWindow.tests_dir): @public('workbench.menu.help') class xTestMenu: vis_label = tm.main.menu_tests @classmethod def <|fim_middle|>(cls): TestWindow() <|fim▁end|>
Do
<|file_name|>pagination.py<|end_file_name|><|fim▁begin|>from collections import OrderedDict from rest_framework import pagination from rest_framework.response import Response __author__ = 'alexandreferreira' class DetailPagination(pagination.PageNumberPagination): def get_paginated_response(self, data): return Response(OrderedDict([ ('count', self.page.paginator.count), ('next', self.get_next_page_number()), ('has_next', self.page.has_next()), ('previous', self.get_previous_page_number()), ('has_previous', self.page.has_previous()), ('current', self.page.number), ('results', data) ])) def get_next_page_number(self): if not self.page.has_next(): return self.page.number return self.page.next_page_number() def get_previous_page_number(self): if not self.page.has_previous(): return 1<|fim▁hole|><|fim▁end|>
return self.page.previous_page_number()
<|file_name|>pagination.py<|end_file_name|><|fim▁begin|>from collections import OrderedDict from rest_framework import pagination from rest_framework.response import Response __author__ = 'alexandreferreira' class DetailPagination(pagination.PageNumberPagination): <|fim_middle|> <|fim▁end|>
def get_paginated_response(self, data): return Response(OrderedDict([ ('count', self.page.paginator.count), ('next', self.get_next_page_number()), ('has_next', self.page.has_next()), ('previous', self.get_previous_page_number()), ('has_previous', self.page.has_previous()), ('current', self.page.number), ('results', data) ])) def get_next_page_number(self): if not self.page.has_next(): return self.page.number return self.page.next_page_number() def get_previous_page_number(self): if not self.page.has_previous(): return 1 return self.page.previous_page_number()
<|file_name|>pagination.py<|end_file_name|><|fim▁begin|>from collections import OrderedDict from rest_framework import pagination from rest_framework.response import Response __author__ = 'alexandreferreira' class DetailPagination(pagination.PageNumberPagination): def get_paginated_response(self, data): <|fim_middle|> def get_next_page_number(self): if not self.page.has_next(): return self.page.number return self.page.next_page_number() def get_previous_page_number(self): if not self.page.has_previous(): return 1 return self.page.previous_page_number()<|fim▁end|>
return Response(OrderedDict([ ('count', self.page.paginator.count), ('next', self.get_next_page_number()), ('has_next', self.page.has_next()), ('previous', self.get_previous_page_number()), ('has_previous', self.page.has_previous()), ('current', self.page.number), ('results', data) ]))
<|file_name|>pagination.py<|end_file_name|><|fim▁begin|>from collections import OrderedDict from rest_framework import pagination from rest_framework.response import Response __author__ = 'alexandreferreira' class DetailPagination(pagination.PageNumberPagination): def get_paginated_response(self, data): return Response(OrderedDict([ ('count', self.page.paginator.count), ('next', self.get_next_page_number()), ('has_next', self.page.has_next()), ('previous', self.get_previous_page_number()), ('has_previous', self.page.has_previous()), ('current', self.page.number), ('results', data) ])) def get_next_page_number(self): <|fim_middle|> def get_previous_page_number(self): if not self.page.has_previous(): return 1 return self.page.previous_page_number()<|fim▁end|>
if not self.page.has_next(): return self.page.number return self.page.next_page_number()
<|file_name|>pagination.py<|end_file_name|><|fim▁begin|>from collections import OrderedDict from rest_framework import pagination from rest_framework.response import Response __author__ = 'alexandreferreira' class DetailPagination(pagination.PageNumberPagination): def get_paginated_response(self, data): return Response(OrderedDict([ ('count', self.page.paginator.count), ('next', self.get_next_page_number()), ('has_next', self.page.has_next()), ('previous', self.get_previous_page_number()), ('has_previous', self.page.has_previous()), ('current', self.page.number), ('results', data) ])) def get_next_page_number(self): if not self.page.has_next(): return self.page.number return self.page.next_page_number() def get_previous_page_number(self): <|fim_middle|> <|fim▁end|>
if not self.page.has_previous(): return 1 return self.page.previous_page_number()
<|file_name|>pagination.py<|end_file_name|><|fim▁begin|>from collections import OrderedDict from rest_framework import pagination from rest_framework.response import Response __author__ = 'alexandreferreira' class DetailPagination(pagination.PageNumberPagination): def get_paginated_response(self, data): return Response(OrderedDict([ ('count', self.page.paginator.count), ('next', self.get_next_page_number()), ('has_next', self.page.has_next()), ('previous', self.get_previous_page_number()), ('has_previous', self.page.has_previous()), ('current', self.page.number), ('results', data) ])) def get_next_page_number(self): if not self.page.has_next(): <|fim_middle|> return self.page.next_page_number() def get_previous_page_number(self): if not self.page.has_previous(): return 1 return self.page.previous_page_number()<|fim▁end|>
return self.page.number
<|file_name|>pagination.py<|end_file_name|><|fim▁begin|>from collections import OrderedDict from rest_framework import pagination from rest_framework.response import Response __author__ = 'alexandreferreira' class DetailPagination(pagination.PageNumberPagination): def get_paginated_response(self, data): return Response(OrderedDict([ ('count', self.page.paginator.count), ('next', self.get_next_page_number()), ('has_next', self.page.has_next()), ('previous', self.get_previous_page_number()), ('has_previous', self.page.has_previous()), ('current', self.page.number), ('results', data) ])) def get_next_page_number(self): if not self.page.has_next(): return self.page.number return self.page.next_page_number() def get_previous_page_number(self): if not self.page.has_previous(): <|fim_middle|> return self.page.previous_page_number()<|fim▁end|>
return 1
<|file_name|>pagination.py<|end_file_name|><|fim▁begin|>from collections import OrderedDict from rest_framework import pagination from rest_framework.response import Response __author__ = 'alexandreferreira' class DetailPagination(pagination.PageNumberPagination): def <|fim_middle|>(self, data): return Response(OrderedDict([ ('count', self.page.paginator.count), ('next', self.get_next_page_number()), ('has_next', self.page.has_next()), ('previous', self.get_previous_page_number()), ('has_previous', self.page.has_previous()), ('current', self.page.number), ('results', data) ])) def get_next_page_number(self): if not self.page.has_next(): return self.page.number return self.page.next_page_number() def get_previous_page_number(self): if not self.page.has_previous(): return 1 return self.page.previous_page_number()<|fim▁end|>
get_paginated_response
<|file_name|>pagination.py<|end_file_name|><|fim▁begin|>from collections import OrderedDict from rest_framework import pagination from rest_framework.response import Response __author__ = 'alexandreferreira' class DetailPagination(pagination.PageNumberPagination): def get_paginated_response(self, data): return Response(OrderedDict([ ('count', self.page.paginator.count), ('next', self.get_next_page_number()), ('has_next', self.page.has_next()), ('previous', self.get_previous_page_number()), ('has_previous', self.page.has_previous()), ('current', self.page.number), ('results', data) ])) def <|fim_middle|>(self): if not self.page.has_next(): return self.page.number return self.page.next_page_number() def get_previous_page_number(self): if not self.page.has_previous(): return 1 return self.page.previous_page_number()<|fim▁end|>
get_next_page_number
<|file_name|>pagination.py<|end_file_name|><|fim▁begin|>from collections import OrderedDict from rest_framework import pagination from rest_framework.response import Response __author__ = 'alexandreferreira' class DetailPagination(pagination.PageNumberPagination): def get_paginated_response(self, data): return Response(OrderedDict([ ('count', self.page.paginator.count), ('next', self.get_next_page_number()), ('has_next', self.page.has_next()), ('previous', self.get_previous_page_number()), ('has_previous', self.page.has_previous()), ('current', self.page.number), ('results', data) ])) def get_next_page_number(self): if not self.page.has_next(): return self.page.number return self.page.next_page_number() def <|fim_middle|>(self): if not self.page.has_previous(): return 1 return self.page.previous_page_number()<|fim▁end|>
get_previous_page_number
<|file_name|>largestRectangleArea.py<|end_file_name|><|fim▁begin|>class Solution: # @param {integer[]} height # @return {integer} def largestRectangleArea(self, height): n = len(height) ma = 0 stack = [-1] for i in xrange(n): while(stack[-1] > -1):<|fim▁hole|> else: break stack.append(i) while(stack[-1] != -1): top = stack.pop() ma = max(ma, height[top]*(n-1-stack[-1])) return ma<|fim▁end|>
if height[i]<height[stack[-1]]: top = stack.pop() ma = max(ma, height[top]*(i-1-stack[-1]))
<|file_name|>largestRectangleArea.py<|end_file_name|><|fim▁begin|>class Solution: # @param {integer[]} height # @return {integer} <|fim_middle|> <|fim▁end|>
def largestRectangleArea(self, height): n = len(height) ma = 0 stack = [-1] for i in xrange(n): while(stack[-1] > -1): if height[i]<height[stack[-1]]: top = stack.pop() ma = max(ma, height[top]*(i-1-stack[-1])) else: break stack.append(i) while(stack[-1] != -1): top = stack.pop() ma = max(ma, height[top]*(n-1-stack[-1])) return ma
<|file_name|>largestRectangleArea.py<|end_file_name|><|fim▁begin|>class Solution: # @param {integer[]} height # @return {integer} def largestRectangleArea(self, height): <|fim_middle|> <|fim▁end|>
n = len(height) ma = 0 stack = [-1] for i in xrange(n): while(stack[-1] > -1): if height[i]<height[stack[-1]]: top = stack.pop() ma = max(ma, height[top]*(i-1-stack[-1])) else: break stack.append(i) while(stack[-1] != -1): top = stack.pop() ma = max(ma, height[top]*(n-1-stack[-1])) return ma
<|file_name|>largestRectangleArea.py<|end_file_name|><|fim▁begin|>class Solution: # @param {integer[]} height # @return {integer} def largestRectangleArea(self, height): n = len(height) ma = 0 stack = [-1] for i in xrange(n): while(stack[-1] > -1): if height[i]<height[stack[-1]]: <|fim_middle|> else: break stack.append(i) while(stack[-1] != -1): top = stack.pop() ma = max(ma, height[top]*(n-1-stack[-1])) return ma<|fim▁end|>
top = stack.pop() ma = max(ma, height[top]*(i-1-stack[-1]))
<|file_name|>largestRectangleArea.py<|end_file_name|><|fim▁begin|>class Solution: # @param {integer[]} height # @return {integer} def largestRectangleArea(self, height): n = len(height) ma = 0 stack = [-1] for i in xrange(n): while(stack[-1] > -1): if height[i]<height[stack[-1]]: top = stack.pop() ma = max(ma, height[top]*(i-1-stack[-1])) else: <|fim_middle|> stack.append(i) while(stack[-1] != -1): top = stack.pop() ma = max(ma, height[top]*(n-1-stack[-1])) return ma<|fim▁end|>
break
<|file_name|>largestRectangleArea.py<|end_file_name|><|fim▁begin|>class Solution: # @param {integer[]} height # @return {integer} def <|fim_middle|>(self, height): n = len(height) ma = 0 stack = [-1] for i in xrange(n): while(stack[-1] > -1): if height[i]<height[stack[-1]]: top = stack.pop() ma = max(ma, height[top]*(i-1-stack[-1])) else: break stack.append(i) while(stack[-1] != -1): top = stack.pop() ma = max(ma, height[top]*(n-1-stack[-1])) return ma<|fim▁end|>
largestRectangleArea
<|file_name|>app.py<|end_file_name|><|fim▁begin|>""" Copyright 2014 Jason Heeris, [email protected] This file is part of the dungeon excavator web interface ("webcavate"). Webcavate is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Webcavate is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with webcavate. If not, see <http://www.gnu.org/licenses/>. """ import argparse import uuid from flask import Flask, render_template, request, make_response, redirect, url_for, flash from dungeon.excavate import render_room HELP_TEXT = """\ Web interface to the dungeon excavator.""" app = Flask('dungeon.web') app.secret_key = str(uuid.uuid4()) @app.route("/") def root(): """ Web interface landing page. """ return render_template('index.html') @app.route("/error") def error(): """ Display errors. """ return render_template('error.html') def make_map(request, format):<|fim▁hole|> try: room_data, content_type = render_room( floor_file.read(), wall_file.read(), floorplan_file.read(), tile_size, format ) except ValueError as ve: flash(str(ve)) return redirect(url_for('error')) # Create response response = make_response(room_data) response.headers['Content-Type'] = content_type return response @app.route("/map.svg", methods=['POST']) def map_svg(): return make_map(request, format='svg') @app.route("/map.png", methods=['POST']) def map_png(): return make_map(request, format='png') @app.route("/map.jpg", methods=['POST']) def map_jpg(): return make_map(request, format='jpg') @app.route("/map", methods=['POST']) def process(): """ Process submitted form data. """ format = request.form['format'] try: node = { 'png': 'map_png', 'svg': 'map_svg', 'jpg': 'map_jpg', }[format] except KeyError: flash("The output format you selected is not supported.") return redirect(url_for('error')) else: return redirect(url_for(node, _method='POST'), code=307) def main(): """ Parse arguments and get things going for the web interface """ parser = argparse.ArgumentParser(description=HELP_TEXT) parser.add_argument( '-p', '--port', help="Port to serve the interface on.", type=int, default=5050 ) parser.add_argument( '-a', '--host', help="Host to server the interface on.", ) args = parser.parse_args() app.run(port=args.port, host=args.host, debug=False)<|fim▁end|>
tile_size = int(request.form['size']) wall_file = request.files['walls'] floor_file = request.files['floor'] floorplan_file = request.files['floorplan']
<|file_name|>app.py<|end_file_name|><|fim▁begin|>""" Copyright 2014 Jason Heeris, [email protected] This file is part of the dungeon excavator web interface ("webcavate"). Webcavate is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Webcavate is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with webcavate. If not, see <http://www.gnu.org/licenses/>. """ import argparse import uuid from flask import Flask, render_template, request, make_response, redirect, url_for, flash from dungeon.excavate import render_room HELP_TEXT = """\ Web interface to the dungeon excavator.""" app = Flask('dungeon.web') app.secret_key = str(uuid.uuid4()) @app.route("/") def root(): <|fim_middle|> @app.route("/error") def error(): """ Display errors. """ return render_template('error.html') def make_map(request, format): tile_size = int(request.form['size']) wall_file = request.files['walls'] floor_file = request.files['floor'] floorplan_file = request.files['floorplan'] try: room_data, content_type = render_room( floor_file.read(), wall_file.read(), floorplan_file.read(), tile_size, format ) except ValueError as ve: flash(str(ve)) return redirect(url_for('error')) # Create response response = make_response(room_data) response.headers['Content-Type'] = content_type return response @app.route("/map.svg", methods=['POST']) def map_svg(): return make_map(request, format='svg') @app.route("/map.png", methods=['POST']) def map_png(): return make_map(request, format='png') @app.route("/map.jpg", methods=['POST']) def map_jpg(): return make_map(request, format='jpg') @app.route("/map", methods=['POST']) def process(): """ Process submitted form data. """ format = request.form['format'] try: node = { 'png': 'map_png', 'svg': 'map_svg', 'jpg': 'map_jpg', }[format] except KeyError: flash("The output format you selected is not supported.") return redirect(url_for('error')) else: return redirect(url_for(node, _method='POST'), code=307) def main(): """ Parse arguments and get things going for the web interface """ parser = argparse.ArgumentParser(description=HELP_TEXT) parser.add_argument( '-p', '--port', help="Port to serve the interface on.", type=int, default=5050 ) parser.add_argument( '-a', '--host', help="Host to server the interface on.", ) args = parser.parse_args() app.run(port=args.port, host=args.host, debug=False) <|fim▁end|>
""" Web interface landing page. """ return render_template('index.html')
<|file_name|>app.py<|end_file_name|><|fim▁begin|>""" Copyright 2014 Jason Heeris, [email protected] This file is part of the dungeon excavator web interface ("webcavate"). Webcavate is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Webcavate is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with webcavate. If not, see <http://www.gnu.org/licenses/>. """ import argparse import uuid from flask import Flask, render_template, request, make_response, redirect, url_for, flash from dungeon.excavate import render_room HELP_TEXT = """\ Web interface to the dungeon excavator.""" app = Flask('dungeon.web') app.secret_key = str(uuid.uuid4()) @app.route("/") def root(): """ Web interface landing page. """ return render_template('index.html') @app.route("/error") def error(): <|fim_middle|> def make_map(request, format): tile_size = int(request.form['size']) wall_file = request.files['walls'] floor_file = request.files['floor'] floorplan_file = request.files['floorplan'] try: room_data, content_type = render_room( floor_file.read(), wall_file.read(), floorplan_file.read(), tile_size, format ) except ValueError as ve: flash(str(ve)) return redirect(url_for('error')) # Create response response = make_response(room_data) response.headers['Content-Type'] = content_type return response @app.route("/map.svg", methods=['POST']) def map_svg(): return make_map(request, format='svg') @app.route("/map.png", methods=['POST']) def map_png(): return make_map(request, format='png') @app.route("/map.jpg", methods=['POST']) def map_jpg(): return make_map(request, format='jpg') @app.route("/map", methods=['POST']) def process(): """ Process submitted form data. """ format = request.form['format'] try: node = { 'png': 'map_png', 'svg': 'map_svg', 'jpg': 'map_jpg', }[format] except KeyError: flash("The output format you selected is not supported.") return redirect(url_for('error')) else: return redirect(url_for(node, _method='POST'), code=307) def main(): """ Parse arguments and get things going for the web interface """ parser = argparse.ArgumentParser(description=HELP_TEXT) parser.add_argument( '-p', '--port', help="Port to serve the interface on.", type=int, default=5050 ) parser.add_argument( '-a', '--host', help="Host to server the interface on.", ) args = parser.parse_args() app.run(port=args.port, host=args.host, debug=False) <|fim▁end|>
""" Display errors. """ return render_template('error.html')
<|file_name|>app.py<|end_file_name|><|fim▁begin|>""" Copyright 2014 Jason Heeris, [email protected] This file is part of the dungeon excavator web interface ("webcavate"). Webcavate is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Webcavate is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with webcavate. If not, see <http://www.gnu.org/licenses/>. """ import argparse import uuid from flask import Flask, render_template, request, make_response, redirect, url_for, flash from dungeon.excavate import render_room HELP_TEXT = """\ Web interface to the dungeon excavator.""" app = Flask('dungeon.web') app.secret_key = str(uuid.uuid4()) @app.route("/") def root(): """ Web interface landing page. """ return render_template('index.html') @app.route("/error") def error(): """ Display errors. """ return render_template('error.html') def make_map(request, format): <|fim_middle|> @app.route("/map.svg", methods=['POST']) def map_svg(): return make_map(request, format='svg') @app.route("/map.png", methods=['POST']) def map_png(): return make_map(request, format='png') @app.route("/map.jpg", methods=['POST']) def map_jpg(): return make_map(request, format='jpg') @app.route("/map", methods=['POST']) def process(): """ Process submitted form data. """ format = request.form['format'] try: node = { 'png': 'map_png', 'svg': 'map_svg', 'jpg': 'map_jpg', }[format] except KeyError: flash("The output format you selected is not supported.") return redirect(url_for('error')) else: return redirect(url_for(node, _method='POST'), code=307) def main(): """ Parse arguments and get things going for the web interface """ parser = argparse.ArgumentParser(description=HELP_TEXT) parser.add_argument( '-p', '--port', help="Port to serve the interface on.", type=int, default=5050 ) parser.add_argument( '-a', '--host', help="Host to server the interface on.", ) args = parser.parse_args() app.run(port=args.port, host=args.host, debug=False) <|fim▁end|>
tile_size = int(request.form['size']) wall_file = request.files['walls'] floor_file = request.files['floor'] floorplan_file = request.files['floorplan'] try: room_data, content_type = render_room( floor_file.read(), wall_file.read(), floorplan_file.read(), tile_size, format ) except ValueError as ve: flash(str(ve)) return redirect(url_for('error')) # Create response response = make_response(room_data) response.headers['Content-Type'] = content_type return response
<|file_name|>app.py<|end_file_name|><|fim▁begin|>""" Copyright 2014 Jason Heeris, [email protected] This file is part of the dungeon excavator web interface ("webcavate"). Webcavate is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Webcavate is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with webcavate. If not, see <http://www.gnu.org/licenses/>. """ import argparse import uuid from flask import Flask, render_template, request, make_response, redirect, url_for, flash from dungeon.excavate import render_room HELP_TEXT = """\ Web interface to the dungeon excavator.""" app = Flask('dungeon.web') app.secret_key = str(uuid.uuid4()) @app.route("/") def root(): """ Web interface landing page. """ return render_template('index.html') @app.route("/error") def error(): """ Display errors. """ return render_template('error.html') def make_map(request, format): tile_size = int(request.form['size']) wall_file = request.files['walls'] floor_file = request.files['floor'] floorplan_file = request.files['floorplan'] try: room_data, content_type = render_room( floor_file.read(), wall_file.read(), floorplan_file.read(), tile_size, format ) except ValueError as ve: flash(str(ve)) return redirect(url_for('error')) # Create response response = make_response(room_data) response.headers['Content-Type'] = content_type return response @app.route("/map.svg", methods=['POST']) def map_svg(): <|fim_middle|> @app.route("/map.png", methods=['POST']) def map_png(): return make_map(request, format='png') @app.route("/map.jpg", methods=['POST']) def map_jpg(): return make_map(request, format='jpg') @app.route("/map", methods=['POST']) def process(): """ Process submitted form data. """ format = request.form['format'] try: node = { 'png': 'map_png', 'svg': 'map_svg', 'jpg': 'map_jpg', }[format] except KeyError: flash("The output format you selected is not supported.") return redirect(url_for('error')) else: return redirect(url_for(node, _method='POST'), code=307) def main(): """ Parse arguments and get things going for the web interface """ parser = argparse.ArgumentParser(description=HELP_TEXT) parser.add_argument( '-p', '--port', help="Port to serve the interface on.", type=int, default=5050 ) parser.add_argument( '-a', '--host', help="Host to server the interface on.", ) args = parser.parse_args() app.run(port=args.port, host=args.host, debug=False) <|fim▁end|>
return make_map(request, format='svg')
<|file_name|>app.py<|end_file_name|><|fim▁begin|>""" Copyright 2014 Jason Heeris, [email protected] This file is part of the dungeon excavator web interface ("webcavate"). Webcavate is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Webcavate is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with webcavate. If not, see <http://www.gnu.org/licenses/>. """ import argparse import uuid from flask import Flask, render_template, request, make_response, redirect, url_for, flash from dungeon.excavate import render_room HELP_TEXT = """\ Web interface to the dungeon excavator.""" app = Flask('dungeon.web') app.secret_key = str(uuid.uuid4()) @app.route("/") def root(): """ Web interface landing page. """ return render_template('index.html') @app.route("/error") def error(): """ Display errors. """ return render_template('error.html') def make_map(request, format): tile_size = int(request.form['size']) wall_file = request.files['walls'] floor_file = request.files['floor'] floorplan_file = request.files['floorplan'] try: room_data, content_type = render_room( floor_file.read(), wall_file.read(), floorplan_file.read(), tile_size, format ) except ValueError as ve: flash(str(ve)) return redirect(url_for('error')) # Create response response = make_response(room_data) response.headers['Content-Type'] = content_type return response @app.route("/map.svg", methods=['POST']) def map_svg(): return make_map(request, format='svg') @app.route("/map.png", methods=['POST']) def map_png(): <|fim_middle|> @app.route("/map.jpg", methods=['POST']) def map_jpg(): return make_map(request, format='jpg') @app.route("/map", methods=['POST']) def process(): """ Process submitted form data. """ format = request.form['format'] try: node = { 'png': 'map_png', 'svg': 'map_svg', 'jpg': 'map_jpg', }[format] except KeyError: flash("The output format you selected is not supported.") return redirect(url_for('error')) else: return redirect(url_for(node, _method='POST'), code=307) def main(): """ Parse arguments and get things going for the web interface """ parser = argparse.ArgumentParser(description=HELP_TEXT) parser.add_argument( '-p', '--port', help="Port to serve the interface on.", type=int, default=5050 ) parser.add_argument( '-a', '--host', help="Host to server the interface on.", ) args = parser.parse_args() app.run(port=args.port, host=args.host, debug=False) <|fim▁end|>
return make_map(request, format='png')
<|file_name|>app.py<|end_file_name|><|fim▁begin|>""" Copyright 2014 Jason Heeris, [email protected] This file is part of the dungeon excavator web interface ("webcavate"). Webcavate is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Webcavate is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with webcavate. If not, see <http://www.gnu.org/licenses/>. """ import argparse import uuid from flask import Flask, render_template, request, make_response, redirect, url_for, flash from dungeon.excavate import render_room HELP_TEXT = """\ Web interface to the dungeon excavator.""" app = Flask('dungeon.web') app.secret_key = str(uuid.uuid4()) @app.route("/") def root(): """ Web interface landing page. """ return render_template('index.html') @app.route("/error") def error(): """ Display errors. """ return render_template('error.html') def make_map(request, format): tile_size = int(request.form['size']) wall_file = request.files['walls'] floor_file = request.files['floor'] floorplan_file = request.files['floorplan'] try: room_data, content_type = render_room( floor_file.read(), wall_file.read(), floorplan_file.read(), tile_size, format ) except ValueError as ve: flash(str(ve)) return redirect(url_for('error')) # Create response response = make_response(room_data) response.headers['Content-Type'] = content_type return response @app.route("/map.svg", methods=['POST']) def map_svg(): return make_map(request, format='svg') @app.route("/map.png", methods=['POST']) def map_png(): return make_map(request, format='png') @app.route("/map.jpg", methods=['POST']) def map_jpg(): <|fim_middle|> @app.route("/map", methods=['POST']) def process(): """ Process submitted form data. """ format = request.form['format'] try: node = { 'png': 'map_png', 'svg': 'map_svg', 'jpg': 'map_jpg', }[format] except KeyError: flash("The output format you selected is not supported.") return redirect(url_for('error')) else: return redirect(url_for(node, _method='POST'), code=307) def main(): """ Parse arguments and get things going for the web interface """ parser = argparse.ArgumentParser(description=HELP_TEXT) parser.add_argument( '-p', '--port', help="Port to serve the interface on.", type=int, default=5050 ) parser.add_argument( '-a', '--host', help="Host to server the interface on.", ) args = parser.parse_args() app.run(port=args.port, host=args.host, debug=False) <|fim▁end|>
return make_map(request, format='jpg')
<|file_name|>app.py<|end_file_name|><|fim▁begin|>""" Copyright 2014 Jason Heeris, [email protected] This file is part of the dungeon excavator web interface ("webcavate"). Webcavate is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Webcavate is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with webcavate. If not, see <http://www.gnu.org/licenses/>. """ import argparse import uuid from flask import Flask, render_template, request, make_response, redirect, url_for, flash from dungeon.excavate import render_room HELP_TEXT = """\ Web interface to the dungeon excavator.""" app = Flask('dungeon.web') app.secret_key = str(uuid.uuid4()) @app.route("/") def root(): """ Web interface landing page. """ return render_template('index.html') @app.route("/error") def error(): """ Display errors. """ return render_template('error.html') def make_map(request, format): tile_size = int(request.form['size']) wall_file = request.files['walls'] floor_file = request.files['floor'] floorplan_file = request.files['floorplan'] try: room_data, content_type = render_room( floor_file.read(), wall_file.read(), floorplan_file.read(), tile_size, format ) except ValueError as ve: flash(str(ve)) return redirect(url_for('error')) # Create response response = make_response(room_data) response.headers['Content-Type'] = content_type return response @app.route("/map.svg", methods=['POST']) def map_svg(): return make_map(request, format='svg') @app.route("/map.png", methods=['POST']) def map_png(): return make_map(request, format='png') @app.route("/map.jpg", methods=['POST']) def map_jpg(): return make_map(request, format='jpg') @app.route("/map", methods=['POST']) def process(): <|fim_middle|> def main(): """ Parse arguments and get things going for the web interface """ parser = argparse.ArgumentParser(description=HELP_TEXT) parser.add_argument( '-p', '--port', help="Port to serve the interface on.", type=int, default=5050 ) parser.add_argument( '-a', '--host', help="Host to server the interface on.", ) args = parser.parse_args() app.run(port=args.port, host=args.host, debug=False) <|fim▁end|>
""" Process submitted form data. """ format = request.form['format'] try: node = { 'png': 'map_png', 'svg': 'map_svg', 'jpg': 'map_jpg', }[format] except KeyError: flash("The output format you selected is not supported.") return redirect(url_for('error')) else: return redirect(url_for(node, _method='POST'), code=307)
<|file_name|>app.py<|end_file_name|><|fim▁begin|>""" Copyright 2014 Jason Heeris, [email protected] This file is part of the dungeon excavator web interface ("webcavate"). Webcavate is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Webcavate is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with webcavate. If not, see <http://www.gnu.org/licenses/>. """ import argparse import uuid from flask import Flask, render_template, request, make_response, redirect, url_for, flash from dungeon.excavate import render_room HELP_TEXT = """\ Web interface to the dungeon excavator.""" app = Flask('dungeon.web') app.secret_key = str(uuid.uuid4()) @app.route("/") def root(): """ Web interface landing page. """ return render_template('index.html') @app.route("/error") def error(): """ Display errors. """ return render_template('error.html') def make_map(request, format): tile_size = int(request.form['size']) wall_file = request.files['walls'] floor_file = request.files['floor'] floorplan_file = request.files['floorplan'] try: room_data, content_type = render_room( floor_file.read(), wall_file.read(), floorplan_file.read(), tile_size, format ) except ValueError as ve: flash(str(ve)) return redirect(url_for('error')) # Create response response = make_response(room_data) response.headers['Content-Type'] = content_type return response @app.route("/map.svg", methods=['POST']) def map_svg(): return make_map(request, format='svg') @app.route("/map.png", methods=['POST']) def map_png(): return make_map(request, format='png') @app.route("/map.jpg", methods=['POST']) def map_jpg(): return make_map(request, format='jpg') @app.route("/map", methods=['POST']) def process(): """ Process submitted form data. """ format = request.form['format'] try: node = { 'png': 'map_png', 'svg': 'map_svg', 'jpg': 'map_jpg', }[format] except KeyError: flash("The output format you selected is not supported.") return redirect(url_for('error')) else: return redirect(url_for(node, _method='POST'), code=307) def main(): <|fim_middle|> <|fim▁end|>
""" Parse arguments and get things going for the web interface """ parser = argparse.ArgumentParser(description=HELP_TEXT) parser.add_argument( '-p', '--port', help="Port to serve the interface on.", type=int, default=5050 ) parser.add_argument( '-a', '--host', help="Host to server the interface on.", ) args = parser.parse_args() app.run(port=args.port, host=args.host, debug=False)
<|file_name|>app.py<|end_file_name|><|fim▁begin|>""" Copyright 2014 Jason Heeris, [email protected] This file is part of the dungeon excavator web interface ("webcavate"). Webcavate is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Webcavate is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with webcavate. If not, see <http://www.gnu.org/licenses/>. """ import argparse import uuid from flask import Flask, render_template, request, make_response, redirect, url_for, flash from dungeon.excavate import render_room HELP_TEXT = """\ Web interface to the dungeon excavator.""" app = Flask('dungeon.web') app.secret_key = str(uuid.uuid4()) @app.route("/") def root(): """ Web interface landing page. """ return render_template('index.html') @app.route("/error") def error(): """ Display errors. """ return render_template('error.html') def make_map(request, format): tile_size = int(request.form['size']) wall_file = request.files['walls'] floor_file = request.files['floor'] floorplan_file = request.files['floorplan'] try: room_data, content_type = render_room( floor_file.read(), wall_file.read(), floorplan_file.read(), tile_size, format ) except ValueError as ve: flash(str(ve)) return redirect(url_for('error')) # Create response response = make_response(room_data) response.headers['Content-Type'] = content_type return response @app.route("/map.svg", methods=['POST']) def map_svg(): return make_map(request, format='svg') @app.route("/map.png", methods=['POST']) def map_png(): return make_map(request, format='png') @app.route("/map.jpg", methods=['POST']) def map_jpg(): return make_map(request, format='jpg') @app.route("/map", methods=['POST']) def process(): """ Process submitted form data. """ format = request.form['format'] try: node = { 'png': 'map_png', 'svg': 'map_svg', 'jpg': 'map_jpg', }[format] except KeyError: flash("The output format you selected is not supported.") return redirect(url_for('error')) else: <|fim_middle|> def main(): """ Parse arguments and get things going for the web interface """ parser = argparse.ArgumentParser(description=HELP_TEXT) parser.add_argument( '-p', '--port', help="Port to serve the interface on.", type=int, default=5050 ) parser.add_argument( '-a', '--host', help="Host to server the interface on.", ) args = parser.parse_args() app.run(port=args.port, host=args.host, debug=False) <|fim▁end|>
return redirect(url_for(node, _method='POST'), code=307)
<|file_name|>app.py<|end_file_name|><|fim▁begin|>""" Copyright 2014 Jason Heeris, [email protected] This file is part of the dungeon excavator web interface ("webcavate"). Webcavate is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Webcavate is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with webcavate. If not, see <http://www.gnu.org/licenses/>. """ import argparse import uuid from flask import Flask, render_template, request, make_response, redirect, url_for, flash from dungeon.excavate import render_room HELP_TEXT = """\ Web interface to the dungeon excavator.""" app = Flask('dungeon.web') app.secret_key = str(uuid.uuid4()) @app.route("/") def <|fim_middle|>(): """ Web interface landing page. """ return render_template('index.html') @app.route("/error") def error(): """ Display errors. """ return render_template('error.html') def make_map(request, format): tile_size = int(request.form['size']) wall_file = request.files['walls'] floor_file = request.files['floor'] floorplan_file = request.files['floorplan'] try: room_data, content_type = render_room( floor_file.read(), wall_file.read(), floorplan_file.read(), tile_size, format ) except ValueError as ve: flash(str(ve)) return redirect(url_for('error')) # Create response response = make_response(room_data) response.headers['Content-Type'] = content_type return response @app.route("/map.svg", methods=['POST']) def map_svg(): return make_map(request, format='svg') @app.route("/map.png", methods=['POST']) def map_png(): return make_map(request, format='png') @app.route("/map.jpg", methods=['POST']) def map_jpg(): return make_map(request, format='jpg') @app.route("/map", methods=['POST']) def process(): """ Process submitted form data. """ format = request.form['format'] try: node = { 'png': 'map_png', 'svg': 'map_svg', 'jpg': 'map_jpg', }[format] except KeyError: flash("The output format you selected is not supported.") return redirect(url_for('error')) else: return redirect(url_for(node, _method='POST'), code=307) def main(): """ Parse arguments and get things going for the web interface """ parser = argparse.ArgumentParser(description=HELP_TEXT) parser.add_argument( '-p', '--port', help="Port to serve the interface on.", type=int, default=5050 ) parser.add_argument( '-a', '--host', help="Host to server the interface on.", ) args = parser.parse_args() app.run(port=args.port, host=args.host, debug=False) <|fim▁end|>
root
<|file_name|>app.py<|end_file_name|><|fim▁begin|>""" Copyright 2014 Jason Heeris, [email protected] This file is part of the dungeon excavator web interface ("webcavate"). Webcavate is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Webcavate is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with webcavate. If not, see <http://www.gnu.org/licenses/>. """ import argparse import uuid from flask import Flask, render_template, request, make_response, redirect, url_for, flash from dungeon.excavate import render_room HELP_TEXT = """\ Web interface to the dungeon excavator.""" app = Flask('dungeon.web') app.secret_key = str(uuid.uuid4()) @app.route("/") def root(): """ Web interface landing page. """ return render_template('index.html') @app.route("/error") def <|fim_middle|>(): """ Display errors. """ return render_template('error.html') def make_map(request, format): tile_size = int(request.form['size']) wall_file = request.files['walls'] floor_file = request.files['floor'] floorplan_file = request.files['floorplan'] try: room_data, content_type = render_room( floor_file.read(), wall_file.read(), floorplan_file.read(), tile_size, format ) except ValueError as ve: flash(str(ve)) return redirect(url_for('error')) # Create response response = make_response(room_data) response.headers['Content-Type'] = content_type return response @app.route("/map.svg", methods=['POST']) def map_svg(): return make_map(request, format='svg') @app.route("/map.png", methods=['POST']) def map_png(): return make_map(request, format='png') @app.route("/map.jpg", methods=['POST']) def map_jpg(): return make_map(request, format='jpg') @app.route("/map", methods=['POST']) def process(): """ Process submitted form data. """ format = request.form['format'] try: node = { 'png': 'map_png', 'svg': 'map_svg', 'jpg': 'map_jpg', }[format] except KeyError: flash("The output format you selected is not supported.") return redirect(url_for('error')) else: return redirect(url_for(node, _method='POST'), code=307) def main(): """ Parse arguments and get things going for the web interface """ parser = argparse.ArgumentParser(description=HELP_TEXT) parser.add_argument( '-p', '--port', help="Port to serve the interface on.", type=int, default=5050 ) parser.add_argument( '-a', '--host', help="Host to server the interface on.", ) args = parser.parse_args() app.run(port=args.port, host=args.host, debug=False) <|fim▁end|>
error
<|file_name|>app.py<|end_file_name|><|fim▁begin|>""" Copyright 2014 Jason Heeris, [email protected] This file is part of the dungeon excavator web interface ("webcavate"). Webcavate is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Webcavate is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with webcavate. If not, see <http://www.gnu.org/licenses/>. """ import argparse import uuid from flask import Flask, render_template, request, make_response, redirect, url_for, flash from dungeon.excavate import render_room HELP_TEXT = """\ Web interface to the dungeon excavator.""" app = Flask('dungeon.web') app.secret_key = str(uuid.uuid4()) @app.route("/") def root(): """ Web interface landing page. """ return render_template('index.html') @app.route("/error") def error(): """ Display errors. """ return render_template('error.html') def <|fim_middle|>(request, format): tile_size = int(request.form['size']) wall_file = request.files['walls'] floor_file = request.files['floor'] floorplan_file = request.files['floorplan'] try: room_data, content_type = render_room( floor_file.read(), wall_file.read(), floorplan_file.read(), tile_size, format ) except ValueError as ve: flash(str(ve)) return redirect(url_for('error')) # Create response response = make_response(room_data) response.headers['Content-Type'] = content_type return response @app.route("/map.svg", methods=['POST']) def map_svg(): return make_map(request, format='svg') @app.route("/map.png", methods=['POST']) def map_png(): return make_map(request, format='png') @app.route("/map.jpg", methods=['POST']) def map_jpg(): return make_map(request, format='jpg') @app.route("/map", methods=['POST']) def process(): """ Process submitted form data. """ format = request.form['format'] try: node = { 'png': 'map_png', 'svg': 'map_svg', 'jpg': 'map_jpg', }[format] except KeyError: flash("The output format you selected is not supported.") return redirect(url_for('error')) else: return redirect(url_for(node, _method='POST'), code=307) def main(): """ Parse arguments and get things going for the web interface """ parser = argparse.ArgumentParser(description=HELP_TEXT) parser.add_argument( '-p', '--port', help="Port to serve the interface on.", type=int, default=5050 ) parser.add_argument( '-a', '--host', help="Host to server the interface on.", ) args = parser.parse_args() app.run(port=args.port, host=args.host, debug=False) <|fim▁end|>
make_map
<|file_name|>app.py<|end_file_name|><|fim▁begin|>""" Copyright 2014 Jason Heeris, [email protected] This file is part of the dungeon excavator web interface ("webcavate"). Webcavate is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Webcavate is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with webcavate. If not, see <http://www.gnu.org/licenses/>. """ import argparse import uuid from flask import Flask, render_template, request, make_response, redirect, url_for, flash from dungeon.excavate import render_room HELP_TEXT = """\ Web interface to the dungeon excavator.""" app = Flask('dungeon.web') app.secret_key = str(uuid.uuid4()) @app.route("/") def root(): """ Web interface landing page. """ return render_template('index.html') @app.route("/error") def error(): """ Display errors. """ return render_template('error.html') def make_map(request, format): tile_size = int(request.form['size']) wall_file = request.files['walls'] floor_file = request.files['floor'] floorplan_file = request.files['floorplan'] try: room_data, content_type = render_room( floor_file.read(), wall_file.read(), floorplan_file.read(), tile_size, format ) except ValueError as ve: flash(str(ve)) return redirect(url_for('error')) # Create response response = make_response(room_data) response.headers['Content-Type'] = content_type return response @app.route("/map.svg", methods=['POST']) def <|fim_middle|>(): return make_map(request, format='svg') @app.route("/map.png", methods=['POST']) def map_png(): return make_map(request, format='png') @app.route("/map.jpg", methods=['POST']) def map_jpg(): return make_map(request, format='jpg') @app.route("/map", methods=['POST']) def process(): """ Process submitted form data. """ format = request.form['format'] try: node = { 'png': 'map_png', 'svg': 'map_svg', 'jpg': 'map_jpg', }[format] except KeyError: flash("The output format you selected is not supported.") return redirect(url_for('error')) else: return redirect(url_for(node, _method='POST'), code=307) def main(): """ Parse arguments and get things going for the web interface """ parser = argparse.ArgumentParser(description=HELP_TEXT) parser.add_argument( '-p', '--port', help="Port to serve the interface on.", type=int, default=5050 ) parser.add_argument( '-a', '--host', help="Host to server the interface on.", ) args = parser.parse_args() app.run(port=args.port, host=args.host, debug=False) <|fim▁end|>
map_svg
<|file_name|>app.py<|end_file_name|><|fim▁begin|>""" Copyright 2014 Jason Heeris, [email protected] This file is part of the dungeon excavator web interface ("webcavate"). Webcavate is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Webcavate is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with webcavate. If not, see <http://www.gnu.org/licenses/>. """ import argparse import uuid from flask import Flask, render_template, request, make_response, redirect, url_for, flash from dungeon.excavate import render_room HELP_TEXT = """\ Web interface to the dungeon excavator.""" app = Flask('dungeon.web') app.secret_key = str(uuid.uuid4()) @app.route("/") def root(): """ Web interface landing page. """ return render_template('index.html') @app.route("/error") def error(): """ Display errors. """ return render_template('error.html') def make_map(request, format): tile_size = int(request.form['size']) wall_file = request.files['walls'] floor_file = request.files['floor'] floorplan_file = request.files['floorplan'] try: room_data, content_type = render_room( floor_file.read(), wall_file.read(), floorplan_file.read(), tile_size, format ) except ValueError as ve: flash(str(ve)) return redirect(url_for('error')) # Create response response = make_response(room_data) response.headers['Content-Type'] = content_type return response @app.route("/map.svg", methods=['POST']) def map_svg(): return make_map(request, format='svg') @app.route("/map.png", methods=['POST']) def <|fim_middle|>(): return make_map(request, format='png') @app.route("/map.jpg", methods=['POST']) def map_jpg(): return make_map(request, format='jpg') @app.route("/map", methods=['POST']) def process(): """ Process submitted form data. """ format = request.form['format'] try: node = { 'png': 'map_png', 'svg': 'map_svg', 'jpg': 'map_jpg', }[format] except KeyError: flash("The output format you selected is not supported.") return redirect(url_for('error')) else: return redirect(url_for(node, _method='POST'), code=307) def main(): """ Parse arguments and get things going for the web interface """ parser = argparse.ArgumentParser(description=HELP_TEXT) parser.add_argument( '-p', '--port', help="Port to serve the interface on.", type=int, default=5050 ) parser.add_argument( '-a', '--host', help="Host to server the interface on.", ) args = parser.parse_args() app.run(port=args.port, host=args.host, debug=False) <|fim▁end|>
map_png
<|file_name|>app.py<|end_file_name|><|fim▁begin|>""" Copyright 2014 Jason Heeris, [email protected] This file is part of the dungeon excavator web interface ("webcavate"). Webcavate is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Webcavate is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with webcavate. If not, see <http://www.gnu.org/licenses/>. """ import argparse import uuid from flask import Flask, render_template, request, make_response, redirect, url_for, flash from dungeon.excavate import render_room HELP_TEXT = """\ Web interface to the dungeon excavator.""" app = Flask('dungeon.web') app.secret_key = str(uuid.uuid4()) @app.route("/") def root(): """ Web interface landing page. """ return render_template('index.html') @app.route("/error") def error(): """ Display errors. """ return render_template('error.html') def make_map(request, format): tile_size = int(request.form['size']) wall_file = request.files['walls'] floor_file = request.files['floor'] floorplan_file = request.files['floorplan'] try: room_data, content_type = render_room( floor_file.read(), wall_file.read(), floorplan_file.read(), tile_size, format ) except ValueError as ve: flash(str(ve)) return redirect(url_for('error')) # Create response response = make_response(room_data) response.headers['Content-Type'] = content_type return response @app.route("/map.svg", methods=['POST']) def map_svg(): return make_map(request, format='svg') @app.route("/map.png", methods=['POST']) def map_png(): return make_map(request, format='png') @app.route("/map.jpg", methods=['POST']) def <|fim_middle|>(): return make_map(request, format='jpg') @app.route("/map", methods=['POST']) def process(): """ Process submitted form data. """ format = request.form['format'] try: node = { 'png': 'map_png', 'svg': 'map_svg', 'jpg': 'map_jpg', }[format] except KeyError: flash("The output format you selected is not supported.") return redirect(url_for('error')) else: return redirect(url_for(node, _method='POST'), code=307) def main(): """ Parse arguments and get things going for the web interface """ parser = argparse.ArgumentParser(description=HELP_TEXT) parser.add_argument( '-p', '--port', help="Port to serve the interface on.", type=int, default=5050 ) parser.add_argument( '-a', '--host', help="Host to server the interface on.", ) args = parser.parse_args() app.run(port=args.port, host=args.host, debug=False) <|fim▁end|>
map_jpg
<|file_name|>app.py<|end_file_name|><|fim▁begin|>""" Copyright 2014 Jason Heeris, [email protected] This file is part of the dungeon excavator web interface ("webcavate"). Webcavate is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Webcavate is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with webcavate. If not, see <http://www.gnu.org/licenses/>. """ import argparse import uuid from flask import Flask, render_template, request, make_response, redirect, url_for, flash from dungeon.excavate import render_room HELP_TEXT = """\ Web interface to the dungeon excavator.""" app = Flask('dungeon.web') app.secret_key = str(uuid.uuid4()) @app.route("/") def root(): """ Web interface landing page. """ return render_template('index.html') @app.route("/error") def error(): """ Display errors. """ return render_template('error.html') def make_map(request, format): tile_size = int(request.form['size']) wall_file = request.files['walls'] floor_file = request.files['floor'] floorplan_file = request.files['floorplan'] try: room_data, content_type = render_room( floor_file.read(), wall_file.read(), floorplan_file.read(), tile_size, format ) except ValueError as ve: flash(str(ve)) return redirect(url_for('error')) # Create response response = make_response(room_data) response.headers['Content-Type'] = content_type return response @app.route("/map.svg", methods=['POST']) def map_svg(): return make_map(request, format='svg') @app.route("/map.png", methods=['POST']) def map_png(): return make_map(request, format='png') @app.route("/map.jpg", methods=['POST']) def map_jpg(): return make_map(request, format='jpg') @app.route("/map", methods=['POST']) def <|fim_middle|>(): """ Process submitted form data. """ format = request.form['format'] try: node = { 'png': 'map_png', 'svg': 'map_svg', 'jpg': 'map_jpg', }[format] except KeyError: flash("The output format you selected is not supported.") return redirect(url_for('error')) else: return redirect(url_for(node, _method='POST'), code=307) def main(): """ Parse arguments and get things going for the web interface """ parser = argparse.ArgumentParser(description=HELP_TEXT) parser.add_argument( '-p', '--port', help="Port to serve the interface on.", type=int, default=5050 ) parser.add_argument( '-a', '--host', help="Host to server the interface on.", ) args = parser.parse_args() app.run(port=args.port, host=args.host, debug=False) <|fim▁end|>
process
<|file_name|>app.py<|end_file_name|><|fim▁begin|>""" Copyright 2014 Jason Heeris, [email protected] This file is part of the dungeon excavator web interface ("webcavate"). Webcavate is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Webcavate is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with webcavate. If not, see <http://www.gnu.org/licenses/>. """ import argparse import uuid from flask import Flask, render_template, request, make_response, redirect, url_for, flash from dungeon.excavate import render_room HELP_TEXT = """\ Web interface to the dungeon excavator.""" app = Flask('dungeon.web') app.secret_key = str(uuid.uuid4()) @app.route("/") def root(): """ Web interface landing page. """ return render_template('index.html') @app.route("/error") def error(): """ Display errors. """ return render_template('error.html') def make_map(request, format): tile_size = int(request.form['size']) wall_file = request.files['walls'] floor_file = request.files['floor'] floorplan_file = request.files['floorplan'] try: room_data, content_type = render_room( floor_file.read(), wall_file.read(), floorplan_file.read(), tile_size, format ) except ValueError as ve: flash(str(ve)) return redirect(url_for('error')) # Create response response = make_response(room_data) response.headers['Content-Type'] = content_type return response @app.route("/map.svg", methods=['POST']) def map_svg(): return make_map(request, format='svg') @app.route("/map.png", methods=['POST']) def map_png(): return make_map(request, format='png') @app.route("/map.jpg", methods=['POST']) def map_jpg(): return make_map(request, format='jpg') @app.route("/map", methods=['POST']) def process(): """ Process submitted form data. """ format = request.form['format'] try: node = { 'png': 'map_png', 'svg': 'map_svg', 'jpg': 'map_jpg', }[format] except KeyError: flash("The output format you selected is not supported.") return redirect(url_for('error')) else: return redirect(url_for(node, _method='POST'), code=307) def <|fim_middle|>(): """ Parse arguments and get things going for the web interface """ parser = argparse.ArgumentParser(description=HELP_TEXT) parser.add_argument( '-p', '--port', help="Port to serve the interface on.", type=int, default=5050 ) parser.add_argument( '-a', '--host', help="Host to server the interface on.", ) args = parser.parse_args() app.run(port=args.port, host=args.host, debug=False) <|fim▁end|>
main
<|file_name|>context.py<|end_file_name|><|fim▁begin|>""" Control global computation context """ from collections import defaultdict _globals = defaultdict(lambda: None) _globals['callbacks'] = set() class set_options(object): """ Set global state within controled context This lets you specify various global settings in a tightly controlled with block Valid keyword arguments currently include: get - the scheduler to use pool - a thread or process pool cache - Cache to use for intermediate results func_loads/func_dumps - loads/dumps functions for serialization of data likely to contain functions. Defaults to dill.loads/dill.dumps rerun_exceptions_locally - rerun failed tasks in master process<|fim▁hole|> Example ------- >>> with set_options(get=dask.get): # doctest: +SKIP ... x = np.array(x) # uses dask.get internally """ def __init__(self, **kwargs): self.old = _globals.copy() _globals.update(kwargs) def __enter__(self): return def __exit__(self, type, value, traceback): _globals.clear() _globals.update(self.old)<|fim▁end|>
<|file_name|>context.py<|end_file_name|><|fim▁begin|>""" Control global computation context """ from collections import defaultdict _globals = defaultdict(lambda: None) _globals['callbacks'] = set() class set_options(object): <|fim_middle|> <|fim▁end|>
""" Set global state within controled context This lets you specify various global settings in a tightly controlled with block Valid keyword arguments currently include: get - the scheduler to use pool - a thread or process pool cache - Cache to use for intermediate results func_loads/func_dumps - loads/dumps functions for serialization of data likely to contain functions. Defaults to dill.loads/dill.dumps rerun_exceptions_locally - rerun failed tasks in master process Example ------- >>> with set_options(get=dask.get): # doctest: +SKIP ... x = np.array(x) # uses dask.get internally """ def __init__(self, **kwargs): self.old = _globals.copy() _globals.update(kwargs) def __enter__(self): return def __exit__(self, type, value, traceback): _globals.clear() _globals.update(self.old)
<|file_name|>context.py<|end_file_name|><|fim▁begin|>""" Control global computation context """ from collections import defaultdict _globals = defaultdict(lambda: None) _globals['callbacks'] = set() class set_options(object): """ Set global state within controled context This lets you specify various global settings in a tightly controlled with block Valid keyword arguments currently include: get - the scheduler to use pool - a thread or process pool cache - Cache to use for intermediate results func_loads/func_dumps - loads/dumps functions for serialization of data likely to contain functions. Defaults to dill.loads/dill.dumps rerun_exceptions_locally - rerun failed tasks in master process Example ------- >>> with set_options(get=dask.get): # doctest: +SKIP ... x = np.array(x) # uses dask.get internally """ def __init__(self, **kwargs): <|fim_middle|> def __enter__(self): return def __exit__(self, type, value, traceback): _globals.clear() _globals.update(self.old) <|fim▁end|>
self.old = _globals.copy() _globals.update(kwargs)
<|file_name|>context.py<|end_file_name|><|fim▁begin|>""" Control global computation context """ from collections import defaultdict _globals = defaultdict(lambda: None) _globals['callbacks'] = set() class set_options(object): """ Set global state within controled context This lets you specify various global settings in a tightly controlled with block Valid keyword arguments currently include: get - the scheduler to use pool - a thread or process pool cache - Cache to use for intermediate results func_loads/func_dumps - loads/dumps functions for serialization of data likely to contain functions. Defaults to dill.loads/dill.dumps rerun_exceptions_locally - rerun failed tasks in master process Example ------- >>> with set_options(get=dask.get): # doctest: +SKIP ... x = np.array(x) # uses dask.get internally """ def __init__(self, **kwargs): self.old = _globals.copy() _globals.update(kwargs) def __enter__(self): <|fim_middle|> def __exit__(self, type, value, traceback): _globals.clear() _globals.update(self.old) <|fim▁end|>
return
<|file_name|>context.py<|end_file_name|><|fim▁begin|>""" Control global computation context """ from collections import defaultdict _globals = defaultdict(lambda: None) _globals['callbacks'] = set() class set_options(object): """ Set global state within controled context This lets you specify various global settings in a tightly controlled with block Valid keyword arguments currently include: get - the scheduler to use pool - a thread or process pool cache - Cache to use for intermediate results func_loads/func_dumps - loads/dumps functions for serialization of data likely to contain functions. Defaults to dill.loads/dill.dumps rerun_exceptions_locally - rerun failed tasks in master process Example ------- >>> with set_options(get=dask.get): # doctest: +SKIP ... x = np.array(x) # uses dask.get internally """ def __init__(self, **kwargs): self.old = _globals.copy() _globals.update(kwargs) def __enter__(self): return def __exit__(self, type, value, traceback): <|fim_middle|> <|fim▁end|>
_globals.clear() _globals.update(self.old)
<|file_name|>context.py<|end_file_name|><|fim▁begin|>""" Control global computation context """ from collections import defaultdict _globals = defaultdict(lambda: None) _globals['callbacks'] = set() class set_options(object): """ Set global state within controled context This lets you specify various global settings in a tightly controlled with block Valid keyword arguments currently include: get - the scheduler to use pool - a thread or process pool cache - Cache to use for intermediate results func_loads/func_dumps - loads/dumps functions for serialization of data likely to contain functions. Defaults to dill.loads/dill.dumps rerun_exceptions_locally - rerun failed tasks in master process Example ------- >>> with set_options(get=dask.get): # doctest: +SKIP ... x = np.array(x) # uses dask.get internally """ def <|fim_middle|>(self, **kwargs): self.old = _globals.copy() _globals.update(kwargs) def __enter__(self): return def __exit__(self, type, value, traceback): _globals.clear() _globals.update(self.old) <|fim▁end|>
__init__
<|file_name|>context.py<|end_file_name|><|fim▁begin|>""" Control global computation context """ from collections import defaultdict _globals = defaultdict(lambda: None) _globals['callbacks'] = set() class set_options(object): """ Set global state within controled context This lets you specify various global settings in a tightly controlled with block Valid keyword arguments currently include: get - the scheduler to use pool - a thread or process pool cache - Cache to use for intermediate results func_loads/func_dumps - loads/dumps functions for serialization of data likely to contain functions. Defaults to dill.loads/dill.dumps rerun_exceptions_locally - rerun failed tasks in master process Example ------- >>> with set_options(get=dask.get): # doctest: +SKIP ... x = np.array(x) # uses dask.get internally """ def __init__(self, **kwargs): self.old = _globals.copy() _globals.update(kwargs) def <|fim_middle|>(self): return def __exit__(self, type, value, traceback): _globals.clear() _globals.update(self.old) <|fim▁end|>
__enter__
<|file_name|>context.py<|end_file_name|><|fim▁begin|>""" Control global computation context """ from collections import defaultdict _globals = defaultdict(lambda: None) _globals['callbacks'] = set() class set_options(object): """ Set global state within controled context This lets you specify various global settings in a tightly controlled with block Valid keyword arguments currently include: get - the scheduler to use pool - a thread or process pool cache - Cache to use for intermediate results func_loads/func_dumps - loads/dumps functions for serialization of data likely to contain functions. Defaults to dill.loads/dill.dumps rerun_exceptions_locally - rerun failed tasks in master process Example ------- >>> with set_options(get=dask.get): # doctest: +SKIP ... x = np.array(x) # uses dask.get internally """ def __init__(self, **kwargs): self.old = _globals.copy() _globals.update(kwargs) def __enter__(self): return def <|fim_middle|>(self, type, value, traceback): _globals.clear() _globals.update(self.old) <|fim▁end|>
__exit__
<|file_name|>myutil.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ This module put my utility functions """ __author__ = "Jiang Yu-Kuan <[email protected]>" __date__ = "2016/02/08 (initial version) ~ 2019/04/17 (last revision)" import re import os import sys #------------------------------------------------------------------------------ # File #------------------------------------------------------------------------------ def save_utf8_file(fn, lines): """Save string lines into an UTF8 text files. """ with open(fn, "w") as out_file: out_file.write("\n".join(lines).encode("utf-8")) def main_basename(path): r"""Return a main name of a basename of a given file path. Example ------- >>> main_basename('c:\code\langconv\MsgID.h') 'MsgID.h' """ base = os.path.basename(path) base_main, _base_ext = os.path.splitext(base) return base_main #------------------------------------------------------------------------------ # Math #------------------------------------------------------------------------------ def is_numeric(str): try: _offset = int(eval(str)) except: return False return True #------------------------------------------------------------------------------ # String #------------------------------------------------------------------------------ def replace_chars(text, replaced_pairs='', deleted_chars=''): """Return a char replaced text. Arguments --------- text -- the text replaced_pairs -- the replaced chars Example ------- >>> replaced = [('a','b'), ('c','d')] >>> removed = 'e' >>> replace_chars('abcde', replaced, removed) 'bbdd' """ for old, new in replaced_pairs: text = text.replace(old, new) for ch in deleted_chars: text = text.replace(ch, '') return text def camel_case(string): """Return camel case string from a space-separated string. Example ------- >>> camel_case('good job') 'GoodJob' """ return ''.join(w.capitalize() for w in string.split()) def replace_punctuations(text): """Replace punctuation characters with abbreviations for a string. """ punctuations = [ ('?', 'Q'), # Q: question mark ('.', 'P'), # P: period; full stop ('!', 'E'), # E: exclamation mark ("'", 'SQ'), # SQ: single quotation mark; single quote ('"', 'DQ'), # DQ: double quotation mark; double quotes ('(', 'LP'), # LP: left parenthese (')', 'RP'), # RP: right parenthese (':', 'Cn'), # Cn: colon (',', 'Ca'), # Ca: comma (';', 'S'), # S: semicolon ] deleted = '+-*/^=%$#@|\\<>{}[]' return replace_chars(text, punctuations, deleted) def remain_alnum(text): """Remain digits and English letters of a string. """ return ''.join(c for c in text if c.isalnum() and ord(' ') <= ord(c) <= ord('z')) #------------------------------------------------------------------------------ # For code generation #------------------------------------------------------------------------------ def c_identifier(text): """Convert input text into an legal identifier in C. Example ------- >>> c_identifier("Hello World") 'HelloWorld' >>> c_identifier("Anti-Shake") 'Antishake' """ if ' ' in text: text = camel_case(text) text = re.sub(r'\+\d+', lambda x: x.group().replace('+', 'P'), text) text = re.sub(r'\-\d+', lambda x: x.group().replace('-', 'N'), text) text = replace_punctuations(text) return remain_alnum(text) def wrap_header_guard(lines, h_fn): """Wrap a C header guard for a given line list. """ def underscore(txt): """Return an under_scores text from a CamelCase text. This function will leave a CamelCase text unchanged. """ s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', txt) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() h_fn_sig = '%s_H_' % underscore(main_basename(h_fn)).upper() begin = ['#ifndef %s' % h_fn_sig] begin += ['#define %s' % h_fn_sig, '', ''] end = ['', '', '#endif // %s' % h_fn_sig, ''] return begin + lines + end <|fim▁hole|> def prefix_info(lines, software, version, author, comment_mark='//'): """Prefix information to the given lines with given comment-mark. """ prefix = ['%s Generated by the %s v%s' % (comment_mark, software, version)] prefix += ['%s !author: %s' % (comment_mark, author)] prefix += ['%s !trail: %s %s' % (comment_mark, os.path.basename(sys.argv[0]), ' '.join(sys.argv[1:]))] return prefix + lines<|fim▁end|>
<|file_name|>myutil.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ This module put my utility functions """ __author__ = "Jiang Yu-Kuan <[email protected]>" __date__ = "2016/02/08 (initial version) ~ 2019/04/17 (last revision)" import re import os import sys #------------------------------------------------------------------------------ # File #------------------------------------------------------------------------------ def save_utf8_file(fn, lines): <|fim_middle|> def main_basename(path): r"""Return a main name of a basename of a given file path. Example ------- >>> main_basename('c:\code\langconv\MsgID.h') 'MsgID.h' """ base = os.path.basename(path) base_main, _base_ext = os.path.splitext(base) return base_main #------------------------------------------------------------------------------ # Math #------------------------------------------------------------------------------ def is_numeric(str): try: _offset = int(eval(str)) except: return False return True #------------------------------------------------------------------------------ # String #------------------------------------------------------------------------------ def replace_chars(text, replaced_pairs='', deleted_chars=''): """Return a char replaced text. Arguments --------- text -- the text replaced_pairs -- the replaced chars Example ------- >>> replaced = [('a','b'), ('c','d')] >>> removed = 'e' >>> replace_chars('abcde', replaced, removed) 'bbdd' """ for old, new in replaced_pairs: text = text.replace(old, new) for ch in deleted_chars: text = text.replace(ch, '') return text def camel_case(string): """Return camel case string from a space-separated string. Example ------- >>> camel_case('good job') 'GoodJob' """ return ''.join(w.capitalize() for w in string.split()) def replace_punctuations(text): """Replace punctuation characters with abbreviations for a string. """ punctuations = [ ('?', 'Q'), # Q: question mark ('.', 'P'), # P: period; full stop ('!', 'E'), # E: exclamation mark ("'", 'SQ'), # SQ: single quotation mark; single quote ('"', 'DQ'), # DQ: double quotation mark; double quotes ('(', 'LP'), # LP: left parenthese (')', 'RP'), # RP: right parenthese (':', 'Cn'), # Cn: colon (',', 'Ca'), # Ca: comma (';', 'S'), # S: semicolon ] deleted = '+-*/^=%$#@|\\<>{}[]' return replace_chars(text, punctuations, deleted) def remain_alnum(text): """Remain digits and English letters of a string. """ return ''.join(c for c in text if c.isalnum() and ord(' ') <= ord(c) <= ord('z')) #------------------------------------------------------------------------------ # For code generation #------------------------------------------------------------------------------ def c_identifier(text): """Convert input text into an legal identifier in C. Example ------- >>> c_identifier("Hello World") 'HelloWorld' >>> c_identifier("Anti-Shake") 'Antishake' """ if ' ' in text: text = camel_case(text) text = re.sub(r'\+\d+', lambda x: x.group().replace('+', 'P'), text) text = re.sub(r'\-\d+', lambda x: x.group().replace('-', 'N'), text) text = replace_punctuations(text) return remain_alnum(text) def wrap_header_guard(lines, h_fn): """Wrap a C header guard for a given line list. """ def underscore(txt): """Return an under_scores text from a CamelCase text. This function will leave a CamelCase text unchanged. """ s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', txt) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() h_fn_sig = '%s_H_' % underscore(main_basename(h_fn)).upper() begin = ['#ifndef %s' % h_fn_sig] begin += ['#define %s' % h_fn_sig, '', ''] end = ['', '', '#endif // %s' % h_fn_sig, ''] return begin + lines + end def prefix_info(lines, software, version, author, comment_mark='//'): """Prefix information to the given lines with given comment-mark. """ prefix = ['%s Generated by the %s v%s' % (comment_mark, software, version)] prefix += ['%s !author: %s' % (comment_mark, author)] prefix += ['%s !trail: %s %s' % (comment_mark, os.path.basename(sys.argv[0]), ' '.join(sys.argv[1:]))] return prefix + lines <|fim▁end|>
"""Save string lines into an UTF8 text files. """ with open(fn, "w") as out_file: out_file.write("\n".join(lines).encode("utf-8"))
<|file_name|>myutil.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ This module put my utility functions """ __author__ = "Jiang Yu-Kuan <[email protected]>" __date__ = "2016/02/08 (initial version) ~ 2019/04/17 (last revision)" import re import os import sys #------------------------------------------------------------------------------ # File #------------------------------------------------------------------------------ def save_utf8_file(fn, lines): """Save string lines into an UTF8 text files. """ with open(fn, "w") as out_file: out_file.write("\n".join(lines).encode("utf-8")) def main_basename(path): <|fim_middle|> #------------------------------------------------------------------------------ # Math #------------------------------------------------------------------------------ def is_numeric(str): try: _offset = int(eval(str)) except: return False return True #------------------------------------------------------------------------------ # String #------------------------------------------------------------------------------ def replace_chars(text, replaced_pairs='', deleted_chars=''): """Return a char replaced text. Arguments --------- text -- the text replaced_pairs -- the replaced chars Example ------- >>> replaced = [('a','b'), ('c','d')] >>> removed = 'e' >>> replace_chars('abcde', replaced, removed) 'bbdd' """ for old, new in replaced_pairs: text = text.replace(old, new) for ch in deleted_chars: text = text.replace(ch, '') return text def camel_case(string): """Return camel case string from a space-separated string. Example ------- >>> camel_case('good job') 'GoodJob' """ return ''.join(w.capitalize() for w in string.split()) def replace_punctuations(text): """Replace punctuation characters with abbreviations for a string. """ punctuations = [ ('?', 'Q'), # Q: question mark ('.', 'P'), # P: period; full stop ('!', 'E'), # E: exclamation mark ("'", 'SQ'), # SQ: single quotation mark; single quote ('"', 'DQ'), # DQ: double quotation mark; double quotes ('(', 'LP'), # LP: left parenthese (')', 'RP'), # RP: right parenthese (':', 'Cn'), # Cn: colon (',', 'Ca'), # Ca: comma (';', 'S'), # S: semicolon ] deleted = '+-*/^=%$#@|\\<>{}[]' return replace_chars(text, punctuations, deleted) def remain_alnum(text): """Remain digits and English letters of a string. """ return ''.join(c for c in text if c.isalnum() and ord(' ') <= ord(c) <= ord('z')) #------------------------------------------------------------------------------ # For code generation #------------------------------------------------------------------------------ def c_identifier(text): """Convert input text into an legal identifier in C. Example ------- >>> c_identifier("Hello World") 'HelloWorld' >>> c_identifier("Anti-Shake") 'Antishake' """ if ' ' in text: text = camel_case(text) text = re.sub(r'\+\d+', lambda x: x.group().replace('+', 'P'), text) text = re.sub(r'\-\d+', lambda x: x.group().replace('-', 'N'), text) text = replace_punctuations(text) return remain_alnum(text) def wrap_header_guard(lines, h_fn): """Wrap a C header guard for a given line list. """ def underscore(txt): """Return an under_scores text from a CamelCase text. This function will leave a CamelCase text unchanged. """ s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', txt) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() h_fn_sig = '%s_H_' % underscore(main_basename(h_fn)).upper() begin = ['#ifndef %s' % h_fn_sig] begin += ['#define %s' % h_fn_sig, '', ''] end = ['', '', '#endif // %s' % h_fn_sig, ''] return begin + lines + end def prefix_info(lines, software, version, author, comment_mark='//'): """Prefix information to the given lines with given comment-mark. """ prefix = ['%s Generated by the %s v%s' % (comment_mark, software, version)] prefix += ['%s !author: %s' % (comment_mark, author)] prefix += ['%s !trail: %s %s' % (comment_mark, os.path.basename(sys.argv[0]), ' '.join(sys.argv[1:]))] return prefix + lines <|fim▁end|>
r"""Return a main name of a basename of a given file path. Example ------- >>> main_basename('c:\code\langconv\MsgID.h') 'MsgID.h' """ base = os.path.basename(path) base_main, _base_ext = os.path.splitext(base) return base_main
<|file_name|>myutil.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ This module put my utility functions """ __author__ = "Jiang Yu-Kuan <[email protected]>" __date__ = "2016/02/08 (initial version) ~ 2019/04/17 (last revision)" import re import os import sys #------------------------------------------------------------------------------ # File #------------------------------------------------------------------------------ def save_utf8_file(fn, lines): """Save string lines into an UTF8 text files. """ with open(fn, "w") as out_file: out_file.write("\n".join(lines).encode("utf-8")) def main_basename(path): r"""Return a main name of a basename of a given file path. Example ------- >>> main_basename('c:\code\langconv\MsgID.h') 'MsgID.h' """ base = os.path.basename(path) base_main, _base_ext = os.path.splitext(base) return base_main #------------------------------------------------------------------------------ # Math #------------------------------------------------------------------------------ def is_numeric(str): <|fim_middle|> #------------------------------------------------------------------------------ # String #------------------------------------------------------------------------------ def replace_chars(text, replaced_pairs='', deleted_chars=''): """Return a char replaced text. Arguments --------- text -- the text replaced_pairs -- the replaced chars Example ------- >>> replaced = [('a','b'), ('c','d')] >>> removed = 'e' >>> replace_chars('abcde', replaced, removed) 'bbdd' """ for old, new in replaced_pairs: text = text.replace(old, new) for ch in deleted_chars: text = text.replace(ch, '') return text def camel_case(string): """Return camel case string from a space-separated string. Example ------- >>> camel_case('good job') 'GoodJob' """ return ''.join(w.capitalize() for w in string.split()) def replace_punctuations(text): """Replace punctuation characters with abbreviations for a string. """ punctuations = [ ('?', 'Q'), # Q: question mark ('.', 'P'), # P: period; full stop ('!', 'E'), # E: exclamation mark ("'", 'SQ'), # SQ: single quotation mark; single quote ('"', 'DQ'), # DQ: double quotation mark; double quotes ('(', 'LP'), # LP: left parenthese (')', 'RP'), # RP: right parenthese (':', 'Cn'), # Cn: colon (',', 'Ca'), # Ca: comma (';', 'S'), # S: semicolon ] deleted = '+-*/^=%$#@|\\<>{}[]' return replace_chars(text, punctuations, deleted) def remain_alnum(text): """Remain digits and English letters of a string. """ return ''.join(c for c in text if c.isalnum() and ord(' ') <= ord(c) <= ord('z')) #------------------------------------------------------------------------------ # For code generation #------------------------------------------------------------------------------ def c_identifier(text): """Convert input text into an legal identifier in C. Example ------- >>> c_identifier("Hello World") 'HelloWorld' >>> c_identifier("Anti-Shake") 'Antishake' """ if ' ' in text: text = camel_case(text) text = re.sub(r'\+\d+', lambda x: x.group().replace('+', 'P'), text) text = re.sub(r'\-\d+', lambda x: x.group().replace('-', 'N'), text) text = replace_punctuations(text) return remain_alnum(text) def wrap_header_guard(lines, h_fn): """Wrap a C header guard for a given line list. """ def underscore(txt): """Return an under_scores text from a CamelCase text. This function will leave a CamelCase text unchanged. """ s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', txt) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() h_fn_sig = '%s_H_' % underscore(main_basename(h_fn)).upper() begin = ['#ifndef %s' % h_fn_sig] begin += ['#define %s' % h_fn_sig, '', ''] end = ['', '', '#endif // %s' % h_fn_sig, ''] return begin + lines + end def prefix_info(lines, software, version, author, comment_mark='//'): """Prefix information to the given lines with given comment-mark. """ prefix = ['%s Generated by the %s v%s' % (comment_mark, software, version)] prefix += ['%s !author: %s' % (comment_mark, author)] prefix += ['%s !trail: %s %s' % (comment_mark, os.path.basename(sys.argv[0]), ' '.join(sys.argv[1:]))] return prefix + lines <|fim▁end|>
try: _offset = int(eval(str)) except: return False return True
<|file_name|>myutil.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ This module put my utility functions """ __author__ = "Jiang Yu-Kuan <[email protected]>" __date__ = "2016/02/08 (initial version) ~ 2019/04/17 (last revision)" import re import os import sys #------------------------------------------------------------------------------ # File #------------------------------------------------------------------------------ def save_utf8_file(fn, lines): """Save string lines into an UTF8 text files. """ with open(fn, "w") as out_file: out_file.write("\n".join(lines).encode("utf-8")) def main_basename(path): r"""Return a main name of a basename of a given file path. Example ------- >>> main_basename('c:\code\langconv\MsgID.h') 'MsgID.h' """ base = os.path.basename(path) base_main, _base_ext = os.path.splitext(base) return base_main #------------------------------------------------------------------------------ # Math #------------------------------------------------------------------------------ def is_numeric(str): try: _offset = int(eval(str)) except: return False return True #------------------------------------------------------------------------------ # String #------------------------------------------------------------------------------ def replace_chars(text, replaced_pairs='', deleted_chars=''): <|fim_middle|> def camel_case(string): """Return camel case string from a space-separated string. Example ------- >>> camel_case('good job') 'GoodJob' """ return ''.join(w.capitalize() for w in string.split()) def replace_punctuations(text): """Replace punctuation characters with abbreviations for a string. """ punctuations = [ ('?', 'Q'), # Q: question mark ('.', 'P'), # P: period; full stop ('!', 'E'), # E: exclamation mark ("'", 'SQ'), # SQ: single quotation mark; single quote ('"', 'DQ'), # DQ: double quotation mark; double quotes ('(', 'LP'), # LP: left parenthese (')', 'RP'), # RP: right parenthese (':', 'Cn'), # Cn: colon (',', 'Ca'), # Ca: comma (';', 'S'), # S: semicolon ] deleted = '+-*/^=%$#@|\\<>{}[]' return replace_chars(text, punctuations, deleted) def remain_alnum(text): """Remain digits and English letters of a string. """ return ''.join(c for c in text if c.isalnum() and ord(' ') <= ord(c) <= ord('z')) #------------------------------------------------------------------------------ # For code generation #------------------------------------------------------------------------------ def c_identifier(text): """Convert input text into an legal identifier in C. Example ------- >>> c_identifier("Hello World") 'HelloWorld' >>> c_identifier("Anti-Shake") 'Antishake' """ if ' ' in text: text = camel_case(text) text = re.sub(r'\+\d+', lambda x: x.group().replace('+', 'P'), text) text = re.sub(r'\-\d+', lambda x: x.group().replace('-', 'N'), text) text = replace_punctuations(text) return remain_alnum(text) def wrap_header_guard(lines, h_fn): """Wrap a C header guard for a given line list. """ def underscore(txt): """Return an under_scores text from a CamelCase text. This function will leave a CamelCase text unchanged. """ s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', txt) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() h_fn_sig = '%s_H_' % underscore(main_basename(h_fn)).upper() begin = ['#ifndef %s' % h_fn_sig] begin += ['#define %s' % h_fn_sig, '', ''] end = ['', '', '#endif // %s' % h_fn_sig, ''] return begin + lines + end def prefix_info(lines, software, version, author, comment_mark='//'): """Prefix information to the given lines with given comment-mark. """ prefix = ['%s Generated by the %s v%s' % (comment_mark, software, version)] prefix += ['%s !author: %s' % (comment_mark, author)] prefix += ['%s !trail: %s %s' % (comment_mark, os.path.basename(sys.argv[0]), ' '.join(sys.argv[1:]))] return prefix + lines <|fim▁end|>
"""Return a char replaced text. Arguments --------- text -- the text replaced_pairs -- the replaced chars Example ------- >>> replaced = [('a','b'), ('c','d')] >>> removed = 'e' >>> replace_chars('abcde', replaced, removed) 'bbdd' """ for old, new in replaced_pairs: text = text.replace(old, new) for ch in deleted_chars: text = text.replace(ch, '') return text
<|file_name|>myutil.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ This module put my utility functions """ __author__ = "Jiang Yu-Kuan <[email protected]>" __date__ = "2016/02/08 (initial version) ~ 2019/04/17 (last revision)" import re import os import sys #------------------------------------------------------------------------------ # File #------------------------------------------------------------------------------ def save_utf8_file(fn, lines): """Save string lines into an UTF8 text files. """ with open(fn, "w") as out_file: out_file.write("\n".join(lines).encode("utf-8")) def main_basename(path): r"""Return a main name of a basename of a given file path. Example ------- >>> main_basename('c:\code\langconv\MsgID.h') 'MsgID.h' """ base = os.path.basename(path) base_main, _base_ext = os.path.splitext(base) return base_main #------------------------------------------------------------------------------ # Math #------------------------------------------------------------------------------ def is_numeric(str): try: _offset = int(eval(str)) except: return False return True #------------------------------------------------------------------------------ # String #------------------------------------------------------------------------------ def replace_chars(text, replaced_pairs='', deleted_chars=''): """Return a char replaced text. Arguments --------- text -- the text replaced_pairs -- the replaced chars Example ------- >>> replaced = [('a','b'), ('c','d')] >>> removed = 'e' >>> replace_chars('abcde', replaced, removed) 'bbdd' """ for old, new in replaced_pairs: text = text.replace(old, new) for ch in deleted_chars: text = text.replace(ch, '') return text def camel_case(string): <|fim_middle|> def replace_punctuations(text): """Replace punctuation characters with abbreviations for a string. """ punctuations = [ ('?', 'Q'), # Q: question mark ('.', 'P'), # P: period; full stop ('!', 'E'), # E: exclamation mark ("'", 'SQ'), # SQ: single quotation mark; single quote ('"', 'DQ'), # DQ: double quotation mark; double quotes ('(', 'LP'), # LP: left parenthese (')', 'RP'), # RP: right parenthese (':', 'Cn'), # Cn: colon (',', 'Ca'), # Ca: comma (';', 'S'), # S: semicolon ] deleted = '+-*/^=%$#@|\\<>{}[]' return replace_chars(text, punctuations, deleted) def remain_alnum(text): """Remain digits and English letters of a string. """ return ''.join(c for c in text if c.isalnum() and ord(' ') <= ord(c) <= ord('z')) #------------------------------------------------------------------------------ # For code generation #------------------------------------------------------------------------------ def c_identifier(text): """Convert input text into an legal identifier in C. Example ------- >>> c_identifier("Hello World") 'HelloWorld' >>> c_identifier("Anti-Shake") 'Antishake' """ if ' ' in text: text = camel_case(text) text = re.sub(r'\+\d+', lambda x: x.group().replace('+', 'P'), text) text = re.sub(r'\-\d+', lambda x: x.group().replace('-', 'N'), text) text = replace_punctuations(text) return remain_alnum(text) def wrap_header_guard(lines, h_fn): """Wrap a C header guard for a given line list. """ def underscore(txt): """Return an under_scores text from a CamelCase text. This function will leave a CamelCase text unchanged. """ s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', txt) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() h_fn_sig = '%s_H_' % underscore(main_basename(h_fn)).upper() begin = ['#ifndef %s' % h_fn_sig] begin += ['#define %s' % h_fn_sig, '', ''] end = ['', '', '#endif // %s' % h_fn_sig, ''] return begin + lines + end def prefix_info(lines, software, version, author, comment_mark='//'): """Prefix information to the given lines with given comment-mark. """ prefix = ['%s Generated by the %s v%s' % (comment_mark, software, version)] prefix += ['%s !author: %s' % (comment_mark, author)] prefix += ['%s !trail: %s %s' % (comment_mark, os.path.basename(sys.argv[0]), ' '.join(sys.argv[1:]))] return prefix + lines <|fim▁end|>
"""Return camel case string from a space-separated string. Example ------- >>> camel_case('good job') 'GoodJob' """ return ''.join(w.capitalize() for w in string.split())
<|file_name|>myutil.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ This module put my utility functions """ __author__ = "Jiang Yu-Kuan <[email protected]>" __date__ = "2016/02/08 (initial version) ~ 2019/04/17 (last revision)" import re import os import sys #------------------------------------------------------------------------------ # File #------------------------------------------------------------------------------ def save_utf8_file(fn, lines): """Save string lines into an UTF8 text files. """ with open(fn, "w") as out_file: out_file.write("\n".join(lines).encode("utf-8")) def main_basename(path): r"""Return a main name of a basename of a given file path. Example ------- >>> main_basename('c:\code\langconv\MsgID.h') 'MsgID.h' """ base = os.path.basename(path) base_main, _base_ext = os.path.splitext(base) return base_main #------------------------------------------------------------------------------ # Math #------------------------------------------------------------------------------ def is_numeric(str): try: _offset = int(eval(str)) except: return False return True #------------------------------------------------------------------------------ # String #------------------------------------------------------------------------------ def replace_chars(text, replaced_pairs='', deleted_chars=''): """Return a char replaced text. Arguments --------- text -- the text replaced_pairs -- the replaced chars Example ------- >>> replaced = [('a','b'), ('c','d')] >>> removed = 'e' >>> replace_chars('abcde', replaced, removed) 'bbdd' """ for old, new in replaced_pairs: text = text.replace(old, new) for ch in deleted_chars: text = text.replace(ch, '') return text def camel_case(string): """Return camel case string from a space-separated string. Example ------- >>> camel_case('good job') 'GoodJob' """ return ''.join(w.capitalize() for w in string.split()) def replace_punctuations(text): <|fim_middle|> def remain_alnum(text): """Remain digits and English letters of a string. """ return ''.join(c for c in text if c.isalnum() and ord(' ') <= ord(c) <= ord('z')) #------------------------------------------------------------------------------ # For code generation #------------------------------------------------------------------------------ def c_identifier(text): """Convert input text into an legal identifier in C. Example ------- >>> c_identifier("Hello World") 'HelloWorld' >>> c_identifier("Anti-Shake") 'Antishake' """ if ' ' in text: text = camel_case(text) text = re.sub(r'\+\d+', lambda x: x.group().replace('+', 'P'), text) text = re.sub(r'\-\d+', lambda x: x.group().replace('-', 'N'), text) text = replace_punctuations(text) return remain_alnum(text) def wrap_header_guard(lines, h_fn): """Wrap a C header guard for a given line list. """ def underscore(txt): """Return an under_scores text from a CamelCase text. This function will leave a CamelCase text unchanged. """ s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', txt) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() h_fn_sig = '%s_H_' % underscore(main_basename(h_fn)).upper() begin = ['#ifndef %s' % h_fn_sig] begin += ['#define %s' % h_fn_sig, '', ''] end = ['', '', '#endif // %s' % h_fn_sig, ''] return begin + lines + end def prefix_info(lines, software, version, author, comment_mark='//'): """Prefix information to the given lines with given comment-mark. """ prefix = ['%s Generated by the %s v%s' % (comment_mark, software, version)] prefix += ['%s !author: %s' % (comment_mark, author)] prefix += ['%s !trail: %s %s' % (comment_mark, os.path.basename(sys.argv[0]), ' '.join(sys.argv[1:]))] return prefix + lines <|fim▁end|>
"""Replace punctuation characters with abbreviations for a string. """ punctuations = [ ('?', 'Q'), # Q: question mark ('.', 'P'), # P: period; full stop ('!', 'E'), # E: exclamation mark ("'", 'SQ'), # SQ: single quotation mark; single quote ('"', 'DQ'), # DQ: double quotation mark; double quotes ('(', 'LP'), # LP: left parenthese (')', 'RP'), # RP: right parenthese (':', 'Cn'), # Cn: colon (',', 'Ca'), # Ca: comma (';', 'S'), # S: semicolon ] deleted = '+-*/^=%$#@|\\<>{}[]' return replace_chars(text, punctuations, deleted)
<|file_name|>myutil.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ This module put my utility functions """ __author__ = "Jiang Yu-Kuan <[email protected]>" __date__ = "2016/02/08 (initial version) ~ 2019/04/17 (last revision)" import re import os import sys #------------------------------------------------------------------------------ # File #------------------------------------------------------------------------------ def save_utf8_file(fn, lines): """Save string lines into an UTF8 text files. """ with open(fn, "w") as out_file: out_file.write("\n".join(lines).encode("utf-8")) def main_basename(path): r"""Return a main name of a basename of a given file path. Example ------- >>> main_basename('c:\code\langconv\MsgID.h') 'MsgID.h' """ base = os.path.basename(path) base_main, _base_ext = os.path.splitext(base) return base_main #------------------------------------------------------------------------------ # Math #------------------------------------------------------------------------------ def is_numeric(str): try: _offset = int(eval(str)) except: return False return True #------------------------------------------------------------------------------ # String #------------------------------------------------------------------------------ def replace_chars(text, replaced_pairs='', deleted_chars=''): """Return a char replaced text. Arguments --------- text -- the text replaced_pairs -- the replaced chars Example ------- >>> replaced = [('a','b'), ('c','d')] >>> removed = 'e' >>> replace_chars('abcde', replaced, removed) 'bbdd' """ for old, new in replaced_pairs: text = text.replace(old, new) for ch in deleted_chars: text = text.replace(ch, '') return text def camel_case(string): """Return camel case string from a space-separated string. Example ------- >>> camel_case('good job') 'GoodJob' """ return ''.join(w.capitalize() for w in string.split()) def replace_punctuations(text): """Replace punctuation characters with abbreviations for a string. """ punctuations = [ ('?', 'Q'), # Q: question mark ('.', 'P'), # P: period; full stop ('!', 'E'), # E: exclamation mark ("'", 'SQ'), # SQ: single quotation mark; single quote ('"', 'DQ'), # DQ: double quotation mark; double quotes ('(', 'LP'), # LP: left parenthese (')', 'RP'), # RP: right parenthese (':', 'Cn'), # Cn: colon (',', 'Ca'), # Ca: comma (';', 'S'), # S: semicolon ] deleted = '+-*/^=%$#@|\\<>{}[]' return replace_chars(text, punctuations, deleted) def remain_alnum(text): <|fim_middle|> #------------------------------------------------------------------------------ # For code generation #------------------------------------------------------------------------------ def c_identifier(text): """Convert input text into an legal identifier in C. Example ------- >>> c_identifier("Hello World") 'HelloWorld' >>> c_identifier("Anti-Shake") 'Antishake' """ if ' ' in text: text = camel_case(text) text = re.sub(r'\+\d+', lambda x: x.group().replace('+', 'P'), text) text = re.sub(r'\-\d+', lambda x: x.group().replace('-', 'N'), text) text = replace_punctuations(text) return remain_alnum(text) def wrap_header_guard(lines, h_fn): """Wrap a C header guard for a given line list. """ def underscore(txt): """Return an under_scores text from a CamelCase text. This function will leave a CamelCase text unchanged. """ s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', txt) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() h_fn_sig = '%s_H_' % underscore(main_basename(h_fn)).upper() begin = ['#ifndef %s' % h_fn_sig] begin += ['#define %s' % h_fn_sig, '', ''] end = ['', '', '#endif // %s' % h_fn_sig, ''] return begin + lines + end def prefix_info(lines, software, version, author, comment_mark='//'): """Prefix information to the given lines with given comment-mark. """ prefix = ['%s Generated by the %s v%s' % (comment_mark, software, version)] prefix += ['%s !author: %s' % (comment_mark, author)] prefix += ['%s !trail: %s %s' % (comment_mark, os.path.basename(sys.argv[0]), ' '.join(sys.argv[1:]))] return prefix + lines <|fim▁end|>
"""Remain digits and English letters of a string. """ return ''.join(c for c in text if c.isalnum() and ord(' ') <= ord(c) <= ord('z'))
<|file_name|>myutil.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ This module put my utility functions """ __author__ = "Jiang Yu-Kuan <[email protected]>" __date__ = "2016/02/08 (initial version) ~ 2019/04/17 (last revision)" import re import os import sys #------------------------------------------------------------------------------ # File #------------------------------------------------------------------------------ def save_utf8_file(fn, lines): """Save string lines into an UTF8 text files. """ with open(fn, "w") as out_file: out_file.write("\n".join(lines).encode("utf-8")) def main_basename(path): r"""Return a main name of a basename of a given file path. Example ------- >>> main_basename('c:\code\langconv\MsgID.h') 'MsgID.h' """ base = os.path.basename(path) base_main, _base_ext = os.path.splitext(base) return base_main #------------------------------------------------------------------------------ # Math #------------------------------------------------------------------------------ def is_numeric(str): try: _offset = int(eval(str)) except: return False return True #------------------------------------------------------------------------------ # String #------------------------------------------------------------------------------ def replace_chars(text, replaced_pairs='', deleted_chars=''): """Return a char replaced text. Arguments --------- text -- the text replaced_pairs -- the replaced chars Example ------- >>> replaced = [('a','b'), ('c','d')] >>> removed = 'e' >>> replace_chars('abcde', replaced, removed) 'bbdd' """ for old, new in replaced_pairs: text = text.replace(old, new) for ch in deleted_chars: text = text.replace(ch, '') return text def camel_case(string): """Return camel case string from a space-separated string. Example ------- >>> camel_case('good job') 'GoodJob' """ return ''.join(w.capitalize() for w in string.split()) def replace_punctuations(text): """Replace punctuation characters with abbreviations for a string. """ punctuations = [ ('?', 'Q'), # Q: question mark ('.', 'P'), # P: period; full stop ('!', 'E'), # E: exclamation mark ("'", 'SQ'), # SQ: single quotation mark; single quote ('"', 'DQ'), # DQ: double quotation mark; double quotes ('(', 'LP'), # LP: left parenthese (')', 'RP'), # RP: right parenthese (':', 'Cn'), # Cn: colon (',', 'Ca'), # Ca: comma (';', 'S'), # S: semicolon ] deleted = '+-*/^=%$#@|\\<>{}[]' return replace_chars(text, punctuations, deleted) def remain_alnum(text): """Remain digits and English letters of a string. """ return ''.join(c for c in text if c.isalnum() and ord(' ') <= ord(c) <= ord('z')) #------------------------------------------------------------------------------ # For code generation #------------------------------------------------------------------------------ def c_identifier(text): <|fim_middle|> def wrap_header_guard(lines, h_fn): """Wrap a C header guard for a given line list. """ def underscore(txt): """Return an under_scores text from a CamelCase text. This function will leave a CamelCase text unchanged. """ s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', txt) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() h_fn_sig = '%s_H_' % underscore(main_basename(h_fn)).upper() begin = ['#ifndef %s' % h_fn_sig] begin += ['#define %s' % h_fn_sig, '', ''] end = ['', '', '#endif // %s' % h_fn_sig, ''] return begin + lines + end def prefix_info(lines, software, version, author, comment_mark='//'): """Prefix information to the given lines with given comment-mark. """ prefix = ['%s Generated by the %s v%s' % (comment_mark, software, version)] prefix += ['%s !author: %s' % (comment_mark, author)] prefix += ['%s !trail: %s %s' % (comment_mark, os.path.basename(sys.argv[0]), ' '.join(sys.argv[1:]))] return prefix + lines <|fim▁end|>
"""Convert input text into an legal identifier in C. Example ------- >>> c_identifier("Hello World") 'HelloWorld' >>> c_identifier("Anti-Shake") 'Antishake' """ if ' ' in text: text = camel_case(text) text = re.sub(r'\+\d+', lambda x: x.group().replace('+', 'P'), text) text = re.sub(r'\-\d+', lambda x: x.group().replace('-', 'N'), text) text = replace_punctuations(text) return remain_alnum(text)
<|file_name|>myutil.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ This module put my utility functions """ __author__ = "Jiang Yu-Kuan <[email protected]>" __date__ = "2016/02/08 (initial version) ~ 2019/04/17 (last revision)" import re import os import sys #------------------------------------------------------------------------------ # File #------------------------------------------------------------------------------ def save_utf8_file(fn, lines): """Save string lines into an UTF8 text files. """ with open(fn, "w") as out_file: out_file.write("\n".join(lines).encode("utf-8")) def main_basename(path): r"""Return a main name of a basename of a given file path. Example ------- >>> main_basename('c:\code\langconv\MsgID.h') 'MsgID.h' """ base = os.path.basename(path) base_main, _base_ext = os.path.splitext(base) return base_main #------------------------------------------------------------------------------ # Math #------------------------------------------------------------------------------ def is_numeric(str): try: _offset = int(eval(str)) except: return False return True #------------------------------------------------------------------------------ # String #------------------------------------------------------------------------------ def replace_chars(text, replaced_pairs='', deleted_chars=''): """Return a char replaced text. Arguments --------- text -- the text replaced_pairs -- the replaced chars Example ------- >>> replaced = [('a','b'), ('c','d')] >>> removed = 'e' >>> replace_chars('abcde', replaced, removed) 'bbdd' """ for old, new in replaced_pairs: text = text.replace(old, new) for ch in deleted_chars: text = text.replace(ch, '') return text def camel_case(string): """Return camel case string from a space-separated string. Example ------- >>> camel_case('good job') 'GoodJob' """ return ''.join(w.capitalize() for w in string.split()) def replace_punctuations(text): """Replace punctuation characters with abbreviations for a string. """ punctuations = [ ('?', 'Q'), # Q: question mark ('.', 'P'), # P: period; full stop ('!', 'E'), # E: exclamation mark ("'", 'SQ'), # SQ: single quotation mark; single quote ('"', 'DQ'), # DQ: double quotation mark; double quotes ('(', 'LP'), # LP: left parenthese (')', 'RP'), # RP: right parenthese (':', 'Cn'), # Cn: colon (',', 'Ca'), # Ca: comma (';', 'S'), # S: semicolon ] deleted = '+-*/^=%$#@|\\<>{}[]' return replace_chars(text, punctuations, deleted) def remain_alnum(text): """Remain digits and English letters of a string. """ return ''.join(c for c in text if c.isalnum() and ord(' ') <= ord(c) <= ord('z')) #------------------------------------------------------------------------------ # For code generation #------------------------------------------------------------------------------ def c_identifier(text): """Convert input text into an legal identifier in C. Example ------- >>> c_identifier("Hello World") 'HelloWorld' >>> c_identifier("Anti-Shake") 'Antishake' """ if ' ' in text: text = camel_case(text) text = re.sub(r'\+\d+', lambda x: x.group().replace('+', 'P'), text) text = re.sub(r'\-\d+', lambda x: x.group().replace('-', 'N'), text) text = replace_punctuations(text) return remain_alnum(text) def wrap_header_guard(lines, h_fn): <|fim_middle|> def prefix_info(lines, software, version, author, comment_mark='//'): """Prefix information to the given lines with given comment-mark. """ prefix = ['%s Generated by the %s v%s' % (comment_mark, software, version)] prefix += ['%s !author: %s' % (comment_mark, author)] prefix += ['%s !trail: %s %s' % (comment_mark, os.path.basename(sys.argv[0]), ' '.join(sys.argv[1:]))] return prefix + lines <|fim▁end|>
"""Wrap a C header guard for a given line list. """ def underscore(txt): """Return an under_scores text from a CamelCase text. This function will leave a CamelCase text unchanged. """ s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', txt) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() h_fn_sig = '%s_H_' % underscore(main_basename(h_fn)).upper() begin = ['#ifndef %s' % h_fn_sig] begin += ['#define %s' % h_fn_sig, '', ''] end = ['', '', '#endif // %s' % h_fn_sig, ''] return begin + lines + end
<|file_name|>myutil.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ This module put my utility functions """ __author__ = "Jiang Yu-Kuan <[email protected]>" __date__ = "2016/02/08 (initial version) ~ 2019/04/17 (last revision)" import re import os import sys #------------------------------------------------------------------------------ # File #------------------------------------------------------------------------------ def save_utf8_file(fn, lines): """Save string lines into an UTF8 text files. """ with open(fn, "w") as out_file: out_file.write("\n".join(lines).encode("utf-8")) def main_basename(path): r"""Return a main name of a basename of a given file path. Example ------- >>> main_basename('c:\code\langconv\MsgID.h') 'MsgID.h' """ base = os.path.basename(path) base_main, _base_ext = os.path.splitext(base) return base_main #------------------------------------------------------------------------------ # Math #------------------------------------------------------------------------------ def is_numeric(str): try: _offset = int(eval(str)) except: return False return True #------------------------------------------------------------------------------ # String #------------------------------------------------------------------------------ def replace_chars(text, replaced_pairs='', deleted_chars=''): """Return a char replaced text. Arguments --------- text -- the text replaced_pairs -- the replaced chars Example ------- >>> replaced = [('a','b'), ('c','d')] >>> removed = 'e' >>> replace_chars('abcde', replaced, removed) 'bbdd' """ for old, new in replaced_pairs: text = text.replace(old, new) for ch in deleted_chars: text = text.replace(ch, '') return text def camel_case(string): """Return camel case string from a space-separated string. Example ------- >>> camel_case('good job') 'GoodJob' """ return ''.join(w.capitalize() for w in string.split()) def replace_punctuations(text): """Replace punctuation characters with abbreviations for a string. """ punctuations = [ ('?', 'Q'), # Q: question mark ('.', 'P'), # P: period; full stop ('!', 'E'), # E: exclamation mark ("'", 'SQ'), # SQ: single quotation mark; single quote ('"', 'DQ'), # DQ: double quotation mark; double quotes ('(', 'LP'), # LP: left parenthese (')', 'RP'), # RP: right parenthese (':', 'Cn'), # Cn: colon (',', 'Ca'), # Ca: comma (';', 'S'), # S: semicolon ] deleted = '+-*/^=%$#@|\\<>{}[]' return replace_chars(text, punctuations, deleted) def remain_alnum(text): """Remain digits and English letters of a string. """ return ''.join(c for c in text if c.isalnum() and ord(' ') <= ord(c) <= ord('z')) #------------------------------------------------------------------------------ # For code generation #------------------------------------------------------------------------------ def c_identifier(text): """Convert input text into an legal identifier in C. Example ------- >>> c_identifier("Hello World") 'HelloWorld' >>> c_identifier("Anti-Shake") 'Antishake' """ if ' ' in text: text = camel_case(text) text = re.sub(r'\+\d+', lambda x: x.group().replace('+', 'P'), text) text = re.sub(r'\-\d+', lambda x: x.group().replace('-', 'N'), text) text = replace_punctuations(text) return remain_alnum(text) def wrap_header_guard(lines, h_fn): """Wrap a C header guard for a given line list. """ def underscore(txt): <|fim_middle|> h_fn_sig = '%s_H_' % underscore(main_basename(h_fn)).upper() begin = ['#ifndef %s' % h_fn_sig] begin += ['#define %s' % h_fn_sig, '', ''] end = ['', '', '#endif // %s' % h_fn_sig, ''] return begin + lines + end def prefix_info(lines, software, version, author, comment_mark='//'): """Prefix information to the given lines with given comment-mark. """ prefix = ['%s Generated by the %s v%s' % (comment_mark, software, version)] prefix += ['%s !author: %s' % (comment_mark, author)] prefix += ['%s !trail: %s %s' % (comment_mark, os.path.basename(sys.argv[0]), ' '.join(sys.argv[1:]))] return prefix + lines <|fim▁end|>
"""Return an under_scores text from a CamelCase text. This function will leave a CamelCase text unchanged. """ s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', txt) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
<|file_name|>myutil.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ This module put my utility functions """ __author__ = "Jiang Yu-Kuan <[email protected]>" __date__ = "2016/02/08 (initial version) ~ 2019/04/17 (last revision)" import re import os import sys #------------------------------------------------------------------------------ # File #------------------------------------------------------------------------------ def save_utf8_file(fn, lines): """Save string lines into an UTF8 text files. """ with open(fn, "w") as out_file: out_file.write("\n".join(lines).encode("utf-8")) def main_basename(path): r"""Return a main name of a basename of a given file path. Example ------- >>> main_basename('c:\code\langconv\MsgID.h') 'MsgID.h' """ base = os.path.basename(path) base_main, _base_ext = os.path.splitext(base) return base_main #------------------------------------------------------------------------------ # Math #------------------------------------------------------------------------------ def is_numeric(str): try: _offset = int(eval(str)) except: return False return True #------------------------------------------------------------------------------ # String #------------------------------------------------------------------------------ def replace_chars(text, replaced_pairs='', deleted_chars=''): """Return a char replaced text. Arguments --------- text -- the text replaced_pairs -- the replaced chars Example ------- >>> replaced = [('a','b'), ('c','d')] >>> removed = 'e' >>> replace_chars('abcde', replaced, removed) 'bbdd' """ for old, new in replaced_pairs: text = text.replace(old, new) for ch in deleted_chars: text = text.replace(ch, '') return text def camel_case(string): """Return camel case string from a space-separated string. Example ------- >>> camel_case('good job') 'GoodJob' """ return ''.join(w.capitalize() for w in string.split()) def replace_punctuations(text): """Replace punctuation characters with abbreviations for a string. """ punctuations = [ ('?', 'Q'), # Q: question mark ('.', 'P'), # P: period; full stop ('!', 'E'), # E: exclamation mark ("'", 'SQ'), # SQ: single quotation mark; single quote ('"', 'DQ'), # DQ: double quotation mark; double quotes ('(', 'LP'), # LP: left parenthese (')', 'RP'), # RP: right parenthese (':', 'Cn'), # Cn: colon (',', 'Ca'), # Ca: comma (';', 'S'), # S: semicolon ] deleted = '+-*/^=%$#@|\\<>{}[]' return replace_chars(text, punctuations, deleted) def remain_alnum(text): """Remain digits and English letters of a string. """ return ''.join(c for c in text if c.isalnum() and ord(' ') <= ord(c) <= ord('z')) #------------------------------------------------------------------------------ # For code generation #------------------------------------------------------------------------------ def c_identifier(text): """Convert input text into an legal identifier in C. Example ------- >>> c_identifier("Hello World") 'HelloWorld' >>> c_identifier("Anti-Shake") 'Antishake' """ if ' ' in text: text = camel_case(text) text = re.sub(r'\+\d+', lambda x: x.group().replace('+', 'P'), text) text = re.sub(r'\-\d+', lambda x: x.group().replace('-', 'N'), text) text = replace_punctuations(text) return remain_alnum(text) def wrap_header_guard(lines, h_fn): """Wrap a C header guard for a given line list. """ def underscore(txt): """Return an under_scores text from a CamelCase text. This function will leave a CamelCase text unchanged. """ s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', txt) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() h_fn_sig = '%s_H_' % underscore(main_basename(h_fn)).upper() begin = ['#ifndef %s' % h_fn_sig] begin += ['#define %s' % h_fn_sig, '', ''] end = ['', '', '#endif // %s' % h_fn_sig, ''] return begin + lines + end def prefix_info(lines, software, version, author, comment_mark='//'): <|fim_middle|> <|fim▁end|>
"""Prefix information to the given lines with given comment-mark. """ prefix = ['%s Generated by the %s v%s' % (comment_mark, software, version)] prefix += ['%s !author: %s' % (comment_mark, author)] prefix += ['%s !trail: %s %s' % (comment_mark, os.path.basename(sys.argv[0]), ' '.join(sys.argv[1:]))] return prefix + lines
<|file_name|>myutil.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ This module put my utility functions """ __author__ = "Jiang Yu-Kuan <[email protected]>" __date__ = "2016/02/08 (initial version) ~ 2019/04/17 (last revision)" import re import os import sys #------------------------------------------------------------------------------ # File #------------------------------------------------------------------------------ def save_utf8_file(fn, lines): """Save string lines into an UTF8 text files. """ with open(fn, "w") as out_file: out_file.write("\n".join(lines).encode("utf-8")) def main_basename(path): r"""Return a main name of a basename of a given file path. Example ------- >>> main_basename('c:\code\langconv\MsgID.h') 'MsgID.h' """ base = os.path.basename(path) base_main, _base_ext = os.path.splitext(base) return base_main #------------------------------------------------------------------------------ # Math #------------------------------------------------------------------------------ def is_numeric(str): try: _offset = int(eval(str)) except: return False return True #------------------------------------------------------------------------------ # String #------------------------------------------------------------------------------ def replace_chars(text, replaced_pairs='', deleted_chars=''): """Return a char replaced text. Arguments --------- text -- the text replaced_pairs -- the replaced chars Example ------- >>> replaced = [('a','b'), ('c','d')] >>> removed = 'e' >>> replace_chars('abcde', replaced, removed) 'bbdd' """ for old, new in replaced_pairs: text = text.replace(old, new) for ch in deleted_chars: text = text.replace(ch, '') return text def camel_case(string): """Return camel case string from a space-separated string. Example ------- >>> camel_case('good job') 'GoodJob' """ return ''.join(w.capitalize() for w in string.split()) def replace_punctuations(text): """Replace punctuation characters with abbreviations for a string. """ punctuations = [ ('?', 'Q'), # Q: question mark ('.', 'P'), # P: period; full stop ('!', 'E'), # E: exclamation mark ("'", 'SQ'), # SQ: single quotation mark; single quote ('"', 'DQ'), # DQ: double quotation mark; double quotes ('(', 'LP'), # LP: left parenthese (')', 'RP'), # RP: right parenthese (':', 'Cn'), # Cn: colon (',', 'Ca'), # Ca: comma (';', 'S'), # S: semicolon ] deleted = '+-*/^=%$#@|\\<>{}[]' return replace_chars(text, punctuations, deleted) def remain_alnum(text): """Remain digits and English letters of a string. """ return ''.join(c for c in text if c.isalnum() and ord(' ') <= ord(c) <= ord('z')) #------------------------------------------------------------------------------ # For code generation #------------------------------------------------------------------------------ def c_identifier(text): """Convert input text into an legal identifier in C. Example ------- >>> c_identifier("Hello World") 'HelloWorld' >>> c_identifier("Anti-Shake") 'Antishake' """ if ' ' in text: <|fim_middle|> text = re.sub(r'\+\d+', lambda x: x.group().replace('+', 'P'), text) text = re.sub(r'\-\d+', lambda x: x.group().replace('-', 'N'), text) text = replace_punctuations(text) return remain_alnum(text) def wrap_header_guard(lines, h_fn): """Wrap a C header guard for a given line list. """ def underscore(txt): """Return an under_scores text from a CamelCase text. This function will leave a CamelCase text unchanged. """ s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', txt) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() h_fn_sig = '%s_H_' % underscore(main_basename(h_fn)).upper() begin = ['#ifndef %s' % h_fn_sig] begin += ['#define %s' % h_fn_sig, '', ''] end = ['', '', '#endif // %s' % h_fn_sig, ''] return begin + lines + end def prefix_info(lines, software, version, author, comment_mark='//'): """Prefix information to the given lines with given comment-mark. """ prefix = ['%s Generated by the %s v%s' % (comment_mark, software, version)] prefix += ['%s !author: %s' % (comment_mark, author)] prefix += ['%s !trail: %s %s' % (comment_mark, os.path.basename(sys.argv[0]), ' '.join(sys.argv[1:]))] return prefix + lines <|fim▁end|>
text = camel_case(text)
<|file_name|>myutil.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ This module put my utility functions """ __author__ = "Jiang Yu-Kuan <[email protected]>" __date__ = "2016/02/08 (initial version) ~ 2019/04/17 (last revision)" import re import os import sys #------------------------------------------------------------------------------ # File #------------------------------------------------------------------------------ def <|fim_middle|>(fn, lines): """Save string lines into an UTF8 text files. """ with open(fn, "w") as out_file: out_file.write("\n".join(lines).encode("utf-8")) def main_basename(path): r"""Return a main name of a basename of a given file path. Example ------- >>> main_basename('c:\code\langconv\MsgID.h') 'MsgID.h' """ base = os.path.basename(path) base_main, _base_ext = os.path.splitext(base) return base_main #------------------------------------------------------------------------------ # Math #------------------------------------------------------------------------------ def is_numeric(str): try: _offset = int(eval(str)) except: return False return True #------------------------------------------------------------------------------ # String #------------------------------------------------------------------------------ def replace_chars(text, replaced_pairs='', deleted_chars=''): """Return a char replaced text. Arguments --------- text -- the text replaced_pairs -- the replaced chars Example ------- >>> replaced = [('a','b'), ('c','d')] >>> removed = 'e' >>> replace_chars('abcde', replaced, removed) 'bbdd' """ for old, new in replaced_pairs: text = text.replace(old, new) for ch in deleted_chars: text = text.replace(ch, '') return text def camel_case(string): """Return camel case string from a space-separated string. Example ------- >>> camel_case('good job') 'GoodJob' """ return ''.join(w.capitalize() for w in string.split()) def replace_punctuations(text): """Replace punctuation characters with abbreviations for a string. """ punctuations = [ ('?', 'Q'), # Q: question mark ('.', 'P'), # P: period; full stop ('!', 'E'), # E: exclamation mark ("'", 'SQ'), # SQ: single quotation mark; single quote ('"', 'DQ'), # DQ: double quotation mark; double quotes ('(', 'LP'), # LP: left parenthese (')', 'RP'), # RP: right parenthese (':', 'Cn'), # Cn: colon (',', 'Ca'), # Ca: comma (';', 'S'), # S: semicolon ] deleted = '+-*/^=%$#@|\\<>{}[]' return replace_chars(text, punctuations, deleted) def remain_alnum(text): """Remain digits and English letters of a string. """ return ''.join(c for c in text if c.isalnum() and ord(' ') <= ord(c) <= ord('z')) #------------------------------------------------------------------------------ # For code generation #------------------------------------------------------------------------------ def c_identifier(text): """Convert input text into an legal identifier in C. Example ------- >>> c_identifier("Hello World") 'HelloWorld' >>> c_identifier("Anti-Shake") 'Antishake' """ if ' ' in text: text = camel_case(text) text = re.sub(r'\+\d+', lambda x: x.group().replace('+', 'P'), text) text = re.sub(r'\-\d+', lambda x: x.group().replace('-', 'N'), text) text = replace_punctuations(text) return remain_alnum(text) def wrap_header_guard(lines, h_fn): """Wrap a C header guard for a given line list. """ def underscore(txt): """Return an under_scores text from a CamelCase text. This function will leave a CamelCase text unchanged. """ s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', txt) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() h_fn_sig = '%s_H_' % underscore(main_basename(h_fn)).upper() begin = ['#ifndef %s' % h_fn_sig] begin += ['#define %s' % h_fn_sig, '', ''] end = ['', '', '#endif // %s' % h_fn_sig, ''] return begin + lines + end def prefix_info(lines, software, version, author, comment_mark='//'): """Prefix information to the given lines with given comment-mark. """ prefix = ['%s Generated by the %s v%s' % (comment_mark, software, version)] prefix += ['%s !author: %s' % (comment_mark, author)] prefix += ['%s !trail: %s %s' % (comment_mark, os.path.basename(sys.argv[0]), ' '.join(sys.argv[1:]))] return prefix + lines <|fim▁end|>
save_utf8_file
<|file_name|>myutil.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ This module put my utility functions """ __author__ = "Jiang Yu-Kuan <[email protected]>" __date__ = "2016/02/08 (initial version) ~ 2019/04/17 (last revision)" import re import os import sys #------------------------------------------------------------------------------ # File #------------------------------------------------------------------------------ def save_utf8_file(fn, lines): """Save string lines into an UTF8 text files. """ with open(fn, "w") as out_file: out_file.write("\n".join(lines).encode("utf-8")) def <|fim_middle|>(path): r"""Return a main name of a basename of a given file path. Example ------- >>> main_basename('c:\code\langconv\MsgID.h') 'MsgID.h' """ base = os.path.basename(path) base_main, _base_ext = os.path.splitext(base) return base_main #------------------------------------------------------------------------------ # Math #------------------------------------------------------------------------------ def is_numeric(str): try: _offset = int(eval(str)) except: return False return True #------------------------------------------------------------------------------ # String #------------------------------------------------------------------------------ def replace_chars(text, replaced_pairs='', deleted_chars=''): """Return a char replaced text. Arguments --------- text -- the text replaced_pairs -- the replaced chars Example ------- >>> replaced = [('a','b'), ('c','d')] >>> removed = 'e' >>> replace_chars('abcde', replaced, removed) 'bbdd' """ for old, new in replaced_pairs: text = text.replace(old, new) for ch in deleted_chars: text = text.replace(ch, '') return text def camel_case(string): """Return camel case string from a space-separated string. Example ------- >>> camel_case('good job') 'GoodJob' """ return ''.join(w.capitalize() for w in string.split()) def replace_punctuations(text): """Replace punctuation characters with abbreviations for a string. """ punctuations = [ ('?', 'Q'), # Q: question mark ('.', 'P'), # P: period; full stop ('!', 'E'), # E: exclamation mark ("'", 'SQ'), # SQ: single quotation mark; single quote ('"', 'DQ'), # DQ: double quotation mark; double quotes ('(', 'LP'), # LP: left parenthese (')', 'RP'), # RP: right parenthese (':', 'Cn'), # Cn: colon (',', 'Ca'), # Ca: comma (';', 'S'), # S: semicolon ] deleted = '+-*/^=%$#@|\\<>{}[]' return replace_chars(text, punctuations, deleted) def remain_alnum(text): """Remain digits and English letters of a string. """ return ''.join(c for c in text if c.isalnum() and ord(' ') <= ord(c) <= ord('z')) #------------------------------------------------------------------------------ # For code generation #------------------------------------------------------------------------------ def c_identifier(text): """Convert input text into an legal identifier in C. Example ------- >>> c_identifier("Hello World") 'HelloWorld' >>> c_identifier("Anti-Shake") 'Antishake' """ if ' ' in text: text = camel_case(text) text = re.sub(r'\+\d+', lambda x: x.group().replace('+', 'P'), text) text = re.sub(r'\-\d+', lambda x: x.group().replace('-', 'N'), text) text = replace_punctuations(text) return remain_alnum(text) def wrap_header_guard(lines, h_fn): """Wrap a C header guard for a given line list. """ def underscore(txt): """Return an under_scores text from a CamelCase text. This function will leave a CamelCase text unchanged. """ s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', txt) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() h_fn_sig = '%s_H_' % underscore(main_basename(h_fn)).upper() begin = ['#ifndef %s' % h_fn_sig] begin += ['#define %s' % h_fn_sig, '', ''] end = ['', '', '#endif // %s' % h_fn_sig, ''] return begin + lines + end def prefix_info(lines, software, version, author, comment_mark='//'): """Prefix information to the given lines with given comment-mark. """ prefix = ['%s Generated by the %s v%s' % (comment_mark, software, version)] prefix += ['%s !author: %s' % (comment_mark, author)] prefix += ['%s !trail: %s %s' % (comment_mark, os.path.basename(sys.argv[0]), ' '.join(sys.argv[1:]))] return prefix + lines <|fim▁end|>
main_basename
<|file_name|>myutil.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ This module put my utility functions """ __author__ = "Jiang Yu-Kuan <[email protected]>" __date__ = "2016/02/08 (initial version) ~ 2019/04/17 (last revision)" import re import os import sys #------------------------------------------------------------------------------ # File #------------------------------------------------------------------------------ def save_utf8_file(fn, lines): """Save string lines into an UTF8 text files. """ with open(fn, "w") as out_file: out_file.write("\n".join(lines).encode("utf-8")) def main_basename(path): r"""Return a main name of a basename of a given file path. Example ------- >>> main_basename('c:\code\langconv\MsgID.h') 'MsgID.h' """ base = os.path.basename(path) base_main, _base_ext = os.path.splitext(base) return base_main #------------------------------------------------------------------------------ # Math #------------------------------------------------------------------------------ def <|fim_middle|>(str): try: _offset = int(eval(str)) except: return False return True #------------------------------------------------------------------------------ # String #------------------------------------------------------------------------------ def replace_chars(text, replaced_pairs='', deleted_chars=''): """Return a char replaced text. Arguments --------- text -- the text replaced_pairs -- the replaced chars Example ------- >>> replaced = [('a','b'), ('c','d')] >>> removed = 'e' >>> replace_chars('abcde', replaced, removed) 'bbdd' """ for old, new in replaced_pairs: text = text.replace(old, new) for ch in deleted_chars: text = text.replace(ch, '') return text def camel_case(string): """Return camel case string from a space-separated string. Example ------- >>> camel_case('good job') 'GoodJob' """ return ''.join(w.capitalize() for w in string.split()) def replace_punctuations(text): """Replace punctuation characters with abbreviations for a string. """ punctuations = [ ('?', 'Q'), # Q: question mark ('.', 'P'), # P: period; full stop ('!', 'E'), # E: exclamation mark ("'", 'SQ'), # SQ: single quotation mark; single quote ('"', 'DQ'), # DQ: double quotation mark; double quotes ('(', 'LP'), # LP: left parenthese (')', 'RP'), # RP: right parenthese (':', 'Cn'), # Cn: colon (',', 'Ca'), # Ca: comma (';', 'S'), # S: semicolon ] deleted = '+-*/^=%$#@|\\<>{}[]' return replace_chars(text, punctuations, deleted) def remain_alnum(text): """Remain digits and English letters of a string. """ return ''.join(c for c in text if c.isalnum() and ord(' ') <= ord(c) <= ord('z')) #------------------------------------------------------------------------------ # For code generation #------------------------------------------------------------------------------ def c_identifier(text): """Convert input text into an legal identifier in C. Example ------- >>> c_identifier("Hello World") 'HelloWorld' >>> c_identifier("Anti-Shake") 'Antishake' """ if ' ' in text: text = camel_case(text) text = re.sub(r'\+\d+', lambda x: x.group().replace('+', 'P'), text) text = re.sub(r'\-\d+', lambda x: x.group().replace('-', 'N'), text) text = replace_punctuations(text) return remain_alnum(text) def wrap_header_guard(lines, h_fn): """Wrap a C header guard for a given line list. """ def underscore(txt): """Return an under_scores text from a CamelCase text. This function will leave a CamelCase text unchanged. """ s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', txt) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() h_fn_sig = '%s_H_' % underscore(main_basename(h_fn)).upper() begin = ['#ifndef %s' % h_fn_sig] begin += ['#define %s' % h_fn_sig, '', ''] end = ['', '', '#endif // %s' % h_fn_sig, ''] return begin + lines + end def prefix_info(lines, software, version, author, comment_mark='//'): """Prefix information to the given lines with given comment-mark. """ prefix = ['%s Generated by the %s v%s' % (comment_mark, software, version)] prefix += ['%s !author: %s' % (comment_mark, author)] prefix += ['%s !trail: %s %s' % (comment_mark, os.path.basename(sys.argv[0]), ' '.join(sys.argv[1:]))] return prefix + lines <|fim▁end|>
is_numeric
<|file_name|>myutil.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ This module put my utility functions """ __author__ = "Jiang Yu-Kuan <[email protected]>" __date__ = "2016/02/08 (initial version) ~ 2019/04/17 (last revision)" import re import os import sys #------------------------------------------------------------------------------ # File #------------------------------------------------------------------------------ def save_utf8_file(fn, lines): """Save string lines into an UTF8 text files. """ with open(fn, "w") as out_file: out_file.write("\n".join(lines).encode("utf-8")) def main_basename(path): r"""Return a main name of a basename of a given file path. Example ------- >>> main_basename('c:\code\langconv\MsgID.h') 'MsgID.h' """ base = os.path.basename(path) base_main, _base_ext = os.path.splitext(base) return base_main #------------------------------------------------------------------------------ # Math #------------------------------------------------------------------------------ def is_numeric(str): try: _offset = int(eval(str)) except: return False return True #------------------------------------------------------------------------------ # String #------------------------------------------------------------------------------ def <|fim_middle|>(text, replaced_pairs='', deleted_chars=''): """Return a char replaced text. Arguments --------- text -- the text replaced_pairs -- the replaced chars Example ------- >>> replaced = [('a','b'), ('c','d')] >>> removed = 'e' >>> replace_chars('abcde', replaced, removed) 'bbdd' """ for old, new in replaced_pairs: text = text.replace(old, new) for ch in deleted_chars: text = text.replace(ch, '') return text def camel_case(string): """Return camel case string from a space-separated string. Example ------- >>> camel_case('good job') 'GoodJob' """ return ''.join(w.capitalize() for w in string.split()) def replace_punctuations(text): """Replace punctuation characters with abbreviations for a string. """ punctuations = [ ('?', 'Q'), # Q: question mark ('.', 'P'), # P: period; full stop ('!', 'E'), # E: exclamation mark ("'", 'SQ'), # SQ: single quotation mark; single quote ('"', 'DQ'), # DQ: double quotation mark; double quotes ('(', 'LP'), # LP: left parenthese (')', 'RP'), # RP: right parenthese (':', 'Cn'), # Cn: colon (',', 'Ca'), # Ca: comma (';', 'S'), # S: semicolon ] deleted = '+-*/^=%$#@|\\<>{}[]' return replace_chars(text, punctuations, deleted) def remain_alnum(text): """Remain digits and English letters of a string. """ return ''.join(c for c in text if c.isalnum() and ord(' ') <= ord(c) <= ord('z')) #------------------------------------------------------------------------------ # For code generation #------------------------------------------------------------------------------ def c_identifier(text): """Convert input text into an legal identifier in C. Example ------- >>> c_identifier("Hello World") 'HelloWorld' >>> c_identifier("Anti-Shake") 'Antishake' """ if ' ' in text: text = camel_case(text) text = re.sub(r'\+\d+', lambda x: x.group().replace('+', 'P'), text) text = re.sub(r'\-\d+', lambda x: x.group().replace('-', 'N'), text) text = replace_punctuations(text) return remain_alnum(text) def wrap_header_guard(lines, h_fn): """Wrap a C header guard for a given line list. """ def underscore(txt): """Return an under_scores text from a CamelCase text. This function will leave a CamelCase text unchanged. """ s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', txt) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() h_fn_sig = '%s_H_' % underscore(main_basename(h_fn)).upper() begin = ['#ifndef %s' % h_fn_sig] begin += ['#define %s' % h_fn_sig, '', ''] end = ['', '', '#endif // %s' % h_fn_sig, ''] return begin + lines + end def prefix_info(lines, software, version, author, comment_mark='//'): """Prefix information to the given lines with given comment-mark. """ prefix = ['%s Generated by the %s v%s' % (comment_mark, software, version)] prefix += ['%s !author: %s' % (comment_mark, author)] prefix += ['%s !trail: %s %s' % (comment_mark, os.path.basename(sys.argv[0]), ' '.join(sys.argv[1:]))] return prefix + lines <|fim▁end|>
replace_chars
<|file_name|>myutil.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ This module put my utility functions """ __author__ = "Jiang Yu-Kuan <[email protected]>" __date__ = "2016/02/08 (initial version) ~ 2019/04/17 (last revision)" import re import os import sys #------------------------------------------------------------------------------ # File #------------------------------------------------------------------------------ def save_utf8_file(fn, lines): """Save string lines into an UTF8 text files. """ with open(fn, "w") as out_file: out_file.write("\n".join(lines).encode("utf-8")) def main_basename(path): r"""Return a main name of a basename of a given file path. Example ------- >>> main_basename('c:\code\langconv\MsgID.h') 'MsgID.h' """ base = os.path.basename(path) base_main, _base_ext = os.path.splitext(base) return base_main #------------------------------------------------------------------------------ # Math #------------------------------------------------------------------------------ def is_numeric(str): try: _offset = int(eval(str)) except: return False return True #------------------------------------------------------------------------------ # String #------------------------------------------------------------------------------ def replace_chars(text, replaced_pairs='', deleted_chars=''): """Return a char replaced text. Arguments --------- text -- the text replaced_pairs -- the replaced chars Example ------- >>> replaced = [('a','b'), ('c','d')] >>> removed = 'e' >>> replace_chars('abcde', replaced, removed) 'bbdd' """ for old, new in replaced_pairs: text = text.replace(old, new) for ch in deleted_chars: text = text.replace(ch, '') return text def <|fim_middle|>(string): """Return camel case string from a space-separated string. Example ------- >>> camel_case('good job') 'GoodJob' """ return ''.join(w.capitalize() for w in string.split()) def replace_punctuations(text): """Replace punctuation characters with abbreviations for a string. """ punctuations = [ ('?', 'Q'), # Q: question mark ('.', 'P'), # P: period; full stop ('!', 'E'), # E: exclamation mark ("'", 'SQ'), # SQ: single quotation mark; single quote ('"', 'DQ'), # DQ: double quotation mark; double quotes ('(', 'LP'), # LP: left parenthese (')', 'RP'), # RP: right parenthese (':', 'Cn'), # Cn: colon (',', 'Ca'), # Ca: comma (';', 'S'), # S: semicolon ] deleted = '+-*/^=%$#@|\\<>{}[]' return replace_chars(text, punctuations, deleted) def remain_alnum(text): """Remain digits and English letters of a string. """ return ''.join(c for c in text if c.isalnum() and ord(' ') <= ord(c) <= ord('z')) #------------------------------------------------------------------------------ # For code generation #------------------------------------------------------------------------------ def c_identifier(text): """Convert input text into an legal identifier in C. Example ------- >>> c_identifier("Hello World") 'HelloWorld' >>> c_identifier("Anti-Shake") 'Antishake' """ if ' ' in text: text = camel_case(text) text = re.sub(r'\+\d+', lambda x: x.group().replace('+', 'P'), text) text = re.sub(r'\-\d+', lambda x: x.group().replace('-', 'N'), text) text = replace_punctuations(text) return remain_alnum(text) def wrap_header_guard(lines, h_fn): """Wrap a C header guard for a given line list. """ def underscore(txt): """Return an under_scores text from a CamelCase text. This function will leave a CamelCase text unchanged. """ s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', txt) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() h_fn_sig = '%s_H_' % underscore(main_basename(h_fn)).upper() begin = ['#ifndef %s' % h_fn_sig] begin += ['#define %s' % h_fn_sig, '', ''] end = ['', '', '#endif // %s' % h_fn_sig, ''] return begin + lines + end def prefix_info(lines, software, version, author, comment_mark='//'): """Prefix information to the given lines with given comment-mark. """ prefix = ['%s Generated by the %s v%s' % (comment_mark, software, version)] prefix += ['%s !author: %s' % (comment_mark, author)] prefix += ['%s !trail: %s %s' % (comment_mark, os.path.basename(sys.argv[0]), ' '.join(sys.argv[1:]))] return prefix + lines <|fim▁end|>
camel_case
<|file_name|>myutil.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ This module put my utility functions """ __author__ = "Jiang Yu-Kuan <[email protected]>" __date__ = "2016/02/08 (initial version) ~ 2019/04/17 (last revision)" import re import os import sys #------------------------------------------------------------------------------ # File #------------------------------------------------------------------------------ def save_utf8_file(fn, lines): """Save string lines into an UTF8 text files. """ with open(fn, "w") as out_file: out_file.write("\n".join(lines).encode("utf-8")) def main_basename(path): r"""Return a main name of a basename of a given file path. Example ------- >>> main_basename('c:\code\langconv\MsgID.h') 'MsgID.h' """ base = os.path.basename(path) base_main, _base_ext = os.path.splitext(base) return base_main #------------------------------------------------------------------------------ # Math #------------------------------------------------------------------------------ def is_numeric(str): try: _offset = int(eval(str)) except: return False return True #------------------------------------------------------------------------------ # String #------------------------------------------------------------------------------ def replace_chars(text, replaced_pairs='', deleted_chars=''): """Return a char replaced text. Arguments --------- text -- the text replaced_pairs -- the replaced chars Example ------- >>> replaced = [('a','b'), ('c','d')] >>> removed = 'e' >>> replace_chars('abcde', replaced, removed) 'bbdd' """ for old, new in replaced_pairs: text = text.replace(old, new) for ch in deleted_chars: text = text.replace(ch, '') return text def camel_case(string): """Return camel case string from a space-separated string. Example ------- >>> camel_case('good job') 'GoodJob' """ return ''.join(w.capitalize() for w in string.split()) def <|fim_middle|>(text): """Replace punctuation characters with abbreviations for a string. """ punctuations = [ ('?', 'Q'), # Q: question mark ('.', 'P'), # P: period; full stop ('!', 'E'), # E: exclamation mark ("'", 'SQ'), # SQ: single quotation mark; single quote ('"', 'DQ'), # DQ: double quotation mark; double quotes ('(', 'LP'), # LP: left parenthese (')', 'RP'), # RP: right parenthese (':', 'Cn'), # Cn: colon (',', 'Ca'), # Ca: comma (';', 'S'), # S: semicolon ] deleted = '+-*/^=%$#@|\\<>{}[]' return replace_chars(text, punctuations, deleted) def remain_alnum(text): """Remain digits and English letters of a string. """ return ''.join(c for c in text if c.isalnum() and ord(' ') <= ord(c) <= ord('z')) #------------------------------------------------------------------------------ # For code generation #------------------------------------------------------------------------------ def c_identifier(text): """Convert input text into an legal identifier in C. Example ------- >>> c_identifier("Hello World") 'HelloWorld' >>> c_identifier("Anti-Shake") 'Antishake' """ if ' ' in text: text = camel_case(text) text = re.sub(r'\+\d+', lambda x: x.group().replace('+', 'P'), text) text = re.sub(r'\-\d+', lambda x: x.group().replace('-', 'N'), text) text = replace_punctuations(text) return remain_alnum(text) def wrap_header_guard(lines, h_fn): """Wrap a C header guard for a given line list. """ def underscore(txt): """Return an under_scores text from a CamelCase text. This function will leave a CamelCase text unchanged. """ s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', txt) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() h_fn_sig = '%s_H_' % underscore(main_basename(h_fn)).upper() begin = ['#ifndef %s' % h_fn_sig] begin += ['#define %s' % h_fn_sig, '', ''] end = ['', '', '#endif // %s' % h_fn_sig, ''] return begin + lines + end def prefix_info(lines, software, version, author, comment_mark='//'): """Prefix information to the given lines with given comment-mark. """ prefix = ['%s Generated by the %s v%s' % (comment_mark, software, version)] prefix += ['%s !author: %s' % (comment_mark, author)] prefix += ['%s !trail: %s %s' % (comment_mark, os.path.basename(sys.argv[0]), ' '.join(sys.argv[1:]))] return prefix + lines <|fim▁end|>
replace_punctuations
<|file_name|>myutil.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ This module put my utility functions """ __author__ = "Jiang Yu-Kuan <[email protected]>" __date__ = "2016/02/08 (initial version) ~ 2019/04/17 (last revision)" import re import os import sys #------------------------------------------------------------------------------ # File #------------------------------------------------------------------------------ def save_utf8_file(fn, lines): """Save string lines into an UTF8 text files. """ with open(fn, "w") as out_file: out_file.write("\n".join(lines).encode("utf-8")) def main_basename(path): r"""Return a main name of a basename of a given file path. Example ------- >>> main_basename('c:\code\langconv\MsgID.h') 'MsgID.h' """ base = os.path.basename(path) base_main, _base_ext = os.path.splitext(base) return base_main #------------------------------------------------------------------------------ # Math #------------------------------------------------------------------------------ def is_numeric(str): try: _offset = int(eval(str)) except: return False return True #------------------------------------------------------------------------------ # String #------------------------------------------------------------------------------ def replace_chars(text, replaced_pairs='', deleted_chars=''): """Return a char replaced text. Arguments --------- text -- the text replaced_pairs -- the replaced chars Example ------- >>> replaced = [('a','b'), ('c','d')] >>> removed = 'e' >>> replace_chars('abcde', replaced, removed) 'bbdd' """ for old, new in replaced_pairs: text = text.replace(old, new) for ch in deleted_chars: text = text.replace(ch, '') return text def camel_case(string): """Return camel case string from a space-separated string. Example ------- >>> camel_case('good job') 'GoodJob' """ return ''.join(w.capitalize() for w in string.split()) def replace_punctuations(text): """Replace punctuation characters with abbreviations for a string. """ punctuations = [ ('?', 'Q'), # Q: question mark ('.', 'P'), # P: period; full stop ('!', 'E'), # E: exclamation mark ("'", 'SQ'), # SQ: single quotation mark; single quote ('"', 'DQ'), # DQ: double quotation mark; double quotes ('(', 'LP'), # LP: left parenthese (')', 'RP'), # RP: right parenthese (':', 'Cn'), # Cn: colon (',', 'Ca'), # Ca: comma (';', 'S'), # S: semicolon ] deleted = '+-*/^=%$#@|\\<>{}[]' return replace_chars(text, punctuations, deleted) def <|fim_middle|>(text): """Remain digits and English letters of a string. """ return ''.join(c for c in text if c.isalnum() and ord(' ') <= ord(c) <= ord('z')) #------------------------------------------------------------------------------ # For code generation #------------------------------------------------------------------------------ def c_identifier(text): """Convert input text into an legal identifier in C. Example ------- >>> c_identifier("Hello World") 'HelloWorld' >>> c_identifier("Anti-Shake") 'Antishake' """ if ' ' in text: text = camel_case(text) text = re.sub(r'\+\d+', lambda x: x.group().replace('+', 'P'), text) text = re.sub(r'\-\d+', lambda x: x.group().replace('-', 'N'), text) text = replace_punctuations(text) return remain_alnum(text) def wrap_header_guard(lines, h_fn): """Wrap a C header guard for a given line list. """ def underscore(txt): """Return an under_scores text from a CamelCase text. This function will leave a CamelCase text unchanged. """ s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', txt) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() h_fn_sig = '%s_H_' % underscore(main_basename(h_fn)).upper() begin = ['#ifndef %s' % h_fn_sig] begin += ['#define %s' % h_fn_sig, '', ''] end = ['', '', '#endif // %s' % h_fn_sig, ''] return begin + lines + end def prefix_info(lines, software, version, author, comment_mark='//'): """Prefix information to the given lines with given comment-mark. """ prefix = ['%s Generated by the %s v%s' % (comment_mark, software, version)] prefix += ['%s !author: %s' % (comment_mark, author)] prefix += ['%s !trail: %s %s' % (comment_mark, os.path.basename(sys.argv[0]), ' '.join(sys.argv[1:]))] return prefix + lines <|fim▁end|>
remain_alnum
<|file_name|>myutil.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ This module put my utility functions """ __author__ = "Jiang Yu-Kuan <[email protected]>" __date__ = "2016/02/08 (initial version) ~ 2019/04/17 (last revision)" import re import os import sys #------------------------------------------------------------------------------ # File #------------------------------------------------------------------------------ def save_utf8_file(fn, lines): """Save string lines into an UTF8 text files. """ with open(fn, "w") as out_file: out_file.write("\n".join(lines).encode("utf-8")) def main_basename(path): r"""Return a main name of a basename of a given file path. Example ------- >>> main_basename('c:\code\langconv\MsgID.h') 'MsgID.h' """ base = os.path.basename(path) base_main, _base_ext = os.path.splitext(base) return base_main #------------------------------------------------------------------------------ # Math #------------------------------------------------------------------------------ def is_numeric(str): try: _offset = int(eval(str)) except: return False return True #------------------------------------------------------------------------------ # String #------------------------------------------------------------------------------ def replace_chars(text, replaced_pairs='', deleted_chars=''): """Return a char replaced text. Arguments --------- text -- the text replaced_pairs -- the replaced chars Example ------- >>> replaced = [('a','b'), ('c','d')] >>> removed = 'e' >>> replace_chars('abcde', replaced, removed) 'bbdd' """ for old, new in replaced_pairs: text = text.replace(old, new) for ch in deleted_chars: text = text.replace(ch, '') return text def camel_case(string): """Return camel case string from a space-separated string. Example ------- >>> camel_case('good job') 'GoodJob' """ return ''.join(w.capitalize() for w in string.split()) def replace_punctuations(text): """Replace punctuation characters with abbreviations for a string. """ punctuations = [ ('?', 'Q'), # Q: question mark ('.', 'P'), # P: period; full stop ('!', 'E'), # E: exclamation mark ("'", 'SQ'), # SQ: single quotation mark; single quote ('"', 'DQ'), # DQ: double quotation mark; double quotes ('(', 'LP'), # LP: left parenthese (')', 'RP'), # RP: right parenthese (':', 'Cn'), # Cn: colon (',', 'Ca'), # Ca: comma (';', 'S'), # S: semicolon ] deleted = '+-*/^=%$#@|\\<>{}[]' return replace_chars(text, punctuations, deleted) def remain_alnum(text): """Remain digits and English letters of a string. """ return ''.join(c for c in text if c.isalnum() and ord(' ') <= ord(c) <= ord('z')) #------------------------------------------------------------------------------ # For code generation #------------------------------------------------------------------------------ def <|fim_middle|>(text): """Convert input text into an legal identifier in C. Example ------- >>> c_identifier("Hello World") 'HelloWorld' >>> c_identifier("Anti-Shake") 'Antishake' """ if ' ' in text: text = camel_case(text) text = re.sub(r'\+\d+', lambda x: x.group().replace('+', 'P'), text) text = re.sub(r'\-\d+', lambda x: x.group().replace('-', 'N'), text) text = replace_punctuations(text) return remain_alnum(text) def wrap_header_guard(lines, h_fn): """Wrap a C header guard for a given line list. """ def underscore(txt): """Return an under_scores text from a CamelCase text. This function will leave a CamelCase text unchanged. """ s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', txt) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() h_fn_sig = '%s_H_' % underscore(main_basename(h_fn)).upper() begin = ['#ifndef %s' % h_fn_sig] begin += ['#define %s' % h_fn_sig, '', ''] end = ['', '', '#endif // %s' % h_fn_sig, ''] return begin + lines + end def prefix_info(lines, software, version, author, comment_mark='//'): """Prefix information to the given lines with given comment-mark. """ prefix = ['%s Generated by the %s v%s' % (comment_mark, software, version)] prefix += ['%s !author: %s' % (comment_mark, author)] prefix += ['%s !trail: %s %s' % (comment_mark, os.path.basename(sys.argv[0]), ' '.join(sys.argv[1:]))] return prefix + lines <|fim▁end|>
c_identifier
<|file_name|>myutil.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ This module put my utility functions """ __author__ = "Jiang Yu-Kuan <[email protected]>" __date__ = "2016/02/08 (initial version) ~ 2019/04/17 (last revision)" import re import os import sys #------------------------------------------------------------------------------ # File #------------------------------------------------------------------------------ def save_utf8_file(fn, lines): """Save string lines into an UTF8 text files. """ with open(fn, "w") as out_file: out_file.write("\n".join(lines).encode("utf-8")) def main_basename(path): r"""Return a main name of a basename of a given file path. Example ------- >>> main_basename('c:\code\langconv\MsgID.h') 'MsgID.h' """ base = os.path.basename(path) base_main, _base_ext = os.path.splitext(base) return base_main #------------------------------------------------------------------------------ # Math #------------------------------------------------------------------------------ def is_numeric(str): try: _offset = int(eval(str)) except: return False return True #------------------------------------------------------------------------------ # String #------------------------------------------------------------------------------ def replace_chars(text, replaced_pairs='', deleted_chars=''): """Return a char replaced text. Arguments --------- text -- the text replaced_pairs -- the replaced chars Example ------- >>> replaced = [('a','b'), ('c','d')] >>> removed = 'e' >>> replace_chars('abcde', replaced, removed) 'bbdd' """ for old, new in replaced_pairs: text = text.replace(old, new) for ch in deleted_chars: text = text.replace(ch, '') return text def camel_case(string): """Return camel case string from a space-separated string. Example ------- >>> camel_case('good job') 'GoodJob' """ return ''.join(w.capitalize() for w in string.split()) def replace_punctuations(text): """Replace punctuation characters with abbreviations for a string. """ punctuations = [ ('?', 'Q'), # Q: question mark ('.', 'P'), # P: period; full stop ('!', 'E'), # E: exclamation mark ("'", 'SQ'), # SQ: single quotation mark; single quote ('"', 'DQ'), # DQ: double quotation mark; double quotes ('(', 'LP'), # LP: left parenthese (')', 'RP'), # RP: right parenthese (':', 'Cn'), # Cn: colon (',', 'Ca'), # Ca: comma (';', 'S'), # S: semicolon ] deleted = '+-*/^=%$#@|\\<>{}[]' return replace_chars(text, punctuations, deleted) def remain_alnum(text): """Remain digits and English letters of a string. """ return ''.join(c for c in text if c.isalnum() and ord(' ') <= ord(c) <= ord('z')) #------------------------------------------------------------------------------ # For code generation #------------------------------------------------------------------------------ def c_identifier(text): """Convert input text into an legal identifier in C. Example ------- >>> c_identifier("Hello World") 'HelloWorld' >>> c_identifier("Anti-Shake") 'Antishake' """ if ' ' in text: text = camel_case(text) text = re.sub(r'\+\d+', lambda x: x.group().replace('+', 'P'), text) text = re.sub(r'\-\d+', lambda x: x.group().replace('-', 'N'), text) text = replace_punctuations(text) return remain_alnum(text) def <|fim_middle|>(lines, h_fn): """Wrap a C header guard for a given line list. """ def underscore(txt): """Return an under_scores text from a CamelCase text. This function will leave a CamelCase text unchanged. """ s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', txt) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() h_fn_sig = '%s_H_' % underscore(main_basename(h_fn)).upper() begin = ['#ifndef %s' % h_fn_sig] begin += ['#define %s' % h_fn_sig, '', ''] end = ['', '', '#endif // %s' % h_fn_sig, ''] return begin + lines + end def prefix_info(lines, software, version, author, comment_mark='//'): """Prefix information to the given lines with given comment-mark. """ prefix = ['%s Generated by the %s v%s' % (comment_mark, software, version)] prefix += ['%s !author: %s' % (comment_mark, author)] prefix += ['%s !trail: %s %s' % (comment_mark, os.path.basename(sys.argv[0]), ' '.join(sys.argv[1:]))] return prefix + lines <|fim▁end|>
wrap_header_guard
<|file_name|>myutil.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ This module put my utility functions """ __author__ = "Jiang Yu-Kuan <[email protected]>" __date__ = "2016/02/08 (initial version) ~ 2019/04/17 (last revision)" import re import os import sys #------------------------------------------------------------------------------ # File #------------------------------------------------------------------------------ def save_utf8_file(fn, lines): """Save string lines into an UTF8 text files. """ with open(fn, "w") as out_file: out_file.write("\n".join(lines).encode("utf-8")) def main_basename(path): r"""Return a main name of a basename of a given file path. Example ------- >>> main_basename('c:\code\langconv\MsgID.h') 'MsgID.h' """ base = os.path.basename(path) base_main, _base_ext = os.path.splitext(base) return base_main #------------------------------------------------------------------------------ # Math #------------------------------------------------------------------------------ def is_numeric(str): try: _offset = int(eval(str)) except: return False return True #------------------------------------------------------------------------------ # String #------------------------------------------------------------------------------ def replace_chars(text, replaced_pairs='', deleted_chars=''): """Return a char replaced text. Arguments --------- text -- the text replaced_pairs -- the replaced chars Example ------- >>> replaced = [('a','b'), ('c','d')] >>> removed = 'e' >>> replace_chars('abcde', replaced, removed) 'bbdd' """ for old, new in replaced_pairs: text = text.replace(old, new) for ch in deleted_chars: text = text.replace(ch, '') return text def camel_case(string): """Return camel case string from a space-separated string. Example ------- >>> camel_case('good job') 'GoodJob' """ return ''.join(w.capitalize() for w in string.split()) def replace_punctuations(text): """Replace punctuation characters with abbreviations for a string. """ punctuations = [ ('?', 'Q'), # Q: question mark ('.', 'P'), # P: period; full stop ('!', 'E'), # E: exclamation mark ("'", 'SQ'), # SQ: single quotation mark; single quote ('"', 'DQ'), # DQ: double quotation mark; double quotes ('(', 'LP'), # LP: left parenthese (')', 'RP'), # RP: right parenthese (':', 'Cn'), # Cn: colon (',', 'Ca'), # Ca: comma (';', 'S'), # S: semicolon ] deleted = '+-*/^=%$#@|\\<>{}[]' return replace_chars(text, punctuations, deleted) def remain_alnum(text): """Remain digits and English letters of a string. """ return ''.join(c for c in text if c.isalnum() and ord(' ') <= ord(c) <= ord('z')) #------------------------------------------------------------------------------ # For code generation #------------------------------------------------------------------------------ def c_identifier(text): """Convert input text into an legal identifier in C. Example ------- >>> c_identifier("Hello World") 'HelloWorld' >>> c_identifier("Anti-Shake") 'Antishake' """ if ' ' in text: text = camel_case(text) text = re.sub(r'\+\d+', lambda x: x.group().replace('+', 'P'), text) text = re.sub(r'\-\d+', lambda x: x.group().replace('-', 'N'), text) text = replace_punctuations(text) return remain_alnum(text) def wrap_header_guard(lines, h_fn): """Wrap a C header guard for a given line list. """ def <|fim_middle|>(txt): """Return an under_scores text from a CamelCase text. This function will leave a CamelCase text unchanged. """ s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', txt) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() h_fn_sig = '%s_H_' % underscore(main_basename(h_fn)).upper() begin = ['#ifndef %s' % h_fn_sig] begin += ['#define %s' % h_fn_sig, '', ''] end = ['', '', '#endif // %s' % h_fn_sig, ''] return begin + lines + end def prefix_info(lines, software, version, author, comment_mark='//'): """Prefix information to the given lines with given comment-mark. """ prefix = ['%s Generated by the %s v%s' % (comment_mark, software, version)] prefix += ['%s !author: %s' % (comment_mark, author)] prefix += ['%s !trail: %s %s' % (comment_mark, os.path.basename(sys.argv[0]), ' '.join(sys.argv[1:]))] return prefix + lines <|fim▁end|>
underscore
<|file_name|>myutil.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ This module put my utility functions """ __author__ = "Jiang Yu-Kuan <[email protected]>" __date__ = "2016/02/08 (initial version) ~ 2019/04/17 (last revision)" import re import os import sys #------------------------------------------------------------------------------ # File #------------------------------------------------------------------------------ def save_utf8_file(fn, lines): """Save string lines into an UTF8 text files. """ with open(fn, "w") as out_file: out_file.write("\n".join(lines).encode("utf-8")) def main_basename(path): r"""Return a main name of a basename of a given file path. Example ------- >>> main_basename('c:\code\langconv\MsgID.h') 'MsgID.h' """ base = os.path.basename(path) base_main, _base_ext = os.path.splitext(base) return base_main #------------------------------------------------------------------------------ # Math #------------------------------------------------------------------------------ def is_numeric(str): try: _offset = int(eval(str)) except: return False return True #------------------------------------------------------------------------------ # String #------------------------------------------------------------------------------ def replace_chars(text, replaced_pairs='', deleted_chars=''): """Return a char replaced text. Arguments --------- text -- the text replaced_pairs -- the replaced chars Example ------- >>> replaced = [('a','b'), ('c','d')] >>> removed = 'e' >>> replace_chars('abcde', replaced, removed) 'bbdd' """ for old, new in replaced_pairs: text = text.replace(old, new) for ch in deleted_chars: text = text.replace(ch, '') return text def camel_case(string): """Return camel case string from a space-separated string. Example ------- >>> camel_case('good job') 'GoodJob' """ return ''.join(w.capitalize() for w in string.split()) def replace_punctuations(text): """Replace punctuation characters with abbreviations for a string. """ punctuations = [ ('?', 'Q'), # Q: question mark ('.', 'P'), # P: period; full stop ('!', 'E'), # E: exclamation mark ("'", 'SQ'), # SQ: single quotation mark; single quote ('"', 'DQ'), # DQ: double quotation mark; double quotes ('(', 'LP'), # LP: left parenthese (')', 'RP'), # RP: right parenthese (':', 'Cn'), # Cn: colon (',', 'Ca'), # Ca: comma (';', 'S'), # S: semicolon ] deleted = '+-*/^=%$#@|\\<>{}[]' return replace_chars(text, punctuations, deleted) def remain_alnum(text): """Remain digits and English letters of a string. """ return ''.join(c for c in text if c.isalnum() and ord(' ') <= ord(c) <= ord('z')) #------------------------------------------------------------------------------ # For code generation #------------------------------------------------------------------------------ def c_identifier(text): """Convert input text into an legal identifier in C. Example ------- >>> c_identifier("Hello World") 'HelloWorld' >>> c_identifier("Anti-Shake") 'Antishake' """ if ' ' in text: text = camel_case(text) text = re.sub(r'\+\d+', lambda x: x.group().replace('+', 'P'), text) text = re.sub(r'\-\d+', lambda x: x.group().replace('-', 'N'), text) text = replace_punctuations(text) return remain_alnum(text) def wrap_header_guard(lines, h_fn): """Wrap a C header guard for a given line list. """ def underscore(txt): """Return an under_scores text from a CamelCase text. This function will leave a CamelCase text unchanged. """ s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', txt) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() h_fn_sig = '%s_H_' % underscore(main_basename(h_fn)).upper() begin = ['#ifndef %s' % h_fn_sig] begin += ['#define %s' % h_fn_sig, '', ''] end = ['', '', '#endif // %s' % h_fn_sig, ''] return begin + lines + end def <|fim_middle|>(lines, software, version, author, comment_mark='//'): """Prefix information to the given lines with given comment-mark. """ prefix = ['%s Generated by the %s v%s' % (comment_mark, software, version)] prefix += ['%s !author: %s' % (comment_mark, author)] prefix += ['%s !trail: %s %s' % (comment_mark, os.path.basename(sys.argv[0]), ' '.join(sys.argv[1:]))] return prefix + lines <|fim▁end|>
prefix_info
<|file_name|>testingColorImg.py<|end_file_name|><|fim▁begin|>import cv2 import numpy as np np.set_printoptions(threshold=np.nan) import util as util import edge_detect import lineseg import drawedgelist # img = cv2.imread("img/Slide2.jpg", 0) img = cv2.imread("unsorted/Unit Tests/lambda.png", 0) im_size = img.shape returnedCanny = cv2.Canny(img, 50, 150, apertureSize = 3) cv2.imshow("newcanny", returnedCanny) skel_dst = util.morpho(returnedCanny) out = edge_detect.mask_contours(edge_detect.create_img(skel_dst)) res = [] # print(np.squeeze(out[0])) # print(out[0][0]) for i in range(len(out)): # Add the first point to the end so the shape closes current = np.squeeze(out[i]) # print('current', current) # print('first', out[i][0]) if current.shape[0] > 2: # res.append(np.concatenate((current, out[i][0]))) # print(res[-1]) res.append(current) # print(np.concatenate((np.squeeze(out[i]), out[i][0]))) res = np.array(res) util.sqz_contours(res) res = lineseg.lineseg(np.array([res[1]]), tol=5) print(res, "res") """ for x in range(len(res)): for y in range(lan ): """ drawedgelist.drawedgelist(res, img) """ seglist = [] for i in range(res.shape[0]): # print('shape', res[i].shape) if res[i].shape[0] > 2: # print(res[i]) # print(res[i][0]) seglist.append(np.concatenate((res[i], [res[i][0]]))) else: seglist.append(res[i]) seglist = np.array(seglist) """ #print(seglist, "seglist") #print(len(seglist), "seglist len") #print(seglist.shape, "seglistshape") #drawedgelist.drawedgelist(seglist) """ # ******* SECTION 2 ******* # SEGMENT AND LABEL THE CURVATURE LINES (CONVEX/CONCAVE). LineFeature, ListPoint = Lseg_to_Lfeat_v4.create_linefeatures(seglist, res, im_size) Line_new, ListPoint_new, line_merged = merge_lines_v4.merge_lines(LineFeature, ListPoint, 10, im_size)<|fim▁hole|>util.draw_lf(Line_new, blank_image) line_newC = LabelLineCurveFeature_v4.classify_curves(img, Line_new, ListPoint_new, 11)"""<|fim▁end|>
#print(Line_new, "line new") print(len(Line_new), "len line new")
<|file_name|>testingColorImg.py<|end_file_name|><|fim▁begin|>import cv2 import numpy as np np.set_printoptions(threshold=np.nan) import util as util import edge_detect import lineseg import drawedgelist # img = cv2.imread("img/Slide2.jpg", 0) img = cv2.imread("unsorted/Unit Tests/lambda.png", 0) im_size = img.shape returnedCanny = cv2.Canny(img, 50, 150, apertureSize = 3) cv2.imshow("newcanny", returnedCanny) skel_dst = util.morpho(returnedCanny) out = edge_detect.mask_contours(edge_detect.create_img(skel_dst)) res = [] # print(np.squeeze(out[0])) # print(out[0][0]) for i in range(len(out)): # Add the first point to the end so the shape closes current = np.squeeze(out[i]) # print('current', current) # print('first', out[i][0]) if current.shape[0] > 2: # res.append(np.concatenate((current, out[i][0]))) # print(res[-1]) <|fim_middle|> # print(np.concatenate((np.squeeze(out[i]), out[i][0]))) res = np.array(res) util.sqz_contours(res) res = lineseg.lineseg(np.array([res[1]]), tol=5) print(res, "res") """ for x in range(len(res)): for y in range(lan ): """ drawedgelist.drawedgelist(res, img) """ seglist = [] for i in range(res.shape[0]): # print('shape', res[i].shape) if res[i].shape[0] > 2: # print(res[i]) # print(res[i][0]) seglist.append(np.concatenate((res[i], [res[i][0]]))) else: seglist.append(res[i]) seglist = np.array(seglist) """ #print(seglist, "seglist") #print(len(seglist), "seglist len") #print(seglist.shape, "seglistshape") #drawedgelist.drawedgelist(seglist) """ # ******* SECTION 2 ******* # SEGMENT AND LABEL THE CURVATURE LINES (CONVEX/CONCAVE). LineFeature, ListPoint = Lseg_to_Lfeat_v4.create_linefeatures(seglist, res, im_size) Line_new, ListPoint_new, line_merged = merge_lines_v4.merge_lines(LineFeature, ListPoint, 10, im_size) #print(Line_new, "line new") print(len(Line_new), "len line new") util.draw_lf(Line_new, blank_image) line_newC = LabelLineCurveFeature_v4.classify_curves(img, Line_new, ListPoint_new, 11)"""<|fim▁end|>
res.append(current)
<|file_name|>largest_BST_in_a_binary_tree.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Created on Thu Nov 19 17:38:50 2015 @author: deep """ from binaryTree import BTree, generateRandomTree, inorder def largestBST(root): if root.left is None and root.right is None: return True, 1, root.value, root.value if root.left: isBSTL, sizeL, minL, maxL = largestBST(root.left) else: isBSTL = True sizeL = 0 minL = -float('inf') if root.right: isBSTR, sizeR, minR, maxR = largestBST(root.right) else: isBSTR = True sizeR = 0 maxR = float('inf') if isBSTL and isBSTR: if maxL <= root.value <= minR: return True, sizeL+sizeR+1, minL, maxR, size = max(sizeL, sizeR) return False, size , None, None root1 = BTree() root1.value = 0 root2 = BTree() root2.value = 0<|fim▁hole|>generateRandomTree(root1,2) root1.left.left.left = root2 inorder(root1) print largestBST(root1)<|fim▁end|>
generateRandomTree(root2,2)
<|file_name|>largest_BST_in_a_binary_tree.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Created on Thu Nov 19 17:38:50 2015 @author: deep """ from binaryTree import BTree, generateRandomTree, inorder def largestBST(root): <|fim_middle|> root1 = BTree() root1.value = 0 root2 = BTree() root2.value = 0 generateRandomTree(root2,2) generateRandomTree(root1,2) root1.left.left.left = root2 inorder(root1) print largestBST(root1) <|fim▁end|>
if root.left is None and root.right is None: return True, 1, root.value, root.value if root.left: isBSTL, sizeL, minL, maxL = largestBST(root.left) else: isBSTL = True sizeL = 0 minL = -float('inf') if root.right: isBSTR, sizeR, minR, maxR = largestBST(root.right) else: isBSTR = True sizeR = 0 maxR = float('inf') if isBSTL and isBSTR: if maxL <= root.value <= minR: return True, sizeL+sizeR+1, minL, maxR, size = max(sizeL, sizeR) return False, size , None, None
<|file_name|>largest_BST_in_a_binary_tree.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Created on Thu Nov 19 17:38:50 2015 @author: deep """ from binaryTree import BTree, generateRandomTree, inorder def largestBST(root): if root.left is None and root.right is None: <|fim_middle|> if root.left: isBSTL, sizeL, minL, maxL = largestBST(root.left) else: isBSTL = True sizeL = 0 minL = -float('inf') if root.right: isBSTR, sizeR, minR, maxR = largestBST(root.right) else: isBSTR = True sizeR = 0 maxR = float('inf') if isBSTL and isBSTR: if maxL <= root.value <= minR: return True, sizeL+sizeR+1, minL, maxR, size = max(sizeL, sizeR) return False, size , None, None root1 = BTree() root1.value = 0 root2 = BTree() root2.value = 0 generateRandomTree(root2,2) generateRandomTree(root1,2) root1.left.left.left = root2 inorder(root1) print largestBST(root1) <|fim▁end|>
return True, 1, root.value, root.value
<|file_name|>largest_BST_in_a_binary_tree.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Created on Thu Nov 19 17:38:50 2015 @author: deep """ from binaryTree import BTree, generateRandomTree, inorder def largestBST(root): if root.left is None and root.right is None: return True, 1, root.value, root.value if root.left: <|fim_middle|> else: isBSTL = True sizeL = 0 minL = -float('inf') if root.right: isBSTR, sizeR, minR, maxR = largestBST(root.right) else: isBSTR = True sizeR = 0 maxR = float('inf') if isBSTL and isBSTR: if maxL <= root.value <= minR: return True, sizeL+sizeR+1, minL, maxR, size = max(sizeL, sizeR) return False, size , None, None root1 = BTree() root1.value = 0 root2 = BTree() root2.value = 0 generateRandomTree(root2,2) generateRandomTree(root1,2) root1.left.left.left = root2 inorder(root1) print largestBST(root1) <|fim▁end|>
isBSTL, sizeL, minL, maxL = largestBST(root.left)
<|file_name|>largest_BST_in_a_binary_tree.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Created on Thu Nov 19 17:38:50 2015 @author: deep """ from binaryTree import BTree, generateRandomTree, inorder def largestBST(root): if root.left is None and root.right is None: return True, 1, root.value, root.value if root.left: isBSTL, sizeL, minL, maxL = largestBST(root.left) else: <|fim_middle|> if root.right: isBSTR, sizeR, minR, maxR = largestBST(root.right) else: isBSTR = True sizeR = 0 maxR = float('inf') if isBSTL and isBSTR: if maxL <= root.value <= minR: return True, sizeL+sizeR+1, minL, maxR, size = max(sizeL, sizeR) return False, size , None, None root1 = BTree() root1.value = 0 root2 = BTree() root2.value = 0 generateRandomTree(root2,2) generateRandomTree(root1,2) root1.left.left.left = root2 inorder(root1) print largestBST(root1) <|fim▁end|>
isBSTL = True sizeL = 0 minL = -float('inf')
<|file_name|>largest_BST_in_a_binary_tree.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Created on Thu Nov 19 17:38:50 2015 @author: deep """ from binaryTree import BTree, generateRandomTree, inorder def largestBST(root): if root.left is None and root.right is None: return True, 1, root.value, root.value if root.left: isBSTL, sizeL, minL, maxL = largestBST(root.left) else: isBSTL = True sizeL = 0 minL = -float('inf') if root.right: <|fim_middle|> else: isBSTR = True sizeR = 0 maxR = float('inf') if isBSTL and isBSTR: if maxL <= root.value <= minR: return True, sizeL+sizeR+1, minL, maxR, size = max(sizeL, sizeR) return False, size , None, None root1 = BTree() root1.value = 0 root2 = BTree() root2.value = 0 generateRandomTree(root2,2) generateRandomTree(root1,2) root1.left.left.left = root2 inorder(root1) print largestBST(root1) <|fim▁end|>
isBSTR, sizeR, minR, maxR = largestBST(root.right)
<|file_name|>largest_BST_in_a_binary_tree.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Created on Thu Nov 19 17:38:50 2015 @author: deep """ from binaryTree import BTree, generateRandomTree, inorder def largestBST(root): if root.left is None and root.right is None: return True, 1, root.value, root.value if root.left: isBSTL, sizeL, minL, maxL = largestBST(root.left) else: isBSTL = True sizeL = 0 minL = -float('inf') if root.right: isBSTR, sizeR, minR, maxR = largestBST(root.right) else: <|fim_middle|> if isBSTL and isBSTR: if maxL <= root.value <= minR: return True, sizeL+sizeR+1, minL, maxR, size = max(sizeL, sizeR) return False, size , None, None root1 = BTree() root1.value = 0 root2 = BTree() root2.value = 0 generateRandomTree(root2,2) generateRandomTree(root1,2) root1.left.left.left = root2 inorder(root1) print largestBST(root1) <|fim▁end|>
isBSTR = True sizeR = 0 maxR = float('inf')
<|file_name|>largest_BST_in_a_binary_tree.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Created on Thu Nov 19 17:38:50 2015 @author: deep """ from binaryTree import BTree, generateRandomTree, inorder def largestBST(root): if root.left is None and root.right is None: return True, 1, root.value, root.value if root.left: isBSTL, sizeL, minL, maxL = largestBST(root.left) else: isBSTL = True sizeL = 0 minL = -float('inf') if root.right: isBSTR, sizeR, minR, maxR = largestBST(root.right) else: isBSTR = True sizeR = 0 maxR = float('inf') if isBSTL and isBSTR: <|fim_middle|> size = max(sizeL, sizeR) return False, size , None, None root1 = BTree() root1.value = 0 root2 = BTree() root2.value = 0 generateRandomTree(root2,2) generateRandomTree(root1,2) root1.left.left.left = root2 inorder(root1) print largestBST(root1) <|fim▁end|>
if maxL <= root.value <= minR: return True, sizeL+sizeR+1, minL, maxR,
<|file_name|>largest_BST_in_a_binary_tree.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Created on Thu Nov 19 17:38:50 2015 @author: deep """ from binaryTree import BTree, generateRandomTree, inorder def largestBST(root): if root.left is None and root.right is None: return True, 1, root.value, root.value if root.left: isBSTL, sizeL, minL, maxL = largestBST(root.left) else: isBSTL = True sizeL = 0 minL = -float('inf') if root.right: isBSTR, sizeR, minR, maxR = largestBST(root.right) else: isBSTR = True sizeR = 0 maxR = float('inf') if isBSTL and isBSTR: if maxL <= root.value <= minR: <|fim_middle|> size = max(sizeL, sizeR) return False, size , None, None root1 = BTree() root1.value = 0 root2 = BTree() root2.value = 0 generateRandomTree(root2,2) generateRandomTree(root1,2) root1.left.left.left = root2 inorder(root1) print largestBST(root1) <|fim▁end|>
return True, sizeL+sizeR+1, minL, maxR,
<|file_name|>largest_BST_in_a_binary_tree.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Created on Thu Nov 19 17:38:50 2015 @author: deep """ from binaryTree import BTree, generateRandomTree, inorder def <|fim_middle|>(root): if root.left is None and root.right is None: return True, 1, root.value, root.value if root.left: isBSTL, sizeL, minL, maxL = largestBST(root.left) else: isBSTL = True sizeL = 0 minL = -float('inf') if root.right: isBSTR, sizeR, minR, maxR = largestBST(root.right) else: isBSTR = True sizeR = 0 maxR = float('inf') if isBSTL and isBSTR: if maxL <= root.value <= minR: return True, sizeL+sizeR+1, minL, maxR, size = max(sizeL, sizeR) return False, size , None, None root1 = BTree() root1.value = 0 root2 = BTree() root2.value = 0 generateRandomTree(root2,2) generateRandomTree(root1,2) root1.left.left.left = root2 inorder(root1) print largestBST(root1) <|fim▁end|>
largestBST
<|file_name|>parser_init_mapping.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """Class representing the mapper for the parser init files.""" from plasoscaffolder.bll.mappings import base_mapping_helper from plasoscaffolder.bll.mappings import base_sqliteplugin_mapping from plasoscaffolder.model import init_data_model class ParserInitMapping( base_sqliteplugin_mapping.BaseSQLitePluginMapper): """Class representing the parser mapper."""<|fim▁hole|> _PARSER_INIT_TEMPLATE = 'parser_init_template.jinja2' def __init__(self, mapping_helper: base_mapping_helper.BaseMappingHelper): """Initializing the init mapper class. Args: mapping_helper (base_mapping_helper.BaseMappingHelper): the helper class for the mapping """ super().__init__() self._helper = mapping_helper def GetRenderedTemplate( self, data: init_data_model.InitDataModel) -> str: """Retrieves the parser init file. Args: data (init_data_model.InitDataModel): the data for init file Returns: str: the rendered template """ context = {'plugin_name': data.plugin_name, 'is_create_template': data.is_create_template} rendered = self._helper.RenderTemplate( self._PARSER_INIT_TEMPLATE, context) return rendered<|fim▁end|>
<|file_name|>parser_init_mapping.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """Class representing the mapper for the parser init files.""" from plasoscaffolder.bll.mappings import base_mapping_helper from plasoscaffolder.bll.mappings import base_sqliteplugin_mapping from plasoscaffolder.model import init_data_model class ParserInitMapping( base_sqliteplugin_mapping.BaseSQLitePluginMapper): <|fim_middle|> <|fim▁end|>
"""Class representing the parser mapper.""" _PARSER_INIT_TEMPLATE = 'parser_init_template.jinja2' def __init__(self, mapping_helper: base_mapping_helper.BaseMappingHelper): """Initializing the init mapper class. Args: mapping_helper (base_mapping_helper.BaseMappingHelper): the helper class for the mapping """ super().__init__() self._helper = mapping_helper def GetRenderedTemplate( self, data: init_data_model.InitDataModel) -> str: """Retrieves the parser init file. Args: data (init_data_model.InitDataModel): the data for init file Returns: str: the rendered template """ context = {'plugin_name': data.plugin_name, 'is_create_template': data.is_create_template} rendered = self._helper.RenderTemplate( self._PARSER_INIT_TEMPLATE, context) return rendered