Example #1
0
    def _update(self, *largs):
        '''(internal) Check if a data is loaded, and pass to the client.'''
        # want to start it ?
        if self._start_wanted:
            if not self._running:
                self.start()
            self._start_wanted = False

        # in pause mode, don't unqueue anything.
        if self._paused:
            self._trigger_update()
            return

        for x in range(self.max_upload_per_frame):
            try:
                filename, data = self._q_done.pop()
            except IndexError:
                return

            # create the image
            image = data  # ProxyImage(data)
            if not image.nocache:
                Cache.append('kv.loader', filename, image)

            # update client
            for c_filename, client in self._client[:]:
                if filename != c_filename:
                    continue
                # got one client to update
                client.image = image
                client.loaded = True
                client.dispatch('on_load')
                self._client.remove((c_filename, client))

        self._trigger_update()
Example #2
0
File: lang.py Project: luuvish/kivy
    def template(self, *args, **ctx):
        '''Create a specialized template using a specific context.
        .. versionadded:: 1.0.5

        With template, you can construct custom widget from a kv lang
        definition by giving them a context. Check :ref:`Template usage
        <template_usage>`.
        '''
        # Prevent naming clash with whatever the user might be putting into the
        # ctx as key.
        name = args[0]
        if name not in self.templates:
            raise Exception('Unknown <%s> template name' % name)
        baseclasses, rule, fn = self.templates[name]
        key = '%s|%s' % (name, baseclasses)
        cls = Cache.get('kv.lang', key)
        if cls is None:
            rootwidgets = []
            for basecls in baseclasses.split('+'):
                rootwidgets.append(Factory.get(basecls))
            cls = ClassType(name, tuple(rootwidgets), {})
            Cache.append('kv.lang', key, cls)
        widget = cls()
        self._apply_rule(widget, rule, rule, template_ctx=ctx)
        return widget
Example #3
0
  def tile_draw(self, nx, ny, tx, ty, sx, sy, zoom, bound):
        '''Draw a specific tile on the screen.
        Return False if the tile is not yet available.'''
        # nx, ny = index of tile
        # tx, ty = real position on scatter
        # sx, sy = real size on scatter
        # pzoom = current zoom level
        image = self.tileserver.get(nx, bound-ny-1, zoom, self.maptype)
        if image in (None, False):
            return

        if not image.texture:
          Logger.exception('Returned image has no texture.')
          return
        if image.texture.wrap is None:
          image.texture.wrap = GL_CLAMP

        alpha = Cache.get('tileserver.tilesalpha', image.id)
        if alpha is None:
          alpha = 0
        if image.loaded:          # as soon as we have the image
          alpha += min(self._dt * 4, 1.0)  # fade it in
        Cache.append('tileserver.tilesalpha', image.id, alpha)

        with self.canvas:
          Color(1, 1, 1, alpha)
          Rectangle(pos=(tx, ty), size=(sx, sy), texture=image.texture)
Example #4
0
    def template(self, *args, **ctx):
        '''Create a specialized template using a specific context.

        .. versionadded:: 1.0.5

        With templates, you can construct custom widgets from a kv lang
        definition by giving them a context. Check :ref:`Template usage
        <template_usage>`.
        '''
        # Prevent naming clash with whatever the user might be putting into the
        # ctx as key.
        name = args[0]
        if name not in self.templates:
            raise Exception('Unknown <%s> template name' % name)
        baseclasses, rule, fn = self.templates[name]
        key = '%s|%s' % (name, baseclasses)
        cls = Cache.get('kv.lang', key)
        if cls is None:
            rootwidgets = []
            for basecls in baseclasses.split('+'):
                rootwidgets.append(Factory.get(basecls))
            cls = type(name, tuple(rootwidgets), {})
            Cache.append('kv.lang', key, cls)
        widget = cls()
        # in previous versions, ``ctx`` is passed as is as ``template_ctx``
        # preventing widgets in it from be collected by the GC. This was
        # especially relevant to AccordionItem's title_template.
        proxy_ctx = {k: get_proxy(v) for k, v in ctx.items()}
        self._apply_rule(widget, rule, rule, template_ctx=proxy_ctx)
        return widget
Example #5
0
    def image(self, filename, load_callback=None, post_callback=None, **kwargs):
        '''Load a image using loader. A Proxy image is returned with a loading
        image.

      ::
            img = Loader.image(filename)
            # img will be a ProxyImage.
            # You'll use it the same as an Image class.
            # Later, when the image is really loaded,
            # the loader will change the img.image property
            # to the new loaded image

        '''
        data = Cache.get('kivy.loader', filename)
        if data not in (None, False):
            # found image, if data is not here, need to reload.
            return ProxyImage(data,
                    loading_image=self.loading_image,
                    loaded=True, **kwargs)

        client = ProxyImage(self.loading_image,
                    loading_image=self.loading_image, **kwargs)
        self._client.append((filename, client))

        if data is None:
            # if data is None, this is really the first time
            self._q_load.append((filename, load_callback, post_callback))
            Cache.append('kivy.loader', filename, False)
            self._start_wanted = True
            self._trigger_update()
        else:
            # already queued for loading
            pass

        return client
Example #6
0
    def template(self, *args, **ctx):
        '''Create a specialized template using a specific context.
        .. versionadded:: 1.0.5

        With template, you can construct custom widget from a kv lang definition
        by giving them a context. Check :ref:`Template usage <template_usage>`.
        '''
        # Prevent naming clash with whatever the user might be putting into the
        # ctx as key.
        name = args[0]
        if not name in self.templates:
            raise Exception('Unknown <%s> template name' % name)
        baseclasses, defs, fn = self.templates[name]
        name, baseclasses
        key = '%s|%s' % (name, baseclasses)
        cls = Cache.get('kv.lang', key)
        if cls is None:
            rootwidgets = []
            for basecls in baseclasses.split('+'):
                rootwidgets.append(Factory.get(basecls))
            cls = ClassType(name, tuple(rootwidgets), {})
            Cache.append('kv.lang', key, cls)
        widget = cls()
        self._push_widgets()
        self._push_ids()
        self.idmap = copy(global_idmap)
        self.idmap['root'] = widget
        self.idmap['ctx'] = QueryDict(ctx)
        self.build_item(widget, defs, is_rule=True)
        self._pop_ids()
        self._pop_widgets()
        return widget
