Ejemplo n.º 1
0
def list_backups() -> None:
    """List all backups in the repository."""
    backups = g.repo.all_backups
    p = Pager()
    for b in backups:
        if not p.print(b):
            break
Ejemplo n.º 2
0
def index():
	article_qry=cms.Article.query().order(-cms.Article.created)
	pager = Pager(query=article_qry, page=util.param('page') or 1)
	article_dbs, _, _ = pager.paginate(page_size=PAGESIZE)
	return flask.render_template(
		theme_file('index.html'),
		cates=cate_list(),
		data=article_dbs,
		pager=pager)
Ejemplo n.º 3
0
  def __init__(self, filename):
    self.pager = Pager(filename)
    self.root_page_num = 0

    # If this is a new database file: initialize the root node
    if self.pager.num_pages == 0:
      root_node = Leaf_Node(self.pager.get_page(self.root_page_num))
      root_node.is_root = True
      self.pager.insert_new_page(root_node)
Ejemplo n.º 4
0
def image_view(ind=None):
    table = read_table(TABLE_FILE)
    pager = Pager(len(table))
    if ind >= pager.count:
        return render_template("404.html"), 404
    else:
        pager.current = ind
        return render_template('imageview.html',
                               index=ind,
                               pager=pager,
                               data=table[ind])
Ejemplo n.º 5
0
def list_all_files() -> None:
    """List all files in the open backup.

    We really don't need this, since "list '*'" does the same thing.
    """
    if g.backup == NO_BKUP:
        util.msg("You must 'use' a backup first.")
    else:
        p = Pager()
        count = 0
        for f in g.repo.next_file(g.backup):
            count += 1
            if not p.print(normalize(f.fname)):
                break
        print('Files found:', count)
Ejemplo n.º 6
0
def tag(tag):
	tag_dbs = [t for t in cms.Tag.alltags() if t.name.lower() == tag.lower()]
	if tag_dbs:
		tag_db = tag_dbs[0]
		article_qry = cms.Article.query(cms.Article.tags==tag).order(-cms.Article.created)
		pager = Pager(query=article_qry, page=util.param('page') or 1)
		article_dbs, _, _ = pager.paginate(page_size=PAGESIZE)
	else:
		pager, article_db, tag_db = None, [], None
	return flask.render_template(
		theme_file('index.html'),
		obj=tag_db,
		cates=cate_list(),
		data=article_dbs,
		pager=pager)
Ejemplo n.º 7
0
def category(category):
	cate_dbs = [c for c in cms.Category.allcates() if c.name.lower() == category.lower()]
	if cate_dbs:
		cate_db = cate_dbs[0]
		article_qry = cms.Article.query(cms.Article.category==cate_db.key).order(-cms.Article.created)
		pager = Pager(query=article_qry, page=util.param('page') or 1)
		article_dbs, _, _ = pager.paginate(page_size=PAGESIZE)
	else:
		pager, article_dbs, cate_db = None, None, None
	return flask.render_template(
		theme_file('index.html'),
		obj=cate_db,
		cates=cate_list(),
		data=article_dbs,
		pager=pager)
Ejemplo n.º 8
0
def list_files(pattern: str, backup: str) -> None:
    """List files in 'backup' that match 'pattern'."""
    xpat = fnmatch.translate(pattern)
    try:
        pat = re.compile(xpat)
        count = 0
        p = Pager()
        for f in g.repo.next_file(backup):
            fname = normalize(f.fname)
            if pat.match(fname):
                if not p.print(fname):
                    break
                count += 1
        # print('Files found:', count)
    except re.error:
        util.error('Bad search pattern')
Ejemplo n.º 9
0
def image_view(sess=None, ind=None):
    if sess not in SESSIONS.keys():
        return render_template("404.html"), 404

    table = read_table(SESSIONS[sess])
    # print(len(table))
    pager = Pager(len(table))
    if ind >= pager.count:
        return render_template("404.html"), 404
    else:
        pager.current = ind
        return render_template('imageview.html',
                               index=ind,
                               pager=pager,
                               cluster=table[ind]['cluster'],
                               sess=sess)
Ejemplo n.º 10
0
 def run(self, params=None):
     '''
     Sets up the pager and go into infinity serving loop.
     '''
     logging.info("OpenFirePager daemon running with PID: %s"
                  % str(self.pid))
     self.pager = Pager(params)
     self.pager.run()
Ejemplo n.º 11
0
class PagerDaemon(DaemonBase):
    """
    PagerDaemon class inherits from DaemonBase to build a Unix daemon
    """

    def __init__(self):
        '''
        Constructor
        '''
        super(PagerDaemon, self).__init__("/tmp/firepagerd.pid")

    def setupLogging(self, params):
        '''
        Logging setup.
        '''
        if params is None:
            raise Exception("Missing arguments for logging setup.")
            return
        if params.loglevel == "debug" or params.verbose:
            loglevel = logging.DEBUG
        else:
            loglevel = logging.INFO
        if params.verbose:
            logfile = None
        else:
            logfile = "/tmp/firepagerd.log"
        # setup logging
        logging.basicConfig(filename=logfile, filemode="w", level=loglevel,
                            format="%(asctime)s [%(levelname)-8s] %(message)s")
        logging.debug("OpenFirePager logging enabled with loglevel: DEBUG")

    def start(self, params, daemonize=True):
        '''
        Runs the server.
        '''
        self.setupLogging(params)
        super(PagerDaemon, self).start(params, daemonize)

    def run(self, params=None):
        '''
        Sets up the pager and go into infinity serving loop.
        '''
        logging.info("OpenFirePager daemon running with PID: %s"
                     % str(self.pid))
        self.pager = Pager(params)
        self.pager.run()
Ejemplo n.º 12
0
def find_files(pattern: str) -> None:
    """Search all backups for files matching 'pattern'."""
    p = Pager()
    try:
        xpat = fnmatch.translate(pattern)
        pat = re.compile(xpat)
        stop = False
        for b in g.repo.all_backups:
            if not stop:
                for f in g.repo.next_file(b):
                    fname = normalize(f.fname)
                    if pat.match(fname):
                        mtime = time.ctime(float(f.mtime))
                        if not p.print(f'{b}\t{mtime}\t{fname}'):
                            stop = True
                            break
    except re.error:
        util.error('Bad search pattern')
Ejemplo n.º 13
0
def molIn():
    global table, pager
    if ((request.form['smiles'] != '')
            and (getmol.ReadMolFromSmile(request.form['smiles']) is not None)):
        add_table(TABLE_FILE, request.form['smiles'])
        table = read_table(TABLE_FILE)
        pager = Pager(len(table))
    else:
        flash("Not a valid SMILE")
    return redirect('/')
