Ejemplo n.º 1
0
    def _makeWdg(self, wdgInfo):
        """Returns a widget depending on wdgInfo:
        - None or False: returns None or False
        - a string: returns an RO.Wdg.StrVariable with text=wdgInfo
        - a Tkinter Variable: returns an RO.Wdg.StrVariable with textvariable=wdgInfo
        - a Tkinter Widget: returns wdgInfo unaltered
        """
        if wdgInfo in (None, False):
            return wdgInfo
        elif isinstance(wdgInfo, Tkinter.Widget):
            # a widget; assume it's a Label widget of some kind
            return wdgInfo

        if isinstance(wdgInfo, Tkinter.Variable):
            # a Tkinter variable
            wdg = Label.StrLabel(
                master=self.master,
                textvariable=wdgInfo,
                helpText=self.helpText,
                helpURL=self.helpURL,
            )
        else:
            wdg = Label.StrLabel(
                master=self.master,
                text=wdgInfo,
                helpText=self.helpText,
                helpURL=self.helpURL,
            )
        return wdg
Ejemplo n.º 2
0
    def testEqual(self):
        field1 = Label.Field()
        field2 = Label.Field()
        self.assertEqual(field1,field2,'Label Field Comparison not working')

        field1.setData('0365')
        field2.setData('0365')
        self.assertEqual(field1,field2,'Label Field Comparison not working')
Ejemplo n.º 3
0
 def get(self):
     user = users.get_current_user()
     if (self.request.get('Type') == 'All'):
         str = Label.get_label_object_list_for_user_JSON(user)
         self.response.out.write(str)
     elif (self.request.get('Type') == 'Unique'):
         str = Label.get_labels_dict_JSON(user) 
         self.response.out.write(str)
Ejemplo n.º 4
0
 def LabelPeaks(self, PeakTolerance = 0.5):
     """
     Should be called once, *if* the annotations differ, so that we can match
     corresponding peaks which have different masses due to PTM attachment.
     """
     # Label the spectra so that I can know which peaks belong to what name eg. b7
     Label.LabelSpectrum(self.SpectrumA, self.PeptideA, PeakTolerance)
     Label.LabelSpectrum(self.SpectrumB, self.PeptideB, PeakTolerance)
Ejemplo n.º 5
0
    def testDifferent(self):
        field1 = Label.Field()
        field1.setData('0365')
        field2 = Label.Field()
        field2.setData('0364')
        self.assertNotEqual(field1,field2,'Label Field Comparison not working')

        field3 = Label.Field()
        self.assertNotEqual(field1,field3,'Label Field Comparison not working')
Ejemplo n.º 6
0
    def initCommandSettingsMenu(self):
        # Labels first
        Label.hideLabels(self.labels)
        self.labels = self.labelDict['commandSettingsMenu']
        Label.showLabels(self.labels)

        # Buttons
        Button.hideButtons(self.buttons)
        self.buttons = self.buttonDict['commandSettingsMenu']
        Button.showButtons(self.buttons)
Ejemplo n.º 7
0
    def initAboutMenu(self):
        # Labels first
        Label.hideLabels(self.labels)
        self.labels = self.labelDict['aboutMenu']
        Label.showLabels(self.labels)

        # Buttons second
        Button.hideButtons(self.buttons)
        self.buttons = self.buttonDict['aboutMenu']
        Button.showButtons(self.buttons)
Ejemplo n.º 8
0
    def __init__(self, master):
        self.master = master
        master.title("A simple GUI")

        self.label = Label(master, text="This is our first GUI!")
        self.label.pack()

        self.greet_button = Button(master, text="Greet", command=self.greet)
        self.greet_button.pack()

        self.close_button = Button(master, text="Close", command=master.quit)
        self.close_button.pack()