Example #7
0
    def _set_filename(self, value):
        if value is None or value == self._filename:
            return
        self._filename = value

        # construct uid as a key for Cache
        uid = '%s|%s|%s' % (self.filename, self._mipmap, 0)
        keep_data = self._keep_data

        # in case of Image have been asked with keep_data
        # check the kv.image cache instead of texture.
        if keep_data:
            image = Cache.get('kv.image', uid)
            if image:
                # we found an image, yeah ! but reset the texture now.
                self.image = image
                self._texture = None
                self._img_iterate()
                return
        else:
            # if we already got a texture, it will be automatically reloaded.
            _texture = Cache.get('kv.texture', uid)
            if _texture:
                return

        # if image not already in cache then load
        tmpfilename = self._filename
        self.image = ImageLoader.load(
                self._filename, keep_data=self._keep_data,
                mipmap=self._mipmap)
        self._filename = tmpfilename
        # put the image into the cache if needed
        if keep_data:
            Cache.append('kv.image', uid, self.image)
Example #8
0
 def scan_qr(self, on_complete):
     dlg = Cache.get('electrum_widgets', 'QrScannerDialog')
     if not dlg:
         dlg = Factory.QrScannerDialog()
         Cache.append('electrum_widgets', 'QrScannerDialog', dlg)
         dlg.bind(on_complete=on_complete)
     dlg.open()
Example #9
0
    def populate(self):
        self._textures = []
        fname = self.filename
        if __debug__:
            Logger.trace('Image: %r, populate to textures (%d)' %
                         (fname, len(self._data)))

        for count in range(len(self._data)):

            # first, check if a texture with the same name already exist in the
            # cache
            chr = type(fname)
            uid = chr(u'%s|%d|%d') % (fname, self._mipmap, count)
            texture = Cache.get('kv.texture', uid)

            # if not create it and append to the cache
            if texture is None:
                imagedata = self._data[count]
                source = '{}{}|'.format(
                    'zip|' if fname.endswith('.zip') else '',
                    self._nocache)
                imagedata.source = chr(source) + uid
                texture = Texture.create_from_data(
                    imagedata, mipmap=self._mipmap)
                if not self._nocache:
                    Cache.append('kv.texture', uid, texture)
                if imagedata.flip_vertical:
                    texture.flip_vertical()

            # set as our current texture
            self._textures.append(texture)

            # release data if ask
            if not self.keep_data:
                self._data[count].release_data()
Example #10
0
    def list_constants(self, shorten=True, show_indx=False):
        "List all env constants."

        consts = Cache.get(category='envcache', key='constants')
        
        if not consts:
            Logger.info("ENV: Building env constants list.")
            consts = []
            i = 1
    
            for k in sorted(self.env_dict.keys()):
                v = self.env_dict[k].strip() 
                row = []
                if show_indx:
                    if shorten and len(v[:50]) > 50:
                        row = (i, k,v[:50])
                else:
                    row = (k, v) 
                        
                consts.append(row)
        
                i += 1
            # Cache constants
            Logger.info("ENV: Caching constants.")
            Cache.append(category='envcache', key='constants', obj=consts)
        else:
            Logger.info("ENV: Retrieved constants from cache.")
                
        return consts
Example #11
0
    def __init__(self):

        # Check and see if constants rebinding is unsuccessful
        try:
            constants.REBIND_CHECK = False
        except const.ConstError:
            Logger.info("ENV: Environment constants are secure.")
        else:
            raise Exception("Error with environment setup.")

        # Environment
        self.env_dict = {}
        # Create cache
        Cache.register(category='envcache', limit=2)

        # Populate constants
        for attr in dir(constants):
            if attr.isupper():
                self.env_dict[attr] = str(
                    getattr(constants, attr)
                ).encode('string_escape')
                
        # Initiate memory tracker
        if constants.PYMPLER_AVAILABLE:
            self.mem_tracker = tracker.SummaryTracker()
Example #12
0
	def next(self):
		if self.Band_num < len(self.Dat.BandsArrays)-1:
			self.Band_num+=1
		Cache.remove('kv.image')
		Cache.remove('kv.texture')
		self.Dat.SaveBAND(self.Dat.BandsArrays[self.Band_num], "TMP.tiff")
		self.A_image = Image("TMP.tiff")
Example #13
0
	def previous(self):
		if self.Band_num >= 0:
			self.Band_num-=1
		Cache.remove('kv.image')
		Cache.remove('kv.texture')
		self.Dat.SaveBAND(self.Dat.BandsArrays[self.Band_num], "TMP.tiff")
		self.A_image = Image("TMP.tiff")
Example #14
0
    def drop_request(self, filename, client, load_callback=None, post_callback=None, **kwargs):
        #Logger.info('_drop_request: from cache queue %s %d %d' % (filename,len(self._client),len(self._q_load)))
        item = None
        for i in self._client:
            if (i[0] == filename):
                #and (i[1] == client):
                item = i
                break
        if item:
            Logger.info('_drop_request: found client %s ' % filename)
            self._client.remove(item)

        item = None
        for i in self._q_load:
            if (i['filename'] == filename):
                #and (i['load_callback'] == load_callback) and (i['post_callback'] == post_callback):
                item = i
                break
        if item:
            Logger.info('_drop_request: found _q_load %s ' % filename)
            self._q_load.remove(item)

        if not kwargs.get('nocache', False):
            #Logger.info('_drop_request: dropped %s ' % filename)
            Cache.remove('kv.loader', filename)
Example #15
0
    def populate(self):
        self._textures = []
        if __debug__:
            Logger.trace("Image: %r, populate to textures (%d)" % (self.filename, len(self._data)))

        for count in xrange(len(self._data)):

            # first, check if a texture with the same name already exist in the
            # cache
            uid = "%s|%s|%s" % (self.filename, self._mipmap, count)
            texture = Cache.get("kv.texture", uid)

            # if not create it and append to the cache
            if texture is None:
                imagedata = self._data[count]
                texture = Texture.create_from_data(imagedata, mipmap=self._mipmap)
                if not self._nocache:
                    Cache.append("kv.texture", uid, texture)
                if imagedata.flip_vertical:
                    texture.flip_vertical()

            # set as our current texture
            self._textures.append(texture)

            # release data if ask
            if not self.keep_data:
                self._data[count].release_data()
