Esempio n. 1
0
def blog_manager(user, blog_posts, authors):

    # Ask for input from the user which we can check against later. Convert to lowercase to check for fewer cases
    action = raw_input(
        'Would you like to (A)dd a blog post, (S)ee existing posts or (Q)uit? '
    ).lower()

    if action == 'a':
        is_author = raw_input(
            'Are you the author of this post? (y/n) ').lower()
        if is_author == 'y':
            author = user
        else:
            author_name = raw_input('What is the name of the author? ')
            author = Author(author_name)
            authors.append(author)
        title = raw_input('What is the title of the blog post? ')
        published_date = raw_input('When was this published? ')
        b = author.write_blog_post(title, published_date)
        blog_posts.append(b)

        print 'Congratulations! You added post {} for {}'.format(b, author)

        blog_manager(user, blog_posts, authors)
    elif action == 's':
        print blog_posts
        blog_manager(user, blog_posts, authors)
    elif action == 'q':
        print 'Thanks for using the blog!'
    else:
        print 'Sorry, I do not understand what you want.'
        blog_manager(user, blog_posts, authors)
Esempio n. 2
0
 def __init__(self, title: str, isbn: str, price: str, author_name: str,
              author_mail: str) -> None:
     self._title = title
     self._isbn = isbn
     self._price = price
     self._author = Author(author_name, author_mail)
     self._author_mail = author_mail
Esempio n. 3
0
    def __init__(self):
        # class attributes
        self.CurrentData = ""
        self.key = ""
        self.author = ""
        self.title = ""
        self.journal = ""
        self.booktitle = ""
        self.year = 0
        self.type = ""

        # class objects
        self.article = Article()
        self.inproceedings = Inproceedings()
        self.authorObject = Author()

        # help with concat strings
        self.strhelper = StringHelper()
        self.authorStringList = []
        self.titleStringList = []
        self.journalStringList = []
        self.booktitleStringList = []

        #
        self.dbConnector = DBConnector
Esempio n. 4
0
def crawl_one(url_token, db_connection, cookies_str):
    profile = load_profile(url_token, cookies_str)
    if not profile:
        return False
    author = Author(url_token, cookies_str, profile['name'], profile['gender'], profile['avatar_url_template'])
    author.load_answers()
    db_connection.save_author(author)
    return True
Esempio n. 5
0
 def __init__(self, rawgitblame):
     self.hash = None
     self.author = Author(None, None)
     self.committer = Author(None, None)
     self.summary = None
     self.filename = None
     self.content = None
     self.__parse(rawgitblame)
Esempio n. 6
0
def crawl_one(url_token, db_connection, cookies_str):
    profile = load_profile(url_token, cookies_str)
    if not profile:
        return False
    author = Author(url_token, cookies_str, profile['name'], profile['gender'],
                    profile['avatar_url_template'])
    author.load_answers()
    db_connection.save_author(author)
    return True
Esempio n. 7
0
 def update(self, conn, field, new_value):
     for row in self.select(conn):
         author = Author(
             row['id'],
             row['name'],
             row['birth'],
         )
         setattr(author, field, new_value)
         author.save(conn)
Esempio n. 8
0
 def delete(self, conn):
     for row in self.select(conn):
         author = Author(
             row['id'],
             row['name'],
             row['birth'],
         )
         author.delete(conn)
         print("")
Esempio n. 9
0
 def add_new_author(self, appInfo, book):
     author = Author(book.author)
     book_list = [book.name]
     appInfo.authors_database.insert_one({
         "name": book.author,
         "birth_year": 0,
         "death_year": 0,
         "description": '',
         "books": book_list,
         "genres": book.genre_list
     })
     author.add_book(book.name)
     new_window = EditingAuthorMenu(appInfo, author)
     new_window.exec_()
     self.close()
Esempio n. 10
0
def main():
    clean_code = Book("Clean Code", 12.4)
    python = Book("Python Code", 12.4)
    boob = Author("Boob", 23)
    john = Author("John", 5)
    boob.write(clean_code)
    boob.write(python)
    john.write(python)

    print(clean_code.authors)
    print(python.authors)

    ####################################
    print(john.books)
    print(boob.books)
    def test_top_level_meta(self):
        author = Author.create_author("Wouter van Veen")

        path = self._test_path
        meta = Meta.create_top_level_meta(None, author, "")
        dataset = StructuredDataSet.create_dataset(path, "test_meta", meta)
        dataset.write()
