Пример #1
0
    def markDestination(self, destination):
        ''' Takes in a parking garage object called destination
            Gets the location of the destination and places a map marker on top of it 
            
            Parameters: destination - ParkingGarage object
            Returns: coords - tuple with the coordinates of the map marker
        '''
        if not isinstance(destination, ParkingGarage):
            pop = Popup(title="Error",
                        content=Label(text="No Destination Input"),
                        size_hint=(.2, .2))
            pop.open()
            return

        #Get the coordinates of the destination
        coder = GoogleGeocoder("AIzaSyDPOAePgFbDCBU0rsOdvWX66C2CPUB2CZM")
        g = coder.get(destination.getLocation())
        coords = (g[0].geometry.location.lat, g[0].geometry.location.lng)

        #Create a marker that holds information on the parking garage
        bub = Bubble(size_hint=(None, None),
                     size=(200, 50),
                     arrow_pos='bottom_left')
        lab = Label(text=("            " + destination.getName()),
                    text_size=(self.width, None))
        lab.height = lab.texture_size[1]
        lab.halign = 'center'
        bub.add_widget(lab)
        m1 = MapMarkerPopup(lat=coords[0], lon=coords[1], placeholder=bub)

        #Mark the map and return the coordinates of the marker
        self.ids.map1.add_marker(m1)
        return coords
Пример #2
0
    def build(self):

        layout = BoxLayout(orientation='vertical')
        self.mapview = MapView(zoom=7, lat=42.6394, lon=25.057)

        bubble = Bubble(orientation="horizontal", padding=5)
        text = "[b]Sample text here[/b]"
        label = Label(text=text, markup=True, halign="center")
        bubble.add_widget(label)
        marker = MapMarkerPopup(id="first",
                                lat=42.6394,
                                lon=25.057,
                                popup_size=('150dp', '100dp'))
        marker.add_widget(bubble)
        self.mapview.add_marker(marker)

        b = BoxLayout(orientation='horizontal',
                      height='52dp',
                      size_hint_y=None)
        b.add_widget(
            Button(text="Zoom in",
                   on_press=lambda a: setattr(self.mapview, 'zoom', self.
                                              mapview.zoom + 1)))
        b.add_widget(
            Button(text="Zoom out",
                   on_press=lambda a: setattr(self.mapview, 'zoom', self.
                                              mapview.zoom - 1)))

        layout.add_widget(b)
        layout.add_widget(self.mapview)
        return layout
Пример #3
0
    def open_bubble_not_set(self, ti_not_set):

        float_lay = FloatLayout()
        float_lay.size_hint = None, None
        float_lay.width = 0
        float_lay.height = 0


        bubble_not_set = Bubble()
        bubble_not_set.size_hint = None, None
        bubble_not_set.width = 80
        bubble_not_set.height = 30
        bubble_not_set.center_x = ti_not_set.center_x
        bubble_not_set.center_y = ti_not_set.center_y - 30
        bubble_not_set.arrow_pos = 'top_mid'
        bubble_not_set.background_color = (1, 0, 0, 1)


        bt_not_set = BubbleButton()
        bt_not_set.font_size = 12

        bt_not_set.text = self.lang['Not_Set']

        bubble_not_set.add_widget(bt_not_set)

        float_lay.add_widget(bubble_not_set)

        #self.add_widget(bubble_not_set)
        self.lay_file_asc.add_widget(float_lay)
        parallel_close = threading.Thread(target=self.close_bubble_not_set, args=(float_lay,))
        parallel_close.start()
Пример #4
0
    def open_bubble_not_set(self, ti_not_set):

        float_lay = FloatLayout()
        float_lay.size_hint = None, None
        float_lay.width = 0
        float_lay.height = 0

        bubble_not_set = Bubble()
        bubble_not_set.size_hint = None, None
        bubble_not_set.width = 80
        bubble_not_set.height = 30
        bubble_not_set.center_x = ti_not_set.center_x
        bubble_not_set.center_y = ti_not_set.center_y - 30
        bubble_not_set.arrow_pos = 'top_mid'
        bubble_not_set.background_color = (1, 0, 0, 1)

        bt_not_set = BubbleButton()
        bt_not_set.font_size = 12

        bt_not_set.text = self.lang['Not_Set']

        bubble_not_set.add_widget(bt_not_set)

        float_lay.add_widget(bubble_not_set)

        #self.add_widget(bubble_not_set)
        self.lay_file_asc.add_widget(float_lay)
        parallel_close = threading.Thread(target=self.close_bubble_not_set,
                                          args=(float_lay, ))
        parallel_close.start()
Пример #5
0
class CalendarButton(FloatLayout):

	def __init__(self, activity, **kwargs):
		self.activity = activity

		super(CalendarButton, self).__init__()
		
		self.buttonInstance = Button(size_hint=(1, 1), pos_hint={'center_x':0.5, 'center_y':0.5}, **kwargs)
		self.buttonInstance.bind(on_release=self.onPressBubble)
		self.add_widget(self.buttonInstance)

		self.bubbleInstance = Bubble(size_hint=(None, None), size=(100, 40), pos_hint={'center_x':0.5, 'center_y':0.5}, arrow_pos='bottom_mid')
		
		self.bubbleChange = BubbleButton(text='Change', font_size=8)
		self.bubbleChange.bind(on_release=self.onPressChange)
		self.bubbleRemove = BubbleButton(text='Remove', font_size=8)
		self.bubbleRemove.bind(on_release=self.onPressRemove)
		
		self.bubbleInstance.add_widget(self.bubbleChange)
		self.bubbleInstance.add_widget(self.bubbleRemove)

	def onPressBubble(self, instance):
		if self.bubbleInstance.parent == None:
			self.add_widget(self.bubbleInstance)
		else:
			self.remove_widget(self.bubbleInstance)
	
	def onPressChange(self, instance):
		self.remove_widget(self.bubbleInstance)
		changeActivity(self.activity)
	
	def onPressRemove(self, instance):
		self.remove_widget(self.bubbleInstance)
		removeActivity(self.activity)
Пример #6
0
    def visualizarVehiculos(
        self
    ):  #Muestro los marcadores con las ubicaciones actualizadas en el mapa
        ip_request = requests.get('https://get.geojs.io/v1/ip.json')
        my_ip = ip_request.json()['ip']  #con mi ip obtengo mi geolocalizacion
        geo_request = requests.get('https://get.geojs.io/v1/ip/geo/' + my_ip +
                                   '.json')
        geo_data = geo_request.json()

        self.longitudActual = float(geo_data['longitude'])
        self.latitudActual = float(geo_data['latitude'])

        self.ids.mapview.center_on(
            self.latitudActual,
            self.longitudActual)  #mapa centrado en ubicacion actual
        self.ids.mapview.zoom = 5

        mapmarkerpopupUbicacionActual = MapMarkerPopup(lat=self.latitudActual,
                                                       lon=self.longitudActual,
                                                       popup_size=(120, 70))
        bubbleUbicacionActual = Bubble()
        labelUbicacionActual = Label(text="[b]Ubicaion actual![/b]",
                                     markup=True,
                                     halign="center")
        bubbleUbicacionActual.add_widget(labelUbicacionActual)
        mapmarkerpopupUbicacionActual.add_widget(
            bubbleUbicacionActual
        )  #creo un marcador con etique para saber la ubicacion actual, es de color rojo

        #self.ids.mapview.center_on(4.795100942698568, -75.6890602859938) #Me centra en la utp.
        if len(self.listaMarker) > 0:
            for marker in range(len(self.listaMarker)):
                self.ids.mapview.remove_widget(self.listaMarker[marker])
            self.listaMarker = [
            ]  #La reseteo para poder meter los mapMarker de los vehiculos actualizados.

        #Se hace la consulta a la BD para obtener las lat y lon de los vehiculos-----------------------BD
        self.listaMarker.append(mapmarkerpopupUbicacionActual)

        #hacer consulta base de datos
        pos = UbicacionVehiculo.obtenerData(UbicacionVehiculo)

        for e in pos:
            mapmarkerpopup = MapMarkerPopup(
                lat=float(e[1]),
                lon=float(e[2]),
                color=(0, 1, 1, 1),
                popup_size=(120, 70))  #acepta 1,0,1,1 o 0,0,0,1 o 0,1,1,1
            bubble = Bubble()
            label = Label(text="[b]" +
                          Vehiculo.getNamevehiculo(Vehiculo, e[0]) + "[/b]",
                          markup=True,
                          halign="center")
            bubble.add_widget(label)
            mapmarkerpopup.add_widget(bubble)
            self.listaMarker.append(mapmarkerpopup)

        for i in range(len(pos)):
            self.ids.mapview.add_widget(self.listaMarker[i])
