예제 #1
0
def main(output=None):
    with HTML(output=output) as doc:
        with TopLevelTag("head") as head:
            with Tag("title") as title:
                title.text = "hello"
                head += title
            doc += head

        with TopLevelTag("body") as body:
            with Tag("h1", klass=("main-text", )) as h1:
                h1.text = "Test"
                body += h1

            with Tag("div", klass=("container", "container-fluid"),
                     id="lead") as div:
                with Tag("p") as paragraph:
                    paragraph.text = "another test"
                    div += paragraph

                with Tag("img", is_single=True, src="/icon.png") as img:
                    div += img

                body += div

            doc += body
예제 #2
0
class ValidFakeDatabase:

    # initializes dummy data to return
  def __init__(self):
    self.dateA = datetime.datetime(2013, 8, 4, 12, 30, 45)
	self.dateB = datetime.datetime(1999, 7, 6, 12, 30, 45)
    self.paperA = Paper("12345", "The Health Benefits of the All-Bacon Diet", ["4445", "666", "123"], ["Genetics", "Bioinformatics", "Search Engines", "Artificial Intelligence"], "Bacon is actually one of the healthiest foods of all time.  This is an abstract!  For the full article, download the PDF.", "1234", self.dateA, datetime.datetime.now(), "1111", ["ref1", "ref2", "ref3"], "14000", ["citation link 1", "citation link 2", "citation link 2"], "Your Favorite Publisher",["Alan Turing", "Shia Leboeuf", "Andrew Davidson"])
    self.paperB = Paper("90210", "The Dangers of Coding While Hungry", ["12068", "7797", "4326"], ["Genetics", "Bioinformatics", "Search Engines", "Artificial Intelligence"], " Abstracts never seem to be simple or contain useful information.", "444", self.dateA, datetime.datetime.now(), "6677", ["ref1", "ref2", "ref3"], "14000", ["citation link 1", "citation link 2", "citation link 2"], "Your Favorite Publisher",["Andrew Davidson","William Shakespeare","Edsger Dijkstra"])
    self.paperC = Paper("666", "The Struggles of Eating a Giordano's Pizza Alone", ["567", "2213", "989"], ["6237", "3177", "432"], "Abstracts are the SparkNotes of the academic world.", "12534434", self.dateB, datetime.datetime.now(), "2345", ["ref1", "ref2", "ref3"], "14000", ["citation link 1", "citation link 2", "citation link 2"], "Prentice Hall", ["Andrew Davidson","William Shakespeare","Edsger Dijkstra"])

    self.authorA = Author("55555", "Shia Leboeuf", "4444", ["0", "1"],["The Health Benefits of the All-Bacon Diet", "The Dangers of Coding While Hungry"],[["Andrew Davidson","William Shakespeare","Edsger Dijkstra"],["Alan Turing", "Shia Leboeuf", "Andrew Davidson"]],[self.dateB,self.dateA])
    self.authorB = Author("43216", "Andrew Davidson", "1", ["0", "1"],["The Health Benefits of the All-Bacon Diet", "The Dangers of Coding While Hungry"],[["Andrew Davidson","William Shakespeare","Edsger Dijkstra"],["Alan Turing", "Shia Leboeuf", "Andrew Davidson"]],[self.dateB,self.dateA])
    self.authorC = Author("6542", "William Shakespeare", "11542", ["2", "1"],["The Struggles of Eating a Giordano's Pizza Alone","The Dangers of Coding While Hungry"],[["Andrew Davidson","William Shakespeare","Edsger Dijkstra"],["Alan Turing", "Shia Leboeuf", "Andrew Davidson"]],[self.dateB,self.dateA])
    self.authorD = Author("64632", "Edsger Dijkstra", "147", ["2", "1"],["The Struggles of Eating a Giordano's Pizza Alone","The Dangers of Coding While Hungry"],[["Andrew Davidson","William Shakespeare","Edsger Dijkstra"],["Alan Turing", "Shia Leboeuf", "Andrew Davidson"]],[self.dateB,self.dateA])
    self.authorE = Author("63421", "Alan Turing", "40000", ["2", "1"],["The Struggles of Eating a Giordano's Pizza Alone","The Dangers of Coding While Hungry"],[["Andrew Davidson","William Shakespeare","Edsger Dijkstra"],["Alan Turing", "Shia Leboeuf", "Andrew Davidson"]],[self.dateB,self.dateA])

    self.tagA = Tag("Genetics", "40000", ["0", "1"])
    self.tagB = Tag("Bioinformatics", "12345", ["0", "1"])
    self.tagC = Tag("Search Engines", "5555", ["2", "3"])
    self.tagD = Tag("Artificial Intelligence", "42", ["2", "3"])
    
    self.publisherA = Publisher("1233", "Your Favorite Publisher",0)
    self.publisherB = Publisher("3468", "Prentice Hall",0)
    self.publisherC = Publisher("8372", "Rose-Hulman",0)

    self.userA = User("0","Otis Redding", ["1", "3"],["Andrew Davidson","Jonathan Jenkins"], [self.paperA, self.paperB, self.paperC], [self.authorA, self.authorB, self.authorC], [self.tagA, self.tagC, self.tagB, self.tagD], "45", "005792830123")