Esempio n. 12
0
	def __load_txt(self):
		rn1 = r"(?P<authors>((\pL\. ?(\pL\. )?\pL+,? )|(\pL+ \pL\. ?(\pL\.)?,? )" #regular for authors
		rn2 = r"|(\p{Lu}\p{Ll}+ \p{Lu}\p{Ll}+,? )"
		rn3 = r")+)"
		ra_ru = r"(?P<article>\p{Lu}\p{Ll}+ \p{Ll}+.*?) *\/\/ *" #regular for article
		ra_eng = r"(?P<article>\p{Lu}.*?) *\/\/ *" #regular for article
		rj = r'(?P<source>[ \pL"“”]+)' #regular for source
		rm = r"(?P<misc>.+)" #regular for misc
		reg_ru = re.compile(rn1+rn2+rn3+ra_ru+rj+rm, re.UNICODE)
		reg_eng = re.compile(rn1+rn3+ra_eng+rj+rm, re.UNICODE)
		data = []
		f = open(self.filename, 'r')
		content = f.read()
		items = content.split('\n')
		for item in items:
			res = None
			if isEnglish(item[:15]):
				res = reg_eng.match(item.strip())
			else:
				res = reg_ru.match(item.strip())
			if res != None:
				publication = Publication()
				publication.authors = Author.parseAuthors(res.group("authors"))


				data.append({"authors": split_authors(res.group("authors")), "article": res.group("article"), "source": res.group("source"), "misc": res.group("misc")})
			else:
				print("Wrong line: " + item)
		return data
Esempio n. 13
0
def save():
    index = list_box_for_texts.curselection()[0]
    album[index].title = title_entry.get()
    album[index].author = Author.from_string(author_entry.get())
    title_entry.delete(0, END)
    author_entry.delete(0, END)
    update_list()
Esempio n. 14
0
 def edit_author(self, name, birth_year=0, death_year=0, description=None):
     this_author = Author(name, birth_year, death_year, description)
     if this_author not in self._author_list:
         return False
     self.delete_author(this_author.name)
     self._author_list.append(this_author)
     return True
Esempio n. 15
0
def author_edit_page(author_id):
    searchform = SearchForm()
    db = current_app.config["db"]
    author = db.get_author_by_id(author_id)
    if author is None:
        abort(404)
    if not current_user.is_admin:
        abort(401)
    form = AuthorForm()
    if form.validate_on_submit():
        name = form.data["name"]
        description = form.data["description"]
        photo = form.data["photo"]
        author_ = Author(id=author_id,
                         name=name,
                         description=description,
                         photo=photo)
        db.update_author(author_)
        flash("Author updated successfully.")
        return redirect(url_for("author_page", author_id=author_id))
    form.name.data = author.name
    form.description.data = author.description if author.description else ""
    form.photo.data = author.photo if author.photo else ""
    return render_template("author_edit.html",
                           form=form,
                           searchform=searchform)
Esempio n. 16
0
 def update_book(self, book_id, book):
     with dbapi2.connect(self.db_url) as connection:
         cursor = connection.cursor()
         if book.author is not None:
             if self.get_author(book.author) is None:
                 book.author = self.add_author(Author(name=book.author))
             else:
                 self.update_author(Author(name=book.author))
                 book.author = self.get_author(book.author).id
         query = "UPDATE BOOK SET TITLE = %s, AUTHORID = %s, YR = %s, PGNUM = %s, COVER = %s, DESCRIPTION = %s WHERE (ID = %s)"
         cursor.execute(
             query, (book.title, book.author, book.year, book.pageNumber,
                     book.cover, book.description, book_id))
         connection.commit()
         self.delete_genres(book_id)
         for genre in book.genres:
             self.add_genre(book_id, genre)