Ejemplo n.º 14
0
    def __init__(self, filename):
        # type: (Text) -> None
        self.filename = filename
        self.pager = Pager.open(filename, max_pages=Table.MAX_PAGES)
        self.root_page_num = 0

        if self.pager.num_pages == 0:
            # new db file
            root_node_page = self.pager.get_page(0)
            root_node = Node.initialize_root_node()
            nodes[id(root_node)] = root_node
Ejemplo n.º 15
0
def map_view(map_ind):
    global groupPager
    global photoPager
    global table_group
    if map_ind >= groupPager.count:
        return render_template("404.html"), 404
    else:
        time_group = filter_cluster(timestamps, map_ind, cluster_labels)
        table_group = sort_cluster(
            filter_cluster(table, map_ind, cluster_labels), time_group)
        # set photo pager to only page through images contained in group
        photoPager = Pager(len(table_group))
        photoPager.current = 0
        groupPager.current = map_ind
        group_locs = filter_cluster(locations, map_ind, cluster_labels)
        group_colors = filter_cluster(cluster_colors, map_ind, cluster_labels)
        folium_map = get_map(group_locs, save=True, colors=group_colors)
        return render_template('map_view.html',
                               groupPager=groupPager,
                               photoPager=photoPager)
Ejemplo n.º 16
0
def cluster():
    global cluster_labels
    global colors_dict
    global cluster_colors
    global groupPager
    cluster_labels = get_labels(locations,
                                float(request.form['clusterdistance']),
                                timestamps)
    colors_dict = get_label_colors(cluster_labels)
    cluster_colors = [colors_dict[i] for i in cluster_labels]
    groupPager = Pager(max(cluster_labels) + 1)
    return redirect('/')
Ejemplo n.º 17
0
class Table:

  def __init__(self, filename):
    self.pager = Pager(filename)
    self.root_page_num = 0

    # If this is a new database file: initialize the root node
    if self.pager.num_pages == 0:
      root_node = Leaf_Node(self.pager.get_page(self.root_page_num))
      root_node.is_root = True
      self.pager.insert_new_page(root_node)


  def get_page(self, page_num):
    return self.pager.get_page(page_num)

  def get_root_page(self):
    return self.get_page(self.root_page_num)

  # save pages to the file
  def flush(self):
    for page_num in range(0, self.pager.num_pages):
      self.pager.flush_page(page_num)

    self.pager.file.close()
Ejemplo n.º 18
0
def molCsvIn():
    global table, pager
    if ((request.form['path'] != '')
            and (os.path.isfile(request.form['path']) is not False)):
        df_inp = pd.read_csv(request.form['path'])
        for i, smile in enumerate(df_inp['SMILES']):
            if getmol.ReadMolFromSmile(smile) is not None:
                add_table(TABLE_FILE, smile)
            else:
                flash(str(i) + ' ' + smile + " is Not a valid SMILE")
            # percent = (i + 1) * 100 // len(df_inp)
            # render_template('progress.html', percent=percent)
        table = read_table(TABLE_FILE)
        pager = Pager(len(table))
    else:
        flash("Not a valid CSV path")
    return redirect('/')
Ejemplo n.º 19
0
def image_view(ind=None, ind2=None):

    pager = Pager(
        db.engine.execute('select count(cameraid) from cameras').scalar())

    data = Camera.query.filter_by(cameraid=ind).first()

    images = Image.query.filter_by(cameraid=ind).order_by(
        Image.curr_time.asc()).all()

    pager2 = Pager(len(images))

    #new way
    #need to get filepath --> 19/19_20180625_132516.jpg
    main_path = "./static/images/" + str(ind).zfill(8)
    all_files = [
        f for f in os.listdir(main_path) if isfile(join(main_path, f))
    ]
    print("File list:")
    print(all_files[:5])

    try:

        if ind2 >= pager2.count or ind >= pager.count:
            flash('Image did not exist')
            return render_template('dirview.html', index=ind, pager=pager)
        else:
            pager.current = ind
            pager2.current = ind2
            filepath = str(ind).zfill(8) + "/" + all_files[
                ind2]  #getting the next image
            print("Indexs: " + str(ind) + " " + str(ind2))
            print("Filepath: " + filepath)

            return render_template('imageview.html',
                                   index=ind2,
                                   pager=pager,
                                   pager2=pager2,
                                   data2=images[ind2],
                                   data=data,
                                   filepath=filepath)

    except IndexError as e:
        return render_template('404.html')