Example #16
0
    def populate(self):
        self._textures = []
        if __debug__:
            Logger.trace('Image: %r, populate to textures (%d)' %
                    (self.filename, len(self._data)))

        for count in xrange(len(self._data)):

            # first, check if a texture with the same name already exist in the
            # cache
            uid = '%s|%s|%s' % (self.filename, self._mipmap, count)
            texture = Cache.get('kv.texture', uid)

            # if not create it and append to the cache
            if texture is None:
                texture = Texture.create_from_data(
                        self._data[count], mipmap=self._mipmap)
                Cache.append('kv.texture', uid, texture)

            # set as our current texture
            self._textures.append(texture)

            # release data if ask
            if not self.keep_data:
                self._data[count].release_data()
Example #17
0
    def _update(self, *largs):
        '''(internal) Check if a data is loaded, and pass to the client'''
        # want to start it ?
        if self._start_wanted:
            if not self._running:
                self.start()
            self._start_wanted = False

        while True:
            try:
                filename, data = self._q_done.pop()
            except IndexError:
                return

            # create the image
            image = data#ProxyImage(data)
            Cache.append('kivy.loader', filename, image)

            # update client
            for c_filename, client in self._client[:]:
                if filename != c_filename:
                    continue
                # got one client to update
                client.image = image
                client.loaded = True
                client.dispatch('on_load')
                self._client.remove((c_filename, client))
Example #18
0
    def __init__(self, filename, **kwargs):
        self.filename = filename

        self.svg_data = Cache.get("kivy.svg", filename)
        if not self.svg_data:
            new_svg = self.load(filename)
            Cache.append("kivy.svg", filename, new_svg)
            self.svg_data = new_svg
Example #19
0
def database():
        """ open/read Redelitoral's database
            sea level's plot from database
        """
        # communicate with Redelitoral database
        try:
        	con=mysql.connector.connect(host='54.204.23.126', port=3306, user='******', passwd='m@r3gr2af0', db='maregrafo')
        	cur = con.cursor()
        	cur.execute("SELECT * FROM medida")
        	rows = cur.fetchall()
        except mysql.connector.Error as err:
  		if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
    		   print("Something is wrong with your user name or password")
  		elif err.errno == errorcode.ER_BAD_DB_ERROR:
    		   print("Database does not exists")
  		else:
                   print(err)
	else:
  		con.close()
        # saving data in a list  
        data = []
        for r in rows:
                data.append(r)
        #select only last 3 days data
        sea_level,sea_mean,min10 =[],[],432
        sea_level = [data[e][3] for e in range(data[-1][0]- min10+1,data[-1][0])]
        #sea_mean =np.mean([data[e][3] for e in range(len(data))])
	sea_mean = np.mean(sea_level)
        # date for axis
        tlast = data[-1][2].strftime('%H:%I %m/%d/%Y')
        tmean = data[-min10/2][2].strftime('%H:%I %m/%d/%Y')
        t0 = data[-min10+1][2].strftime('%H:%I %m/%d/%Y')
        n0,nlast,nmean = 0,min10+1,min10/2
        # plots  
        plot_mean= [sea_mean]* (min10+1)
        fig = plt.figure(figsize=(5,4),dpi=200)
        ax = fig.add_subplot(111)
        ax.plot(sea_level,'bo')
        ax.plot(plot_mean,'b--')
        ax.set_ylim([0.5, 2.0])
        ax.set_xlim([0,min10+2])
        ax.set_xticks([n0,nmean,nlast])
        ax.set_xticklabels([t0,tmean,tlast])
        # annotate min and max values from the last 3 days 
        id_max=np.where(sea_level==np.max(sea_level))[0][0]
        id_min=np.where(sea_level==np.min(sea_level))[0][0]
        plt.text(id_max-5,sea_level[id_max]+0.07, '%s'%sea_level[id_max],fontsize=10)
        plt.text(id_max-5,sea_level[id_max]+0.14, 'max',fontsize=10)
        plt.text(id_min-5,sea_level[id_min]-0.07, '%s'%sea_level[id_min],fontsize=10)
        plt.text(id_min-5,sea_level[id_min]-0.14, 'min',fontsize=10)
        plt.text(min10-50,sea_mean-0.1, 'mean',fontsize=10)
        # title and legend
        ax.set_ylabel('Meters',fontsize=10)
        ax.set_xlabel('Date',fontsize=10)
        plt.title('Sea level for the last 3 days')  
        savefig('fig_data.png', bbox_inches='tight')
        Cache.register('fig_data.png', limit=10, timeout=5) 
        return
Example #20
0
	def onKeyDown(self, keyboard, keycode, text, modifiers):
		
		Cache.print_usage()
		
		if keycode[0] == 32:
			
			self.userEvent()
				
		pass		
Example #21
0
 def on_source(self, instance, value):
     if not value:
         self.texture = None
     else:
         filename = resource_find(value)
         texture = Cache.get('kv.texture', filename)
         if not texture:
             image = CoreImage(filename)
             texture = image.texture
             Cache.append('kv.texture', filename, texture)
         self.texture = texture
Example #22
0
    def _set_filename(self, value):
        #Logger.info('CoreImageOpenCV: value %s' % (value))
        if value is None or value == self._filename:
            return
        self._filename = value

        # construct uid as a key for Cache
        if (self.res_width > 0) or (self.res_height > 0):
            uid = '%s|%d|%d|%s|%s' % (self.filename, self.res_width, self.res_height, self._mipmap, 0)
        else:
            uid = '%s|%s|%s' % (self.filename, self._mipmap, 0)

        # in case of Image have been asked with keep_data
        # check the kv.image cache instead of texture.
        image = Cache.get('kv.image', uid)
        if image:
            # we found an image, yeah ! but reset the texture now.
            self.image = image
            # if image.__class__ is core image then it's a texture
            # from atlas or other sources and has no data so skip
            if (image.__class__ != self.__class__ and
                    not image.keep_data and self._keep_data):
                self.remove_from_cache()
                self._filename = ''
                self._set_filename(value)
            else:
                self._texture = None
                self._img_iterate()
            return
        else:
            # if we already got a texture, it will be automatically reloaded.
            _texture = Cache.get('kv.texture', uid)
            if _texture:
                self._texture = _texture
                return

        # if image not already in cache then load
        tmpfilename = self._filename
        #Logger.info('CoreImageOpenCV: set_filename %s' % (tmpfilename))
        #Logger.info('CoreImageOpenCV: %d %d' % (self.res_width, self.res_height))
        image = ImageLoader.load(
            self._filename, keep_data=self._keep_data,
            mipmap=self._mipmap, nocache=self._nocache, res_width=self.res_width,
            res_height=self.res_height, load_exif=self.load_exif)
        self._filename = tmpfilename

        # put the image into the cache if needed
        if isinstance(image, Texture):
            self._texture = image
            self._size = image.size
        else:
            self.image = image
            if not self._nocache:
                Cache.append('kv.image', uid, self.image)
        def on_success(request, response):
            response = json.loads(response)

            try:
                hrate = response['bpi'][mintime]
                hrate = abs(btc_amt) * decimal.Decimal(hrate)
                Cache.append('history_rate', uid, hrate)
            except KeyError:
                hrate = 'not found'

            self.parent.set_history_rate(item, hrate)