Esempio n. 17
0
def author_iterator(n_messages):
  return (
    Author(data["value"]["user"],data["value"]["latest_tweets"]) for data
    in get_list_of_messages_from_unclassified_users(n_messages).find(
      {"value.count": {"$gte": n_messages}},
      {"_id": 0, "value.count": 1, "value.latest_tweets": 1, "value.user": 1}
    )
  )
Esempio n. 18
0
def init():
    print("Begin initialize...")
    db_connection = DBConnection()
    url_token_set = db_connection.restore_url_token()

    origin = Author(ORIGIN_URL_TOKEN, COOKIES_STR, ORIGIN_NAME, ORIGIN_GENDER,
                    ORIGIN_AVATAR_URL_TEMPLATE)
    return db_connection, url_token_set, origin
Esempio n. 19
0
 def author_by_id(self, **query_dict):
     """
     Get information about an author from their id.
     Input example: { 'id' : '2546' }
     """
     goodreads_request = GoodreadsRequest("author/show.xml", query_dict,
                                          self)
     response = goodreads_request.request()
     return Author(response['author'])
Esempio n. 20
0
    def __init__(self, logstring):
        loglist = logstring.split("\n")
        self.hash = loglist[0]
        self.subject = loglist[2]
        self.author = Author(loglist[3], loglist[4])
        self.committer = Author(loglist[5], loglist[6])

        try:
            self.date = datetime.strptime(loglist[1][:-6], "%Y-%m-%dT%H:%M:%S")
        except:
            print "Error parsing date of %s" % logstring
            raise

        try:
            self.diffstats = [Diffstat(diffstat) for diffstat in loglist[8:-1]]
        except:
            print "Error parsing diffstat of %s" % logstring
            raise
Esempio n. 21
0
 def parse(self, response):
     author_name = response.css('h1::text').extract_first()
     author = Author(name=author_name, songs=[])
     song_list = response.css('ul.cnt-list li a')
     for song in song_list:
         title = song.css('::text').extract_first()
         link = song.css('::attr(href)').extract_first()
         author.songs.append(
             Song(author_name, title, config.page_url + link, None))
     self.authors.append(author)
Esempio n. 22
0
    def from_json(path: Path) -> "Meta":
        text = path.read_text()
        json_data = json.loads(text)
        authors = list(
            map(lambda author_content: Author.from_dict(author_content),
                json_data["authors"]))

        return Meta(path, int(json_data["dataset_id"]),
                    int(json_data["branch_id"]), json_data["description"],
                    authors)
Esempio n. 23
0
 def get_author(self, name):
     with dbapi2.connect(self.db_url) as connection:
         cursor = connection.cursor()
         query = "SELECT ID, DESCRIPTION, PHOTO FROM AUTHOR WHERE (NAME = %s)"
         cursor.execute(query, (name, ))
         try:
             id, description, photo = cursor.fetchone()
         except:
             return None
     return Author(name=name, id=id, description=description, photo=photo)
Esempio n. 24
0
 def register_book(book):
     """Регистрация новой книги в магазине."""
     BookStore.book_index.append(book)
     BookStore.log(str(book))
     for edition in book.editions:
         if (BookStore.publisher_index.get(edition.publisher, False)):
             BookStore.publisher_index[edition.publisher].add(edition)
         else:
             from publisher import Publisher
             publisher = Publisher(edition.publisher)
             publisher.add(edition)
             BookStore.publisher_index[edition.publisher] = publisher
     if (BookStore.author_index.get(book.author, False)):
         BookStore.author_index[book.author].add(book)
     else:
         from author import Author
         author = Author(book.author)
         author.add(book)
         BookStore.author_index[book.author] = author
     return BookStore.book_index, BookStore.publisher_index, BookStore.author_index
Esempio n. 25
0
 def __init__(self, author, country, imageLink, language, link, pages,
              title, year):
     self.author = []
     self.author.append(Author(author))
     self.country = country
     self.imageLink = imageLink
     self.language = language
     self.link = link
     self.pages = pages
     self.title = title
     self.year = year