예제 #3
0
	def run(self, edit):
		view = self.view
		new_selections = []
		for region in view.sel():
			source = view.substr(region)
			if not source.strip():
				region = view.word(region)
				source = view.substr(region)
			if not source.strip():
				new_selections.append(sublime.Region(region.a, region.b))
				pass
			else:
				if re.match("^\s", source):
					view.replace(edit, region, '<p>'+source+'</p>')
					new_selections.append(sublime.Region(region.end()+3, region.end()+3))
				elif Tag.is_self_closing(source):
					view.replace(edit, region, '<'+source+'/>')
					new_selections.append(sublime.Region(region.end()+3, region.end()+3))
				else:
					tag = source.split('\r')[0].split('\n')[0].split(' ')[0]
					if tag and Tag.is_valid(tag) and tag != '<' and tag != '</' and tag != '>':
						view.replace(edit, region, '<'+source+'></'+tag+'>')
						new_selections.append(sublime.Region(region.end()+2, region.end()+2))
					else:
						new_selections.append(sublime.Region(region.end(), region.end()))

		view.sel().clear()
		for sel in new_selections:
			view.sel().add(sel)
	def close_tag(self, data, is_xml):

		data = data.split('<')
		data.reverse()

		try:
			i = 0
			lenght = len(data)-1
			while i < lenght:
				tag = Tag.name(data[i], True, is_xml)
				# if opening tag, close the tag
				if tag:
					if not Tag.is_closing(data[i]):
						return '</'+Tag.name(data[i], True, is_xml)+''
					# if closing tag, jump to opening tag
					else:
						i = i+1
						skip = 0
						while i < lenght:
							if Tag.name(data[i], True, is_xml) == tag:
								if not Tag.is_closing(data[i]):
									if skip == 0:
										break
									else:
										skip = skip-1
								else:
									skip = skip+1
							i = i+1
				i = i+1
			return ''
		except:
			return '';
    def close_tag(self, data, is_xml):

        data = data.split('<')
        data.reverse()
        data.pop(0)

        try:
            i = 0
            lenght = len(data) - 1
            while i < lenght:
                tag = Tag.name(data[i], True, is_xml)
                # if opening tag, close the tag
                if tag and not Tag.is_closing(data[i]):
                    return '/' + Tag.name(data[i], True, is_xml) + ''
                # if closing tag, jump to opening tag
                else:
                    if tag:
                        i = i + 1
                        skip = 0
                        while i < lenght:
                            if Tag.name(data[i], True, is_xml) == tag:
                                if not Tag.is_closing(data[i]):
                                    if skip == 0:
                                        break
                                    else:
                                        skip = skip - 1
                                else:
                                    skip = skip + 1
                            i = i + 1
                i = i + 1
            return '/'
        except:
            return '/'
class TagScreen:
    """
	A screen which handles adding a tag to a post

	This module is responsible for providing the UI of the screen
	which the user can interface with to add tags to posts
	"""
    def __init__(self, terminal, post):
        """
		Creates an instance of TagScreen

		Parameters:
			terminal:
				A Terminal object allowing for this module to interface
				with the OS terminal
			post:
				A PostQuery Object which contains information about the post
				who is getting a tag
		Returns:
			An instance of TagScreen
		"""
        self.__chkinp__ = CheckInput()
        self.__terminal__ = terminal
        self.__post__ = post
        self.__tag__ = Tag(terminal.getDBName())

    def printTitle(self):
        """
		Prints text identifying this screen to the user and providing some information
		"""
        self.__terminal__.clear()
        self.__terminal__.printCenter("Tag the post")
        self.__terminal__.printCenter(
            "The post you are currently tagging has the title " +
            self.__post__.title)

    def printScreen(self):
        """
		Serves as the main loop of the module. Allowing the user
		to interface with the program by providing a tag
		"""
        self.printTitle()
        invalidInput = True

        try:
            userInput = input("Enter tag you would like to add to the post: ")
            if self.__chkinp__.checkEscape(userInput):
                return None
            self.__tag__.addTag(self.__post__.pid, userInput)
        except Exception as e:
            print(e)
        else:
            print("Tag successfully added!")
        finally:
            input("Type enter to continue: ")
예제 #7
0
    def on_saveButton_click(self, widget):
        tagName = self.tagEntry.get_text()
        tagField = self.tagFieldEntry.get_text()
        tagDescription = self.tagDescriptionEntry.get_text()

        myTag = Tag(tagName, tagField, tagDescription)
        print("this is  my tag: ", myTag.TagName, myTag.TaggedField,
              myTag.TagAnnotation)
        myTag.saveTag(tagName, tagField, tagDescription)

        self.destroy()
예제 #8
0
 def get_um(self, id):
     self.query.execute("SELECT * FROM tag WHERE id=(%s)", (id, ))
     consult = self.query.fetchone()
     if consult:
         tag = Tag(consult[1], id=consult[0])
         return tag
     return False
예제 #9
0
 def get_all(self):
     tags = []
     self.query.execute("SELECT * FROM tag ORDER BY nome")
     tagsQuery = self.query.fetchall()
     for tag in tagsQuery:
         tags.append(Tag(tag[1], id=tag[0]))
     return tags
예제 #10
0
 def parse(cls, buf):
     buf = str(buf)
     buf = buf.replace("'", '"') 
     
     data  = json.loads(buf)   
     srcDevUUID  = data['srcDevUUID']
     deltaUpdate = data['deltaUpdate']
     
     contentListJSON = data['contentList']
     contentList = []
     for c in contentListJSON:
        
         contentId   = c['contentId']
         size        = c['size']
 
         tagListJSON = c['tagList']
         tagList = []
         for t in tagListJSON:
             newTag = Tag(t['name'], t['quality']) 
             tagList.append(newTag)
                 
         newContent = Content(contentId, size)
         newContent.tagList = tagList
         contentList.append(newContent)
         
     return cls(srcDevUUID, deltaUpdate, contentList)
    def __init__(self, terminal, post):
        """
		Creates an instance of TagScreen

		Parameters:
			terminal:
				A Terminal object allowing for this module to interface
				with the OS terminal
			post:
				A PostQuery Object which contains information about the post
				who is getting a tag
		Returns:
			An instance of TagScreen
		"""
        self.__chkinp__ = CheckInput()
        self.__terminal__ = terminal
        self.__post__ = post
        self.__tag__ = Tag(terminal.getDBName())