Ejemplo n.º 9
0
def transform_image_to_RGB(path_data,
                           from_picture=0,
                           to_picture=2,
                           mode="test",
                           end_name='leftImg8bit.png'):
    """
    :param path_data: path to the folder that contain all the data
    :param from_picture: first picture that will be transform
    :param to_picture: last picture that will be transform
    :param mode: train val or test
    :param end_name: end of the name of image that you want to keep
    :return: Nothing but save to_picture-from_picture images into RGB format that will be in the path_data/mode
    location and have the exact end_name
    """
    # Make the DataSet and the names
    paths, names = make_dataset(mode=mode,
                                path_data=path_data,
                                end_name=end_name)

    # sort the path and name so that it is always organized in the same way
    paths.sort()
    names.sort()

    # Reduce the number of image
    paths = paths  #[from_picture:to_picture]
    names = names  #[from_picture:to_picture]

    # Create the dictionary that will transform 1D to RBG image
    labels = Label.create_label_plot()
    train_id2label = Label.train_id2label(labels)

    # Loop over each picture
    for i in range(len(paths)):
        # Create the Picture type
        picture = Picture(path_image=paths[i])

        # Transform into RGB
        RGB = picture.classes_to_color(id_to_label=train_id2label)

        # Change the name
        path_export_color = paths[i].replace(end_name, 'prediction_color.png')

        # transform into PIL image
        RGB = np.uint8(RGB)
        RGB = Image.fromarray(RGB)

        # Save the file
        RGB.save(path_export_color)
        with open(
                "/home_expes/kt82128h/GridNet/Python_Files/Python_print_test.txt",
                'a') as txtfile:
            txtfile.write("image saved " + path_export_color + "\n")
Ejemplo n.º 10
0
    def initLabels(self):

        self.labelDict['startMenu'] = [
            Label.showText(self, 1 / 2, 1 / 4, 3 / 4, 1 / 8, 10,
                           __class__.largeStyle,
                           'Sustainable Earth Arduino Garden')
        ]
        self.labelDict['commandsMenu'] = [
            Label.showText(self, 1 / 2, 1 / 8, 1 / 2, 1 / 12, 10,
                           __class__.largeStyle, 'Garden Command Center'),
            Label.showText(self, 1 / 3, 1 / 2, 1 / 2, 14 / 25, 10,
                           __class__.smallStyle, self.logText)
        ]
        self.labelDict['settingsMenu'] = [
            Label.showText(self, 1 / 2, 1 / 8, 1 / 2, 1 / 12, 10,
                           __class__.largeStyle, 'General Settings')
        ]
        self.labelDict['aboutMenu'] = [
            Label.showText(self, 1 / 2, 1 / 8, 1 / 2, 1 / 12, 10,
                           __class__.largeStyle, 'About'),
            Label.showText(self, 1 / 2, 1 / 2, 3 / 5, 1 / 3, 10,
                           __class__.smallStyle, self.aboutText)
        ]
        self.labelDict['commandSettingsMenu'] = [
            Label.showText(self, 1 / 2, 1 / 8, 1 / 2, 1 / 12, 10,
                           __class__.largeStyle, 'Garden Water Settings'),
            Label.showText(
                self, 1 / 3, 16 / 36, 1 / 3, 1 / 20, 10, __class__.smallStyle,
                'Watering Interval: %d minutes' %
                arduinoControl.waterInterval),
        ]
Ejemplo n.º 11
0
    def find_top_labels(self, g, k=6):
        labels = self.__ontology.get_labels()
        label_score = []
        for i in range(len(labels)):
            # put a condition that verifies if the labels is
            #print labels[i] + ' -- ' + g.get_name()
            score = self.__predictor.run(labels[i], g)

            label_score.append((score, labels[i]))

        #print 'feature: ' + repr(g.get_features())
        #print 'labels: ' + repr(labels)
        #print 'scores: ' + repr(label_score)
        label_score.sort(reverse=True)
        #print 'scores: ' + repr(label_score)

        feature_bond_structure = self.__ontology.get_bond_structure(
            g.get_name())
        #print g.get_name() + ' ' + repr(feature_bond_structure)

        for i in range(k):
            name = label_score[i][1]
            print 'label: ' + name
            # when features connect to labels
            label_modalities = self.__ontology.get_modalities(name)
            #print 'modalities: '+repr(label_modalities)
            for bond in feature_bond_structure:
                if bond[0] in label_modalities:
                    score = label_score[i][0]
                    level = self.__ontology.get_level(name)
                    modality = self.__ontology.get_modalities(name)
                    g.add_top_label(
                        Label(name, modality, level, score, -1, 0.0))
                    break