Esempio n. 26
0
def compose_publication(zipped_publication):
    grouped_publication = group_publication(zipped_publication)
    authors = Author.parse_authors(grouped_publication.get("T_AUTHOR"))
    source = Source(grouped_publication.get("T_JOURNAL"))
    misc = Misc(grouped_publication.get("T_LOCATION"),
                grouped_publication.get("T_PUBLISHER"),
                grouped_publication.get("T_YEAR"),
                grouped_publication.get("T_VOLUME"),
                grouped_publication.get("T_PAGES"))
    return Publication(grouped_publication.get("T_TITLE"), authors, source,
                       misc)
Esempio n. 27
0
def updateState(author: Author, url_token_set: set, waiting_list: Queue):
    url_token_set.add(author.url_token)
    for followee in author.followees:
        if followee['user_type'] != 'people' or\
           followee['follower_count'] < 100 or \
           followee['url_token'] in url_token_set:
            continue
        next_author = Author(followee['url_token'], COOKIES_STR,
                             followee['name'], followee['gender'],
                             followee['avatar_url_template'])
        waiting_list.put(next_author)
Esempio n. 28
0
   def __init__(self):

      self.series = Series()
      self.author = Author()
      self.book = Book()
      self.whenRead = WhenRead()

      #establish list of fields the book method is purely responsible for
      # updating
      self.bookOnlyFields = ['book_id', 'title', 'notes', 'published',
                             'owner_status_id', 'read_status_id', 'type_id', 
                             'series_num']
Esempio n. 29
0
def addBook():
    authorNameInput = str(input('Enter author name: '))
    authorEmailInput = str(input('Enter author email: '))
    authorGenderInput = str(input('Enter author gender: '))

    bookNameInput = str(input('Enter book name: '))
    bookPriceInput = float(input('Enter book price: '))
    bookQtyInput = int(input('Enter book quantity: '))

    atInput = Author(authorNameInput, authorEmailInput, authorGenderInput)
    atList.append(atInput)
    bookList.append(Book(bookNameInput, atInput, bookPriceInput, bookQtyInput))
Esempio n. 30
0
def add_authors(authProfiles):
    """Add a list of authors"""
    formatted = [Author(
        name=i['name'], 
        gs_profile_id=i['gs_profile_id'], 
        affiliation=i['affiliation'], 
        interest=', '.join(i['interest'])
        ) for i in authProfiles]
    print('WRITE: %d authors to database...' % len(authProfiles))
    session.add_all(formatted)
    queue_todo(formatted, AUTHOR)
    session.commit()
Esempio n. 31
0
 def __init__(self, appInfo, author):
     super(EditingAuthorMenu, self).__init__()
     loadUi('adding_author.ui', self)
     this_author = Author()
     for book in author.book_list:
         this_author.add_book(book)
     for genre in author.genre_list:
         this_author.add_genre(genre)
     appInfo.library.delete_author(author.name)
     self.lineEdit.setText(author.name)
     self.lineEdit_2.setText(str(author.birth_year))
     self.lineEdit_3.setText(str(author.death_year))
     self.textEdit.setText(author.description)
     self.pushButton_8.clicked.connect(self.closing)
     self.pushButton_9.clicked.connect(
         lambda: self.adding(appInfo, this_author, author.name))
     self.pushButton_5.clicked.connect(
         lambda: self.adding_book(this_author, appInfo))
     self.pushButton_6.clicked.connect(
         lambda: self.adding_genre(this_author))
     self.pushButton_10.clicked.connect(
         lambda: self.delete_book(this_author))
     self.pushButton_11.clicked.connect(
         lambda: self.delete_genre(this_author))
     self.update_tables(this_author)
Esempio n. 32
0
def get_team(user):
    logging.debug(f'In get_teams: Cookies: {request.cookies}')
    logging.debug(f'In get_t teams: session: {session}')

    if 'oauth_token' not in session.keys():
        return 'Login first'
    github = OAuth2Session(
        app.config['CLIENT_ID'], token=session['oauth_token'])
    author = Author(github, user)
    if not author:
        logging.debug( 'User login is not valid')
    team_comments = author.get_team_by_pullrequests()
    logging.debug(f'by comments: {team_comments}')

    team_close_commits = author.get_team_by_close_commits()
    logging.debug(f'by close commits: {team_close_commits}')

    team_followers = author.get_followers()
    logging.debug(f'by followers: {team_followers}')

    team_following = author.get_following()
    team = combineTeams(team_followers, team_following,
                        team_close_commits, team_comments, user)
    logging.debug(f'all teammates: {team}')

    resp = jsonify({'team': team})

    resp.headers['Access-Control-Allow-Credentials'] = "true"
    resp.headers['Access-Control-Allow-Origin'] = URL

    return resp
    def test_branching(self):
        author = Author.create_author("Wouter van Veen")

        path = self._test_path
        meta = Meta.create_top_level_meta(None, author, "")
        dataset = StructuredDataSet.create_dataset(path, "test_meta_branching",
                                                   meta)

        x = dataset["x"]

        x["xx"] = numpy.zeros(30)

        dataset.write()
        x.meta.write()