Пример #7
0
 def __init__(self, grid, **kwargs):
     super(Marker, self).__init__(**kwargs)
     bubble = Bubble(arrow_pos='left_bottom')
     self.label = Label()
     bubble.add_widget(self.label)
     self.add_widget(bubble)
     self.grid = grid
     self.update_text()
Пример #8
0
 def test_add_two_content_widgets_fails(self):
     from kivy.uix.bubble import BubbleException
     bubble = Bubble()
     content_1 = BubbleContent()
     content_2 = BubbleContent()
     bubble.add_widget(content_1)
     with self.assertRaises(BubbleException):
         bubble.add_widget(content_2)
Пример #9
0
    def test_add_remove_content(self):
        bubble = Bubble()
        content = BubbleContent()
        bubble.add_widget(content)
        self.render(bubble)

        bubble.remove_widget(content)
        self.render(bubble)
Пример #10
0
    def test_add_content_with_buttons(self):
        bubble = Bubble()

        content = BubbleContent()
        content.add_widget(BubbleButton(text="Option A"))
        content.add_widget(BubbleButton(text="Option B"))

        bubble.add_widget(content)
        self.render(bubble)
Пример #11
0
 def show_bubble(self, bx, by):
     bubble = Bubble(size_hint=[None, None], size=[20, 20], pos=[bx, by])
     bubble.add_widget(
         BubbleButton(text='WRONG',
                      font_size='10sp',
                      color=[0, 0, 0, 1],
                      size=[6, 3]))
     bubble.background_color = (255, 0, 0, 1)
     bubble.arrow_pos = 'bottom_right'
     self.ids.bbox.add_widget(bubble)
     Clock.schedule_once(partial(self.remove_bubble, bubble), 1.5)
Пример #12
0
	def signal(self):
		my_bubble= Bubble(orientation = 'vertical',size_hint=(None, None),size=(600, 100),pos=(200,0))
		my_bubble.background_color =(20, 0, 0, .5) 
		my_bubble.border = [50, 50, 50, 10]
		my_bubble.size = (150, 50)
		my_bubble.arrow_pos= 'top_mid'
		my_bub_btn1= BubbleButton(text='Remove signal')
		#my_bub_btn1.bind(on_release=lambda my_bub_btn1: self.Update(1, my_bubble, my_bub_btn1))
		my_bub_btn1.bind(on_release=lambda my_bub_btn1: self.RemoveBub(my_bubble))
		my_bubble.add_widget(my_bub_btn1)
		self.add_widget(my_bubble)
Пример #13
0
class SettingView(ToggleButton):
    parameter = StringProperty("Parameter")
    formatStr = StringProperty("%d")
    value = NumericProperty(0)
    minVal = NumericProperty(0)
    maxVal = NumericProperty(0)
    delta = NumericProperty(1)
    unit = StringProperty("unit")
    
    def __init__(self, **kwargs):
        super(SettingView, self).__init__(**kwargs)
        
        self.register_event_type('on_change')
        
        self.text = ("[size=60]"+self.formatStr+"[/size][size=15]%s[/size]\n[size=20]%s[/size]") % (self.value, self.unit, self.parameter)
        self.valign = 'bottom'
        self.halign = 'center'
        self.markup = True

    def decr(self, evt):
        if self.value > self.minVal:
            self.value = self.value - self.delta
            self.text = ("[size=60]"+self.formatStr+"[/size][size=15]%s[/size]\n[size=20]%s[/size]") % (self.value, self.unit, self.parameter)
    
    def incr(self, evt):
        if self.value < self.maxVal:
            self.value = self.value + self.delta
            self.text = ("[size=60]"+self.formatStr+"[/size][size=15]%s[/size]\n[size=20]%s[/size]") % (self.value, self.unit, self.parameter)
    
    def on_state(self, widget, state):
        # super(SettingView, self).on_state(**kwargs)
        
        if self.state == 'down':
            bubbleHeight = 50
            self.bubble = Bubble(size_hint=(None,None), size=(self.width, bubbleHeight), center_x=self.center_x, y=self.height-bubbleHeight)
            b1 = BubbleButton(text="-", font_size=40)
            b1.bind(on_press = self.decr)
            b2 = BubbleButton(text="+", font_size=40)
            b2.bind(on_press = self.incr)
            self.text_size = self.size
            self.text_size[1] -= 10
            self.valign='bottom'
            self.bubble.add_widget(b1)
            self.bubble.add_widget(b2)

            self.add_widget(self.bubble)
        else:
            self.remove_widget(self.bubble)
            self.valign='center'
            self.dispatch('on_change', self.value)
            
    def on_change(self, event):
        pass
Пример #14
0
 def show_timer(self):
     self.dynamic_button = "Pause"
     bubble = Bubble(size_hint=[None, None], size=[50, 35], pos=[375, 490])
     bubble.add_widget(
         BubbleButton(text='START',
                      font_size='15sp',
                      color=[0, 0, 0, 1],
                      size=[10, 10]))
     bubble.background_color = (0, 0, 0, 0)
     self.ids.bbox.add_widget(bubble)
     Clock.schedule_interval(self.Running_Clock, 1)
     Clock.schedule_once(partial(self.remove_bubble, bubble), 1)
Пример #15
0
def show_bubble(self, *args):
    my_bubble = Bubble(orientation="horizontal", pos=(280, 400))
    my_bubble.background_color = (20, 0, 0, 0.5)
    my_bubble.border = [50, 50, 50, 10]
    my_bubble.arrow_pos = "top_left"
    my_bub_btn1 = BubbleButton(text="Copy", size_hint=(None, None), size=(80, 50), pos=(200, 400))
    my_bub_btn2 = BubbleButton(text="Cut", size_hint=(None, None), size=(80, 50), pos=(300, 400))
    my_bub_btn3 = BubbleButton(text="Paste", size_hint=(None, None), size=(80, 50), pos=(300, 400))
    # Add items to bubble
    my_bubble.add_widget(my_bub_btn1)
    my_bubble.add_widget(my_bub_btn2)
    my_bubble.add_widget(my_bub_btn3)
    self.add_widget(my_bubble)
Пример #16
0
 def timer_bubble(self, tx1, tx2, clr, fn):
     bubble = Bubble(size_hint=[None, None], size=[50, 35], pos=[375, 490])
     bubble.add_widget(
         BubbleButton(text="{:02d}:{:02d}".format(tx1, tx2),
                      font_size='15sp',
                      color=[0, 0, 0, clr],
                      size=[10, 10]))
     bubble.background_color = (0, 0, 0, 0)
     self.ids.bbox.add_widget(bubble)
     if fn == "stop":
         Clock.schedule_once(partial(self.remove_bubble, bubble), 60)
     if fn == "run":
         Clock.schedule_once(partial(self.remove_bubble, bubble), 1)
Пример #17
0
class ToolSelectFunction(Spinner):
    def __init__(self, **kwargs):
        self.map_pars = {}
        self.bubble = None
        self.bubb_layout = None
        self.button = None
        self.func_des = None
        self.background_color = (0.46, 0.46, 0.46, 0.6)
        super(ToolSelectFunction, self).__init__(**kwargs)

    def _on_dropdown_select(self, instance, data, *largs):
        self.text = data
        self.is_open = False
        #print('select function',self.text)
        self.func_des = '[color=#ffff00][i][b]' + self.parent.tool_library.read_obj.get_func_des(
            self.text) + '[/i][/b][/color]'
        self.set_select_parameter(self.text)

        if self.bubble is None:

            self.bubble = Bubble(size_hint=(.3, .2))
            self.bubb_layout = AnchorLayout(anchor_x='right', anchor_y='top')

            def remove_bubble(instance):
                self.bubb_layout.remove_widget(self.bubble)
                self.parent.parent.remove_widget(self.bubb_layout)
                self.bubble = None
                self.bubb_layout = None

            self.button = BubbleButton(text=self.func_des,
                                       halign='left',
                                       valign='middle',
                                       text_size=(300, 300),
                                       background_color=(0, 0, 1, 1),
                                       markup=True)
            self.button.bind(on_press=remove_bubble)
            self.bubble.add_widget(self.button)
            self.bubble.arrow_pos = 'top_mid'
            self.bubb_layout.add_widget(self.bubble)
            self.parent.parent.parent.add_widget(self.bubb_layout)

        else:
            self.button.text = self.func_des

    def set_select_parameter(self, function):
        self.parent.tool_parameter.text = 'Select Parameter'
        self.map_pars = self.parent.tool_library.read_obj.get_pars_type(
            function)

        #print('map_pars',map_pars)
        self.parent.tool_parameter.values = self.map_pars.keys()