Ejemplo n.º 12
0
 def get(self):
     t = get_template('search.html')
     c = Context()
     user = users.get_current_user()
     if self.request.get('action_type') == "ShowLabel":
         label_name = self.request.get('Id') 
         htmlParser = Label.get_articles_list_with_label_as_HTMLParser(user, label_name)
         
     elif self.request.get('action_type') == "ShowPending":
         label_name = self.request.get('pending_id')
         htmlParser = PendingSharedLabel.pending_share_preview_as_HTMLparser(user, label_name)
         if (isinstance( htmlParser, int)):
             self.response.out.write("an error occurred")
             return     
     
     results = htmlParser.results    
     my_html_parser_encoder = JSONConvertors.HTMLparserEncoder()
     resultsJSON = my_html_parser_encoder.encode(htmlParser)      
     c['users'] = users
     c['hidden_label_name'] = label_name
     c['results'] = results
     c['resultsJSON'] = resultsJSON
     c['formAction'] = '/AddFollow'
     c['showlabel'] = True
     c['showlabelsearch'] = True
     self.response.out.write(t.render(c))
Ejemplo n.º 13
0
 def post(self):
     user = users.get_current_user()
     label_name = self.request.get('label_name')
     article_key = self.request.get('article_key')
     comment_content =self.request.get('comment_content')
     res = Label.update_comment(user, label_name, article_key, comment_content)
     self.response.out.write(simplejson.dumps(res))
Ejemplo n.º 14
0
    def _makeWdg(self, wdgInfo, **kargs):
        """Return a widget depending on wdgInfo:
        - None or False: returns None or False
        - a string: returns a Label with text=wdgInfo
        - a Tkinter Variable: returns a Label with textvariable=wdgInfo
        - a Tkinter Widget: returns wdgInfo unaltered
        
        kargs is ignored if wdgInfo is a widget
        """
        if wdgInfo is None:
            return wdgInfo
        elif isinstance(wdgInfo, Tkinter.Widget):
            # a widget; assume it's a Label widget of some kind
            return wdgInfo
        
        # at this point we know we are going to create our own widget
        # set up the keyword arguments
        kargs.setdefault("helpText", self.helpText)
        kargs.setdefault("helpURL", self.helpURL)
        if isinstance(wdgInfo, Tkinter.Variable):
            kargs["textvariable"] = wdgInfo
        else:
            kargs["text"] = wdgInfo

        return Label.StrLabel(self, **kargs)
Ejemplo n.º 15
0
 def testLabelFormat(self):
     """
     Confirm that an integer or floating point value is not accepted a labeValue
     """
     label = Label.Field()
     self.assertRaises(Exception.A429Exception,label.setData,5)
     self.assertRaises(Exception.A429Exception,label.setData,8.5)
Ejemplo n.º 16
0
    def handleScannedPartId(self, partId):
        result = self.partDB.db.query(filter=lambda k, v: (k == partId))

        if len(result) == 0:
            raise Exception('Part ID %s not found in database.' % (partId))

        if self.partDB.args.fix:
            result = self.partDB.db.query(filter=lambda k, v: (k == partId))
            data = result[partId]

            distributorMatches = {}
            for distributorName in data['distributor']:
                minimumData = {
                    'distributor': {
                        distributorName: {
                            'distributorPartNumber':
                            data['distributor'][distributorName]
                            ['distributorPartNumber']
                        }
                    }
                }

                newData = self.partDB.distributors[distributorName].getData(
                    minimumData)

                Database.mergeData(data, newData, override=True)

            self.partDB.db.update(data)

            if len(result) > 0:
                if (self.partDB.args.printLabel):
                    label = Label.Label()
                    label.createLabelFromData(data=data)
                    label.cupsPrint(printerName=self.partDB.args.printerName)
            else:
                raise Exception('ID %s not found in database.' %
                                (self.partDB.args.id))

            return

        data = result[partId]

        self.partDB.displayItem(data)

        print(
            'Quantity is %u. Scan/Enter new quantity (+/- for relative) or press return:'
            % data['quantity'])
        quantityInput = self.scanAndInput()
        if quantityInput != b'':
            quantityInputAscii = quantityInput.decode('ascii')
            # check if first character is + or -
            if (quantityInputAscii[0]) == '+' or (quantityInputAscii[0]
                                                  == '-'):
                data['quantity'] += int(quantityInputAscii)
            else:
                data['quantity'] = int(quantityInputAscii)

            print('New quantity is %u.' % (data['quantity']))
            self.partDB.db.update(data)