Esempio n. 34
0
    def __init__(self, form_dict):
        """initialize variables and bring in column metadata"""
        self.book_id = form_dict["book_id"]
        self.activity = form_dict["activity"]
        self.connection = getDictConnection()
        self.columns = loadYaml("columns")
        self.author = Author()
        self.record_dict = dict.copy(form_dict)
        self.added_new_rec = False

        del self.record_dict["book_id"]
        del self.record_dict["activity"]

        if self.activity == "submit_new":
            start_sql = 'insert into book (title) values ("starter")'
            start = execute(self.connection, start_sql)
            find_sql = "select book_id from book where title like 'starter'"
            find = execute(self.connection, find_sql)
            self.book_id = find[0]["book_id"]
            self.activity = "update"
            self.added_new_rec = True
Esempio n. 35
0
class Record:
    """Preside over a single record in the database
        including updating it"""

    def __init__(self, form_dict):
        """initialize variables and bring in column metadata"""
        self.book_id = form_dict["book_id"]
        self.activity = form_dict["activity"]
        self.connection = getDictConnection()
        self.columns = loadYaml("columns")
        self.author = Author()
        self.record_dict = dict.copy(form_dict)
        self.added_new_rec = False

        del self.record_dict["book_id"]
        del self.record_dict["activity"]

        if self.activity == "submit_new":
            start_sql = 'insert into book (title) values ("starter")'
            start = execute(self.connection, start_sql)
            find_sql = "select book_id from book where title like 'starter'"
            find = execute(self.connection, find_sql)
            self.book_id = find[0]["book_id"]
            self.activity = "update"
            self.added_new_rec = True

    def debug(self):
        return self.record_dict, self.processRecordDict()

    def updateRecord(self):
        """ given a dict of column value pairs
        figure out which should be updated
        update tables with new vals if necessary
        return two lists: changes made, values added"""

        book_items = {}
        update_dict = {}
        when_read_items = {}
        series_items = {}
        updated = {}
        added = {}
        removed = {}

        # sort and pre-process dict
        update_dict, author_items = self.processRecordDict()

        if update_dict:
            for column, value in update_dict.items():

                record_table = ""

                # figure out which table needs to be updated, amend that dict{}
                record_table = self.columns[column][0]["from"]

                if record_table == "book":
                    book_items.update({column: value})
                if record_table == "when_read":
                    when_read_items.update({column: value})
                if record_table == "series":
                    series_items.update({column: value})

            if book_items:
                book_updates, book_adds = self.updateBook(book_items)
                updated.update(book_updates)
                added.update(book_adds)

            if series_items:
                series_updates, series_adds = self.updateSeries(series_items)
                updated.update(series_updates)
                added.update(series_adds)

            if when_read_items:
                when_updates, when_adds = self.updateWhenRead(when_read_items)
                updated.update(when_updates)
                added.update(when_adds)

        # send author_items out to be handled
        #        author_updates = self.updateAuthor(author_items)
        #        updated.update(author_updates)

        if self.added_new_rec:
            return self.book_id

        else:
            return updated, added

    def updateBook(self, book_items):
        updates = {}
        adds = {}

        if self.activity == "update":
            for item in book_items:
                sql = "update book set %s = %s where book.book_id = %s" % (item, book_items[item], self.book_id)
                results = execute(self.connection, sql)
                updates[item] = book_items[item]

        return updates, adds

    def updateSeries(self, series_items):
        series_id = "NULL"
        series = series_items["series"]
        updates = {}
        adds = {}

        # if the series recieved isn't blank, check if it is in the DB yet
        # if not add it and append message with that info
        # retrieve the series_id for the requested series
        if series != "''":
            searchSQL = "select series from series where series like %s" % series
            searchResults = execute(self.connection, searchSQL)

            if not searchResults:
                addSQL = "insert into series (series) values (%s)" % series
                addResults = execute(self.connection, addSQL)
                adds["series"] = series

            IdSQL = "select series_id from series where series like %s" % series
            IdResults = execute(self.connection, IdSQL)

            series_id = IdResults[0]["series_id"]

        # set the series_id in the book table to the correct series
        updateSQL = "update book set series_id = %s where book_id = %s" % (series_id, self.book_id)
        updateReults = execute(self.connection, updateSQL)
        updates["series"] = series
        return updates, adds

    def updateWhenRead(self, when_read_items):
        updates = {}
        adds = {}
        when = when_read_items["when_read"]

        if when != "":
            when = (datetime.strptime(when, "%m/%d/%Y")).date()
            when = when.isoformat()
            sql = "insert into when_read (when_read, book_id) values (%s, %s)" % (when, self.book_id)
            results = execute(self.connection, sql)
            adds["when_read"] = when

        return updates, adds

    def updateAuthor(self, author_items):
        firstLast = author_items.copy()
        fullNames = []
        listofAuthors = []
        authorIdDict = self.author.getAuthorIdDict()
        add = []
        remove = []
        update = {}

        # make a list of full names and a seperate dict for first and last name
        for item in author_items:
            if "full" in str(item):
                fullNames.append(author_items[item])
                del firstLast[item]

        # If any item in firstLast has a value set newName to true
        newName = False
        for key, value in firstLast.items():
            if value:
                newName = True

        # bring in the data currently in the DB
        authorsOnRecord = self.author.getAuthors(self.book_id, "concat")

        # make a list of full names in the DB
        for count in range(len(authorsOnRecord)):
            listofAuthors.append(authorsOnRecord[count]["name"])

        # compare the list of full names currently in the DB to the
        # full names in author items to see what has to be added or removed
        for item in listofAuthors:
            if item not in fullNames:
                remove.append(item)
        for item in fullNames:
            if item not in listofAuthors:
                add.append(item)

        # check if the new first and last name is in the DB yet
        if newName:
            sql = """                                                        
               select author_id from author                                   
               where last_name like '%s' and first_name like '%s'              
               """ % (
                author_items["author_last_name"],
                author_items["author_first_name"],
            )
            matches = execute(self.connection, sql)

            # if the name is not in the DB add it and refresh the authorIdDict
            if not matches:
                sql = """
                      insert into author (last_name, first_name)
                      values ('%s', '%s')
                      """ % (
                    author_items["author_last_name"],
                    author_items["author_first_name"],
                )
                results = execute(self.connection, sql)
                authorIdDict = self.author.getAuthorIdDict()

            # concat the first and last name add it to add list
            name = "%s, %s" % (author_items["author_last_name"], author_items["author_first_name"])
            add.append(name)

        # add the book_id/author_id pairs to the book_author table
        for item in add:
            author_id = authorIdDict[item]
            sql = """insert into book_author (author_id, book_id)
                   values (%s, %s)""" % (
                author_id,
                self.book_id,
            )
            results = execute(self.connection, sql)
            update[item] = "added to record"

        # remove the book_id/author_id pairs from the book_author table
        for item in remove:
            author_id = authorIdDict[item]
            sql = """delete from book_author
                  where book_id = %s and author_id = %s                      
                  """ % (
                self.book_id,
                author_id,
            )
            results = execute(self.connection, sql)
            update[item] = "removed from record"

        return update

    def processRecordDict(self):
        """given a dict of record items to update prepare them for DB insertion
        by: segregating author items from dict, calling selectDiffColumns,
        prepping the formats of the remaining values for insertion. Returns
        update_dict and author_items"""

        process_dict = dict.copy(self.record_dict)

        author_items = {}
        # find all keys with author in them, add those to author items
        for item in process_dict:
            if "author" in str(item):
                author_items[item] = process_dict[item]

        # remove all the stuff in author items from record dict
        for item in author_items:
            del process_dict[item]

        # if the acitvity is 'edit'call selectDiffCols on the remaining dict
        # if that returns any values format them for the DB and return them
        # otherwise all values need to be processed
        if self.activity == "update":
            update_dict = self.selectDiffColumns(process_dict)
        else:
            update_dict = process_dict

        if update_dict:
            for column, value in update_dict.items():
                colType = self.columns[column][0]["type"]

                # prep dic vlaues for database update
                if colType == "string" or colType == "int":
                    if value:
                        update_dict[column] = "'" + value + "'"
                    else:
                        update_dict[column] = "'" + "'"

        return update_dict, author_items

    def selectDiffColumns(self, recievedData):
        """ given a dic of data recieve about a record
            compare it to the data in the DB
            remove entries in the recieved dictionary that already exist
            return truncated dict"""
        query = Query()
        where = "book.book_id =" + str(self.book_id)
        recordData = query.getData("edit", where)
        remove = []
        for col, val in recordData[0].items():
            if val == "":
                recordData[0][col] = None
            else:
                recordData[0][col] = str(val)

        for col in recievedData:
            if recievedData[col] == recordData[0][col]:
                remove.append(col)
        for col in remove:
            del recievedData[col]

        return recievedData