Пример #18
0
class UseBubble(object):
    bubble = None
    callbackid = None
    def openbubble(self, buttonfunclist, data=None):
        if self.bubble:
            logging.error("Bubble already called")
            return
        self.bubble = Bubble(height=30, width=10, pos=self.to_window(self.x, self.y+30), size_hint=(None, None))
        for text, func in buttonfunclist:
            button = BubbleButton(text=text, height=30)
            self.bubble.width += 10 + len(text)*10
            self.call(button, func, data)
            self.bubble.add_widget(button)
        root = App.get_running_app().root
        #self.get_root_window().add_widget(self.bubble, root.canvas)
        root.add_widget(self.bubble)
        self.callbackid = root.fbind("on_touch_down", self.touch_grab)
    def touch_grab(self, widget, touch):
        touch.grab(self)
    def on_touch_up(self, touch):
        if touch.grab_current is self:
            touch.ungrab(self)
            self.close_on_pos(touch.pos)
        return True


    def closebubble(self):
        if self.bubble:
            #self.get_root_window().remove_widget(self.bubble)
            root = App.get_running_app().root
            root.unbind_uid("on_touch_down", self.callbackid)
            root.clear_widgets([self.bubble])
            self.bubble = None
    def on_parent(self, instance, value):
        self.closebubble()

    def call(self, button, funccall, data):
        def _call(instance):
            self.closebubble()
            if data:
                return funccall(data)
            else:
                return funccall()
        button.bind(on_press=_call)

    def close_on_pos(self, pos):
        bubble = self.bubble
        if bubble:
            if not bubble.collide_point(*pos) and not self.collide_point(*pos):
                self.closebubble()
Пример #19
0
	def add_new_marker(self, lat, lon, unit_name):
		print("add_new_marker")
		self.units_markers[unit_name] = MapMarkerPopup(lat=float(lat),lon=float(lon))
		self.units_markers[unit_name].popup_size = ( 230, 130 )

		buble = Bubble()

		box = BoxLayout(orientation="horizontal", padding="5px")#.add_widget(Label(text=unit_name))
		box.add_widget(AsyncImage(source="http://cs618620.vk.me/v618620602/1a4b3/-A6cSynXWf0.jpg", mipmap=True))
		box.add_widget(Label(text=unit_name, markup=True, halign="center"))

		buble.add_widget(box)

		self.units_markers[unit_name].add_widget(buble)

		self.mapview.add_marker( self.units_markers[unit_name] )
		self.mapview.do_update(None)
    def build(self):

        MainAppWindow = AppBody(orientation='vertical')
        ToolBar = Bubble(size_hint=[1, .1])
        MainAppWindow.add_widget(ToolBar)
        WorkArea = AnchorLayout()
        MainAppWindow.add_widget(WorkArea)

        self.Timer_icon = Timer_icon = HeaderLables(size_hint=[1 / 5, 1])
        Timer_icon.img1.source = 'icons8-alarm-clock-96.png'
        Timer_icon.btn1.bind(on_release=self.GoTOTimer_widget)

        self.Stopclock_widget = Stopclock_widget = HeaderLables(
            size_hint=[1 / 5, 1])
        Stopclock_widget.img1.source = 'icons8-sport-stopwatch-96.png'
        Stopclock_widget.btn1.bind(on_release=self.GoTOStopclock_widget)

        self.Alarm_widget = Alarm_widget = HeaderLables(size_hint=[1 / 5, 1])
        Alarm_widget.img1.source = 'icons8-alarm-96.png'
        Alarm_widget.btn1.bind(on_release=self.GoTOAlarm_widget)

        self.Cust_widget = Cust_widget = HeaderLables(size_hint=[1 / 5, 1])
        Cust_widget.img1.source = 'icons8-star-96.png'
        Cust_widget.btn1.bind(on_release=self.GoTOCust_widget)

        self.Settings_widget = Settings_widget = HeaderLables(
            size_hint=[1 / 5, 1])
        Settings_widget.img1.source = 'icons8-settings-96.png'
        Settings_widget.btn1.bind(on_release=self.GoTOSettings_widget)

        ToolBar.add_widget(Timer_icon)
        ToolBar.add_widget(Stopclock_widget)
        ToolBar.add_widget(Alarm_widget)
        ToolBar.add_widget(Cust_widget)
        ToolBar.add_widget(Settings_widget)

        self.myTimer = Timer_widget()
        self.myStopClock = StopClockWidget()
        self.myAM = AM_SM()
        carousel = Carousel(direction='right')
        carousel.add_widget(self.myTimer)
        carousel.add_widget(self.myStopClock)
        carousel.add_widget(self.myAM)
        WorkArea.add_widget(carousel)
        return MainAppWindow
Пример #21
0
 def decoded(self, val):
     '''
     if self.message.text != "Labels: ":
         self.message.text += ", "
         
     self.message.text += val
     '''
     
     if val not in self.labels:
         self.labels.append(val)
         
         #obtener informacion del warehouse leido
         wh = Warehouses.Query.get(objectId=val)
         
         
         box = Bubble(size_hint_y=None, height=200)
                 
         labelreceipt = LabelReceipt()
         
         labelreceipt.receipt.text = "Receipt#: " + str(wh.Receipt)
         labelreceipt.zone.text = "Zone: " + wh.Zone
         labelreceipt.volume.text = "Volume: " + wh.Volume
         labelreceipt.consignee.text = "[b]Consignee:[/b]\n" + wh.Consignee.Name
         labelreceipt.country.text = "Country: " + wh.Country
         labelreceipt.objectId.text = "ID: " + wh.objectId
         
         '''
         labelreceipt.zone.text = wh.Zone
         '''
                 
         #box.add_widget(Label(text="ID:"+val))
         box.add_widget(labelreceipt)
         
         if os.path.isfile("box.png"):
             print "BOX IMAGE FOUND"
                             
         self.boxlabels.add_widget( box )
         vibrator.vibrate(.2)
Пример #22
0
 def show_bubble(self, *args):
     my_bubble = Bubble(orientation='horizontal', pos=(280, 400))
     # Customizing my bubble
     my_bubble.background_color = (0, 0, 0, .5)
     my_bubble.border = [50, 50, 50, 10]
     my_bubble.arrow_pos = 'top_left'
     my_bub_btn1 = BubbleButton(text='Copy',
                                size_hint=(None, None),
                                size=(80, 50),
                                pos=(200, 400))
     my_bub_btn2 = BubbleButton(text='Cut',
                                size_hint=(None, None),
                                size=(80, 50),
                                pos=(300, 400))
     my_bub_btn3 = BubbleButton(text='Paste',
                                size_hint=(None, None),
                                size=(80, 50),
                                pos=(300, 400))
     # Add items to bubble
     my_bubble.add_widget(my_bub_btn1)
     my_bubble.add_widget(my_bub_btn2)
     my_bubble.add_widget(my_bub_btn3)
     self.add_widget(my_bubble)
Пример #23
0
def mark(position, mapview, marker, result=[]):
    LAT, LON = position
    if not result:
        # m = marker(lat = LAT, lon = LON, source = "Map-Marker-PNG-Pic_3_1.png")
        bubble = Bubble(orientation="horizontal", padding=5)
        text = "[b]Self[/b]"
        label = Label(text=text, markup=True, halign="center")
        bubble.add_widget(label)
        m = MapMarkerPopup(lat=LAT,
                           lon=LON,
                           popup_size=(100, 50),
                           source="Map-Marker-PNG-Pic_3_1.png")
        m.add_widget(bubble)
    else:
        place_detail = get_place_details(result["place_id"])
        photo = get_photo_html(result)
        phone = get_phone_number(place_detail)
        name = result["name"]
        rating = get_rating(result)

        # m = marker(lat = LAT, lon = LON) marker has been replaced by mapmarkerpopup
        bubble = Bubble(orientation="vertical", padding=5)
        if photo:
            image = AsyncImage(source=photo, mipmap=True)
            bubble.add_widget(image)
        if len(name) > 30:
            index1 = name.find(",")
            index2 = name.find(" ", int(len(name) / 2))
            if index1 > 15:
                name = name[:index1] + "\n" + name[index1:]
            elif index2 > 20:
                name = name[:index2] + "\n" + name[index2:]

        text = "[b]" + name + "[/b]\n" + "Phone Number: " + phone + "\n" + "Rating: " + rating
        label = Label(text=text, markup=True, halign="center")
        bubble.add_widget(label)
        m = MapMarkerPopup(lat=LAT, lon=LON, popup_size=(250, 230))
        m.add_widget(bubble)
    marker_list.append(m)
    mapview.add_marker(m)