Ejemplo n.º 17
0
 def testPackNoData(self):
     '''
     Call pack when the label was not set
     '''
     labelField = Label.Field()
     labelField.setData(str(41))
     labelField.clear()
     self.assertRaises(Exception.A429NoData,labelField.pack)
Ejemplo n.º 18
0
 def get(self):
     user = users.get_current_user()
     label_name = self.request.get('label_name')
     res = Label.delete_label(user,label_name)
     if (not res):
         self.response.out.write(simplejson.dumps(""))
     else:    
         self.response.out.write(simplejson.dumps(label_name))
Ejemplo n.º 19
0
 def testLabelPacking(self):
     """
     pack different labels and confirm they are coded properly
     """
     for label,packed in self.refValues:
         labelField = Label.Field()
         labelField.setData(str(label))
         self.assertEqual(labelField.pack(),packed, "Label Not Packed Properly")
Ejemplo n.º 20
0
 def testLabelUnpacking(self):
     """
     unpack different labels and confirm they are decoded properly
     """
     for label,packed in self.refValues:
         labelField = Label.Field()
         labelField.unpack(packed)
         self.assertEqual(labelField.getData(),int(str(label),8), "Label Not Unpacked Properly")
Ejemplo n.º 21
0
 def _useAttributes(self, attributes):
     if "assignee" in attributes:  # pragma no branch
         assert attributes["assignee"] is None or isinstance(attributes["assignee"], dict), attributes["assignee"]
         self._assignee = None if attributes["assignee"] is None else NamedUser.NamedUser(self._requester, attributes["assignee"], completed=False)
     if "body" in attributes:  # pragma no branch
         assert attributes["body"] is None or isinstance(attributes["body"], (str, unicode)), attributes["body"]
         self._body = attributes["body"]
     if "closed_at" in attributes:  # pragma no branch
         assert attributes["closed_at"] is None or isinstance(attributes["closed_at"], (str, unicode)), attributes["closed_at"]
         self._closed_at = self._parseDatetime(attributes["closed_at"])
     if "closed_by" in attributes:  # pragma no branch
         assert attributes["closed_by"] is None or isinstance(attributes["closed_by"], dict), attributes["closed_by"]
         self._closed_by = None if attributes["closed_by"] is None else NamedUser.NamedUser(self._requester, attributes["closed_by"], completed=False)
     if "comments" in attributes:  # pragma no branch
         assert attributes["comments"] is None or isinstance(attributes["comments"], (int, long)), attributes["comments"]
         self._comments = attributes["comments"]
     if "created_at" in attributes:  # pragma no branch
         assert attributes["created_at"] is None or isinstance(attributes["created_at"], (str, unicode)), attributes["created_at"]
         self._created_at = self._parseDatetime(attributes["created_at"])
     if "html_url" in attributes:  # pragma no branch
         assert attributes["html_url"] is None or isinstance(attributes["html_url"], (str, unicode)), attributes["html_url"]
         self._html_url = attributes["html_url"]
     if "id" in attributes:  # pragma no branch
         assert attributes["id"] is None or isinstance(attributes["id"], (int, long)), attributes["id"]
         self._id = attributes["id"]
     if "labels" in attributes:  # pragma no branch
         assert attributes["labels"] is None or all(isinstance(element, dict) for element in attributes["labels"]), attributes["labels"]
         self._labels = None if attributes["labels"] is None else [
             Label.Label(self._requester, element, completed=False)
             for element in attributes["labels"]
         ]
     if "milestone" in attributes:  # pragma no branch
         assert attributes["milestone"] is None or isinstance(attributes["milestone"], dict), attributes["milestone"]
         self._milestone = None if attributes["milestone"] is None else Milestone.Milestone(self._requester, attributes["milestone"], completed=False)
     if "number" in attributes:  # pragma no branch
         assert attributes["number"] is None or isinstance(attributes["number"], (int, long)), attributes["number"]
         self._number = attributes["number"]
     if "pull_request" in attributes:  # pragma no branch
         assert attributes["pull_request"] is None or isinstance(attributes["pull_request"], dict), attributes["pull_request"]
         self._pull_request = None if attributes["pull_request"] is None else IssuePullRequest.IssuePullRequest(self._requester, attributes["pull_request"], completed=False)
     if "repository" in attributes:  # pragma no branch
         assert attributes["repository"] is None or isinstance(attributes["repository"], dict), attributes["repository"]
         self._repository = None if attributes["repository"] is None else Repository.Repository(self._requester, attributes["repository"], completed=False)
     if "state" in attributes:  # pragma no branch
         assert attributes["state"] is None or isinstance(attributes["state"], (str, unicode)), attributes["state"]
         self._state = attributes["state"]
     if "title" in attributes:  # pragma no branch
         assert attributes["title"] is None or isinstance(attributes["title"], (str, unicode)), attributes["title"]
         self._title = attributes["title"]
     if "updated_at" in attributes:  # pragma no branch
         assert attributes["updated_at"] is None or isinstance(attributes["updated_at"], (str, unicode)), attributes["updated_at"]
         self._updated_at = self._parseDatetime(attributes["updated_at"])
     if "url" in attributes:  # pragma no branch
         assert attributes["url"] is None or isinstance(attributes["url"], (str, unicode)), attributes["url"]
         self._url = attributes["url"]
     if "user" in attributes:  # pragma no branch
         assert attributes["user"] is None or isinstance(attributes["user"], dict), attributes["user"]
         self._user = None if attributes["user"] is None else NamedUser.NamedUser(self._requester, attributes["user"], completed=False)