Esempio n. 36
0
#!/usr/bin/env python

from author import Author
#from authors import Authors

# build report body:
authors = Author()
count = authors.countAuthors()
body = "<p>There are %s authors in the library.</p>" % count

# Output HTML
print 'Content-Type: text/html\n'

print "<html>"
print "<h3>Count Authors</h3>"
print body
print "</html>"
Esempio n. 37
0
def parse_file(filename):
    """
    parse a file and create a set of authors
    :param filename: file to parse
    :return: set of author elements
    """

    authors = set()
    firstline = True # ignore the first line

    with open(filename, 'r') as f:
        for l in f:
            if firstline:
                firstline = False
                continue
            p = l.rstrip().split("\t")

            if len(p) < 15:
                sys.stderr.write("ERROR: Malformed: {}\t{}\n".format(len(p), p))
                continue

            auth = Author(p[2])

            try:
                if p[1]:
                    auth.orcid = p[1]
                if p[3]:
                    auth.lastname = p[3]
                    auth.lastnamelower = p[3].lower()
                if p[4]:
                    auth.firstname = p[4]
                    auth.firstnamelower = p[4].lower()
                if p[5]:
                    auth.middleinitial = p[5]
                if p[6]:
                    auth.email = p[6].replace(' ', '')
                if p[14]:
                    auth.order = int(p[14])
                if p[15]:
                    auth.contribution = p[15]

                primary = Address()
                if p[7]:
                    primary.department = p[7]
                if p[8]:
                    primary.institution = p[8]
                if p[9]:
                    primary.street = p[9]
                if p[10]:
                    primary.city = p[10]
                if p[11]:
                    primary.state = p[11]
                if p[12]:
                    primary.zip = p[12]
                if p[13]:
                    primary.country = p[13]

                auth.primaryaddress = primary

                secondary = Address()
                if len(p) > 17 and p[17]:
                    secondary.department = p[17]
                if len(p) > 18 and p[18]:
                    secondary.institution = p[18]
                if len(p) > 19 and p[19]:
                    secondary.street = p[19]
                if len(p) > 20 and p[20]:
                    secondary.city = p[20]
                if len(p) > 21 and p[21]:
                    secondary.state = p[21]
                if len(p) > 22 and p[22]:
                    secondary.zip = p[22]
                if len(p) > 23 and p[23]:
                    secondary.country = p[23]

                if secondary.is_valid():
                    auth.secondaryaddress = secondary
            except Exception as err:
                sys.stderr.write("Error parsing {}: {}\n".format(p[2], err))
                continue

            authors.add(auth)
    return authors