Пример #24
0
class Demoer(FloatLayout):
    def __init__(self, *args, **kwargs):
        self.state = ToolState.EMPTY

        # dimensions of the area where nodes can be placed
        self.workAreaXDim = 720
        self.workAreaYDim = 520
        self.workAreaXPos = 40
        self.workAreaYPos = 40

        # multiple choice bubble menu for node addition
        self.defaultBubble = Bubble(size_hint=(None, None), size=(250, 40))
        self.newComputerButton = Button(text="Nowy komputer")
        self.newRouterButton = Button(text="Nowy router")
        self.defaultBubble.add_widget(self.newComputerButton)
        self.defaultBubble.add_widget(self.newRouterButton)

        # coordinates of node-button to be placed
        self.pendingNodePosX = 0
        self.pendingNodePosY = 0

        # multiple choice bubble menu for node editing/removal
        self.nodeBubble = Bubble(size_hint=(None, None), size=(250, 40))
        self.newConnButton = Button(text="Dodaj połączenie")
        self.deleteNodeButton = Button(text="Usuń węzeł")
        self.nodeBubble.add_widget(self.newConnButton)
        self.nodeBubble.add_widget(self.deleteNodeButton)

        # reference to button being edited/removed
        self.pendingNodeRef = Button()

        # global state - adding connection or not
        self.isInConnectionMode = False
        self.netManager = NetworkManager(self.__deleteLine, self.appendLog,
                                         self.animatePacket)

        # define widgets of side panel and add them to window
        self.sidePanelTabbedPanel = TabbedPanel(do_default_tab=False,
                                                size=(200, 600),
                                                pos=(800, 0),
                                                background_color=(0, 0, 0, 0),
                                                tab_width=100)

        # define widgets of log display and add them to window
        self.sidePanelLogTab = TabbedPanelItem(text="Symulacja")
        self.sidePanelLogLayout = GridLayout(cols=1,
                                             spacing=10,
                                             size_hint=(None, None),
                                             size=(200, 550))
        self.logField = TextInput(padding=10,
                                  readonly=True,
                                  size_hint_max_y=None,
                                  size_hint=(None, None),
                                  size=(190, 550))
        self.logField.bind(minimum_height=self.logField.setter('height'))
        self.sidePanelLogScrollView = ScrollView(
            size_hint=(None, None),
            size=(200, 450),
            scroll_type=['bars'],
            bar_width=10,
            bar_inactive_color=[1, 1, 1, .8],
            bar_color=[0.3, 1, 1, 1])
        self.sidePanelLogScrollView.add_widget(self.logField)
        self.sidePanelLogLayout.add_widget(self.sidePanelLogScrollView)
        self.sidePanelLogTab.add_widget(self.sidePanelLogLayout)
        self.sidePanelTabbedPanel.add_widget(self.sidePanelLogTab)

        # A welcome log
        self.appendLog('A new workspace has been created.')

        # define widgets of node edit panel to be added to window later
        # when a node is selected, add sidePanelNodeTab with the proper tab name to sidePanelTabbedPanel
        # and fill sidePanelNodeTab with content - interface configuration form
        self.sidePanelNodeTab = TabbedPanelItem()
        self.sidePanelNodeLayout = GridLayout(cols=1,
                                              spacing=5,
                                              size_hint=(None, None),
                                              size=(200, 550))
        self.sidePanelNodeLayout.bind(
            minimum_height=self.sidePanelNodeLayout.setter('height'))
        self.sidePanelNodeScrollView = ScrollView(
            size_hint=(None, None),
            size=(200, 550),
            pos=(800, 0),
            scroll_type=['bars'],
            bar_width=10,
            bar_inactive_color=[1, 1, 1, .8],
            bar_color=[1, 1, 1, 1])
        self.sidePanelNodeTab.add_widget(self.sidePanelNodeScrollView)
        self.sidePanelNodeScrollView.add_widget(self.sidePanelNodeLayout)

        # define simulation-related buttons and add them to the window
        self.toggleSimButton = Button(text="Symuluj")
        self.addPacketButton = Button(text="Nowy pakiet",
                                      on_press=self.on_new_packet)
        self.stepSimButton = Button(text=">|", on_press=self.on_step)
        self.playSimButton = Button(text=">")
        self.simButtonLayout = BoxLayout()
        self.sidePanelLogLayout.add_widget(self.addPacketButton)
        self.sidePanelLogLayout.add_widget(self.toggleSimButton)
        self.sidePanelLogLayout.add_widget(self.simButtonLayout)
        self.simButtonLayout.add_widget(self.playSimButton)
        self.simButtonLayout.add_widget(self.stepSimButton)

        self.packetNodes = []

        # set window color
        Window.clearcolor = (0.7, 0.7, 0.7, 1)

        super(Demoer, self).__init__(*args, **kwargs)

        self.add_widget(self.sidePanelTabbedPanel)

        # create delimiter line around the work area
        self.canvas.before.add(
            Line(rectangle=(self.workAreaXPos, self.workAreaYPos,
                            self.workAreaXDim, self.workAreaYDim),
                 width=0.5))

        # create background square behind side panel
        with self.canvas.before:
            Color(0.3, 0.3, 0.3, 1)
            Rectangle(pos=(2 * self.workAreaXPos + self.workAreaXDim, 0),
                      size=(200, 600))
            Color(1, 1, 1, 1)

    # switch between placing connection or editing nodes
    def toggleConnectionMode(self, instance):
        self.clearBubbles()
        if not self.isInConnectionMode:
            self.pendingNodeRef.background_color = (1, 0.5, 0.5, 1)
            self.isInConnectionMode = True
        else:
            self.pendingNodeRef.background_color = (1, 1, 1, 1)
            self.isInConnectionMode = False

    # display node property edit tab
    def showNodeEditPanel(self, instance):
        node_name = self.netManager.getNodeName(instance)
        self.sidePanelNodeTab.text = node_name

        if len(self.sidePanelTabbedPanel.children) == 2:
            self.sidePanelTabbedPanel.add_widget(self.sidePanelNodeTab)

        self.sidePanelTabbedPanel.switch_to(self.sidePanelNodeTab)

        self.sidePanelNodeLayout.clear_widgets()
        self.sidePanelNodeLayout.add_widget(
            Label(text="Interfejsy węzła " + node_name + ":",
                  size_hint=(1, None)))

        interfaces = self.netManager.getNodeInterfaces(instance)
        for label, (ip, conn) in interfaces.items():
            self.sidePanelNodeLayout.add_widget(
                Label(text=label, size_hint=(1, None), height=30))
            input_field = TextInput(text=ip,
                                    multiline=False,
                                    size_hint=(1, None),
                                    height=30)
            cb = functools.partial(self.on_node_edit, conn, instance)
            input_field.bind(on_text_validate=cb)
            self.sidePanelNodeLayout.add_widget(input_field)

    # remove active bubble menus
    def clearBubbles(self):
        self.remove_widget(self.nodeBubble)
        self.remove_widget(self.defaultBubble)

    def __deleteLine(self, line):
        self.canvas.before.remove(line)

    # remove active node after clicking in bubble menu
    def deleteNode(self, instance):
        self.clearBubbles()
        self.remove_widget(self.pendingNodeRef)
        self.netManager.deleteNode(self.pendingNodeRef)

        if self.sidePanelNodeTab.text == self.pendingNodeRef.children[0].text:
            self.sidePanelTabbedPanel.remove_widget(self.sidePanelNodeTab)
            self.sidePanelTabbedPanel.switch_to(self.sidePanelLogTab)

    # add pending node as computer after clicking in bubble menu
    def addComputer(self, instance):
        nodeButton = Button(pos=(self.pendingNodePosY, self.pendingNodePosX),
                            size_hint=(None, None),
                            size=(40, 40))
        nodeImg = Image(source="Images/computer.png")
        nodeLabel = Label()
        nodeButton.add_widget(nodeImg)
        nodeButton.add_widget(nodeLabel)
        nodeImg.center_x = nodeImg.parent.center_x
        nodeImg.center_y = nodeImg.parent.center_y + 10
        nodeLabel.center_x = nodeLabel.parent.center_x
        nodeLabel.center_y = nodeLabel.parent.center_y - 10
        nodeButton.bind(on_press=self.showNodeBubble)
        self.add_widget(nodeButton)
        self.netManager.addComputer(nodeButton)
        nodeLabel.text = self.netManager.getNodeName(nodeButton)

    # add pending node as router after clicking in bubble menu
    def addRouter(self, instance):
        nodeButton = Button(pos=(self.pendingNodePosY, self.pendingNodePosX),
                            size_hint=(None, None),
                            size=(40, 40))
        nodeImg = Image(source="Images/router.png")
        nodeLabel = Label()
        nodeButton.add_widget(nodeImg)
        nodeButton.add_widget(nodeLabel)
        nodeImg.center_x = nodeImg.parent.center_x
        nodeImg.center_y = nodeImg.parent.center_y + 10
        nodeLabel.center_x = nodeLabel.parent.center_x
        nodeLabel.center_y = nodeLabel.parent.center_y - 10
        nodeButton.bind(on_press=self.showNodeBubble)
        self.add_widget(nodeButton)
        self.netManager.addRouter(nodeButton)
        nodeLabel.text = self.netManager.getNodeName(nodeButton)

    # show bubble menu on click on node
    # OR create connection between active node and clicked node when in connection mode
    # OR select nodes for packet transmission
    def showNodeBubble(self, instance):
        if self.state == ToolState.SELECTING_PACKET_NODE1:
            self.packetNodes.append(instance)
            instance.background_color = (1, 0.5, 0.5, 1)
            self.state = ToolState.SELECTING_PACKET_NODE2
        elif self.state == ToolState.SELECTING_PACKET_NODE2:
            packetNodes = self.packetNodes.copy()
            packetNodes.append(instance)
            try:
                self.netManager.preparePacket(tuple(packetNodes))
            except DemoerException as e:
                self.showPopup('Error', e.message)
            else:
                instance.background_color = (1, 0.5, 0.5, 1)
                self.state = ToolState.EMPTY
                self.packetNodes.clear()
        else:
            if not self.isInConnectionMode:
                self.showNodeEditPanel(instance)
                self.clearBubbles()
                self.pendingNodeRef = instance
                self.nodeBubble.pos = (instance.pos[0] - 105,
                                       instance.pos[1] + 40)
                self.deleteNodeButton.bind(on_press=self.deleteNode)
                self.newConnButton.bind(on_press=self.toggleConnectionMode)
                self.add_widget(self.nodeBubble)
            else:
                try:
                    connection = self.netManager.addConnection(
                        instance, self.pendingNodeRef)
                except DemoerException as e:
                    self.showPopup('Error', e.message)
                else:
                    line = Line(points=[
                        self.pendingNodeRef.pos[0] + 20,
                        self.pendingNodeRef.pos[1] + 20, instance.pos[0] + 20,
                        instance.pos[1] + 20
                    ],
                                width=2)
                    self.canvas.before.add(line)
                    connection.setArg(line)
                    self.toggleConnectionMode(Button())

    # show bubble on right-clicking canvas
    def showDefaultBubble(self, posx, posy):
        self.clearBubbles()
        self.pendingNodePosY = posx - 20
        self.pendingNodePosX = posy - 20
        self.defaultBubble.pos = (posx - 125, posy)
        self.newComputerButton.bind(on_press=self.addComputer)
        self.newRouterButton.bind(on_press=self.addRouter)
        self.add_widget(self.defaultBubble)

    def animatePacket(self, sourceWidget, targetWidget):
        print('Animating')
        img = Image(source='Images/packet.png', pos=sourceWidget.pos)
        anim = Animation(x=targetWidget.pos[0], y=targetWidget.pos[1])
        self.add_widget(img)
        anim.start(img)

    def showPopup(self, title, content):
        popup = Popup(title=title,
                      content=Label(text=content),
                      size_hint=(None, None),
                      size=(500, 200))
        popup.open()

    def appendLog(self, content):
        self.logField.text = self.logField.text + content + '\n\n'

    def on_step(self, instance):
        try:
            self.netManager.stepSimulation()
        except DemoerException as e:
            self.showPopup('Error', e.message)

    def on_new_packet(self, instance):
        if not self.state == ToolState.EMPTY:
            return

        self.state = ToolState.SELECTING_PACKET_NODE1

    def on_node_edit(self, connection, node_button, text_input):
        try:
            self.netManager.setAddress(node_button, connection,
                                       text_input.text)
        except DemoerException as e:
            self.showPopup('Error', e.message)

    def on_touch_down(self, touch, after=False):
        if after:
            self.remove_widget(self.defaultBubble)
            if self.workAreaXPos + self.workAreaXDim > touch.pos[0] > self.workAreaXPos \
                    and self.workAreaYPos + self.workAreaYDim > touch.pos[1] > self.workAreaYPos:
                if touch.button == "right":
                    if self.state != ToolState.EMPTY:
                        self.state = ToolState.EMPTY
                        self.packetNodes.clear()
                    else:
                        if not self.isInConnectionMode:
                            self.showDefaultBubble(touch.x, touch.y)
                        else:
                            self.toggleConnectionMode(Button())
        else:
            Clock.schedule_once(lambda dt: self.on_touch_down(touch, True),
                                0.01)
            return super(Demoer, self).on_touch_down(touch)