Ejemplo n.º 22
0
 def post(self):
     user = users.get_current_user()
     label_name = self.request.get('label_name')
     new_name = self.request.get('new_name')
     res = Label.rename_label(user, label_name, new_name)
     if (res != True):
         self.response.out.write(simplejson.dumps(""))
     else:    
         self.response.out.write(simplejson.dumps(label_name + "_|_" + new_name))
Ejemplo n.º 23
0
 def create_label(self, name, color):
     assert isinstance(name, (str, unicode)), name
     assert isinstance(color, (str, unicode)), color
     post_parameters = {
         "name": name,
         "color": color,
     }
     headers, data = self._requester.requestAndCheck(
         "POST", self.url + "/labels", None, post_parameters)
     return Label.Label(self._requester, data, completed=True)
Ejemplo n.º 24
0
    def set_text(self, text):
        if type(text) in StringTypes:
            self.text = text
        else:
            raise TypeError, type(text)

        if not self.label:
            self.label = Label(h_align=Align.CENTER,
                               v_align=Align.CENTER,
                               text_prop={
                                   'align_h': 'center',
                                   'align_v': 'center',
                                   'mode': 'hard',
                                   'hfill': False
                               })
            self.label.set_text(text)
            self.add_child(self.label)
        else:
            self.label.set_text(text)
Ejemplo n.º 25
0
 def run(self):
     result = self.partDB.db.query(
         filter=lambda k, v: (k == self.partDB.args.id))
     if len(result) > 0:
         label = Label.Label()
         label.createLabelFromData(data=result[self.partDB.args.id])
         label.cupsPrint(printerName=self.partDB.args.printerName)
     else:
         raise Exception('ID %s not found in database.' %
                         (self.partDB.args.id))
Ejemplo n.º 26
0
 def getSurface(self):
     self.labelAmount = Label.Label(
         "Amount: " + str(self.amount))  #Update the amount label
     #Recreate surface after amount change
     self.surface = pygame.image.load(self.icon).convert()
     self.surface.blit(self.labelName.getSurface(), (0, 0))
     self.surface.blit(self.labelPrice.getSurface(),
                       (0, 0 + self.height / 3))
     self.surface.blit(self.labelAmount.getSurface(),
                       (0, 0 + self.height * 2 / 3))
     return self.surface
Ejemplo n.º 27
0
    def body(self, master):
        Label.StrLabel(master=master,
                       text="Delete Preseturation:").grid(row=0,
                                                          column=0,
                                                          columnspan=5)
        self.currNameWdg = OptionMenu.OptionMenu(
            master=master,
            items=self._currNameList,
        )

        self.currNameWdg.grid(row=1, column=1)