Ejemplo n.º 20
0
    def __init__(self, name, model, view, ids=[], domain=[], context={}, **kw):

        super(List, self).__init__(name=name, model=model, ids=ids)

        self.context = context or {}
        self.domain = domain or []

        if name.endswith('/'):
            self._name = name[:-1]

        if name != '_terp_list':
            self.source = self.name.replace('/', '/') or None

        self.selectable = kw.get('selectable', 0)
        self.editable = kw.get('editable', False)
        self.pageable = kw.get('pageable', True)

        self.offset = kw.get('offset', 0)
        self.limit = kw.get('limit', 0)
        self.count = kw.get('count', 0)
        self.link = kw.get('nolinks', 1)
        self.attr_limit = 0
        self.m2m = False
        self.concurrency_info = None
        self.selector = None

        if self.selectable == 1:
            self.selector = 'radio'

        if self.selectable == 2:
            self.selector = 'checkbox'

        fields = view['fields']
        dom = xml.dom.minidom.parseString(view['arch'].encode('utf-8'))
        root = dom.childNodes[0]

        attrs = tools.node_attributes(root)
        self.string = attrs.get('string', '')

        # is relational field (M2M/O2M)
        if self.source:
            self.attr_limit = cherrypy.request.app.config['openerp-web'].get(
                'child.listgrid.limit', 20)
            self.attr_limit = int(attrs.get('limit', self.attr_limit))
        else:
            self.min_rows = 5

        try:
            self.min_rows = int(attrs.get('min_rows'))
        except:
            pass

        try:
            if self.limit == 0:
                self.limit = self.attr_limit

        except:
            pass

        self.colors = {}
        for color_spec in attrs.get('colors', '').split(';'):
            if color_spec:
                colour, test = color_spec.split(':')
                self.colors[colour] = test

        proxy = rpc.RPCProxy(model)

        if ids == None:
            if self.limit > 0:
                ids = proxy.search(domain, self.offset, self.limit, 0, context)
            else:
                ids = proxy.search(domain, 0, 0, 0, context)

            self.count = proxy.search_count(domain, context)

        self.data_dict = {}
        data = []

        if ids and not isinstance(ids, list):
            ids = [ids]

        if ids and len(ids) > 0:

            ctx = rpc.session.context.copy()
            ctx.update(context)

            if self.limit and len(ids) > self.limit and self.limit != -1:
                new_ids = ids[self.offset:self.offset + self.limit]
                data = proxy.read(new_ids,
                                  fields.keys() + ['__last_update'], ctx)
            else:
                data = proxy.read(ids, fields.keys() + ['__last_update'], ctx)
            self._update_concurrency_info(self.model, data)
            self.concurrency_info = ConcurrencyInfo(self.model, ids)

            for item in data:
                self.data_dict[item['id']] = item.copy()

            self.ids = ids

        self.values = copy.deepcopy(data)
        self.headers, self.hiddens, self.data, self.field_total, self.buttons = self.parse(
            root, fields, data)

        for k, v in self.field_total.items():
            self.field_total[k][1] = self.do_sum(self.data, k)

        self.columns = len(self.headers)

        self.columns += (self.selectable or 0) and 1
        self.columns += (self.editable or 0) and 2
        self.columns += (self.buttons or 0) and 1

        if self.pageable:
            self.pager = Pager(ids=self.ids,
                               offset=self.offset,
                               limit=self.limit,
                               count=self.count,
                               def_limit=self.attr_limit)
            self.pager._name = self.name

        # make editors
        if self.editable and attrs.get('editable') in ('top', 'bottom'):

            for f, fa in self.headers:
                k = fa.get('type', 'char')
                if k not in form.WIDGETS:
                    k = 'char'

                fa['prefix'] = '_terp_listfields' + (
                    (self.name != '_terp_list' or '') and '/' + self.name)
                fa['inline'] = True
                self.editors[f] = form.WIDGETS[k](**fa)

            # generate hidden fields
            for f, fa in self.hiddens:
                k = fa.get('type', 'char')
                if k not in form.WIDGETS:
                    k = 'char'

                fa['prefix'] = '_terp_listfields' + (
                    (self.name != '_terp_list' or '') and '/' + self.name)
                self.editors[f] = form.Hidden(**fa)

        # limit the data
        if self.pageable and len(self.data) > self.limit and self.limit != -1:
            self.data = self.data[self.offset:]
            self.data = self.data[:min(self.limit, len(self.data))]
Ejemplo n.º 21
0
        if 'children' not in pages[page_name]:
            pages[page_name]['children'] = {}
            case = importlib.import_module('apps.' + app + '.' + next_page)
            test = case.Module(pager, next_page)
            test.test()
        else:
            next_level = level + 1
            dispatch(next_page, pages[page_name]['children'], next_level)


# localhost = input('Please input the localhost:')

localhost = "http://localhost:8080"
app = 'zg'

# 引入测试用例配置
lib = importlib.import_module('config.' + app)
modules = lib.get_modules()

# 实例化测试报告类
report = Report(app)
# 实例化 web driver 重构类
pager = Pager(report, localhost, modules)
pager.get('')

print('# # # # # TEST START # # # # #')
dispatch('', modules)
print('# # # # # TEST COMPLETE # # # # # \n')