Пример #25
0
    def ftp_transfer(Screen):
        """
		    accessing the global performance data
            """
        # todo: what is going wrong here?
        global avoid_double_execution
        if (bool(avoid_double_execution)):
            # get timestamp
            timestamp = datetime.datetime.now()

            # portfolio pandas datastructure
            # todo: extend
            # table format
            # 13 pcs
            # |timestamp | latitude | longitude | beer | wine | shots | cigarettes | tired | stressed | water | sleep | food | hang_level
            try:

                # global table to be stored on server
                new_table = numpy.array([
                    timestamp, Screen.lat, Screen.lon, setc.num_beer,
                    setc.num_wine, setc.num_shot, setc.num_cig, setc.num_tired,
                    setc.num_stress, setc.num_water, setc.num_sleep,
                    setc.num_food, setc.hangover_level
                ],
                                        dtype='string')

            except:
                tb = traceback.format_exc()
                print(tb)
            # filename of global performance data
            filename = "schlukniktable.csv"

            # combine global and local table
            try:
                # append old table to new table
                results = numpy.append(new_table, Screen.global_history)

                # get total number of entries
                Screen.get_total_entries = len(results) / 13
                # prepare graphs
                Screen.prepareGraphs(Screen)
                results = results.reshape((len(results) / 13, 13))
                # store data as a local csv file
                numpy.savetxt(filename,
                              results,
                              delimiter=';',
                              fmt=('%s', '%s', '%s', '%s', '%s', '%s', '%s',
                                   '%s', '%s', '%s', '%s', '%s', '%s'))

            except:
                tb = traceback.format_exc()
                print(tb)
            # up load to ftp
            # File FTP transfer
# domain name or server ip:
            ftp = FTP('singing-wires.de')
            # how to encrypt this?
            ftp.login(user='******', passwd='Holz0815')
            ftp.cwd('/html/schluknik')

            # todo: store as .csv file
            with open(filename, "a+") as f:
                ftp.storlines("STOR " + filename, open(filename, 'r'))
                ftp.quit()

            # finished ftp connection now fill result computer
            lat = numpy.array(results)[:, 1].tolist()
            lon = numpy.array(results)[:, 2].tolist()
            info_box_beer = numpy.array(results)[:, 12].tolist()

            # create result screen widget
            map = MapScreen(name='map')
            try:
                # todo: can this be more pythonic?BeerScreen
                i = 0
                # set marker for every entry in table
                for item in lat:
                    # change this to pop up marker
                    a = Bubble(size=(400, 400))
                    a.add_widget(
                        Label(text='hangover level ' + str(info_box_beer[i])))
                    m = MapMarkerPopup(lon=float(lon[i]),
                                       lat=float(lat[i]),
                                       placeholder=a)
                    map.ids.map.add_marker(m)
                    i = i + 1
                Screen.manager.add_widget(map)
            except:
                tb = traceback.format_exc()
                print(tb)
            # switch to the result screen
            Screen.manager.current = 'result'
            avoid_double_execution = False
            return
Пример #26
0
 def test_add_arbitrary_content(self):
     from kivy.uix.gridlayout import GridLayout
     bubble = Bubble()
     content = GridLayout()
     bubble.add_widget(content)
     self.render(bubble)