Esempio n. 38
0
class DetailProcessor():

   def __init__(self):

      self.series = Series()
      self.author = Author()
      self.book = Book()
      self.whenRead = WhenRead()

      #establish list of fields the book method is purely responsible for
      # updating
      self.bookOnlyFields = ['book_id', 'title', 'notes', 'published',
                             'owner_status_id', 'read_status_id', 'type_id', 
                             'series_num']

   def processForm(self, formDict):

      message = 'Record Updated'
      book_id = formDict['book_id']
      #if the record is new first call the add new book method, reciecve a new
      # book_id, append it to the dictionary
      # the send the dictionary to the update methods
      if formDict['activity'] == 'submit_new':
         book_id = self.book.addBook()
         formDict['book_id'] = book_id
         message = 'Record Added'

      bookDict = {}
      #create a special dictionary of fields the book method is responsible for
      # updating itself.
      for field in self.bookOnlyFields:
         bookDict[field] = formDict[field]

      #run the seriesUpdate method which will add a series to the DB if
      # necessary. append the new series id to the  bookDict
      seriesUpdate = self.series.updateSeries(formDict)
      bookDict['series_id'] = seriesUpdate

      bookUpdate = self.book.updateBook(bookDict)
      authorUpdate = self.author.updateAuthor(formDict)

      if formDict['when_read'] != '':
         dateUpdate = self.whenRead.updateWhenRead(formDict)

      #message =  self.buildMessasge() # insert all update return values
      return message, book_id

   def buildMessage(self, updated, added= None):
      '''accepts dict of fields updated and their new values
      returns properly formatted string for message display'''

      updates = ''
      adds = ''
      
      if updated:
         updates = 'Updated: <br> '
         for item in updated:
            if item in self.columns:
               d_name = self.columns[item][0]['display']
               updates += '%s changed to:  %s <br>'\
                   %(d_name, updated[item])
            else:
               updates += '%s was %s <br>' %(item, updated[item])

      if added:
         adds = 'Added: <br> '
         for item in added:
            adds += '%s: %s ' %(item, added[item])

      message = 'For this record the following fields were <br> %s %s'\
          %(updates, adds)

      if not added and not updated:
         message = 'Message: No fields changed, no updates made'
        
      return message