예제 #12
0
    def run(self, edit):

        view = self.view
        is_xml = Tag.view_is_xml(view)

        closed_some_tag = False
        new_selections = []
        new_selections_insert = []

        for region in view.sel():
            cursorPosition = region.begin()

            tag = self.close_tag(
                view.substr(sublime.Region(0, cursorPosition)), is_xml)

            if tag and tag != '</':
                if region.empty():
                    replace = False
                    view.insert(edit, cursorPosition, tag)
                else:
                    replace = True
                    view.replace(edit,
                                 sublime.Region(region.begin(), region.end()),
                                 '')
                    view.insert(edit, cursorPosition, tag)
                if tag != '</':
                    closed_some_tag = True
                    if replace:
                        new_selections_insert.append(
                            sublime.Region(region.begin() + len(tag),
                                           region.begin() + len(tag)))
                    else:
                        new_selections_insert.append(
                            sublime.Region(region.end() + len(tag),
                                           region.end() + len(tag)))
                else:
                    new_selections.append(
                        sublime.Region(region.end() + len(tag),
                                       region.end() + len(tag)))
            else:
                new_selections.append(
                    sublime.Region(region.end(), region.end()))

        view.sel().clear()

        # we inserted the "</tagname" part.
        # running the command "insert" with parameter ">" to allow
        # to the application indent these tags correctly
        if closed_some_tag:
            view.run_command('hide_auto_complete')
            for sel in new_selections_insert:
                view.sel().add(sel)
            view.run_command('insert', {"characters": ">"})
            view.run_command('reindent', {"force_indent": False})

        for sel in new_selections:
            view.sel().add(sel)
예제 #13
0
 def tags(self, value):
     self.taint("tags")
     print "Setting tags for %s to %s" % (self, value)
     if isinstance(value, XMLCLASS) and value.tag == "tags":
         self._tags = list()
         for element in value:
             self.tags.append(Tag(element, self.rsapi))
         # for element ...
     else:
         self._tags = value
예제 #14
0
	def run(self, edit):
		if s.get('enable_close_tag_on_slash') == False:
			self.view.run_command('insert',  {"characters": "/"})
			return

		view = self.view
		is_xml = Tag.view_is_xml(view)

		closed_some_tag = False
		new_selections = []
		new_selections_insert = []

		for region in view.sel():
			cursorPosition = region.begin()
			previousCharacter = view.substr(sublime.Region(cursorPosition - 1, cursorPosition))

			if '<' == previousCharacter:
				tag = self.close_tag(view.substr(sublime.Region(0, cursorPosition)), is_xml)
				if region.empty():
					replace = False
					view.insert(edit, cursorPosition, tag);
				else:
					replace = True
					view.replace(edit, sublime.Region(region.begin(), region.end()), '');
					view.insert(edit, cursorPosition, tag);
				if tag != '/':
					closed_some_tag = True
					if replace:
						new_selections_insert.append(sublime.Region(region.begin()+len(tag), region.begin()+len(tag)))
					else:
						new_selections_insert.append(sublime.Region(region.end()+len(tag), region.end()+len(tag)))
				else:
					new_selections.append(sublime.Region(region.end()+len(tag), region.end()+len(tag)))
			else:
				if region.empty():
					view.insert(edit, cursorPosition, '/');
				else:
					view.replace(edit, sublime.Region(region.begin(), region.end()), '/');
				new_selections.append(sublime.Region(region.end(), region.end()))

		view.sel().clear()

		# we inserted the "</tagname" part.
		# running the command "insert" with parameter ">" to allow
		# to the application indent these tags correctly
		if closed_some_tag:
			view.run_command('hide_auto_complete')
			for sel in new_selections_insert:
				view.sel().add(sel)
			view.run_command('insert',  {"characters": ">"})
			view.run_command('reindent',  {"force_indent": False})

		for sel in new_selections:
			view.sel().add(sel)
예제 #15
0
 def get_all_tags_post(self, id):
     """Retorna todas as tag de um post
     """
     tags = []
     self.query.execute("SELECT * FROM post_tag WHERE post_id=(%s)", (id, ))
     tagQuery = self.query.fetchall()
     for tag in tagQuery:
         self.query.execute("SELECT * FROM tag WHERE id=(%s)", (tag[1], ))
         consult = self.query.fetchone()
         if consult:
             tags.append(Tag(consult[1], id=consult[0]))
     return tags
예제 #16
0
    def run(self, edit):
        view = self.view
        new_selections = []
        for region in view.sel():
            source = view.substr(region)
            if not source.strip():
                region = view.word(region)
                source = view.substr(region)
            if not source.strip():
                new_selections.append(sublime.Region(region.a, region.b))
                pass
            else:
                if re.match("^\s", source):
                    view.replace(edit, region, '<p>' + source + '</p>')
                    new_selections.append(
                        sublime.Region(region.end() + 3,
                                       region.end() + 3))
                elif Tag.is_self_closing(source):
                    view.replace(edit, region, '<' + source + '/>')
                    new_selections.append(
                        sublime.Region(region.end() + 3,
                                       region.end() + 3))
                else:
                    tag = source.split('\r')[0].split('\n')[0].split(' ')[0]
                    if tag and Tag.is_valid(
                            tag) and tag != '<' and tag != '</' and tag != '>':
                        view.replace(edit, region,
                                     '<' + source + '></' + tag + '>')
                        new_selections.append(
                            sublime.Region(region.end() + 2,
                                           region.end() + 2))
                    else:
                        new_selections.append(
                            sublime.Region(region.end(), region.end()))

        view.sel().clear()
        for sel in new_selections:
            view.sel().add(sel)
	def run(self, edit):

		view = self.view
		is_xml = Tag.view_is_xml(view);

		closed_some_tag = False
		new_selections = []
		new_selections_insert = []

		for region in view.sel():
			cursorPosition = region.begin()

			tag = self.close_tag(view.substr(sublime.Region(0, cursorPosition)), is_xml)

			if tag and tag != '</':
				if region.empty():
					replace = False
					view.insert(edit, cursorPosition, tag);
				else:
					replace = True
					view.replace(edit, sublime.Region(region.begin(), region.end()), '');
					view.insert(edit, cursorPosition, tag);
				if tag != '</':
					closed_some_tag = True
					if replace:
						new_selections_insert.append(sublime.Region(region.begin()+len(tag), region.begin()+len(tag)))
					else:
						new_selections_insert.append(sublime.Region(region.end()+len(tag), region.end()+len(tag)))
				else:
					new_selections.append(sublime.Region(region.end()+len(tag), region.end()+len(tag)))
			else:
				new_selections.append(sublime.Region(region.end(), region.end()))

		view.sel().clear()

		# we inserted the "</tagname" part.
		# running the command "insert" with parameter ">" to allow
		# to the application indent these tags correctly
		if closed_some_tag:
			view.run_command('hide_auto_complete')
			for sel in new_selections_insert:
				view.sel().add(sel)
			view.run_command('insert',  {"characters": ">"})

		for sel in new_selections:
			view.sel().add(sel)