Пример #27
0
class Neighbourhood(Widget, HoverBehavior):
    def __init__(self, shp, name, indic, ids, **kwargs):
        #self.app = App.get_running_app()
        Widget.__init__(self, **kwargs)
        #super(Neighbourhood, self).__init__(**kwargs)
        self.shape = shp
        self.getshape()
        self.indic = indic.values
        self.name = name
        self.score = 0
        self.bubb = Bubble()
        self.idso = ids

        with self.canvas:

            random = randint(0, 10)

            color = colors[random]

            cast = '#' + color

            Color(*get_color_from_hex(cast))
            Mesh(fmt=self.vfmt,
                 mode='triangle_fan',
                 indices=self.indices,
                 vertices=self.vertices)

            self.vrt = []
            j = 0
            #print("vertices ", len(self.vertices))
            for i in range(int(len(self.vertices) / 4)):
                x = self.vertices[j]
                y = self.vertices[j + 1]
                self.vrt.append([x, y])
                j = j + 4

            Color(*get_color_from_hex("#FFFFFF"))

            Line(points=self.vrt, width=1)

    def updateIndic(self, indn, w):
        print("dat ", dat.iloc[self.idso, indn])
        print("weight ", w * (dat.iloc[self.idso, indn] / 10))
        dat.iloc[self.idso,
                 indn] = dat.iloc[self.idso,
                                  indn] + w * (dat.iloc[self.idso, indn] / 100)
        print("dat ", dat.iloc[self.idso, indn])

    #update the indicator circle with the neighbourhood values
    def switchInfo(self):
        values = []

        #housing
        idx = [
            0, 5, 13, 12, 15, 16, 17, 18, 19, 20, 21, 22, 32, 33, 34, 35, 36,
            37, 38, 39, 40, 41
        ]
        hous = 0

        for i in range(len(idx)):
            hous = hous + dat.iloc[self.idso, idx[i]] * highWeights[idx[i]]
        values.append(hous)

        #leisure
        idx = [44, 3, 4, 25]
        leis = 0
        for i in range(len(idx)):
            leis = leis + dat.iloc[self.idso, idx[i]] * highWeights[idx[i]]
        values.append(leis)

        #health
        idx = [6, 9, 27, 28]
        health = 0
        for i in range(len(idx)):
            health = health + dat.iloc[self.idso, idx[i]] * highWeights[idx[i]]
        values.append(health)

        #environment
        idx = [23, 24, 26, 29, 30, 31, 42, 43]
        envi = 0
        for i in range(len(idx)):
            envi = envi + dat.iloc[self.idso, idx[i]] * highWeights[idx[i]]
        values.append(envi)

        #services
        idx = [1, 2, 8, 11, 12]
        se = 0
        for i in range(len(idx)):
            se = se + dat.iloc[self.idso, idx[i]] * highWeights[idx[i]]
        values.append(se)

        # assign values to bubbles
        pb = App.get_running_app(
        ).root.ids['third'].ids['form'].ids['c1'].ids['pb']
        pb.set_value(values[0] * 100)
        print("house ", values[0])
        pb.draw()

        pb = App.get_running_app(
        ).root.ids['third'].ids['form'].ids['c2'].ids['pb']
        pb.set_value(values[1] * 100)
        print("leis ", values[1])
        pb.draw()

        pb = App.get_running_app(
        ).root.ids['third'].ids['form'].ids['c3'].ids['pb']
        pb.set_value(values[2] * 100)
        pb.draw()

        pb = App.get_running_app(
        ).root.ids['third'].ids['form'].ids['c4'].ids['pb']
        pb.set_value(values[3] * 100)
        pb.draw()

        pb = App.get_running_app(
        ).root.ids['third'].ids['form'].ids['c5'].ids['pb']
        pb.set_value(values[4] * 100)
        pb.draw()
        #side= aploc.ids['sidemenu']

        print("value ", values)

    #activate when a shape is clicked on

    def on_touch_down(self, touch):
        #  vrt= [[10,390],[10,280],[30,200],[39,190],[60,150],[40,201]]
        #print("touched somwhere")
        aploc = App.get_running_app().root.ids['third'].ids['form']
        informenu = aploc.ids['nd']
        uc = aploc.ids['uc']

        if point_inside_polygon(touch.x, touch.y, self.vrt):
            print("---------")
            print("name ", self.name)
            print("self id ", self.idso)
            print("score ", initScores[self.idso])

            uc.setActive(self, self.idso)

            print("state ", informenu.state)

            informenu.toggle_state()

            self.switchInfo()

    def on_enter(self, *args):

        #print("args ", self.border_point)
        pos = self.border_point
        xy = self.to_widget(*pos)

        #if not hasattr(self, 'self.bubb'):

        self.bubb.background_color = [1, 1, 1, 0.4]
        self.bubb.add_widget(Label(text=self.name))
        self.bubb.add_widget(Label(text=str(self.score)))
        self.bubb.size_hint: (0.01, 0.1)
        #self.add_widget(self.bubb)

    def on_leave(self, *args):
        #self.remove_widget(self.bubb)
        #self.clear_widgets()

        pass

    def scale(self, px, py, polygon):

        j = 0

        #print("before scale ", px[0])

        for i in range(len(px) - 1):

            scaledx = ((px[i] - minx) / (maxx - minx)) * 450

            scaledy = ((py[i] - miny) / (maxy - miny)) * 450
            self.indices[i] = i
            self.vertices[j] = scaledx + 270
            self.vertices[j + 1] = scaledy + 80
            j = j + 4

    def center(self):
        pass

    def getVertices(self, px, py, polygon):

        self.vertices = 4 * (len(px) - 1) * [0]
        self.indices = [0] * len(px)
        j = 0
        #print("len ",len(px))

        #scale coordinate to be between 0-500
        self.scale(px, py, polygon)

    def getshape(self):

        pointsx, pointsy = getpoints(self.shape)

        self.vfmt = [(b'vPosition', 2, 'float'), (b'vCenter', 2, 'float')]

        self.getVertices(pointsx, pointsy, geom)
    def lugaresParaUbicacionActual(
            self):  #Los lugares cercanos a mi ubicacion actual me los muestra.
        for marker in range(len(self.listaMarker)):
            self.ids.mapview.remove_widget(self.listaMarker[marker])
        self.listaMarker = []
        CLIENT_ID = ''  # your Foursquare ID
        CLIENT_SECRET = ''  # your Foursquare Secret
        VERSION = '20190717'
        LIMIT = 50
        neighborhood_latitude = self.latitudActual
        neighborhood_longitude = self.longitudActual
        radius = 500
        url = 'https://api.foursquare.com/v2/venues/explore?&client_id={}&client_secret={}&v={}&ll={},{}&radius={}&limit={}'.format(
            CLIENT_ID, CLIENT_SECRET, VERSION, neighborhood_latitude,
            neighborhood_longitude, radius, LIMIT)
        results = requests.get(url).json()
        lugares = results['response']['groups'][0]['items']
        lugaresCercanos = json_normalize(lugares)

        filtered_columns = [
            'venue.name', 'venue.categories', 'venue.location.lat',
            'venue.location.lng'
        ]
        lugaresCercanos = lugaresCercanos.loc[:, filtered_columns]
        # filter the category for each row
        lugaresCercanos['venue.categories'] = lugaresCercanos.apply(
            lambda categorias: categorias, axis=1)
        # clean columns
        lugaresCercanos.columns = [
            col.split(".")[-1] for col in lugaresCercanos.columns
        ]

        self.ids.mapview.center_on(
            self.latitudActual,
            self.longitudActual)  #mapa centrado en ubicacion actual
        self.ids.mapview.zoom = 17

        mapmarkerpopupUbicacionActual = MapMarkerPopup(lat=self.latitudActual,
                                                       lon=self.longitudActual,
                                                       popup_size=(120, 70))
        bubbleUbicacionActual = Bubble()
        labelUbicacionActual = Label(text="[b]Ubicaion actual![/b]",
                                     markup=True,
                                     halign="center")
        bubbleUbicacionActual.add_widget(labelUbicacionActual)
        mapmarkerpopupUbicacionActual.add_widget(bubbleUbicacionActual)
        self.listaMarker.append(mapmarkerpopupUbicacionActual)
        #El for es para obtener la ubicacion de los lugares cercanos que necesito, y poner los marcadores
        for lat, lng, categoria in zip(lugaresCercanos.lat,
                                       lugaresCercanos.lng,
                                       lugaresCercanos.categories):
            mapmarkerpopup = MapMarkerPopup(lat=lat,
                                            lon=lng,
                                            color=(1, 0, 1, 1),
                                            popup_size=(300, 70))
            bubble = Bubble()
            label = Label(text=categoria, halign="center")
            bubble.add_widget(label)
            mapmarkerpopup.add_widget(bubble)
            self.listaMarker.append(mapmarkerpopup)

        for i in range(len(self.listaMarker)):
            self.ids.mapview.add_widget(self.listaMarker[i])