Example #24
0
 def show_tx_details(self, item):
     ra_dialog = Cache.get('electrum_widgets', 'RecentActivityDialog')
     if not ra_dialog:
         Factory.register('RecentActivityDialog',
                          module='electrum_gui.kivy.uix.dialogs.carousel_dialog')
         Factory.register('GridView',
                          module='electrum_gui.kivy.uix.gridview')
         ra_dialog = ra_dialog = Factory.RecentActivityDialog()
         Cache.append('electrum_widgets', 'RecentActivityDialog', ra_dialog)
     ra_dialog.item = item
     ra_dialog.open()
Example #25
0
 def update(self):
     '''Must be called to get pull image from the workers queue
     '''
     
     pop = self.q_out.pop
     while True:
         try:
             filename, image = pop()
             self.q_count -= 1
         except:
             return
         Cache.append('tileserver.tiles', filename, image)
Example #26
0
 def _create_line_label(self, text):
     # Create a label from a text, using line options
     ntext = text.replace("\n", "").replace("\t", " " * self.tab_width)
     kw = self._get_line_options()
     cid = "%s\0%s" % (ntext, str(kw))
     texture = Cache.get("textinput.label", cid)
     if not texture:
         label = Label(text=ntext, **kw)
         label.refresh()
         texture = label.texture
         Cache.append("textinput.label", cid, texture)
     return texture
Example #27
0
 def _create_line_label(self, text):
     # Create a label from a text, using line options
     ntext = text.replace('\n', '').replace('\t', ' ' * self.tab_width)
     kw = self._get_line_options()
     cid = '%s\0%s' % (ntext, str(kw))
     texture = Cache.get('textinput.label', cid)
     if not texture:
         label = Label(text=ntext, **kw)
         label.refresh()
         texture = label.texture
         Cache.append('textinput.label', cid, texture)
     return texture
Example #28
0
 def texture_update(self, *largs):
     if not self.source:
         self.texture = None
     else:
         filename = resource_find(self.source)
         mipmap = self.mipmap
         uid = '%s|%s' % (filename, mipmap)
         texture = Cache.get('kv.texture', uid)
         if not texture:
             image = CoreImage(filename, mipmap=mipmap)
             texture = image.texture
             Cache.append('kv.texture', uid, texture)
         self.texture = texture
Example #29
0
    def image(self, filename, load_callback=None, post_callback=None,
              **kwargs):
        '''Load a image using the Loader. A ProxyImage is returned with a
        loading image. You can use it as follows::

            from kivy.app import App
            from kivy.uix.image import Image
            from kivy.loader import Loader

            class TestApp(App):
                def _image_loaded(self, proxyImage):
                    if proxyImage.image.texture:
                        self.image.texture = proxyImage.image.texture

                def build(self):
                    proxyImage = Loader.image("myPic.jpg")
                    proxyImage.bind(on_load=self._image_loaded)
                    self.image = Image()
                    return self.image

            TestApp().run()

        In order to cancel all background loading, call *Loader.stop()*.
        '''
        data = Cache.get('kv.loader', filename)
        if data not in (None, False):
            # found image, if data is not here, need to reload.
            return ProxyImage(data,
                              loading_image=self.loading_image,
                              loaded=True, **kwargs)

        client = ProxyImage(self.loading_image,
                            loading_image=self.loading_image, **kwargs)
        self._client.append((filename, client))

        if data is None:
            # if data is None, this is really the first time
            self._q_load.appendleft({
                'filename': filename,
                'load_callback': load_callback,
                'post_callback': post_callback,
                'kwargs': kwargs})
            if not kwargs.get('nocache', False):
                Cache.append('kv.loader', filename, False)
            self._start_wanted = True
            self._trigger_update()
        else:
            # already queued for loading
            pass

        return client
Example #30
0
 def _get_text_width(self, text):
     # fix cursor placement diff cause of markup
     kw = self._line_options
     ntext = text.replace('\t', ' ' * self.tab_width)
     cid = '%s\0%s' % (ntext, str(kw))
     width = Cache.get('textinput.label.width', cid)
     if not width:
         texture = self._create_line_label(ntext)
         # use width of texture of '.' instead of ' ' in start of line,
         # which is of 0 width in markup
         width =  texture.width if texture else\
             self._label_cached.get_extents('.')[0] * len(ntext)
         Cache.append('codeinput.label.width', cid, width)
     return width
Example #31
0
def on_lect_select(self, dropdown, txt):
    """
    This method updates GUI according to selected lecture.
    :param self: It is for handling class structure.
    :param dropdown: It is dropdown menu.
    :param txt: It is lecture code selected on dropdown menu.
    :return:
    """

    try:
        self.check_live_exam.cancel()
    except:
        pass
    finally:
        Clock.schedule_once(partial(check_live_exam.is_active,
                                    self
                                    )
                            )
        self.check_live_exam = Clock.schedule_interval(partial(check_live_exam.is_active,
                                                               self
                                                               ),
                                                       5.0
                                                       )

    dropdown.select(txt)

    self.ids["txt_hint"].opacity = 0

    self.ids["btn_exams"].disabled = False
    self.ids["btn_stats_personal"].disabled = False

    self.ids["txt_lect_code"].opacity = 1
    self.ids["txt_lect_name"].opacity = 1

    for lect in self.data:
        if txt in lect.replace("_", " ").upper():
            self.ids["txt_lect_code"].text = txt
            self.ids["txt_lect_name"].text = " ".join(lect.split("_")[2:]).title()

            Cache.append("lect",
                         "code",
                         txt
                         )
            Cache.append("lect",
                         "name",
                         self.ids["txt_lect_name"].text
                         )

            break

    self.ids["layout_exams"].opacity = 1

    self.data_exams = database_api.getExamsOfLecture(Cache.get("info", "token"),
                                                     self.ids["txt_lect_code"].text
                                                     )

    args_converter = lambda row_index, x: {"text": x.replace("_", " ").title(),
                                           "selected_color": (.843, .82, .82, 1),
                                           "deselected_color": (.57, .67, .68, 1),
                                           "background_down": "data/img/widget_gray_75.png",
                                           "font_name": "data/font/CaviarDreams_Bold.ttf",
                                           "font_size": self.height / 25,
                                           "size_hint_y": None,
                                           "height": self.height / 10
                                           }
    self.ids["list_exams"].adapter = ListAdapter(data=[i[1] for i in self.data_exams],
                                                 cls=ListItemButton,
                                                 args_converter=args_converter,
                                                 allow_empty_selection=False
                                                 )
    self.ids["list_exams"].adapter.bind(on_selection_change=partial(on_exam_select,
                                                                    self
                                                                    )
                                        )