예제 #18
0
 def run(self, asap=False, from_command=False):
     now = time()
     if asap == False and (now - Pref.time < Pref.wait_time):
         return
     if (Pref.enable_live_tag_linting
             or from_command) and Pref.modified and not Pref.running:
         Pref.modified = False
         if from_command:
             Pref.view = sublime.active_window().active_view()
         if Pref.view:
             view = Pref.view
             Pref.view_size = view.size()
             if Pref.view_size > 10485760:
                 return
             if Pref.view.settings().get(
                     'is_widget') or Pref.view.is_scratch():
                 return
             file_ext = ('name.' + (view.file_name() or '')).split('.')
             file_ext.reverse()
             file_ext = file_ext.pop(0).lower()
             if not from_command and file_ext not in Pref.enable_live_tag_linting_document_types:
                 return
             Pref.running = True
             is_xml = Tag.view_is_xml(view)
             if from_command:
                 if view.sel():
                     region = view.sel()[0]
                     if region.empty():
                         region = sublime.Region(0, view.size())
                 else:
                     region = sublime.Region(0, view.size())
             else:
                 region = sublime.Region(0, view.size())
             original_position = region.begin()
             content = view.substr(region)
             TagLintThread(view, content, original_position, is_xml,
                           from_command).start()
         else:
             self.guess_view()
예제 #19
0
파일: tag_lint.py 프로젝트: 62Gerente/unix
	def run(self, asap = False, from_command = False):
		now = time()
		if asap == False and (now - Pref.time < Pref.wait_time):
			return
		if (Pref.enable_live_tag_linting or from_command) and Pref.modified and not Pref.running:
			Pref.modified = False
			if from_command:
				Pref.view = sublime.active_window().active_view()
			if Pref.view:
				view = Pref.view
				Pref.view_size = view.size()
				if Pref.view_size > 10485760:
					return
				if Pref.view.settings().get('is_widget') or Pref.view.is_scratch():
					return
				file_ext = ('name.'+(view.file_name() or '')).split('.')
				file_ext.reverse()
				file_ext = file_ext.pop(0).lower()
				if not from_command and file_ext not in Pref.enable_live_tag_linting_document_types:
					return
				Pref.running = True
				is_xml = Tag.view_is_xml(view)
				if from_command:
					if view.sel():
						region = view.sel()[0]
						if region.empty():
							region = sublime.Region(0, view.size())
					else:
						region = sublime.Region(0, view.size())
				else:
					region = sublime.Region(0, view.size())
				original_position = region.begin()
				content = view.substr(region)
				TagLintThread(view, content, original_position, is_xml, from_command).start()
			else:
				self.guess_view()
예제 #20
0
 def add_tag(self, data):
     tag = Tag(data, self.rsapi)
     self.tags.append(tag)
예제 #21
0
    def parseMessage(self, client, message):
        """
        Check who is the message from to redirect it to User / Tag / Camera / Calibration
        or create a new instance of User / Tag / Camera / Calibration
        :param client:
        :param message:
        :return:
        """
        if self.cameras.has_key(str(client['address'])):
            #print "Message from Camera"
            self.cameras[str(client['address'])].push(message)
            # Update all cameras counters
            #Todo: Change this method for checking all cameras for lost point (auto check inside point2D ?)
            for key in self.cameras.keys():
                self.cameras[key].update()

        elif self.users.has_key(str(client['address'])):
            print "Message from User"

        elif self.tags.has_key(str(client['address'])):
            print "Message from Tag"

        elif self.calibration.has_key(str(client['address'])):
            self.calibration[str(client['address'])].push(message)
            print "Message from Calibration"

        # This message is coming from an unknown client
        else:
            if message.split("-")[0] == "camera":
                self.cameras[str(client['address'])] = Camera(
                    client,
                    message.split("-")[1])
                # Add Observers linking every user to every camera's update
                for key in self.users:
                    if isinstance(self.users[key], User):
                        self.cameras[str(
                            client['address'])].new2DPointNotifier.addObserver(
                                self.users[key].position.newPoint2DObserver)
                        self.cameras[str(
                            client['address']
                        )].point2DdeletedNotifier.addObserver(
                            self.users[key].position.point2DDeletedObserver)

            elif message.split("-")[0] == "tag":
                self.tags[str(client['address'])] = Tag(
                    self.server, client,
                    message.split("-")[1])
                for key in self.users:
                    if isinstance(self.users[key], User):
                        # Assign a Tag to User with no Tag
                        if self.users[key].tag == None:
                            self.users[key].setTag(self.tags[str(
                                client['address'])])

            elif message.split("-")[0] == "user":
                user = User(self.server, client, message.split("-")[1])
                self.users[str(client['address'])] = user
                # Add Observers linking every user to every camera's update
                for key in self.cameras:
                    if isinstance(self.cameras[key], Camera):
                        self.cameras[key].new2DPointNotifier.addObserver(
                            user.position.newPoint2DObserver)
                        self.cameras[key].point2DdeletedNotifier.addObserver(
                            user.position.point2DDeletedObserver)

                for key in self.tags:
                    if isinstance(self.tags[key], Tag):
                        # Assign a Tag to new User
                        if self.tags[key].isAssigned() == False:
                            user.setTag(self.tags[key])

            elif message == "calibration":
                if (len(self.tags) > 0):
                    self.calibration[str(client['address'])] = Calibration(
                        self.server, client, self.cameras,
                        self.tags.values()[0])
                else:
                    self.server.send_message(
                        client,
                        "Please connect a Tag first, and start Calibration again."
                    )