Ejemplo n.º 28
0
 def __init__(self,name,parity='odd'):
     '''
     Create an A429 Message by simply adding a label and a parity bit
     Note that the parity is odd by default but can be modified as necessary
     '''
     self.name = name
     self._fields = list()
     self.fieldAdditionRules = (self.__field_overlaps,self.__field_name_already_exist)
      
     self.addField(Label.Field())
     self.addField(Parity.Field(parity))
Ejemplo n.º 29
0
 def __init__(self, name, id, price, amount, location, width, height, icon,
              command, commandRight):
     self.name = name
     self.id = id
     self.price = price
     self.amount = amount
     self.location = location
     self.width = width
     self.height = height
     self.icon = icon
     self.surface = pygame.image.load(icon).convert()
     self.button = Button.Button(width, height, location, command,
                                 commandRight, self)
     self.totalPrice = price * amount
     self.labelName = Label.Label("Name: " + str(name))
     self.labelPrice = Label.Label("Price: " + str(price))
     self.labelAmount = Label.Label("Amount: " + str(amount))
     self.surface.blit(self.labelName.getSurface(), (0, 0))
     self.surface.blit(self.labelPrice.getSurface(), (0, 0 + height / 3))
     self.surface.blit(self.labelAmount.getSurface(),
                       (0, 0 + height * 2 / 3))
    def on_loop(self):
        if self._screen == "Main":
            self.title = Label.Label("Main Screen").getSurface()
            self.buttons = []
            for itemCat in self._itemCategories:
                self.buttons.append(itemCat.getButton())
            self.buttons.append(self.checkoutButton)

        elif self._screen.find("itemCatScreen:") != -1:
            self.title = Label.Label(
                "Item Category Screen of: " + self._itemCategories[int(
                    self._screen.replace("itemCatScreen:", ""))].name
            ).getSurface()
            itemCatNumber = int(self._screen.replace("itemCatScreen:", ""))
            self.buttons = []
            for item in self._itemCategories[itemCatNumber].items:
                self.buttons.append(item.getButton())
            self.buttons.append(self.backButton)

        elif self._screen == "checkOut":
            self.title = Label.Label("Check Out Screen").getSurface()
            self.buttons = []

            self.buttons.append(self.finishButton)
            self.buttons.append(self.addMoney10Button)
            self.buttons.append(self.addMoney10MButton)
            self.buttons.append(self.backButton)
            itemsShopped = []
            for itemCat in self._itemCategories:
                for item in itemCat.items:
                    if item.amount > 0:
                        itemsShopped.append(item)

            self.surfacesOfItemsShopped = []
            for item in itemsShopped:
                self.surfacesOfItemsShopped.append(
                    Label.Label("Name: " + item.name + "Price: " +
                                str(item.price) + " Amount: " +
                                str(item.amount) + " TotPrice: " +
                                str(item.getTotalPrice())))
Ejemplo n.º 31
0
	def __init__(self, director, size, color):
		gtk.Layout.__init__(self)
		self._canRecord = True
		try:
			s = subprocess.Popen(['ffmpeg'], \
			stderr=subprocess.STDOUT, stdout=subprocess.PIPE).communicate()[0]
		except OSError:
			self._canRecord = False
		self._director = director
		self._color = color
		self._size = size
		#self.set_double_buffered(True)	# this is possibly set by default. need to come up with another double buffering solution
		self._screenshotPath = ""
		self._screenshotName = ""
		self._isRecording = False

		self._renderNode = Node(MakeRect(0,0,self._size.width, self._size.height))
		self._renderNode.setBackgroundColor(Color(1.0, 1.0, 1.0, 0.90))
		label = Label("Rendering video...", color=BlackColor())
		label.setFontSize(36)
		label.setPosition(Point(0, self._size.height/2))
		self._renderNode.addChild(label)

		self._framerate = None
		self._exposeCounter = 0
		self.set_flags(gtk.CAN_FOCUS)
		self.grab_focus()
		self.set_events(GTK_EVENT_MASKS)
		self.set_size_request(size.width, size.height)
		self.connect("expose-event", self._onExpose)
		gestureDispatch = self._director.getGestureDispatch()
		self.connect("motion-notify-event", gestureDispatch._onMouseMotion)
		self.connect("button-press-event", gestureDispatch._onMousePress)
		self.connect("button-release-event", gestureDispatch._onMouseRelease)
		self.connect("scroll-event", gestureDispatch._onMouseScroll)
		self.connect("key-press-event", gestureDispatch._onKeyPress)
		self.connect("key-release-event", gestureDispatch._onKeyRelease)