input(report.file_name)
Ejemplo n.º 22
0
    def initUI(self):
        QApplication.setStyle(QStyleFactory.create('Cleanlooks'))

        self.setStyleSheet("QLabel {font: 15pt} QPushButton {font: 15pt}")
        self.setWindowTitle('Programmer')

        # Create the actions for the program
        exitAction = Action(resource.path('icons/toolbar/exit.png'), 'Exit Programmer', self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip('Exit application')
        exitAction.triggered.connect(self.close)

        refreshAction = Action(resource.path('icons/toolbar/refresh.png'), 'Refresh Serial Ports', self)
        refreshAction.setShortcut('Ctrl+R')
        refreshAction.setStatusTip('Refresh Serial Port List')
        refreshAction.triggered.connect(self.refreshPorts)

        openAction = Action(resource.path('icons/toolbar/open.png'), 'Select MX2+ Firmware', self)
        openAction.setStatusTip('Open MX2+ OTA File.')
        openAction.setShortcut('Ctrl+O')
        openAction.triggered.connect(self.onOpenFirmwareFile)

        openBleAction = Action(resource.path('icons/toolbar/open.png'), 'Select BLE Firmware', self)
        openBleAction.setStatusTip('Open BLE Project File.')
        openBleAction.setShortcut('Ctrl+B')
        openBleAction.triggered.connect(self.onOpenBLEProject)

        aboutAction = Action(resource.path('icons/toolbar/about.png'), 'About', self)
        aboutAction.setStatusTip('About MX2+ Programmer')
        aboutAction.triggered.connect(self.about)

        switchInfoAction = Action(resource.path('icons/toolbar/info.png'), 'DIP Switch Info', self)
        switchInfoAction.setStatusTip('MX2+ DIP Switch Info')
        switchInfoAction.triggered.connect(self.showSwitchInfo)

        bleInfoAction = Action(resource.path('icons/toolbar/info.png'), 'BLE Programmer Info', self)
        bleInfoAction.setStatusTip('BLE Programmer Info')
        bleInfoAction.triggered.connect(self.showBLEInfo)

        # Create the widgets for the program (embeddable in the
        # toolbar or elsewhere)
        self.port_selector = QComboBox(self)
        self.refreshPorts()
        self.port_selector.activated[str].connect(self.changePort)

        # Set up the Menus for the program
        self.menubar_init()
        self.menubar_add_menu('&File')
        self.menu_add_action('&File', exitAction)
        self.menu_add_action('&File', refreshAction)
        self.menu_add_action('&File', openAction)
        self.menu_add_action('&File', openBleAction)

        self.menubar_add_menu('&Help')
        self.menu_add_action('&Help', aboutAction)
        self.menu_add_action('&Help', switchInfoAction)
        self.menu_add_action('&Help', bleInfoAction)

        # Set up the toolbars for the program
        self.toolbar_init()
        self.toolbar_create('toolbar1')
        self.toolbar_add_action('toolbar1', exitAction)

        self.toolbar_add_separator('toolbar1')
        self.toolbar_add_action('toolbar1', refreshAction)
        self.toolbar_add_widget('toolbar1', QLabel(' Serial Port: '))
        self.toolbar_add_widget('toolbar1', self.port_selector)

        self.toolbar_add_separator('toolbar1')
        self.toolbar_add_action('toolbar1', openAction)

        self.toolbar_add_widget('toolbar1', QLabel(' MX2+ Version: '))
        self.firmwareLabel = QLabel('<b><i>unknown</i></b>')
        self.toolbar_add_widget('toolbar1', self.firmwareLabel)

        self.toolbar_add_widget('toolbar1', QLabel(' crc: '))
        self.crcLabel = QLabel('<b><i>unknown</i></b>')
        self.toolbar_add_widget('toolbar1', self.crcLabel)

        self.toolbar_add_separator('toolbar1')
        self.toolbar_add_action('toolbar1', openBleAction)
        self.toolbar_add_widget('toolbar1', QLabel(' BLE: '))
        self.bleLabel = QLabel('<b><i>unknown</i></b>')
        self.toolbar_add_widget('toolbar1', self.bleLabel)

        # main UI
        self.startPage = pages.StartPage()
        self.bootloaderPage = pages.BootloaderPage()
        self.firmwarePage = pages.FirmwarePage()
        self.blePage = pages.BLEPage()
        self.endPage = pages.EndPage()

        self.pager = Pager()
        self.pager.addPage(self.startPage)
        self.pager.addPage(self.bootloaderPage)
        self.pager.addPage(self.firmwarePage)
        self.pager.addPage(self.blePage)
        self.pager.addPage(self.endPage)

        # main controls
        '''
        self.scrollArea = QScrollArea(self)
        self.scrollArea.setWidget(self.pager)
        self.scrollArea.setWidgetResizable(True)
        self.setCentralWidget(self.scrollArea)
        '''
        self.setCentralWidget(self.pager)
        self.setGeometry(0, 0, 1200, 1000)
        self.center()
        self.show()
        #self.setFixedSize(self.size())

        # force the user to select OTA file
        self.timer = QTimer()
        self.timer.setSingleShot(True)
        self.timer.timeout.connect(self.onOpenFirmwareFile)
        self.timer.start(500)

        # force the user to select project.bgproj file
        self.timer2 = QTimer()
        self.timer2.setSingleShot(True)
        self.timer2.setInterval(500)
        self.timer2.timeout.connect(self.onOpenBLEProject)
        self.timer.timeout.connect(self.timer2.start)
Ejemplo n.º 23
0
class Programmer(QMainWindow):
    def __init__(self):
        super().__init__()

        self.port = None
        self.sdthread = None
        self.sdbtthread = None
        self.smartDrive = None
        self.fwFileName = None
        self.bleFileName = None
        self.initUI()
        self.initSD()

    def initUI(self):
        QApplication.setStyle(QStyleFactory.create('Cleanlooks'))

        self.setStyleSheet("QLabel {font: 15pt} QPushButton {font: 15pt}")
        self.setWindowTitle('Programmer')

        # Create the actions for the program
        exitAction = Action(resource.path('icons/toolbar/exit.png'), 'Exit Programmer', self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip('Exit application')
        exitAction.triggered.connect(self.close)

        refreshAction = Action(resource.path('icons/toolbar/refresh.png'), 'Refresh Serial Ports', self)
        refreshAction.setShortcut('Ctrl+R')
        refreshAction.setStatusTip('Refresh Serial Port List')
        refreshAction.triggered.connect(self.refreshPorts)

        openAction = Action(resource.path('icons/toolbar/open.png'), 'Select MX2+ Firmware', self)
        openAction.setStatusTip('Open MX2+ OTA File.')
        openAction.setShortcut('Ctrl+O')
        openAction.triggered.connect(self.onOpenFirmwareFile)

        openBleAction = Action(resource.path('icons/toolbar/open.png'), 'Select BLE Firmware', self)
        openBleAction.setStatusTip('Open BLE Project File.')
        openBleAction.setShortcut('Ctrl+B')
        openBleAction.triggered.connect(self.onOpenBLEProject)

        aboutAction = Action(resource.path('icons/toolbar/about.png'), 'About', self)
        aboutAction.setStatusTip('About MX2+ Programmer')
        aboutAction.triggered.connect(self.about)

        switchInfoAction = Action(resource.path('icons/toolbar/info.png'), 'DIP Switch Info', self)
        switchInfoAction.setStatusTip('MX2+ DIP Switch Info')
        switchInfoAction.triggered.connect(self.showSwitchInfo)

        bleInfoAction = Action(resource.path('icons/toolbar/info.png'), 'BLE Programmer Info', self)
        bleInfoAction.setStatusTip('BLE Programmer Info')
        bleInfoAction.triggered.connect(self.showBLEInfo)

        # Create the widgets for the program (embeddable in the
        # toolbar or elsewhere)
        self.port_selector = QComboBox(self)
        self.refreshPorts()
        self.port_selector.activated[str].connect(self.changePort)

        # Set up the Menus for the program
        self.menubar_init()
        self.menubar_add_menu('&File')
        self.menu_add_action('&File', exitAction)
        self.menu_add_action('&File', refreshAction)
        self.menu_add_action('&File', openAction)
        self.menu_add_action('&File', openBleAction)

        self.menubar_add_menu('&Help')
        self.menu_add_action('&Help', aboutAction)
        self.menu_add_action('&Help', switchInfoAction)
        self.menu_add_action('&Help', bleInfoAction)

        # Set up the toolbars for the program
        self.toolbar_init()
        self.toolbar_create('toolbar1')
        self.toolbar_add_action('toolbar1', exitAction)

        self.toolbar_add_separator('toolbar1')
        self.toolbar_add_action('toolbar1', refreshAction)
        self.toolbar_add_widget('toolbar1', QLabel(' Serial Port: '))
        self.toolbar_add_widget('toolbar1', self.port_selector)

        self.toolbar_add_separator('toolbar1')
        self.toolbar_add_action('toolbar1', openAction)

        self.toolbar_add_widget('toolbar1', QLabel(' MX2+ Version: '))
        self.firmwareLabel = QLabel('<b><i>unknown</i></b>')
        self.toolbar_add_widget('toolbar1', self.firmwareLabel)

        self.toolbar_add_widget('toolbar1', QLabel(' crc: '))
        self.crcLabel = QLabel('<b><i>unknown</i></b>')
        self.toolbar_add_widget('toolbar1', self.crcLabel)

        self.toolbar_add_separator('toolbar1')
        self.toolbar_add_action('toolbar1', openBleAction)
        self.toolbar_add_widget('toolbar1', QLabel(' BLE: '))
        self.bleLabel = QLabel('<b><i>unknown</i></b>')
        self.toolbar_add_widget('toolbar1', self.bleLabel)

        # main UI
        self.startPage = pages.StartPage()
        self.bootloaderPage = pages.BootloaderPage()
        self.firmwarePage = pages.FirmwarePage()
        self.blePage = pages.BLEPage()
        self.endPage = pages.EndPage()

        self.pager = Pager()
        self.pager.addPage(self.startPage)
        self.pager.addPage(self.bootloaderPage)
        self.pager.addPage(self.firmwarePage)
        self.pager.addPage(self.blePage)
        self.pager.addPage(self.endPage)

        # main controls
        '''
        self.scrollArea = QScrollArea(self)
        self.scrollArea.setWidget(self.pager)
        self.scrollArea.setWidgetResizable(True)
        self.setCentralWidget(self.scrollArea)
        '''
        self.setCentralWidget(self.pager)
        self.setGeometry(0, 0, 1200, 1000)
        self.center()
        self.show()
        #self.setFixedSize(self.size())

        # force the user to select OTA file
        self.timer = QTimer()
        self.timer.setSingleShot(True)
        self.timer.timeout.connect(self.onOpenFirmwareFile)
        self.timer.start(500)

        # force the user to select project.bgproj file
        self.timer2 = QTimer()
        self.timer2.setSingleShot(True)
        self.timer2.setInterval(500)
        self.timer2.timeout.connect(self.onOpenBLEProject)
        self.timer.timeout.connect(self.timer2.start)

    def initSD(self):
        # manage the smartdrive thread
        self.sdthread = QThread()
        # create the smartdrive
        self.smartDrive = SmartDrive(self.port)
        # move the smartdrive to the thread
        self.smartDrive.moveToThread(self.sdthread)

        # manage the smartdrive bluetooth thread
        self.sdbtthread = QThread()
        # create the smartdrive bluetooth
        self.smartDriveBluetooth = SmartDriveBluetooth()
        # move the smartdrive to the thread
        self.smartDriveBluetooth.moveToThread(self.sdbtthread)

        # wire up all the events
        self.port_selector.currentIndexChanged[str].connect(self.smartDrive.onPortSelected)

        self.smartDrive.invalidFirmware.connect(self.onInvalidFirmwareFile)

        # bootloader page
        self.smartDrive.bootloaderStatus.connect(self.bootloaderPage.onProgressUpdate)
        self.smartDrive.bootloaderFailed.connect(self.bootloaderPage.onBootloaderFailed)
        self.smartDrive.bootloaderFinished.connect(self.bootloaderPage.onBootloaderFinished)
        self.bootloaderPage.start.connect(self.smartDrive.programBootloader)
        self.bootloaderPage.stop.connect(self.smartDrive.stop)
        self.bootloaderPage.finished.connect(self.pager.onNext)

        # smartdrive page
        self.smartDrive.firmwareStatus.connect(self.firmwarePage.onProgressUpdate)
        self.smartDrive.firmwareFinished.connect(self.firmwarePage.onFirmwareFinished)
        self.smartDrive.firmwareFailed.connect(self.firmwarePage.onFirmwareFailed)
        self.firmwarePage.start.connect(self.smartDrive.programFirmware)
        self.firmwarePage.stop.connect(self.smartDrive.stop)
        self.firmwarePage.finished.connect(self.pager.onNext)

        # ble page
        self.smartDriveBluetooth.status.connect(self.blePage.onProgressUpdate)
        self.smartDriveBluetooth.deviceInfo.connect(self.blePage.onDeviceInfo)
        self.smartDriveBluetooth.firmwareFinished.connect(self.blePage.onFirmwareFinished)
        self.smartDriveBluetooth.failed.connect(self.blePage.onFirmwareFailed)
        self.blePage.start.connect(self.smartDriveBluetooth.start)
        self.blePage.stop.connect(self.smartDriveBluetooth.stop)
        self.blePage.finished.connect(self.pager.onNext)

        self.endPage.finished.connect(self.bootloaderPage.reset)
        self.endPage.finished.connect(self.firmwarePage.reset)
        self.endPage.finished.connect(self.blePage.reset)
        # start the SD thread
        self.sdthread.start()
        # start the SDBT thread
        self.sdbtthread.start()

    # Functions for serial port control
    def refreshPorts(self):
        self.serial_ports = listSerialPorts()
        self.port_selector.clear()
        self.port_selector.addItems(self.serial_ports)
        if self.port is None and len(self.serial_ports):
            self.port = self.serial_ports[0]
        if self.port is not None and len(self.serial_ports):
            self.port_selector.setCurrentIndex(
                self.serial_ports.index(self.port)
            )
        else:
            self.port_selector.setCurrentIndex(-1)

    def changePort(self, newPort):
        if newPort != self.port:
            self.port = newPort

    # functions for selecting the MX2+ firmware file
    def onInvalidFirmwareFile(self, err):
        QMessageBox.critical(
            self, 'OTA File Error', err.replace('\n', '<br>'),
            QMessageBox.Ok, QMessageBox.Ok)

    def onOpenFirmwareFile(self):
        fname, _ = QFileDialog.getOpenFileName(
            self,
            'Select MX2+ Firmware OTA File',
            '',
            'OTA Files (*.ota)',
            options=QFileDialog.Options()
        )
        if fname is not None and len(fname) > 0:
            self.fwFileName = fname
            self.smartDrive.onFirmwareFileSelected(self.fwFileName)
            self.firmwareLabel.setText('<b><i>{}</i></b>'.format(self.smartDrive.version))
            self.crcLabel.setText('<b><i>{}</i></b>'.format(self.smartDrive.crc))

    def onOpenBLEProject(self):
        fname, _ = QFileDialog.getOpenFileName(
            self,
            'Select SmartDrive BLE Firmware File',
            '',
            'Firmware Files (*.fw)',
            options=QFileDialog.Options()
        )
        if fname is not None and len(fname) > 0:
            self.bleFileName = fname
            self.smartDriveBluetooth.onFirmwareFileSelected(self.bleFileName)
            self.bleLabel.setText('<b><i>{}</i></b>'.format(self.bleFileName))

    # functions for controlling the programming
    def stop(self):
        self.smartDrive.stop()
        self.sdthread.quit()
        self.sdthread.wait()
        self.smartDriveBluetooth.stop()
        self.sdbtthread.quit()
        self.sdbtthread.wait()

    # general functions
    def about(self):
        msg = '''
SmartDrive MX2+ Programmer

This program walks the user through the programming process for the software on the SmartDrive MX2+.

It allows the user to select the serial port on which they've connected the SmartDrive, as well as the specific firmware file they wish to upload to the SmartDrive.
        '''
        QMessageBox.information(
            self, 'About', msg.replace('\n', '<br>'),
            QMessageBox.Ok, QMessageBox.Ok)

    def showSwitchInfo(self):
        msg = '''
1. Required for programming bootloader
2. Required for programming SmartDrive
3. Cleans the SmartDrive EEPROM
4. UNUSED
5. Locks the settings on the SD to what they are at that time (or what is saved in the SD EEPROM)
6. UNUSED
7. Limit the max speed to 6 km/h
8. Force boot into bootloader for bluetooth OTA programming (DEBUGGING ONLY)
        '''
        QMessageBox.information(
            self, 'DIP Switch Info', msg.replace('\n', '<br>'),
            QMessageBox.Ok, QMessageBox.Ok)

    def showBLEInfo(self):
        msg = '''
To program the SmartDrive bluetooth chip you must have BLE SW Update tool installed. Once it is installed, you will need to tell the tool where 'bgbuild.exe' is located on your system. To do this, press the 'BGBuild' menu button in the TOP LEFT of the BLE SW Update Tool and press 'Select manually...' - the bgbuild.exe should be in the folder 'C:\\Bluegiga\\ble-1.5.0-137\\bin'
        '''
        QMessageBox.information(
            self, 'BLE Programming Info', msg.replace('\n', '<br>'),
            QMessageBox.Ok, QMessageBox.Ok)

    # window functions
    def center(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    def closeEvent(self, event):
        reply = QMessageBox.question(
            self, 'Quit',
            'Sure you want to quit?', QMessageBox.Yes |
            QMessageBox.No, QMessageBox.No)

        if reply == QMessageBox.Yes:
            self.stop()
            event.accept()
        else:
            event.ignore()

    from menubar import \
        menubar_init, \
        menubar_add_menu, \
        menu_add_action

    from toolbar import \
        toolbar_init, \
        toolbar_create, \
        toolbar_add_action, \
        toolbar_add_widget, \
        toolbar_add_separator, \
        toolbar_remove

    from action import \
        action_init, \
        action_create

    from context_menu import \
        context_menu_init, \
        context_menu_create, \
        context_menu_add_action
Ejemplo n.º 24
0
    def __init__(self, name, model, view, ids=[], domain=[], context={}, **kw):

        super(List, self).__init__(name=name, model=model, ids=ids)

        self.context = context or {}
        self.domain = domain or []
        custom_search_domain = getattr(cherrypy.request,
                                       'custom_search_domain', [])
        custom_filter_domain = getattr(cherrypy.request,
                                       'custom_filter_domain', [])

        if name.endswith('/'):
            self._name = name[:-1]
        if name != '_terp_list':
            self.source = self.name.replace('/', '/') or None

        self.sort_order = kw.get('sort_order', '')
        self.sort_key = kw.get('sort_key', '')
        #this Condition is for Dashboard to avoid new, edit, delete operation
        self.dashboard = 0

        self.selectable = kw.get('selectable', 0)
        self.editable = kw.get('editable', False)
        self.pageable = kw.get('pageable', True)
        self.view_mode = kw.get('view_mode', [])

        self.offset = kw.get('offset', 0)
        self.limit = kw.get('limit', 0)
        self.count = kw.get('count', 0)
        self.link = kw.get('nolinks')
        self.m2m = kw.get('m2m', 0)
        self.o2m = kw.get('o2m', 0)
        self.concurrency_info = None
        self.selector = None

        terp_params = getattr(cherrypy.request, 'terp_params', {})
        if terp_params:
            if terp_params.get('_terp_model'):
                if terp_params[
                        '_terp_model'] == 'board.board' and terp_params.view_type == 'form':
                    self.dashboard = 1
            if terp_params.get('_terp_source'):
                if (str(terp_params.source)
                        == self.source) or (terp_params.source == '_terp_list'
                                            and terp_params.sort_key):
                    self.sort_key = terp_params.sort_key
                    self.sort_order = terp_params.sort_order

        if self.selectable == 1:
            self.selector = 'radio'

        if self.selectable == 2:
            self.selector = 'checkbox'

        fields = view['fields']
        dom = xml.dom.minidom.parseString(view['arch'].encode('utf-8'))
        root = dom.childNodes[0]

        attrs = node_attributes(root)
        self.string = attrs.get('string', '')

        search_param = copy.deepcopy(domain) or []
        if custom_search_domain:
            for elem in custom_search_domain:
                if elem not in self.domain:
                    search_param.append(elem)

            for elem in custom_filter_domain:
                if elem not in self.domain:
                    search_param.append(elem)

        try:
            self.limit = int(attrs.get('limit'))
        except:
            pass

        self.colors = {}
        for color_spec in attrs.get('colors', '').split(';'):
            if color_spec:
                colour, test = color_spec.split(':')
                self.colors[colour] = test

        proxy = rpc.RPCProxy(model)
        default_data = kw.get('default_data', [])
        search_text = terp_params.get('_terp_search_text', False)
        if not self.source:
            self.source = terp_params.get('_terp_source', None)
        if not default_data and not self.o2m and not self.m2m:
            if self.limit > 0:
                if self.sort_key:
                    ids = proxy.search(search_param, self.offset, self.limit,
                                       self.sort_key + ' ' + self.sort_order,
                                       context)
                else:
                    if search_text:
                        if self.source == '_terp_list':
                            ids = proxy.search(search_param, self.offset,
                                               self.limit, False, context)
                    else:
                        ids = proxy.search(search_param, self.offset,
                                           self.limit, False, context)
            else:
                if self.sort_key:
                    ids = proxy.search(search_param, 0, 0,
                                       self.sort_key + ' ' + self.sort_order,
                                       context)
                else:
                    ids = proxy.search(search_param, 0, 0, 0, context)
            if len(ids) < self.limit:
                if self.offset > 0:
                    self.count = len(ids) + self.offset
                else:
                    self.count = len(ids)
            else:
                self.count = proxy.search_count(search_param, context)

        if not default_data and self.m2m and not self.view_using_sum_attrs(
                root):
            # for many2many we limits 'ids' to be readed only when view is not
            # using sum, otherwise we need to get all 'ids' to compute sums correctly
            if ids and self.limit not in (0, -1):
                ids = self.ids[self.offset:self.offset + self.limit]

        self.data_dict = {}
        data = []

        if ids and not isinstance(ids, (list, tuple)):
            ids = [ids]

        if ids and len(ids) > 0:

            ctx = rpc.session.context.copy()
            ctx.update(context)

            try:
                data = proxy.read(ids, fields.keys() + ['__last_update'], ctx)
            except:
                pass

            ConcurrencyInfo.update(self.model, data)
            cherrypy.response.headers.pop('X-Concurrency-Info', None)
            self.concurrency_info = ConcurrencyInfo(self.model, ids)

            order_data = [(d['id'], d) for d in data]
            orderer = dict(zip(ids, count()))
            ordering = sorted(order_data,
                              key=lambda object: orderer[object[0]])
            data = [i[1] for i in ordering]

            for item in data:
                self.data_dict[item['id']] = item.copy()

            if not self.m2m:
                # update active 'ids' except for many2many which need to get
                # all known ids for update to work correctly
                self.ids = ids
        elif kw.get('default_data', []):
            data = kw['default_data']

        self.values = copy.deepcopy(data)
        self.headers, self.hiddens, self.data, self.field_total, self.buttons = self.parse(
            root, fields, data)

        for k, v in self.field_total.items():
            if (len([test[0] for test in self.hiddens if test[0] == k])) <= 0:
                self.field_total[k][1] = self.do_sum(self.data, k)

        self.columns = len(self.headers)

        self.columns += (self.selectable or 0) and 1
        self.columns += (self.editable or 0) and 2
        self.columns += (self.buttons or 0) and 1

        if self.pageable:
            self.pager = Pager(ids=self.ids,
                               offset=self.offset,
                               limit=self.limit,
                               count=self.count)
            self.pager._name = self.name

        # when view is editable, make sure all fields are correctly prefixed
        # otherwise they may conflict with parent view fields
        if self.editable:
            for f, fa in self.headers + self.hiddens:
                if not isinstance(fa, int):
                    fa['prefix'] = '_terp_listfields' + (
                        (self.name != '_terp_list' or '') and '/' + self.name)

        if self.editable and context.get(
                'set_editable'
        ):  #Treeview editable by default or set_editable in context
            attrs['editable'] = "bottom"

        # make editors
        if self.editable and attrs.get('editable') in ('top', 'bottom'):

            for f, fa in self.headers:
                if not isinstance(fa, int):
                    fa['prefix'] = '_terp_listfields' + (
                        (self.name != '_terp_list' or '') and '/' + self.name)
                    fa['inline'] = True
                    if fa.get('type') == 'one2many':
                        self.edit_inline = False
                        self.editors = {}
                        break
                    Widget = get_widget(fa.get('type',
                                               'char')) or get_widget('char')
                    self.editors[f] = Widget(**fa)

            # generate hidden fields
            if self.editors:
                for f, fa in self.hiddens:
                    fa['prefix'] = '_terp_listfields' + (
                        (self.name != '_terp_list' or '') and '/' + self.name)
                    self.editors[f] = form.Hidden(**fa)

        # limit the data
        if self.pageable and len(self.data) > self.limit and self.limit != -1:
            self.data = self.data[self.offset:]
            self.data = self.data[:min(self.limit, len(self.data))]
    def __init__(self, name, model, view, ids=[], domain=[], context={}, **kw):

        self.context = context or {}
        self.domain = copy.deepcopy(domain) or []
        self.group_by_no_leaf = self.context.get('group_by_no_leaf', 0)
        self.selectable = kw.get('selectable', 0)
        self.editable = kw.get('editable', False)
        self.pageable = kw.get('pageable', True)

        self.offset = kw.get('offset', 0)
        self.limit = kw.get('limit', 0)
        self.count = kw.get('count', 0)
        self.link = kw.get('nolinks')

        proxy = rpc.RPCProxy(model)

        # adding the piece of code to set limit as 0 to get rid of pager's negative offset error.
        # Here, we don't change the self.limit as Pager needs -1 to treat Unlimited limit  atribute
        terp_offset, terp_limit = self.offset, self.limit
        if self.limit < 0:
            terp_offset, terp_limit = 0, 0

        custom_search_domain = getattr(cherrypy.request,
                                       'custom_search_domain', [])
        custom_filter_domain = getattr(cherrypy.request,
                                       'custom_filter_domain', [])

        if custom_search_domain:
            self.domain.extend(i for i in custom_search_domain
                               if i not in domain)

        elif custom_filter_domain:
            self.domain.extend(i for i in custom_filter_domain
                               if i not in domain)

        if ids is None and not self.group_by_no_leaf:

            ids = proxy.search(self.domain, terp_offset, terp_limit, 0,
                               self.context)

            if len(ids) < self.limit:
                self.count = len(ids)
            else:
                self.count = proxy.search_count(domain, context)

        if ids and not isinstance(ids, list):
            ids = [ids]

        self.ids = ids

        self.concurrency_info = None

        self.group_by_ctx = kw.get('group_by_ctx', [])

        if not isinstance(self.group_by_ctx, list):
            self.group_by_ctx = [self.group_by_ctx]

        fields = view['fields']
        self.grp_records = []

        self.context.update(rpc.session.context.copy())

        if self.group_by_no_leaf:
            self.limit = -1

        super(ListGroup, self).__init__(name=name,
                                        model=model,
                                        view=view,
                                        ids=self.ids,
                                        domain=self.domain,
                                        context=self.context,
                                        limit=self.limit,
                                        count=self.count,
                                        offset=self.offset,
                                        editable=self.editable,
                                        selectable=self.selectable)

        if self.group_by_ctx:
            self.context['group_by'] = self.group_by_ctx
        else:
            self.group_by_ctx = self.context.get('group_by', [])

        self.group_by_ctx, self.hiddens, self.headers = parse(
            self.group_by_ctx, self.hiddens, self.headers, None,
            self.group_by_ctx)

        self.grp_records = proxy.read_group(
            self.context.get('__domain', []) + (self.domain or []),
            fields.keys(), self.group_by_ctx, 0, False, self.context)

        terp_params = getattr(cherrypy.request, 'terp_params', [])
        if terp_params.sort_key and terp_params.sort_key in self.group_by_ctx and self.group_by_ctx.index(
                terp_params.sort_key) == 0:
            if terp_params.sort_order == 'desc':
                rev = True
            else:
                rev = False
            self.grp_records = sorted(self.grp_records,
                                      key=itemgetter(terp_params.sort_key),
                                      reverse=rev)

        for grp_rec in self.grp_records:
            if not grp_rec.get('__domain'):
                grp_rec['__domain'] = self.context.get(
                    '__domain', []) + (self.domain or [])
            if not grp_rec.get('__context'):
                grp_rec['__context'] = {'group_by': self.group_by_ctx}

        self.grouped, grp_ids = parse_groups(self.group_by_ctx,
                                             self.grp_records, self.headers,
                                             self.ids, model, terp_offset,
                                             terp_limit, self.context,
                                             self.data, self.field_total,
                                             fields)

        if self.pageable:
            self.count = len(self.grouped)
            self.pager = Pager(ids=self.ids,
                               offset=self.offset,
                               limit=self.limit,
                               count=self.count)
            self.pager._name = self.name
Ejemplo n.º 26
0
if len(locations) > 0:
    # TODO: change static min_dist of 5 km to user input
    cluster_labels = get_labels(locations, 5, timestamps)
    colors_dict = get_label_colors(cluster_labels)
    cluster_colors = [colors_dict[i] for i in cluster_labels]
else:
    print("No GPS data could be parsed for provided photos.")
    exit()

# table is equivalent to files but has an easy handover to html
table = [{
    'name': os.path.join('images', os.path.basename(p))
} for p in file_names]
table_group = table
# pagers that help update the page, Pager class defined in pager.py
photoPager = Pager(len(file_names))
groupPager = Pager(max(cluster_labels) + 1)

# Start flask app
app = Flask(__name__, static_folder=STATIC_DIR)
app.config.update(APPNAME=APPNAME)


@app.route('/')
def index():
    global groupPager
    global photoPager
    # reset pagers on return to index
    groupPager.current = 0
    photoPager.current = 0
    folium_map = get_map(locations, save=True, colors=cluster_colors)
Ejemplo n.º 27
0
 def setUp(self) -> None:
     self.dist1 = DistSite('Kidega', 'query', 'https://kidega.com/arama',
                           'searcHeadArea.txt', 20, 'page')
     self.url1 = Url(self.dist1, 'python')
     self.page1 = Page(self.url1)
     self.pager1 = Pager(self.page1)
Ejemplo n.º 28
0
def main():
    pager = Pager()
    while True:
        pager.loop()
Ejemplo n.º 29
0
def read_table(url):
    """Return a list of dict"""
    # r = requests.get(url)
    with open(url) as f:
        return [row for row in csv.DictReader(f.readlines())]


APPNAME = "SmartPathology"
STATIC_FOLDER = 'examples'
TABLE_FILE = "examples/catalog.csv"
save_path = 'predicitons/'
UPLOAD_FOLDER = 'examples/images/'
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])

table = read_table(TABLE_FILE)
pager = Pager(len(table))

filename = ""

app = Flask(__name__, static_folder=STATIC_FOLDER)
app.config.update(APPNAME=APPNAME, )

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER


def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


@app.route('/')
Ejemplo n.º 30
0
STATIC_FOLDER = ''
# TABLE_FILE = "example/fakecatalog.csv"
diction = open("dress.test.json.pt", 'rb')
diction = pickle.load(diction)

n = len(diction)
print('the length of diction is: ',)
asin_array = []

for asin in diction:
    asin_array.append(asin)



# table = read_table(TABLE_FILE)
pager = Pager(n)


app = Flask(__name__, static_folder=STATIC_FOLDER)
app.config.update(
    APPNAME=APPNAME,
    )


@app.route('/')
def index():
    return redirect('/0')


@app.route('/<int:ind>/')
def image_view(ind=None):
Ejemplo n.º 31
0
    def __init__(self, **attrs):
        super(M2M, self).__init__(**attrs)

        ids = None
        params = getattr(cherrypy.request, 'terp_params', None)
        if not params:
            params = TinyDict()
            params.model = attrs.get('relation', 'model')
            params.ids = attrs.get('value', [])
            params.name = attrs.get('name', '')

        current = params.chain_get(self.name)
        if current and params.source == self.name:
            ids = current.ids

        self.model = attrs.get('relation', 'model')
        self.link = attrs.get('link', 1)
        self.onchange = None # override onchange in js code

        self.relation = attrs.get('relation', '')
        self.domain = attrs.get('domain', [])
        self.context = attrs.get('context', {}) or {}        

        view = attrs.get('views', {})
        mode = str(attrs.get('mode', 'tree,form')).split(',')

        self.view = view

        view_mode = mode
        view_type = mode[0]

        self.switch_to = view_mode[-1]
        if view_type == view_mode[-1]: self.switch_to = view_mode[0]
        
        if ids is None:
            ids = attrs.get('value', [])

        id = (ids or None) and ids[0]

        pprefix = ''
        if '/' in self.name:
            pprefix = self.name[:self.name.rindex('/')]

        current = params.chain_get(self.name)

        if not current:
            current = TinyDict()

        current.offset = current.offset or 0
        current.limit = current.limit or 0
        current.count = len(ids or [])

        if current.view_mode: view_mode = current.view_mode
        if current.view_type: view_type = current.view_type

        if current and params.source == self.name:
            id = current.id

        id = id or None

        current.model = self.model
        current.id = id

        if isinstance(ids, tuple):
            ids = list(ids)

        current.ids = ids or []
        current.view_mode = view_mode
        current.view_type = view_type
        current.domain = current.domain or []
        current.context = current.context or {}
        
        if isinstance(self.context, basestring):
            ctx = cherrypy.request.terp_record
            ctx['current_date'] = time.strftime('%Y-%m-%d')
            ctx['time'] = time
            ctx['context'] = current.context
            ctx['active_id'] = current.id or False

            # XXX: parent record for O2M
            #if self.parent:
            #    ctx['parent'] = EvalEnvironment(self.parent)

            try:
                ctx = tools.expr_eval(self.context, ctx)
                current.context.update(ctx)
            except:
                pass

        if current.view_type == 'tree' and self.readonly:
            self.editable = False

        if self.editable is False:
            selectable = 0
        else:
            selectable = 2

        # try to get original input values if creating validation form
        if not params.filter_action:
            try:
                current.ids = eval(cherrypy.request.terp_data.get(self.name))
            except:
                pass

        self.screen = Screen(current, prefix=self.name, views_preloaded=view,
                             editable=False, readonly=self.editable,
                             selectable=selectable, nolinks=self.link)
        
        if view_type == 'tree':
            limit = 20
            if self.screen.widget.attr_limit:
                limit = self.screen.widget.attr_limit
            if current.limit == 0:
                current.limit = limit
                
            self.screen.widget.pageable = Pager(ids=current.ids, offset=current.offset, limit=current.limit,
                                                count=current.count, def_limit=limit)

        self.screen.widget.checkbox_name = False
        self.screen.widget.m2m = True

        self.validator = validators.many2many()
Ejemplo n.º 32
0
def cleardb():
    global table, pager
    delete_table()
    table = read_table(TABLE_FILE)
    pager = Pager(len(table))
    return redirect('/')