Example #32
0
 def __del__(self):
     # TODO ask for confirmation if file is unsaved
     # Remove from cache
     Cache.remove("code_tab", self.full_path)
Example #33
0
import os

from kivy.cache import Cache
from kivy.uix.codeinput import CodeInput
from kivy.uix.tabbedpanel import TabbedPanelHeader

from editor.components.dialogs.file_chooser_dialog import FileChooserDialog
from editor.utils import lexer_utils

Cache.register("code_tabs")


class CodeTab(TabbedPanelHeader):
    @staticmethod
    def get_or_create(file_name):
        """
        Check whether an input file is already loaded as a code tab, or load it.

        :param file_name: The input file name to check or create.
        :return: The code tab corresponding to the input file.
        """
        code_tab = Cache.get("code_tabs", file_name)
        if code_tab is None:
            # Did not find tab, create it instead
            code_tab = CodeTab(file_name=file_name)
            Cache.append("code_tabs", key=file_name, obj=code_tab)
        return code_tab

    def __init__(self, **kwargs):
        # Extract file from arguments
        file_name = kwargs.pop("file_name", None)
Example #34
0
#Factory.register('OutputItem', module='electrum_bitcoinprivate_gui.kivy.uix.dialogs')

from .uix.dialogs.installwizard import InstallWizard
from .uix.dialogs import InfoBubble
from .uix.dialogs import OutputList, OutputItem

#from kivy.core.window import Window
#Window.softinput_mode = 'below_target'

# delayed imports: for startup speed on android
notification = app = ref = None
util = False

# register widget cache for keeping memory down timeout to forever to cache
# the data
Cache.register('electrum_bitcoinprivate_widgets', timeout=0)

from kivy.uix.screenmanager import Screen
from kivy.uix.tabbedpanel import TabbedPanel
from kivy.uix.label import Label
from kivy.core.clipboard import Clipboard

Factory.register('TabbedCarousel', module='electrum_bitcoinprivate_gui.kivy.uix.screens')