예제 #22
0
 def add_tag(self, n, q):
     tag = Tag(n, q)
     self.tagList.append(tag)
예제 #23
0
 def add_tag(self, tag_name, tag_description, field_name):
     if tag_name in self.tag:
         return False
     else:
         self.tag[tag_name] = Tag(tag_name, tag_description, field_name)
         return True
예제 #24
0
    def run(self, edit):
        if s.get('enable_close_tag_on_slash') == False:
            self.view.run_command('insert', {"characters": "/"})
            return

        view = self.view
        is_xml = Tag.view_is_xml(view)

        closed_some_tag = False
        new_selections = []
        new_selections_insert = []

        for region in view.sel():
            cursorPosition = region.begin()
            previousCharacter = view.substr(
                sublime.Region(cursorPosition - 1, cursorPosition))

            if '<' == previousCharacter:
                tag = self.close_tag(
                    view.substr(sublime.Region(0, cursorPosition)), is_xml)
                if region.empty():
                    replace = False
                    view.insert(edit, cursorPosition, tag)
                else:
                    replace = True
                    view.replace(edit,
                                 sublime.Region(region.begin(), region.end()),
                                 '')
                    view.insert(edit, cursorPosition, tag)
                if tag != '/':
                    closed_some_tag = True
                    if replace:
                        new_selections_insert.append(
                            sublime.Region(region.begin() + len(tag),
                                           region.begin() + len(tag)))
                    else:
                        new_selections_insert.append(
                            sublime.Region(region.end() + len(tag),
                                           region.end() + len(tag)))
                else:
                    new_selections.append(
                        sublime.Region(region.end() + len(tag),
                                       region.end() + len(tag)))
            else:
                if region.empty():
                    view.insert(edit, cursorPosition, '/')
                else:
                    view.replace(edit,
                                 sublime.Region(region.begin(), region.end()),
                                 '/')
                new_selections.append(
                    sublime.Region(region.end(), region.end()))

        view.sel().clear()

        # we inserted the "</tagname" part.
        # running the command "insert" with parameter ">" to allow
        # to the application indent these tags correctly
        if closed_some_tag:
            view.run_command('hide_auto_complete')
            for sel in new_selections_insert:
                view.sel().add(sel)
            view.run_command('insert', {"characters": ">"})

        for sel in new_selections:
            view.sel().add(sel)
예제 #25
0
    def run(self):

        begin = time()

        content = self.content
        original_position = self.original_position
        is_xml = self.is_xml

        # remove unparseable content

        # comments
        unparseable = content.split('<!--')
        content = unparseable.pop(0)
        l = len(unparseable)
        i = 0
        while i < l:
            tmp = unparseable[i].split('-->')
            content += '....'
            content += len(tmp.pop(0)) * '.'
            content += '...'
            content += "...".join(tmp)
            i += 1

        unparseable = content.split('/*')
        content = unparseable.pop(0)
        l = len(unparseable)
        i = 0
        while i < l:
            tmp = unparseable[i].split('*/')
            content += '..'
            content += len(tmp.pop(0)) * '.'
            content += '..'
            content += "..".join(tmp)
            i += 1

        # script
        unparseable = content.split('<script')
        content = unparseable.pop(0)
        l = len(unparseable)
        i = 0
        while i < l:
            tmp = unparseable[i].split('</script>')
            content += '.......'
            content += len(tmp.pop(0)) * '.'
            content += '.........'
            content += ".........".join(tmp)
            i += 1

        # script
        unparseable = content.split('<style')
        content = unparseable.pop(0)
        l = len(unparseable)
        i = 0
        while i < l:
            tmp = unparseable[i].split('</style>')
            content += '......'
            content += len(tmp.pop(0)) * '.'
            content += '........'
            content += "........".join(tmp)
            i += 1

        # linting: opening tags

        data = content.split('<')

        position = original_position + len(data.pop(0))

        invalid_tag_located_at = -1

        i = 0
        lenght = len(data)
        first_at = 0
        while i < lenght:
            tag = Tag.name(data[i], False, is_xml)
            if tag and tag != 'html' and tag != 'body':
                # if opening tag, then check if closing tag exists
                if not Tag.is_closing(data[i]):
                    # print tag+' is opening '
                    if first_at == 0:
                        first_at = position
                    a = i + 1
                    skip = 0
                    while a < lenght:
                        inner_tag_name = Tag.name(data[a], False, is_xml)
                        # check if same tag was found
                        if inner_tag_name and inner_tag_name == tag:
                            # check if tag is closing
                            if Tag.is_closing(data[a]):
                                if skip == 0:
                                    break
                                else:
                                    skip = skip - 1
                            else:
                                skip = skip + 1
                        a = a + 1
                    if a >= lenght:
                        self.message = '"' + tag + '" tag is not closing'
                        invalid_tag_located_at = position
                        break
            position += len(data[i]) + 1
            i = i + 1

        # linting: closing tags

        if invalid_tag_located_at == -1:

            position = original_position + len(content)

            data = content.split('<')
            data.reverse()

            i = 0
            lenght = len(data) - 1
            while i < lenght:
                tag = Tag.name(data[i], False, is_xml)
                if tag and tag != 'html' and tag != 'body':
                    # if closing tag, check if opening tag exists
                    if Tag.is_closing(data[i]):
                        # print tag+' is closing '
                        a = i + 1
                        skip = 0
                        while a < lenght:
                            inner_tag_name = Tag.name(data[a], False, is_xml)
                            if inner_tag_name and inner_tag_name == tag:
                                # check if tag is opening
                                if not Tag.is_closing(data[a]):
                                    if skip == 0:
                                        break
                                    else:
                                        skip = skip - 1
                                else:
                                    skip = skip + 1
                            a = a + 1
                        if a >= lenght:
                            self.message = '"' + tag + '" tag is not opening'
                            invalid_tag_located_at = position - (len(data[i]) +
                                                                 1)
                            if invalid_tag_located_at < first_at:
                                invalid_tag_located_at = -1
                            break
                position -= len(data[i]) + 1
                i = i + 1

        elapsed_time = time() - begin

        # print 'Benchmark: '+str(elapsed_time)

        self.invalid_tag_located_at = invalid_tag_located_at

        sublime.set_timeout(
            lambda: tag_lint.
            display(self.view, self.message, self.invalid_tag_located_at, self.
                    from_command), 0)