def pending_share_preview_as_HTMLparser(invited_user, pending_id):
    pending_obj = get_single_pending(invited_user, pending_id)
    if not isinstance(pending_obj, PendingSharedLabel):
        return pending_obj
    
    article_objects_list = Label.get_articles_list_with_label(pending_obj.inviting_user, pending_obj.label_name)
    if (article_objects_list == -7):
        return -7
    
    html_parser = HTMLparser.HTMLparser(url=None, html=None)
    html_parser.results =  article_objects_list
    html_parser.numOfResults = len(article_objects_list)
    return html_parser
    
    
Ejemplo n.º 33
0
    def set_text(self, text):
        if type(text) in StringTypes:
            self.text = text
        else:
            raise TypeError, type(text)

        if not self.label:
            self.label = Label(h_align = Align.CENTER, v_align = Align.CENTER,
                               text_prop = { 'align_h': 'center',
                                             'align_v': 'center',
                                             'mode' : 'hard',
                                             'hfill': False } )
            self.label.set_text(text)
            self.add_child(self.label)
        else:
            self.label.set_text(text)
Ejemplo n.º 34
0
 def post(self):
     t = get_template('search.html')
     c = Context()
     user = users.get_current_user()
     search_term = self.request.get('SearchTerm')
     label_name = self.request.get('hidden_label_name')
     htmlParser = Label.search_in_labels_return_HTMLparser(user, label_name, search_term)
     results = htmlParser.results
     if len(results) == 0:
         self.response.out.write("No results found")
         return
     my_html_parser_encoder = JSONConvertors.HTMLparserEncoder()
     resultsJSON = my_html_parser_encoder.encode(htmlParser)
     c['users'] = users
     c['results'] = results
     c['resultsJSON'] = resultsJSON
     c['formAction'] = '/AddFollow'
     c['showlabel'] = True
     c['showlabelsearch'] = False
     self.response.out.write(t.render(c))
def acceptPendingSharedLabel(invited_user, pending_id):
    try:
        query = db.GqlQuery("SELECT * FROM PendingSharedLabel WHERE invited_user = :1 "+ 
                        "AND Id = :2 ", 
                        invited_user, pending_id)
    except Exception:
        return -7   
     
    num_results = query.count(10)
    if (num_results == 0):
        return -4
    for pending_obj in query:
        num = Label.execute_label_sharing_after_approved(pending_obj.inviting_user,pending_obj.label_name,pending_obj.invited_user)
        if (num < 0):
            return num
        try:
            pending_obj.delete()
        except Exception:
            return -7

    return num # return number of articles added on this label
Ejemplo n.º 36
0
 def post(self):
     label_name = self.request.get('label_name')
     user = users.get_current_user()
     res = Label.get_emails_of_users_on_this_shared_label(user, label_name)
     self.response.out.write(res) 