# Register fonts without this you won't be able to use bold/italic...
# inside markup.
from kivy.core.text import Label
Label.register('Roboto',
               'gui/kivy/data/fonts/Roboto.ttf',
               'gui/kivy/data/fonts/Roboto.ttf',
               'gui/kivy/data/fonts/Roboto-Bold.ttf',
Example #35
0
#from httplib import HTTPConnection
from urllib2 import urlopen
from random import randint

from kvmap.core.projections import unit_to_latlon, fix180

__all__ = ('TileServer')

### static configuration - TODO: parametrize ####################################
# number of threads to use
TILESERVER_POOLSIZE = 10
TILESERVER_MAXPIPELINE = 2
#################################################################################

### init cache - TODO: parametrize ##############################################
Cache.register('tileserver.tiles', limit=10, timeout=10)  #1000/10000
Cache.register('tileserver.tilesalpha', limit=10, timeout=10)
#################################################################################

GMAPS_CROPSIZE = 256


class TileServer(object):
    '''Base implementation for a tile provider.
    Check GoogleTileServer and YahooTileServer if you intend to use more
    '''
    provider_name = 'unknown'
    providers = dict()

    @staticmethod
    def register(cls):
Example #36
0
#Factory.register('OutputItem', module='electrum_zclassic_gui.kivy.uix.dialogs')

from .uix.dialogs.installwizard import InstallWizard
from .uix.dialogs import InfoBubble
from .uix.dialogs import OutputList, OutputItem

#from kivy.core.window import Window
#Window.softinput_mode = 'below_target'

# delayed imports: for startup speed on android
notification = app = ref = None
util = False

# register widget cache for keeping memory down timeout to forever to cache
# the data
Cache.register('electrum_zclassic_widgets', timeout=0)

from kivy.uix.screenmanager import Screen
from kivy.uix.tabbedpanel import TabbedPanel
from kivy.uix.label import Label
from kivy.core.clipboard import Clipboard

Factory.register('TabbedCarousel',
                 module='electrum_zclassic_gui.kivy.uix.screens')

# Register fonts without this you won't be able to use bold/italic...
# inside markup.
from kivy.core.text import Label
Label.register('Roboto', 'gui/kivy/data/fonts/Roboto.ttf',
               'gui/kivy/data/fonts/Roboto.ttf',
               'gui/kivy/data/fonts/Roboto-Bold.ttf',
Example #37
0
This module is responsible for getting the conversion rates from different
bitcoin exchanges.
'''

import decimal
import json

from kivy.network.urlrequest import UrlRequest
from kivy.event import EventDispatcher
from kivy.properties import (OptionProperty, StringProperty, AliasProperty,
    ListProperty)
from kivy.clock import Clock
from kivy.cache import Cache

# Register local cache
Cache.register('history_rate', timeout=220)

EXCHANGES = ["BitcoinAverage",
             "BitcoinVenezuela",
             "BitPay",
             "Blockchain",
             "BTCChina",
             "CaVirtEx",
             "Coinbase",
             "CoinDesk",
             "LocalBitcoins",
             "Winkdex"]

HISTORY_EXCHNAGES = ['Coindesk',
                     'Winkdex',
                     'BitcoinVenezuela']
Example #38
0
            J1=9     J2=12    J3=31    J4=34    J5=53    J6=56    J7=75    J8=78    J9=97    J10=100    J11=119    J12=122    J13=141    J14=144    J15=163    J16=166    J17=185    J18=188
             |         |        |        |        |        |        |        |        |         |          |          |          |          |          |          |          |          |
            K1=10----K2=11    K3=32----K4=33    K5=54----K6=55    K7=76----K8=77    K9=98----K10=99     K11=120----K12=121    K13=142----K14=143    K15=164----K16=165    K17=186----K18=187


'''
'''
Globals
'''
count = 0
global LED_ROUTE_IMAGES
LED_ROUTE_IMAGES = [None] * 228
'''
In order to not have to access the SD card which can be slow, here we make sure everything stays in the cache increasing performance. (Hopefully)
'''
Cache.register('kv.image', limit=None, timeout=None)

# Window.fullscreen = 'auto'
LED_COUNT = 198
LED_PIN = 18
LED_FREQ_HZ = 800000
LED_DMA = 5
LED_BRIGHTNESS = 255
LED_INVERT = False
LED_CHANNEL = 0

# LED_STRIP = ws.WS2811_STRIP_GRB
# strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL, LED_STRIP)
# strip.begin()

Example #39
0
    def update(self, dt):
        main_screen = Cache.get('cache', 'MainScreen')
        ret, frame = self.capture.read()
        # if frame gotten successfully
        if ret:
            # Create a copy of original frame
            clear_frame = copy.deepcopy(frame)
            # Object Detection
            frame, scores, num_detections, boxes = self.detector.detect(
                frame, resizing_factor=4)
            # convert it to texture
            buf1 = cv2.flip(frame, 0)
            buf = buf1.tostring()
            image_texture = Texture.create(size=(frame.shape[1],
                                                 frame.shape[0]),
                                           colorfmt='bgr')
            image_texture.blit_buffer(buf, colorfmt='bgr', bufferfmt='ubyte')

            for i in range(int(num_detections[0])):
                # Extracting license plates and read them
                if scores[0][i] > (self.detection_certainty / 100):
                    height, width, channels = frame.shape
                    # For All detected objects in the picture
                    # Bounding box coordinates
                    ymin = int((boxes[0][i][0] * height))
                    xmin = int((boxes[0][i][1] * width))
                    ymax = int((boxes[0][i][2] * height))
                    xmax = int((boxes[0][i][3] * width))
                    lp_np = clear_frame[ymin:ymax, xmin:xmax]
                    # Read text from license plate image
                    prediction, probability = self.reader.read(lp_np)
                    if probability > (self.reading_certainty / 100):

                        if not self.list:
                            self.list.append([prediction, probability, lp_np])
                        else:
                            element = self.list[len(self.list) - 1]
                            # Probably same picture but different prediction
                            if self.non_overlap(prediction, element[0]) <= 2:
                                self.list.append(
                                    [prediction, probability, lp_np])
                            # Different picture get out prediction with highest probability
                            # TODO: Get out best prediction at the end of the video since there won't be any other to push it out (use frame count)
                            else:
                                probability = 0
                                for p in self.list:
                                    if p[1] > probability:
                                        prediction = p[0]
                                        probability = p[1]
                                        lp_np = p[2]

                                if not self.reader.processed(prediction):
                                    lp_buf1 = cv2.flip(lp_np, 0)
                                    lp_buf = lp_buf1.tostring()
                                    lp_image_texture = Texture.create(
                                        size=(lp_np.shape[1], lp_np.shape[0]),
                                        colorfmt='bgr')
                                    lp_image_texture.blit_buffer(
                                        lp_buf,
                                        colorfmt='bgr',
                                        bufferfmt='ubyte')
                                    # TODO: Query database to fill out make_model, parking_permit, valid
                                    # display image from the texture
                                    record = Record()
                                    record.update(
                                        image_texture=lp_image_texture,
                                        predicted_text=prediction,
                                        time=datetime.datetime.now().strftime(
                                            "%Y-%m-%d\n%H:%M:%S"),
                                        make_model='Ford\nTaurus',
                                        parking_permit='West\nW00013332',
                                        valid='Yes')
                                    main_screen.ids.data_grid.add_widget(
                                        record,
                                        len(main_screen.ids.data_grid.children)
                                    )

                                    self.reader.processed_set.add(prediction)
                                self.list = []

            self.texture = image_texture
Example #40
0
 def remove_from_cache(self, filename):
     Cache.remove('kv.loader', filename)
Example #41
0
    This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.
"""

from kivy.cache          import Cache
from ORCA.utils.LoadFile import LoadFile

__all__ = ['CachedFile','ClearCache']

uCacheName = 'CachedFiles'
Cache.register(category = uCacheName,  timeout=120)



def CachedFile(oFileName):
    """
    Returns the content of a file as string, using a cache if already loaded

    :rtype: string
    :param cFileName oFileName:
    :return: The content of a file
    """

    uFileContent = Cache.get(category = uCacheName, key = oFileName.string)
    if uFileContent is None:
        uFileContent = LoadFile(oFileName)
Example #42
0
from kivy.clock import Clock
from kivy.cache import Cache
from kivy.core.image import ImageLoader, Image
from kivy.compat import PY2, string_types
from kivy.config import Config
from kivy.utils import platform

from collections import deque
from time import sleep
from os.path import join
from os import write, close, unlink, environ
import threading
import mimetypes

# Register a cache for loader
Cache.register('kv.loader', limit=500, timeout=60)


class ProxyImage(Image):
    '''Image returned by the Loader.image() function.

    :Properties:
        `loaded`: bool, defaults to False
            This value may be True if the image is already cached.

    :Events:
        `on_load`
            Fired when the image is loaded or changed.
        `on_error`
            Fired when the image cannot be loaded.
            `error`: Exception data that ocurred
Example #43
0
    def load(filename, **kwargs):

        # atlas ?
        if filename[:8] == 'atlas://':
            # remove the url
            rfn = filename[8:]
            # last field is the ID
            try:
                rfn, uid = rfn.rsplit('/', 1)
            except ValueError:
                raise ValueError('Image: Invalid %s name for atlas' % filename)

            # search if we already got the atlas loaded
            atlas = Cache.get('kv.atlas', rfn)

            # atlas already loaded, so reupload the missing texture in cache,
            # because when it's not in use, the texture can be removed from the
            # kv.texture cache.
            if atlas:
                texture = atlas[uid]
                fn = 'atlas://%s/%s' % (rfn, uid)
                cid = '{}|{:d}|{:d}'.format(fn, False, 0)
                Cache.append('kv.texture', cid, texture)
                return Image(texture)

            # search with resource
            afn = rfn
            if not afn.endswith('.atlas'):
                afn += '.atlas'
            afn = resource_find(afn)
            if not afn:
                raise Exception('Unable to found %r atlas' % afn)
            atlas = Atlas(afn)
            Cache.append('kv.atlas', rfn, atlas)
            # first time, fill our texture cache.
            for nid, texture in atlas.textures.items():
                fn = 'atlas://%s/%s' % (rfn, nid)
                cid = '{}|{:d}|{:d}'.format(fn, False, 0)
                Cache.append('kv.texture', cid, texture)
            return Image(atlas[uid])

        # extract extensions
        ext = filename.split('.')[-1].lower()

        # prevent url querystrings
        if filename.startswith((('http://', 'https://'))):
            ext = ext.split('?')[0]

        filename = resource_find(filename)

        # special case. When we are trying to load a "zip" file with image, we
        # will use the special zip_loader in ImageLoader. This might return a
        # sequence of images contained in the zip.
        if ext == 'zip':
            return ImageLoader.zip_loader(filename)
        else:
            im = None
            for loader in ImageLoader.loaders:
                if ext not in loader.extensions():
                    continue
                Logger.debug('Image%s: Load <%s>' %
                             (loader.__name__[11:], filename))
                im = loader(filename, **kwargs)
                break
            if im is None:
                raise Exception('Unknown <%s> type, no loader found.' % ext)
            return im
Example #44
0
 def _get_data_from_cache(key):
     return Cache.get('json_cache', key)
Example #45
0
 def exist(self, nx, ny, zoom, maptype, format='png'):
     filename = self.to_filename(nx, ny, zoom, maptype, format)
     img = Cache.get('tileserver.tiles', filename)
     return bool(img)
Example #46
0
from kivy.uix.label import Label
from kivy.uix.popup import Popup
from kivy.graphics.texture import Texture
from kivy.graphics import Rectangle, RoundedRectangle, Color
from kivy.cache import Cache
from kivy.uix.settings import Settings
from threading import Thread, Event
import cv2
import numpy
import copy
import datetime
import os
import time
# Create a cache to store global variables and objects
# So they can be used across different screens and other classes
Cache.register('cache')


class BootScreen(Screen):

    boot_text = StringProperty('Initialization')
    init_text = StringProperty('Initializing...')
    title = 'Boot Screen'
    ready = False
    init_thread = None
    init_thread_stop_event = Event()

    def do_everything(self, dt=1):
        Clock.schedule_interval(self.boot, 1.0 / 3)
        self.init_thread = Thread(target=self.init_kivycapture,
                                  args=(1, self.init_thread_stop_event))
Example #47
0
def MfxRoot(**kw):
    mainWindow = Cache.get('LAppCache', 'mainWindow')
    logging.info('tkwrap: top = %s' % str(mainWindow))
    return mainWindow
            K1=10----K2=11    K3=32----K4=33    K5=54----K6=55    K7=76----K8=77    K9=98----K10=99     K11=120----K12=121    K13=142----K14=143    K15=164----K16=165    K17=186----K18=187


'''
'''
Globals
'''
count = 0
global LED_ROUTE_IMAGES, problemButton, Routes, filterBox, FilterLabel, filteredCommandStr, orderCommandStr, addedCommandStr, pageIndex
LED_ROUTE_IMAGES = [None] * 228


##ASSIGN ALL THE PHOTOS TO AN OBJECT SO WE DON'T ACCESS THE DISK ANYMORE##
im = CoreImage("images/2017/moon-0-0.png")

Cache.register('moonboardCache', limit=1000, timeout=999999)
Cache.register('kv.image', limit=None, timeout=None)

# Window.fullscreen = 'auto'
LED_COUNT = 198
LED_PIN = 18
LED_FREQ_HZ = 800000
LED_DMA = 5
LED_BRIGHTNESS = 255
LED_INVERT = False
LED_CHANNEL = 0


#LED_STRIP = ws.WS2811_STRIP_GRB
#strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL, LED_STRIP)
#strip.begin()
Example #49
0
    log('OpenGL informations')
    log('-------------------')

    from kivy.core.gl import glGetString, GL_VENDOR, GL_RENDERER, GL_VERSION
    log('GL Vendor: %s' % glGetString(GL_VENDOR))
    log('GL Renderer: %s' % glGetString(GL_RENDERER))
    log('GL Version: %s' % glGetString(GL_VERSION))
    log('')

    log('Benchmark')
    log('---------')

    for x in benchs:
        # clean cache to prevent weird case
        for cat in Cache._categories:
            Cache.remove(cat)

        # force gc before next test
        gc.collect()

        log('%2d/%-2d %-60s' % (benchs.index(x) + 1, len(benchs), x.__doc__),
            False)
        try:
            sys.stderr.write('.')
            test = x()
        except Exception, e:
            log('failed %s' % str(e))
            import traceback
            traceback.print_exc()
            continue
Example #50
0
from kivy.logger import Logger
from kivy.cache import Cache
from kivy.clock import Clock
from kivy.atlas import Atlas
from kivy.resources import resource_find
from kivy.utils import platform
from kivy.compat import string_types
from kivy.setupconfig import USE_SDL2
import zipfile
from io import BytesIO

# late binding
Texture = TextureRegion = None

# register image caching only for keep_data=True
Cache.register('kv.image', timeout=60)
Cache.register('kv.atlas')


class ImageData(object):
    '''Container for images and mipmap images.
    The container will always have at least the mipmap level 0.
    '''

    __slots__ = ('fmt', 'mipmaps', 'source', 'flip_vertical', 'source_image')
    _supported_fmts = ('rgb', 'rgba', 'bgr', 'bgra', 's3tc_dxt1', 's3tc_dxt3',
                       's3tc_dxt5', 'pvrtc_rgb2', 'pvrtc_rgb4', 'pvrtc_rgba2',
                       'pvrtc_rgba4', 'etc1_rgb8')

    def __init__(self,
                 width,
    def __init__(self):
        super().__init__()

        def load_LWF_data(path):
            try:
                file = open(path, 'rb')
                binary = file.read()
                data = Data(binary, len(binary))
                file.close()
                return data
            except Exception:
                return None

        self.display = Widget()
        # display.pos = (0, 250)
        self.add_widget(self.display)

        factory = KivyRendererFactory(self.display, '../../res/lwf',
                                      self.load_texture)

        self.lwfs = []

        data = load_LWF_data('../../res/lwf/character_active.lwf')
        cutin1 = LWF(data, factory)
        cutin1.property.move(150, 150)
        self.lwfs.append(cutin1)
        # cutin4 = LWF(data, factory)

        # cutin1.set_preferred_frame_rate(30)
        # cutin2 = LWF(data, factory)
        # cutin3 = LWF(data, factory)
        # self.lwfs.append(cutin2)
        # self.lwfs.append(cutin3)
        # self.lwfs.append(cutin4)

        # cutin2.property.move(0, 861)
        # cutin3.property.move(0, 668)
        # cutin4.property.move(0, 475)

        # self.node = LWFNode.create('../../res/lwf/assist_cutin.lwf', factory)
        # self.node.pos = (0, 1054)
        # self.node.
        # self.node2 = LWFNode.create('../../res/lwf/assist_cutin.lwf')
        # self.node2.pos = (0, 861)
        # self.node3 = LWFNode.create('../../res/lwf/assist_cutin.lwf')
        # self.node3.pos = (0, 668)
        # self.node4 = LWFNode.create('../../res/lwf/assist_cutin.lwf')
        # self.node4.pos = (0, 475)

        # self.node.lwf.scale_for_width(1706, 960)
        # self.add_widget(self.node)
        # self.add_widget(self.node2)
        # self.add_widget(self.node3)
        # self.add_widget(self.node4)

        self.add_widget(
            Button(on_release=lambda button: self.stop_start(), pos=(0, 750)))

        # background = Image(source='../../res/uix/screens/dungeon_battle/background.png', keep_ratio=False, allow_stretch=True)
        # background.size = (1920, 1080)
        # self.add_widget(background)
        #
        # names = ['hero_bell', 'catty_chloe', 'badass_ais', 'siren_song_riveria']
        # self.characters = []
        # for x, name in enumerate(names):
        #     character = Character(name, x * 250)
        #     self.characters.append(character)
        #     self.add_widget(character)

        Clock.schedule_interval(lambda dt: self.update(dt), 1 / 30)
        Clock.schedule_interval(lambda dt: self.render(), 1 / 30)

        Cache.register('textures')
Example #52
0
 def _load_data_to_cache(data):
     key = ''.join(
         random.choice(string.ascii_uppercase + string.digits)
         for _ in range(7))
     Cache.append('json_cache', key, data)
     return key
Example #53
0
 def get_screen(self, screen_name):
     return Cache.get('screens', screen_name)
Example #54
0
    def set_config(bike_model, rest_rm) -> None:
        Cache.remove('bike', 'rm')
        Cache.append('bike', 'rm', rest_rm)

        Cache.remove('bike', 'title')
        Cache.remove('bike', 'power')
        Cache.remove('bike', 'speed')
        Cache.remove('bike', 'acceleration')
        Cache.remove('bike', 'agility')

        Cache.append('bike', 'title', bike_model.title)
        Cache.append('bike', 'power', bike_model.power)
        Cache.append('bike', 'speed', bike_model.speed)
        Cache.append('bike', 'acceleration', bike_model.acceleration)
        Cache.append('bike', 'agility', bike_model.agility)
Example #55
0
 def on_close(self):
     # Get screen manager
     sm = Cache.get('cache', 'ScreenManager')
     # Switch to main screen
     sm.current = 'MainScreen'
Example #56
0
Factory.register('OutputList', module='denariium_gui.kivy.uix.dialogs')
Factory.register('OutputItem', module='denariium_gui.kivy.uix.dialogs')


#from kivy.core.window import Window
#Window.softinput_mode = 'below_target'


# delayed imports: for startup speed on android
notification = app = ref = None
util = False


# register widget cache for keeping memory down timeout to forever to cache
# the data
Cache.register('denariium_widgets', timeout=0)

from kivy.uix.screenmanager import Screen
from kivy.uix.tabbedpanel import TabbedPanel
from kivy.uix.label import Label
from kivy.core.clipboard import Clipboard

Factory.register('TabbedCarousel', module='denariium_gui.kivy.uix.screens')

# Register fonts without this you won't be able to use bold/italic...
# inside markup.
from kivy.core.text import Label
Label.register('Roboto',
               'gui/kivy/data/fonts/Roboto.ttf',
               'gui/kivy/data/fonts/Roboto.ttf',
               'gui/kivy/data/fonts/Roboto-Bold.ttf',
Example #57
0
import kivy.lang.builder  # imported as absolute to avoid circular import
from kivy.logger import Logger
from kivy.cache import Cache
from kivy import require
from kivy.resources import resource_find
from kivy.utils import rgba
import kivy.metrics as Metrics

__all__ = ('Parser', 'ParserException')

trace = Logger.trace
global_idmap = {}

# register cache for creating new classtype (template)
Cache.register('kv.lang')

# all previously included files
__KV_INCLUDES__ = []

# precompile regexp expression
lang_str = re.compile(
    "((?:'''.*?''')|"
    "(?:(?:(?<!')|''')'(?:[^']|\\\\')+?'(?:(?!')|'''))|"
    '(?:""".*?""")|'
    '(?:(?:(?<!")|""")"(?:[^"]|\\\\")+?"(?:(?!")|""")))', re.DOTALL)