def scrape_page(page_link):
    page_reponse = requests.get(page_link)
    page_soup = BeautifulSoup(page_reponse.text, "html.parser")

    try:
        image_url = page_soup.select_one(
            ".recipeGallerySegment .bigImg img")['src']

        if "without-watermark" not in image_url:
            global recipes_with_watermarks
            recipes_with_watermarks += 1
            return

        recipe_title = page_soup.select_one(
            ".recipeTitleSegment h1").text.strip()
        before_split = page_soup.select_one(".method .info .info").text.strip()

        recipe_preparation_time = int(re.findall("\d+", before_split)[0])
        if "min" in before_split:
            recipe_preparation_time = int(60 * recipe_preparation_time)
        elif "val" in before_split:
            recipe_preparation_time = int(60 * 60 * recipe_preparation_time)
        recipe_portion_amount = page_soup.select_one(".info").text.strip()
        if len(recipe_portion_amount) is 0:
            recipe_portion_amount = int(4)
        else:
            recipe_portion_amount = int(
                re.findall("\d+", recipe_portion_amount)[0])

        recipe_description = ''
        try:
            recipe_description = page_soup.select_one(
                ".authorsDescription").text.strip()
        except AttributeError:
            recipe_description = ''
            print('No description')

        amounts = page_soup.select(".ingredients .infoA table tr")
        recipe_products = []
        for amount in amounts:
            cells = amount.select("td")
            if len(cells) is 1:
                continue
            quantity = cells[0].text.strip()
            product_name = cells[1].text.strip()[0:30].strip()
            new_product = Product(product_name, quantity)
            recipe_products.append(new_product.__dict__)

        steps = page_soup.select(".infoA .description")
        recipe_steps = []
        for step in steps:
            step_text = step.select_one(".text")
            # print(step_text.text)
            new_step = Step(step_text.text)
            recipe_steps.append(new_step.__dict__)

        recipe_view_count = int(0)
        recipe_rating = int(0)
        recipe_votes_count = int(0)

        image_extension = image_url.split('.')[-1]
        image_fileName = ''
        image_name = ''
        while True:
            image_name = uuid.uuid4().hex
            image_fileName = image_name + "." + image_extension
            if not os.path.isfile("Photos/" + image_fileName):
                break

        opener = urllib.request.URLopener()
        opener.addheader(
            'User-Agent',
            'Mozilla/5.0 (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Mobile/7B405'
        )
        opener.retrieve(image_url, "Photos/" + image_fileName)
        # urllib.request.urlretrieve(image_url, "Photos/" + image_fileName)

        recipe_image = Photo(image_fileName)
        recipe_images = []
        recipe_images.append(recipe_image.__dict__)

        # Tags
        recipe_tags = []
        temp = Tag("grilio patiekalai")
        recipe_tags.append(temp.__dict__)

        tags = page_soup.select(".guidelinesSegment a")
        for tag in tags:
            if not "lamaistas" in tag.text:
                new_tag = Tag(tag.text)
                recipe_tags.append(new_tag.__dict__)

        new_recipe = Recipe(recipe_title, recipe_products, recipe_steps,
                            recipe_portion_amount, recipe_preparation_time,
                            recipe_description, recipe_view_count,
                            recipe_rating, recipe_votes_count, recipe_images,
                            recipe_tags)
        new_recipes.append(new_recipe.__dict__)
        print("Saved " + page_link + " " + str(len(new_recipes)))
    except Exception as e:
        print("Error " + str(e) + " || " + page_link)