Ejemplo n.º 37
0
class Button(Container):
    """
    left      x coordinate. Integer
    top       y coordinate. Integer
    width     Integer
    height    Integer
    text      The label on the button. String
    handler   Function to call when button is hit
    bg_color  Background color (Color)
    fg_color  Foreground color (Color)
    selected_bg_color  Background color (Color)
    selected_fg_color  Foreground color (Color)
    border    Border
    bd_color  Border color (Color)
    bd_width  Border width Integer
    """
    def __init__(self, text=' ', handler=None, left=None, top=None,
                 width=70, height=None, bg_color=None, fg_color=None,
                 selected_bg_color=None, selected_fg_color=None,
                 border=-1, bd_color=None, bd_width=None):

        default_button_height = 25

        if not height:
            height = default_button_height

        Container.__init__(self, 'widget', left, top, width, height, bg_color,
                           fg_color, selected_bg_color, selected_fg_color,
                           border, bd_color, bd_width)

        self.h_margin = 2
        self.v_margin = 2
        self.handler  = handler

        if text and type(text) in StringTypes:
            self.set_text(text)
        else:
            self.set_text('')

        button_normal      = self.content_layout.types['button']
        font_percent       = button_normal.font.size * 100 / default_button_height
        self.info_normal   = button_normal, int(font_percent * self.height / 120)

        button_selected    = self.content_layout.types['button selected']
        font_percent       = button_selected.font.size * 100 / default_button_height
        self.info_selected = button_selected, int(font_percent * self.height / 120)

        self.fg_color  = fg_color or Color(button_normal.rectangle.color)
        self.bg_color  = bg_color or Color(button_normal.rectangle.bgcolor)

        self.selected_fg_color = selected_fg_color or Color(button_selected.rectangle.color)
        self.selected_bg_color = selected_bg_color or Color(button_selected.rectangle.bgcolor)

        # now check the height, maybe the font is too large
        self.height = max(self.height, button_normal.height + 2 * self.v_margin,
                          button_selected.font.height + 2 * self.v_margin)

        # the label to not selected font
        self.__set_font__()

        self.set_v_align(Align.BOTTOM)
        self.set_h_align(Align.CENTER)


    def __set_font__(self):
        if self.selected:
            i = self.info_selected
        else:
            i = self.info_normal
        self.label.set_font(i[0].font.name, i[1], Color(i[0].font.color))


    def toggle_selected(self):
        self.selected = not self.selected
        self.__set_font__()


    def _draw(self):
        if not self.width or not self.height or not self.text:
            raise TypeError, 'Not all needed variables set.'

        if self.selected:
            rect = self.content_layout.types['button selected'].rectangle
        else:
            rect = self.content_layout.types['button'].rectangle

        self.surface = self.get_surface()
        if not self.border:
            self.osd.drawroundbox(0, 0, self.width, self.height,
                                  rect.bgcolor, rect.size, rect.color,
                                  rect.radius, self.surface)
        else:
            self.osd.drawroundbox(0, 0, self.width, self.height,
                                  rect.bgcolor, 0, rect.color,
                                  0, self.surface)
        Container._draw(self)


    def get_text(self):
        return self.text


    def set_text(self, text):
        if type(text) in StringTypes:
            self.text = text
        else:
            raise TypeError, type(text)

        if not self.label:
            self.label = Label(h_align = Align.CENTER, v_align = Align.CENTER,
                               text_prop = { 'align_h': 'center',
                                             'align_v': 'center',
                                             'mode' : 'hard',
                                             'hfill': False } )
            self.label.set_text(text)
            self.add_child(self.label)
        else:
            self.label.set_text(text)
Ejemplo n.º 38
0
 def post(self):
     user = users.get_current_user()
     res = Label.add_label_JSON_INPUT(user,self.request.body)
     self.response.out.write(simplejson.dumps(res))
Ejemplo n.º 39
0
 def post(self):
     inviting_user = users.get_current_user()
     label_name = self.request.get('label_name')
     new_user_email = self.request.get('user_name')
     res = Label.get_label_by_email(inviting_user , new_user_email, label_name)
     self.response.out.write(simplejson.dumps(res))
Ejemplo n.º 40
0
import Label as lbx

W = 180
H = 50

X = 19
Y = 49

GapX = 15
GapY = 2

NumPerRow = 3

print cur_page_data
for i in range(len(cur_page_data)):
	item = cur_page_data[i]
	rowIdx, colIdx = divmod(i, NumPerRow)
	x = X + colIdx * (W + GapX)
	y = Y + rowIdx * (H + GapY)
	print x, y
	lbx.fill_rect( (x, y, W, H), 0xf9d8a8 )
	lbx.draw_text( unicode(item['Item Name']), 12,  (x + 10, y + 10, 0, 0), family=u"Verdana")
Ejemplo n.º 41
0
 def post(self):
     user = users.get_current_user()
     label_name = self.request.get('label_name')
     article_key = self.request.get('article_key')
     res = Label.remove_label_from_article(user, label_name, article_key)
     self.response.out.write(simplejson.dumps(res))
Ejemplo n.º 42
0
 def post(self):
     label_name = self.request.get('label_name')
     user = users.get_current_user()
     res = Label.remove_user_from_shared_label(user, label_name)
     self.response.out.write(simplejson.dumps(res)) 
Ejemplo n.º 43
0
 def post(self):
     label_name = self.request.get('label_name')
     user = users.get_current_user()
     res = Label.duplicate_label_to_private(user, label_name)
     self.response.out.write(res)