Пример #29
0
 def start(self, uuid, market):
     bubble = Bubble(arrow_pos="right_mid")
     bubble.add_widget(BubbleButton(text=market))
     self.add_widget(bubble, 4)
Пример #30
0
class Player(BoxLayout, BorderBehavior):
    name = StringProperty("player")
    number = NumericProperty(0)
    icon = StringProperty()
    alive = BooleanProperty(True)
    mafia = BooleanProperty(False)
    agent = BooleanProperty(False)
    is_on_trial = BooleanProperty(False)
    strategic_value = NumericProperty(0)
    # Holds a reference to the action that is to be taken on another player.
    current_action = StringProperty()
    actions = DictProperty()

    def __iter__(self):
        flattened_actions = self.actions.copy()
        for action, decision in self.actions.items():
            flattened_actions[action] = decision.copy()
            for key, value in decision.items():
                if hasattr(value, "number"):
                    flattened_actions[action][key] = value.number

        return iter([('name', self.name),
                     ('agent', self.agent),
                     ('number', self.number),
                     ('is_on_trial', self.is_on_trial),
                     ('icon', self.icon),
                     ('mafia', self.mafia),
                     ('alive', self.alive),
                     ('strategic_value', self.strategic_value),
                     ('current_action', self.current_action),
                     ('actions', flattened_actions)])

    def suspect(self, other):
        pass

    def accuse(self, other):
        pass

    def kill(self, other):
        pass

    def die(self):
        stage = App.get_running_app().root.current_screen
        stage.players[self.number].alive = self.alive = False
        stage.players[self.number].icon = self.icon = "data/icons/player_dead.png"

    def set_strategic_value(self, strategic_value):
        tolerance = 1.5

        if strategic_value > tolerance:
            self.borders = (2, "solid", to_rgba("05F5F5"))
        elif strategic_value < tolerance:
            self.borders = (2, "solid", to_rgba("05F5F5"))
        else:
            self.borders = (2, "solid", to_rgba("05F5F5"))

        self.update_borders()

    def ready_action(self, action) -> None:
        """
        Designate the current player as the one who will be performing actions.
        This is done by setting the player instance as the selected player.
        """
        stage = App.get_running_app().root.current_screen
        self.current_action = action.lower()
        stage.selected_player = self
        Logger.info(f"Player: {self.name} readies {self.current_action}")

        if self.current_action == "die":
            self.die()

        if self.current_action == "guilty" or self.current_action == "innocent":
            stage.players[self.number].actions["vote"]["decision"] = self.current_action

        if self.current_action == "abstain":
            # Fix Issue #17
            stage.players[self.number].actions["accuse"]["player"] = None
            stage.players[self.number].actions["suspect"]["player"] = None
            stage.selected_player = None

    def act_on(self, player) -> None:
        assert self.actions is not None
        assert player is not None
        assert issubclass(type(self), Player)
        assert self.actions != {}

        self.current_action = self.current_action.lower()

        if self == player:
            Logger.warning(f"Player: {self.name} tried to act on themselves.")
            return

        if self.current_action == 'suspect' and self.actions["accuse"]["player"] != player:
            self.actions["suspect"]['player'] = player
        elif self.current_action == 'accuse' and self.actions["suspect"]["player"] != player:
            self.actions["accuse"]['player'] = player

        Logger.info(f"Player: {self.name} {self.current_action} {player.name}")

    def show_bubble(self) -> None:
        self.bubb = Bubble(size_hint=(None, None),
                           size=(160, 30),
                           pos_hint={'center_x': .5, 'y': .6})
        accuse = BubbleButton(text='Accuse')
        suspect = BubbleButton(text='Suspect')
        accuse.bind(on_press=partial(self.hide_bubble, accuse))
        suspect.bind(on_press=partial(self.hide_bubble, suspect))
        self.bubb.add_widget(accuse)
        self.bubb.add_widget(suspect)
        self.ids.empty.add_widget(self.bubb)

    def hide_bubble(self, instance, *args):
        self.ids.empty.remove_widget(self.bubb)
Пример #31
0
class VideoItem(BoxLayout):
    def __init__(self, imageSource, title, videoID):
        super(VideoItem, self).__init__()
        #store video data
        self.id = videoID
        self.title = title
        self.actualSongImage = imageSource
        self.orientation = 'horizontal'
        #place image and title on screen
        imag = AnchorLayout(anchor_x='center')
        ttl = AnchorLayout(anchor_x='right', anchor_y='bottom')
        toPlaylist = AnchorLayout(anchor_x='right',
                                  anchor_y='top',
                                  size_hint=(.1, .1))
        #add button to add song to playlist
        toPlaylist.add_widget(Button(text='+', on_press=self.showBuuble))
        img = AsyncImage(source=imageSource)
        btn = Button(background_color=(0, 0, 0, 0))
        btn.bind(on_press=self.playSong)
        imag.add_widget(btn)
        imag.add_widget(img)
        ttl.add_widget(
            Label(bold=True,
                  font_size='22sp',
                  text=title,
                  text_size=(200, None)))
        #add all widgets
        self.add_widget(imag)
        self.add_widget(ttl)
        self.add_widget(toPlaylist)
        self.bubbleClicked = False

    #method to play a result song
    def playSong(self, instance):
        audioPlayer.playSong("https://www.youtube.com/watch?v=" + self.id)
        MainLayout.actualSongImage = self.actualSongImage
        MainLayout.actualSongLength = audioPlayer.getLength()
        #change flag if it's first song
        if MainLayout.firstSong:
            audioPlayer.pauseSong()
            audioPlayer.playSong("https://www.youtube.com/watch?v=" + self.id)
            MainLayout.firstSong = False

    #method to add song to playlist
    def addToPlaylist(self, playlist, title, image, song, bubble, instance):
        playlistManager.addToPlaylist(playlist, title, image, song)
        self.remove_widget(bubble)

    #method to show bubble with playlists
    def showBuuble(self, instance):
        #if bubble is already clicked
        if self.bubbleClicked:
            self.remove_widget(self.bubb)
            self.bubbleClicked = False
        #if bubble is not clicked
        else:
            self.bubb = Bubble(orientation='horizontal',
                               arrow_pos='bottom_mid')

            l = playlistManager.getPlaylists()
            for playlist in l:
                self.bubb.add_widget(
                    Button(text=playlist,
                           on_press=partial(self.addToPlaylist, playlist,
                                            self.title, self.actualSongImage,
                                            self.id, self.bubb),
                           size_hint=(.2, .2),
                           size=(200, 200)))
            self.add_widget(self.bubb)
            self.bubbleClicked = True
Пример #32
0
 def show_text(self, text):
     bubble = Bubble(arrow_pos='top_mid', size_hint=(None, None), size=(200, 100), pos_hint={'x': 0.1, 'y': 0.15})
     bubble.background_color = (1, 0, 0, 0.5)
     bubble.add_widget(Label(text=text))
     self.add_widget(bubble)
     Clock.schedule_once(lambda dt: self.remove_widget(bubble), 1.5)