예제 #27
0
파일: tag_lint.py 프로젝트: sbusso/st2_conf
    def run(self):

        begin = time()

        content = self.content
        original_position = self.original_position
        is_xml = self.is_xml

        # remove unparseable content

        # comments
        unparseable = content.split("<!--")
        content = unparseable.pop(0)
        l = len(unparseable)
        i = 0
        while i < l:
            tmp = unparseable[i].split("-->")
            content += "...."
            content += len(tmp.pop(0)) * "."
            content += "..."
            content += "...".join(tmp)
            i += 1

        unparseable = content.split("/*")
        content = unparseable.pop(0)
        l = len(unparseable)
        i = 0
        while i < l:
            tmp = unparseable[i].split("*/")
            content += ".."
            content += len(tmp.pop(0)) * "."
            content += ".."
            content += "..".join(tmp)
            i += 1

            # script
        unparseable = content.split("<script")
        content = unparseable.pop(0)
        l = len(unparseable)
        i = 0
        while i < l:
            tmp = unparseable[i].split("</script>")
            content += "......."
            content += len(tmp.pop(0)) * "."
            content += "........."
            content += ".........".join(tmp)
            i += 1

            # script
        unparseable = content.split("<style")
        content = unparseable.pop(0)
        l = len(unparseable)
        i = 0
        while i < l:
            tmp = unparseable[i].split("</style>")
            content += "......"
            content += len(tmp.pop(0)) * "."
            content += "........"
            content += "........".join(tmp)
            i += 1

            # linting: opening tags

        data = content.split("<")

        position = original_position + len(data.pop(0))

        invalid_tag_located_at = -1

        i = 0
        lenght = len(data)
        first_at = 0
        while i < lenght:
            tag = Tag.name(data[i], False, is_xml)
            if tag and tag != "html" and tag != "body" and tag != "head":
                # if opening tag, then check if closing tag exists
                if not Tag.is_closing(data[i]):
                    # print tag+' is opening '
                    if first_at == 0:
                        first_at = position
                    a = i + 1
                    skip = 0
                    while a < lenght:
                        inner_tag_name = Tag.name(data[a], False, is_xml)
                        # check if same tag was found
                        if inner_tag_name and inner_tag_name == tag:
                            # check if tag is closing
                            if Tag.is_closing(data[a]):
                                if skip == 0:
                                    break
                                else:
                                    skip = skip - 1
                            else:
                                skip = skip + 1
                        a = a + 1
                    if a >= lenght:
                        self.message = '"' + tag + '" tag is not closing'
                        invalid_tag_located_at = position
                        break
            position += len(data[i]) + 1
            i = i + 1

            # linting: closing tags

        if invalid_tag_located_at == -1:

            position = original_position + len(content)

            data = content.split("<")
            data.reverse()

            i = 0
            lenght = len(data) - 1
            while i < lenght:
                tag = Tag.name(data[i], False, is_xml)
                if tag and tag != "html" and tag != "body" and tag != "head":
                    # if closing tag, check if opening tag exists
                    if Tag.is_closing(data[i]):
                        # print tag+' is closing '
                        a = i + 1
                        skip = 0
                        while a < lenght:
                            inner_tag_name = Tag.name(data[a], False, is_xml)
                            if inner_tag_name and inner_tag_name == tag:
                                # check if tag is opening
                                if not Tag.is_closing(data[a]):
                                    if skip == 0:
                                        break
                                    else:
                                        skip = skip - 1
                                else:
                                    skip = skip + 1
                            a = a + 1
                        if a >= lenght:
                            self.message = '"' + tag + '" tag is not opening'
                            invalid_tag_located_at = position - (len(data[i]) + 1)
                            if invalid_tag_located_at < first_at:
                                invalid_tag_located_at = -1
                            break
                position -= len(data[i]) + 1
                i = i + 1

        elapsed_time = time() - begin

        # print 'Benchmark: '+str(elapsed_time)

        self.invalid_tag_located_at = invalid_tag_located_at

        sublime.set_timeout(
            lambda: tag_lint.display(self.view, self.message, self.invalid_tag_located_at, self.from_command), 0
        )
예제 #28
0
from HTML import HTML
from TopLevelTag import TopLevelTag
from Tag import Tag

if __name__ == "__main__":
    with HTML("test.html") as doc:
        with TopLevelTag("head") as head:
            with Tag("title") as title:
                title.text = "hello"
                head += title
            doc += head

        with TopLevelTag("body") as body:
            with Tag("h1", klass=("main-text", )) as h1:
                h1.text = "Test"
                body += h1

            with Tag("div", klass=("container", "container-fluid"),
                     id="lead") as div:
                with Tag("p") as paragraph:
                    paragraph.text = "another test"
                    div += paragraph

                with Tag("img",
                         is_single=True,
                         src="/icon.png",
                         data_image="responsive") as img:
                    div += img

                body += div
예제 #29
0
 def __init__(self, screenProps):
     self.game = Tag.Tag(screenProps)
     self.playGame()
예제 #30
0
            print("not verified")
    else:
        print("not verified")
    # print("Time Consumed in step 6 (by Tag)")
    # print("% s seconds" % (time.time() - start))


if __name__ == "__main__":


    reader1 = Reader(11542) # creating new Reader object reader1

    reader_registration(reader1) # registration of reader1 (1152) with server


    tag1 = Tag(103)   # creating new Tag object tag1
    tag_registration(tag1) # registration of tag1 (101) with server
    # print("Time Consumed in Tag Registration ")
    # print("% s seconds" % (time.time() - start))
    tag2 = Tag(102)  # creating new Tag object(tag2) which is not register with server
    tag2.pid = generateRandom() # assigning fake pid to tag2 object
    tag2.x = generateRandom() # assigning fake x to tag2 object

    # start = time.time()
    print("Authentication result of tag1 using reader1 =>")
    Authentication(reader1, tag1) # trying to authenticate tag1 using reader1
    print("Authentication result of tag2 using reader1 =>")
    Authentication(reader1, tag2) # trying to authenticate tag2 using reader1

    # print("Time Consumed in tag Authentication ")
    # print("% s seconds" % (time.time() - start))
예제 #31
0
     "Updates the volume and volume group tags from the given volume backup id"
 )
 parser.add_argument(
     '--boot_volume_id',
     help=
     "Updates the boot volume and boot volume group tags from the given volume id"
 )
 parser.add_argument(
     '--boot_volume_backup_id',
     help=
     "Updates the boot volume and boot volume group tags from the given boot volume backup id"
 )
 args = parser.parse_args()
 if (args.all):
     from Tag import Tag
     tagObj = Tag()
     tagObj.update_tags_from_compartment()
 else:
     if (args.compartment_id):
         from Tag import Tag
         compartment_id = str(args.compartment_id)
         tagObj = Tag(compartment_id)
         if (args.instance_id):
             instance_id = str(args.instance_id)
             tagObj.update_tags_from_instance(instance_id)
         elif (args.volume_id):
             volume_id = args.volume_id
             tagObj.update_backup_tags_from_volume(volume_id)
         elif (args.boot_volume_id):
             volume_id = args.boot_volume_id
             tagObj.update_backup_tags_from_boot_volume(volume_id)