Esempio n. 39
0
    def get_authors(self):
        authors = self.xml.get_nodes('Creator')
        r_authors = []
        #self.debug = True
        for author in authors:
            #print(author)
            #print(type(author))
            a = Author()

            a.set_author_id(self.xml.get_text('CreatorID', author))
            a.set_author_date(self.xml.get_text('Dates', author))
            a.set_author_loc(self.xml.get_text('Location', author))
            a.set_author_name(self.xml.get_text('Name', author))
            a.set_author_num(self.xml.get_text('Numeration', author))
            a.set_author_role(self.xml.get_text('Role', author))
            a.set_author_title(self.xml.get_text('Title', author))
            a.set_author_unit(self.xml.get_text('Unit', author))
            if self.debug:
                print('xxx---------  ')
                print(a.get_author_id())
                print(a.get_author_date())
                print(a.get_author_loc())
                print(a.get_author_name())
                print(a.get_author_num())
                print(a.get_author_role())
                print(a.get_author_title())
                print(a.get_author_unit())
                print('---------  ')
            r_authors.append(a)
        #self.debug = False
        return r_authors
Esempio n. 40
0
#!/usr/bin/env python
from author import Author
import sqlite3
import sys

if len(sys.argv) != 3:
    print("ERROR: Author's name and date of birth (YYYY-MM-DD) must be specified")
    sys.exit(1)

conn = sqlite3.connect('../db/books.db')
new_author = Author(None, sys.argv[1], sys.argv[2])
new_author.save(conn)
print(
    'Author {}, born on {}, inserted with id {}'.format(
        new_author.name,
        new_author.birth,
        new_author.id,
    ))
conn.close()
Esempio n. 41
0
#!/usr/bin/env python

from author import Author
#from authors import Authors

# build report body:
authors = Author()
results = authors.booksByAuthor()

# build html table
table = '<table border="1" cellpadding="3" cellspacing="0">\n'
table += ' <tr><th>Author</th><th>Books</th></tr>\n'
for r in results:
    table += ' <tr><td>%s</td><td align="right">%s</td></tr>\n' % r
table += '</table>\n'

# Output HTML
print 'Content-Type: text/html\n'

print "<html>"
print "<h3>Books by Author</h3>"
print table
print "</html>"