lang_key = re.compile('([a-zA-Z_]+)')
lang_keyvalue = re.compile('([a-zA-Z_][a-zA-Z0-9_.]*\.[a-zA-Z0-9_.]+)')
lang_tr = re.compile('(_\()')
lang_cls_split_pat = re.compile(', *')
from .uix.dialogs.installwizard import InstallWizard
from .uix.dialogs import InfoBubble, crash_reporter
from .uix.dialogs import OutputList, OutputItem
from .uix.dialogs import TopLabel, RefLabel

#from kivy.core.window import Window
#Window.softinput_mode = 'below_target'

# delayed imports: for startup speed on android
notification = app = ref = None
util = False

# register widget cache for keeping memory down timeout to forever to cache
# the data
Cache.register('electrum_widgets', timeout=0)

from kivy.uix.screenmanager import Screen
from kivy.uix.tabbedpanel import TabbedPanel
from kivy.uix.label import Label
from kivy.core.clipboard import Clipboard

Factory.register('TabbedCarousel', module='electrum.gui.kivy.uix.screens')

# Register fonts without this you won't be able to use bold/italic...
# inside markup.
from kivy.core.text import Label
Label.register('Roboto', 'electrum/gui/kivy/data/fonts/Roboto.ttf',
               'electrum/gui/kivy/data/fonts/Roboto.ttf',
               'electrum/gui/kivy/data/fonts/Roboto-Bold.ttf',
               'electrum/gui/kivy/data/fonts/Roboto-Bold.ttf')
Example #59
0
def ClearCache():
    """ Clears the cache and frees memory """
    Cache.remove(category = uCacheName)
Example #60
0
 def add_new_contact(self):
     dlg = Cache.get('electrum_widgets', 'NewContactDialog')
     if not dlg:
         dlg = NewContactDialog()
         Cache.append('electrum_widgets', 'NewContactDialog', dlg)
     dlg.open()