예제 #32
0
    description = "\n".join([
        "This updates the tags of volumes and volume groups. Logs out on out.log",
        "pip install -r requirements.txt", "python main.py <config_profile>"
    ])
    parser = argparse.ArgumentParser(
        description=description,
        formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("--all",
                        help="Update all the tags in the tenancy",
                        action="store_true")
    parser.add_argument(
        '--compartment_id',
        help=
        "Updates all the volume and backups tag from instances in the specified compartment "
    )
    args = parser.parse_args()
    if (args.all):
        from Tag import Tag
        tagObj = Tag()
        tagObj.update_tags_from_compartment()
    else:
        if (args.compartment_id):
            from Tag import Tag
            compartment_id = str(args.compartment_id)
            tagObj = Tag(compartment_id)
            tagObj.update_tags_from_compartment()
        else:
            print(
                "Please provide --compartment_id or --all. For further run --help"
            )
예제 #33
0
파일: tag_lint.py 프로젝트: 62Gerente/unix
	def run(self):

		begin = time()

		content           = self.content
		original_position = self.original_position
		is_xml            = self.is_xml

		# remove unparseable content

		content = Tag.clean_html(content)

		# linting: opening tags

		data = content.split('<')

		position = original_position+len(data.pop(0))

		invalid_tag_located_at = -1

		i = 0
		lenght = len(data)
		first_at = 0
		while i < lenght:
			tag = Tag.name(data[i], False, is_xml)
			if tag and tag != 'html' and tag != 'body' and tag != 'head':
				# if opening tag, then check if closing tag exists
				if not Tag.is_closing(data[i]):
					# print tag+' is opening '
					if first_at == 0:
						first_at = position
					a = i+1
					skip = 0
					while a < lenght:
						inner_tag_name    = Tag.name(data[a], False, is_xml)
						# check if same tag was found
						if inner_tag_name and inner_tag_name == tag:
							# check if tag is closing
							if Tag.is_closing(data[a]):
								if skip == 0:
									break
								else:
									skip = skip-1
							else:
								skip = skip+1
						a = a+1
					if a >= lenght:
						self.message = '"'+tag+'" tag is not closing'
						invalid_tag_located_at = position
						break
			position += len(data[i])+1
			i = i+1

		# linting: closing tags

		if invalid_tag_located_at == -1:

			position = original_position+len(content);

			data = content.split('<')
			data.reverse()

			i = 0
			lenght = len(data)-1
			while i < lenght:
				tag = Tag.name(data[i], False, is_xml)
				if tag and tag != 'html' and tag != 'body' and tag != 'head':
					# if closing tag, check if opening tag exists
					if Tag.is_closing(data[i]):
						# print tag+' is closing '
						a = i+1
						skip = 0
						while a < lenght:
							inner_tag_name    = Tag.name(data[a], False, is_xml)
							if inner_tag_name and inner_tag_name == tag:
								# check if tag is opening
								if not Tag.is_closing(data[a]):
									if skip == 0:
										break
									else:
										skip = skip-1
								else:
									skip = skip+1
							a = a+1
						if a >= lenght:
							self.message = '"'+tag+'" tag is not opening'
							invalid_tag_located_at = position-(len(data[i])+1)
							if invalid_tag_located_at < first_at:
								invalid_tag_located_at = -1
							break
				position -= len(data[i])+1
				i = i+1

		elapsed_time = time() - begin;

		# print 'Benchmark: '+str(elapsed_time)

		self.invalid_tag_located_at = invalid_tag_located_at

		sublime.set_timeout(lambda:tag_lint.display(self.view, self.message, self.invalid_tag_located_at, self.from_command), 0)
예제 #34
0
import sublime, sublime_plugin
from Tag import Tag

Tag = Tag.Tag()


def plugin_loaded():
    global s
    s = sublime.load_settings('Tag Package.sublime-settings')


class TagCloseTagOnSlashCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        if s.get('enable_close_tag_on_slash') == False:
            self.view.run_command('insert', {"characters": "/"})
            return

        view = self.view
        is_xml = Tag.view_is_xml(view)

        closed_some_tag = False
        new_selections = []
        new_selections_insert = []

        for region in view.sel():
            cursorPosition = region.begin()
            previousCharacter = view.substr(
                sublime.Region(cursorPosition - 1, cursorPosition))

            if '<' == previousCharacter:
                tag = self.close_tag(
예제 #35
0
 def addTag(self, tagId, timeStamp):
     tag = Tag(tagId, timeStamp)
     self.tags.append(tag)
     self.addToUnq(tagId)
 def getTag(self, tag):
   viewCount = self.redisDB.get("Tag:"+tag+":ViewCount")
   if viewCount == None:
     return None
   paperIDs = self.redisDB.zrange("Tag:"+tag+":Papers",0,-1)
   return Tag(tag, viewCount, paperIDs)  
예제 #37
0
import sublime, sublime_plugin
from Tag import Tag

Tag = Tag()


class TagCloseTagCommand(sublime_plugin.TextCommand):
    def run(self, edit):

        view = self.view
        is_xml = Tag.view_is_xml(view)

        closed_some_tag = False
        new_selections = []
        new_selections_insert = []

        for region in view.sel():
            cursorPosition = region.begin()

            tag = self.close_tag(
                view.substr(sublime.Region(0, cursorPosition)), is_xml)

            if tag and tag != '</':
                if region.empty():
                    replace = False
                    view.insert(edit, cursorPosition, tag)
                else:
                    replace = True
                    view.replace(edit,
                                 sublime.Region(region.begin(), region.end()),
                                 '')
예제 #38
0
 def __init__(self, model="JRA55", LatOut=False, LonOut=False, miss=-9999.):
   Tag.__init__(self, model=model, res="bn", miss=miss)
   self.LatIn   = self.Front.Lat
   self.LonIn   = self.Front.Lon
   self.LatOut  = LatOut
   self.LonOut  = LonOut