Пример #33
0
class SliderButton(ActionButton):
    percentage = NumericProperty(50)
    label = StringProperty("")
    type = OptionProperty("volume", options=["volume", "pitch", "speed"])
    icons = {
        "volume": {
            "high": "atlas://data/images/defaulttheme/audio-volume-high",
            "medium": "atlas://data/images/defaulttheme/audio-volume-medium",
            "low": "atlas://data/images/defaulttheme/audio-volume-low",
            "none": "atlas://data/images/defaulttheme/audio-volume-muted"
        },
        "speed": {
            "high": "atlas://data/images/defaulttheme/speed_fast",
            "medium": "atlas://data/images/defaulttheme/speed_normal",
            "low": "atlas://data/images/defaulttheme/speed_slow",
            "none": "atlas://data/images/defaulttheme/speed_slow"
        },
        "pitch": {
            "high": "atlas://data/images/defaulttheme/pitch_high",
            "medium": "atlas://data/images/defaulttheme/pitch_medium",
            "low": "atlas://data/images/defaulttheme/pitch_low",
            "none": "atlas://data/images/defaulttheme/pitch_low"
        },
        "close": "atlas://data/images/defaulttheme/cancel"
    }

    def __init__(self, **kwargs):
        super(SliderButton, self).__init__(**kwargs)

        App.get_running_app().bind(on_start=self.update_icons)
        self.bind(on_release=self._open)
        self.update_icons()

    def _open(self, *args, **kwargs):
        try:
            self.remove_widget(self.bubble)
            self.percentage = self.slider.value
            del self.bubble, self.slider
            self.update_icons()
        except AttributeError:
            self.bubble = Bubble(orientation="vertical", size=(48, 200))
            self.update_bubble_pos()
            self.bind(pos=self.update_bubble_pos)

            def on_perc(slider, value):
                slider.btn.percentage = value

            label = Label(text=self.label, size_hint_y=None, height=25)
            self.bubble.add_widget(label)
            self.slider = Slider(orientation="vertical",
                                 min=0,
                                 max=100,
                                 value=self.percentage)
            self.slider.btn = self
            self.slider.bind(value=on_perc)
            self.bubble.add_widget(self.slider)

            def on_reset(bbtn, *args, **kwargs):
                bbtn.slider.value = bbtn.reset_value

            bbtn = BubbleButton(text=self.reset_text,
                                size_hint_y=None,
                                height=40)
            bbtn.slider = self.slider
            bbtn.reset_value = self.reset_value
            bbtn.bind(on_release=on_reset)
            self.bubble.add_widget(bbtn)
            self.add_widget(self.bubble)
            self.icon = self.icons["close"]

    def update_icons(self, *args, **kwargs):
        if self.type == "volume":
            self.reset_value = 0
            self.reset_text = "Mute"
        else:
            self.reset_value = 50
            self.reset_text = "Reset"

        if self.percentage == 0:
            self.icon = self.icons[self.type]["none"]
        elif self.percentage > 0 and self.percentage < 33:
            self.icon = self.icons[self.type]["low"]
        elif self.percentage >= 33 and self.percentage <= 66:
            self.icon = self.icons[self.type]["medium"]
        elif self.percentage > 66 and self.percentage <= 100:
            self.icon = self.icons[self.type]["high"]

    def update_bubble_pos(self, *args):
        self.bubble.pos = (self.pos[0], self.pos[1] + 48)
Пример #34
0
class SliderButton(ActionButton):
    percentage = NumericProperty(50)
    label = StringProperty("")
    type = OptionProperty("volume", options=["volume", "pitch", "speed"])
    icons = {"volume":
                {"high":     "atlas://data/images/defaulttheme/audio-volume-high",
                 "medium":   "atlas://data/images/defaulttheme/audio-volume-medium",
                 "low":      "atlas://data/images/defaulttheme/audio-volume-low",
                 "none":     "atlas://data/images/defaulttheme/audio-volume-muted"},
             "speed":
                {"high":     "atlas://data/images/defaulttheme/speed_fast",
                 "medium":   "atlas://data/images/defaulttheme/speed_normal",
                 "low":      "atlas://data/images/defaulttheme/speed_slow",
                 "none":     "atlas://data/images/defaulttheme/speed_slow"},
             "pitch":
                {"high":     "atlas://data/images/defaulttheme/pitch_high",
                 "medium":   "atlas://data/images/defaulttheme/pitch_medium",
                 "low":      "atlas://data/images/defaulttheme/pitch_low",
                 "none":     "atlas://data/images/defaulttheme/pitch_low"},
             "close":        "atlas://data/images/defaulttheme/cancel"}


    def __init__(self, **kwargs):
        super(SliderButton, self).__init__(**kwargs)

        App.get_running_app().bind(on_start=self.update_icons)
        self.bind(on_release=self._open)
        self.update_icons()

    def _open(self, *args, **kwargs):
        try:
            self.remove_widget(self.bubble)
            self.percentage = self.slider.value
            del self.bubble, self.slider
            self.update_icons()
        except AttributeError:
            self.bubble = Bubble(orientation="vertical", size=(48, 200))
            self.update_bubble_pos()
            self.bind(pos=self.update_bubble_pos)
            def on_perc(slider, value):
                slider.btn.percentage = value
            label = Label(text=self.label, size_hint_y=None, height=25)
            self.bubble.add_widget(label)
            self.slider = Slider(orientation="vertical", min=0, max=100, value=self.percentage)
            self.slider.btn = self
            self.slider.bind(value=on_perc)
            self.bubble.add_widget(self.slider)
            def on_reset(bbtn, *args, **kwargs):
                bbtn.slider.value = bbtn.reset_value
            bbtn = BubbleButton(text=self.reset_text, size_hint_y=None, height=40)
            bbtn.slider = self.slider
            bbtn.reset_value = self.reset_value
            bbtn.bind(on_release=on_reset)
            self.bubble.add_widget(bbtn)
            self.add_widget(self.bubble)
            self.icon = self.icons["close"]

    def update_icons(self, *args, **kwargs):
        if self.type == "volume":
            self.reset_value = 0
            self.reset_text = "Mute"
        else:
            self.reset_value = 50
            self.reset_text = "Reset"

        if self.percentage == 0:
                self.icon = self.icons[self.type]["none"]
        elif self.percentage > 0 and self.percentage < 33:
                self.icon = self.icons[self.type]["low"]
        elif self.percentage >= 33 and self.percentage <= 66:
                self.icon = self.icons[self.type]["medium"]
        elif self.percentage > 66 and self.percentage <= 100:
                self.icon = self.icons[self.type]["high"]

    def update_bubble_pos(self, *args):
        self.bubble.pos = (self.pos[0], self.pos[1] + 48)
Пример #35
0
    def update_aircraft(self, request, result):
        if self.update_in_progress:
            return
        self.update_in_progress = True
        list_of_aircraft = result["aircraft"]

        # Update tracked aircraft and mark stale ones as inactive
        for a_tracked_aircraft in self.list_of_tracked_aircraft:
            aircraft_active = False
            for an_aircraft in list_of_aircraft:
                if an_aircraft["hex"] == a_tracked_aircraft.hex:
                    a_tracked_aircraft.data = an_aircraft
                    aircraft_active = True
                    break
            a_tracked_aircraft.active = aircraft_active

        # Add newly detected aircraft
        for an_aircraft in list_of_aircraft:
            aircraft_tracked = False
            for a_tracked_aircraft in self.list_of_tracked_aircraft:
                if a_tracked_aircraft.hex == an_aircraft["hex"]:
                    aircraft_tracked = True
                    break
            if not aircraft_tracked:
                a_tracked_aircraft = Aircraft()
                a_tracked_aircraft.hex = an_aircraft["hex"]
                a_tracked_aircraft.active = True
                a_tracked_aircraft.data = an_aircraft
                self.list_of_tracked_aircraft.append(a_tracked_aircraft)

        # Set up markers
        for a_tracked_aircraft in self.list_of_tracked_aircraft:
            active = a_tracked_aircraft.active
            data = a_tracked_aircraft.data
            position_known = "lat" in data and "lon" in data and "track" in data
            has_marker = hasattr(a_tracked_aircraft, "marker")

            if active and position_known:
                if has_marker:
                    marker = a_tracked_aircraft.marker
                else:
                    marker = AircraftMarker()
                    marker.anchor_x = 0.5
                    marker.anchor_y = 0.5
                    a_tracked_aircraft.marker = marker
                    marker.popup_size = (80, 25)
                    a_tracked_aircraft.labelmode = 1
                    label = Label()
                    bubble = Bubble()
                    label.color = (1, 1, 0, 1)
                    label.outline_color = (0, 0, 0, 1)
                    bubble.add_widget(label)
                    marker.add_widget(bubble)
                    a_tracked_aircraft.label = label
                if hasattr(a_tracked_aircraft, "label"):
                    label = a_tracked_aircraft.label
                    if "flight" in data:
                        label.text = data["flight"]
                    else:
                        label.text = "unknown"
                    if marker.full_label:
                        marker.popup_size = (80, 100)
                        if "altitude" in data:
                            label.text = label.text + \
                                "\nALT: {}".format(data["altitude"])
                        if "vert_rate" in data:
                            label.text = label.text + \
                                "\nRoC: {}".format(data["vert_rate"])
                        if "track" in data:
                            label.text = label.text + \
                                "\nTRK: {}".format(data["track"])
                        if "speed" in data:
                            label.text = label.text + \
                                "\nSPD: {}".format(data["speed"])
                    else:
                        marker.popup_size = (80, 25)

                marker.source = "icons/plane{}.png".format(
                    round(a_tracked_aircraft.data["track"]/10)*10)
                marker.lat = a_tracked_aircraft.data["lat"]
                marker.lon = a_tracked_aircraft.data["lon"]
                if not has_marker:
                    self.add_marker(
                        a_tracked_aircraft.marker, layer=self.aircraft_layer)
            else:
                if has_marker:
                    self.remove_marker(a_tracked_aircraft.marker)
                    delattr(a_tracked_aircraft, "marker")
                if not active:
                    self.list_of_tracked_aircraft.remove(a_tracked_aircraft)
        self.aircraft_layer.reposition()
        self.update_in_progress = False