예제 #1
0
파일: DAO.py 프로젝트: joubu/CDL
    def reload_config(cls):
        from modele import Config, Category
        dir_user = unicode(os.path.join(os.path.expanduser("~"), 'Canal_DL'))
        player = u'vlc'

        c = Config(dir_user, player)
        base_url_1 = u"http://service.canal-plus.com/video/rest/search/cplus/"
        base_url_2 = u"http://service.canal-plus.com/video/rest/getMEAs/cplus/"
        categories = {
                 "pepites": { "code": u"PEPITES_SUR_LE_NET", "url": base_url_1 + u"pepites"},
                 "guignols": { "code": u"LES_GUIGNOLS", "url":  base_url_1 + u"guignols"},
                 "grand": { "code": u"LE_GRAND_JOURNAL", "url":  base_url_2 + u"39"},
                 "groland": { "code": u"GROLAND", "url": base_url_2 + u"130"},
                 "petit": { "code": u"LE_PETIT_JOURNAL", "url": base_url_1 + u"petit"},
                 "jt": { "code": u"LE.JT.DE.CANAL", "url": base_url_2 + u"39"},
                 "explorateurs": { "code": u"LES_NOUVEAUX_EXPLORATEURS", "url": base_url_1 + u"LES_NOUVEAUX_EXPLORATEURS"},
                 "supplement": { "code": u"LE_SUPPLEMENT", "url": base_url_2 + u"1080"},
                 "links": { "code": u"L_OEIL_DE_LINKS", "url": base_url_1 + u"L_OEIL_DE_LINKS"},
                 "salut": { "code": u"SALUT_LES_TERRIENS", "url": base_url_1 + u"SALUT_LES_TERRIENS"},
                 "zapping": { "code": u"ZAPPING", "url": base_url_2 + u"39"}
                }

        for k, v in categories.iteritems():
            c.categories_availables.append(
                Category(k, dir_user, v['code'], v['url'], create_path=True)
            )

        petit = session.query(Category).filter(Category.name==u'petit').first()
        zapping = session.query(Category).filter(Category.name==u'zapping').first()
        c.categories.append(petit)
        c.categories.append(zapping)

        cls.commit()

        return c
예제 #2
0
def compress_smallest_box():
	last_box = session.query(func.max(sqlalchemy.cast(InvCard.box, sqlalchemy.Integer))).first()[0]
	box_capacity = list(metadata.bind.execute("select box,60 - count(*) as c from inv_cards where box not null group by box having c>0 order by c desc;"))
	remove_box = box_capacity[0][0]
	box_capacity = box_capacity[1:]

	cards_in_remove_box = InvCard.query.filter_by(box=str(remove_box)).order_by(InvCard.box_index.desc()).all()

	move_orders = fit_boxes(box_capacity, len(cards_in_remove_box))
	i=0

	print "********** move %d cards from box %s **********" % (60-box_capacity[0][1], remove_box)
	print "\tall boxes: %s" % sorted([int(x) for x in [remove_box] + [b for b,o in move_orders]])
	for box, count in move_orders:
		max_index = session.query(func.max(InvCard.box_index)).filter_by(box=box).one()[0]
		print "======= moving %d cards to box %s ======" % (count, box)
		for card in cards_in_remove_box[i:count+i]:
			print u"move %s to %s/%d" % (card, box, max_index)
			max_index += 1
			card.box = box
			card.box_index = max_index
		i+=count
	
	if remove_box != last_box:
		cards_in_last_box = InvCard.query.filter_by(box=str(last_box)).order_by(InvCard.box_index).all()
		print "********** finally, move all %d cards from %s to %s **********" % (len(cards_in_last_box),last_box, remove_box)
		for card in cards_in_last_box:
			card.box = remove_box
	raw_input()
	session.commit()
예제 #3
0
def compress_smallest_box():
	last_box = session.query(func.max(sqlalchemy.cast(InvCard.box, sqlalchemy.Integer))).first()[0]
	box_capacity = list(metadata.bind.execute("select box,60 - count(*) as c from inv_cards where box not null group by box having c>0 order by c desc;"))
	if len(box_capacity) <= 0:
		raise Exception("there are no boxes in inventory to compress")
	remove_box = box_capacity[0][0]
	box_capacity = box_capacity[1:]

	cards_in_remove_box = InvCard.query.filter_by(box=str(remove_box)).order_by(InvCard.box_index.desc()).all()

	move_orders = fit_boxes(box_capacity, len(cards_in_remove_box))
	i=0

	print "********** move %d cards from box %s **********" % (60-box_capacity[0][1], remove_box)
	print "\tall boxes: %s" % sorted([int(x) for x in [remove_box] + [b for b,o in move_orders]])
	for box, count in move_orders:
		max_index = session.query(func.max(InvCard.box_index)).filter_by(box=box).one()[0]
		print "======= moving %d cards to box %s ======" % (count, box)
		for card in cards_in_remove_box[i:count+i]:
			print u"move %s to %s/%d" % (card, box, max_index)
			max_index += 1
			card.box = box
			card.box_index = max_index
		i+=count
	
	if remove_box != last_box:
		cards_in_last_box = InvCard.query.filter_by(box=str(last_box)).order_by(InvCard.box_index).all()
		print "********** finally, move all %d cards from %s to %s **********" % (len(cards_in_last_box),last_box, remove_box)
		for card in cards_in_last_box:
			card.box = remove_box
	raw_input()
	session.commit()
예제 #4
0
파일: DAO.py 프로젝트: joubu/CDL
 def downloads(cls):
     try:
         from modele import Download, Config
         url_blacklist = [e.url for e in 
                 session.query(Config).first().blacklist]
                     
         return session.query(Download).filter(
                 not_(Download.url.in_(url_blacklist))).all()
     except Exception, e:
         return None
예제 #5
0
파일: DAO.py 프로젝트: joubu/CDL
    def downloads(cls):
        try:
            from modele import Download, Config
            url_blacklist = [
                e.url for e in session.query(Config).first().blacklist
            ]

            return session.query(Download).filter(
                not_(Download.url.in_(url_blacklist))).all()
        except Exception, e:
            return None
예제 #6
0
 def test_setup_then_teardown(self):
     try:
         from elixir import session as elixir_session
     except ImportError:
         from elixir import objectstore as elixir_session
     
     eq_(len(elixir_session.query(self.CategoryEntity).all()), 0)
     
     data = self.fixture.data(self.CategoryData)
     data.setup()
     
     eq_(len(elixir_session.query(self.CategoryEntity).all()), 2)
     
     data.teardown()
     eq_(elixir_session.query(self.CategoryEntity).all(), [])
예제 #7
0
    def test_setup_then_teardown(self):
        try:
            from elixir import session as elixir_session
        except ImportError:
            from elixir import objectstore as elixir_session

        eq_(len(elixir_session.query(self.CategoryEntity).all()), 0)

        data = self.fixture.data(self.CategoryData)
        data.setup()

        eq_(len(elixir_session.query(self.CategoryEntity).all()), 2)

        data.teardown()
        eq_(elixir_session.query(self.CategoryEntity).all(), [])
예제 #8
0
 def get_query(self):
     """:return: an sqlalchemy query for all the objects that should be
     displayed in the table or the selection view.  Overwrite this method to
     change the default query, which selects all rows in the database.
     """
     from elixir import session
     return session.query(self.entity)
예제 #9
0
def entity_setstate(entity, d):
    """Set the state of an SQLAlchemy entity

    In:
      - ``entity`` -- the newly created and not yet initialized SQLAlchemy entity
      - ``d`` -- the state dictionary (created by ``entity_getstate()``)
    """
    # Copy the _not_ SQLAlchemy managed attributes to our entity
    key = d.pop('_sa_key', None)
    entity.__dict__.update(d)

    if key is not None:
        # Fetch a new and initialized SQLAlchemy from the database
        x = session.query(entity.__class__).get(key)
        session.expunge(x)

        # Copy its state to our entity
        entity.__dict__.update(x.__dict__)

        # Adjust the entity SQLAlchemy state
        state = x._sa_instance_state.__getstate__()
        state['instance'] = entity
        entity._sa_instance_state.__setstate__(state)

        # Add the entity to the current database session
        session.add(entity)
예제 #10
0
def entity_setstate(entity, d):
    """Set the state of an SQLAlchemy entity

    In:
      - ``entity`` -- the newly created and not yet initialized SQLAlchemy entity
      - ``d`` -- the state dictionary (created by ``entity_getstate()``)
    """
    # Copy the _not_ SQLAlchemy managed attributes to our entity
    key = d.pop('_sa_key', None)
    entity.__dict__.update(d)

    if key is not None:
        # Fetch a new and initialized SQLAlchemy from the database
        x = session.query(entity.__class__).get(key)
        session.expunge(x)

        # Copy its state to our entity
        entity.__dict__.update(x.__dict__)

        # Adjust the entity SQLAlchemy state
        state = x._sa_instance_state.__getstate__()
        state['instance'] = entity
        entity._sa_instance_state.__setstate__(state)

        # Add the entity to the current database session
        session.add(entity)
예제 #11
0
def run_scan_setup(cam_index=0):
    setup_all(True)

    cam = cv.CreateCameraCapture(cam_index)
    scan_card.setup_windows()

    # main loop
    run = True
    while run:
        # for now, name the next box as the largest integer box name, +1
        current_max_box = session.query(func.max(sqlalchemy.cast(InvCard.box, sqlalchemy.Integer))).first()[0]
        if current_max_box is None:
            # if there is no current box, just start at 1
            next_box = 1
        else:
            next_box = current_max_box + 1

        print "box to scan[%02d]: " % next_box,
        answer = ("%s" % raw_input().rstrip())
        if answer != '' and answer != 'q':
            next_box = answer
            capture_box(cam, next_box)
        if answer == 'q':
            run = False
            run_match()
예제 #12
0
파일: db.py 프로젝트: Xifax/suzu
 def addItemsToDbGrade(self, grade):
     success = False
     try:
         grade = int(grade)
         if 0 < grade < 11:
             selection = self.db.character.filter(self.db.character.grade==grade).all()
             
             now = datetime.now()
             grade = u'grade' + str(grade)
             
             for kanji in selection:
                 if session.query(Kanji).filter_by(character = kanji.literal).count()  == 0:
                     Kanji(character = kanji.literal, tags = grade, next_quiz = now, leitner_grade = Leitner.grades.None.index, active = True, 
                     current_session = False, been_in_session = 0)
             
             success = True
             try: 
                 session.commit()
             except IntegrityError:
                 session.rollback()
                 success = False
     except:
         success = False
         
     return success
예제 #13
0
파일: DAO.py 프로젝트: joubu/CDL
 def category(cls, name):
     try:
         from modele import Category
         return session.query(Category).filter(
             Category.name == name).first()
     except:
         return None
예제 #14
0
파일: DAO.py 프로젝트: joubu/CDL
 def download(cls, url, category, description, name):
     from modele import Download
     try:
         download = session.query(Download).filter(Download.url==unicode(url)).one()
         return download
     except:
         return Download(url, category, name, description)
예제 #15
0
파일: db.py 프로젝트: Xifax/suzu
 def addItemsToDbJlpt(self, jlptGrade):
     success = False
     try:
         jlptGrade = int(jlptGrade)
         if 0 < jlptGrade < 5:
             selection = self.db.character.filter(self.db.character.jlpt==jlptGrade).all()
             #time for next quiz
             now = datetime.now()
             
             jlpt = u'jlpt' + str(jlptGrade)
             
             for kanji in selection:
                 #check if already exists    (time consuming?)
                 #if len(Kanji.query.filter_by(character = kanji.literal).all()) == 0:
                 if session.query(Kanji).filter_by(character = kanji.literal).count()  == 0:
                 # for easier management
                     Kanji(character = kanji.literal, tags = jlpt, next_quiz = now, leitner_grade = Leitner.grades.None.index, active = True, 
                     current_session = False, been_in_session = 0)
                 success = True
             try: 
                 session.commit()
             except IntegrityError:
                 session.rollback()      #is it ok in case just one item err'd?
                 success = False
     except ValueError, e:
         log.error(e)
예제 #16
0
 def test_delete_entity(self):
     fr = self.article.add_locale('fr', title='Les mille et une nuits', content=u"J'ai entendu dire, Ô mon roi, dit Scheherazade")
     session.commit()
     session.expunge_all()
     article = Article.get(1)
     session.delete(article)
     session.commit()
     assert session.query(Article.__localized_class__).count() == 0
예제 #17
0
파일: DAO.py 프로젝트: joubu/CDL
    def config(cls):
        from modele import Config
        try:
            config = session.query(Config).all()[-1]
        except:
            config = cls.reload_config()

        return config
예제 #18
0
    def get_query(self):
        """:return: an sqlalchemy query for all the objects that should be
        displayed in the table or the selection view.  Overwrite this method to
        change the default query, which selects all rows in the database.
        """
        from elixir import session

        return session.query(self.entity)
예제 #19
0
파일: db.py 프로젝트: Xifax/suzu
 def addItemsToDb(self, jlpt=-1, grade=-1, frequency=0, compare='='):
     success = False
     
     if frequency == 0:
         try:
             jlpt = int(jlpt)
             grade = int(grade)
             
             if (0 < grade < 11) or (0 < jlpt < 5):
                 #if jlpt != '-1':
                 #elif grade != '-1':
                 selection = self.db.character.filter(or_(self.db.character.grade==grade, self.db.character.jlpt==jlpt)).all()   #add timers
                 
                 now = datetime.now()
                 grade = u'grade' + str(grade)
                 jlpt = u'jlpt' + str(jlpt)
                 
                 for kanji in selection:
                     if session.query(Kanji).filter_by(character = kanji.literal).count()  == 0:
                         Kanji(character = kanji.literal, tags = jlpt + u';' + grade, next_quiz = now, leitner_grade = Leitner.grades.None.index, active = True, 
                         current_session = False, been_in_session = 0)
                 
                 success = True
                 try: 
                     session.commit()
                 except IntegrityError:
                     session.rollback()
                     success = False
         except:
             success = False
     elif frequency > 0:
         
         selection = self.db.character.filter(self.db.character.freq==frequency).all()
         for kanji in selection:
                     if session.query(Kanji).filter_by(character = kanji.literal).count()  == 0:
                         Kanji(character = kanji.literal, tags = u'', next_quiz = now, leitner_grade = Leitner.grades.None.index, active = True, 
                         current_session = False, been_in_session = 0)
                 
         success = True
         try:
             session.commit()
         except IntegrityError:
             session.rollback()
             success = False
         
     return success
예제 #20
0
파일: DAO.py 프로젝트: joubu/CDL
 def download(cls, url, category, description, name):
     from modele import Download
     try:
         download = session.query(Download).filter(
             Download.url == unicode(url)).one()
         return download
     except:
         return Download(url, category, name, description)
예제 #21
0
파일: DAO.py 프로젝트: joubu/CDL
    def config(cls):
        from modele import Config
        try:
            config = session.query(Config).all()[-1]
        except:
            config = cls.reload_config()

        return config
예제 #22
0
    def getTagsRelated(self, tags):
        tags = make_list(tags)

        tasks = session.query(Task.id).filter(
            Task.tags.any(Tag.title.in_(tags)))
        task_ids = [t[0] for t in tasks]
        new_tags =  Tag.query.filter(Tag.tasks.any(Task.id.in_(task_ids))) \
                             .filter(not_(Tag.title.in_(tags)))
        return new_tags.all()
예제 #23
0
파일: __init__.py 프로젝트: Ting-Hua/gtdzen
    def getTagsRelated(self, tags):
        tags = make_list(tags)

        tasks = session.query(Task.id).filter(
                    Task.tags.any(Tag.title.in_(tags)))
        task_ids = [t[0] for t in tasks]
        new_tags =  Tag.query.filter(Tag.tasks.any(Task.id.in_(task_ids))) \
                             .filter(not_(Tag.title.in_(tags)))
        return new_tags.all()
예제 #24
0
파일: DAO.py 프로젝트: joubu/CDL
 def already_downloaded(cls, url):
     try:
         from modele import Video
         video = session.query(Video).filter(Video.url==url).first()
         if video:
             return True
         return False
     except:
         return False
예제 #25
0
파일: DAO.py 프로젝트: joubu/CDL
 def already_downloaded(cls, url):
     try:
         from modele import Video
         video = session.query(Video).filter(Video.url == url).first()
         if video:
             return True
         return False
     except:
         return False
예제 #26
0
파일: db.py 프로젝트: Xifax/suzu
 def countItemsByGrades(self):
     results = {}
     i = 1
     jlpt = u'jlpt'
     grade = u'grade'
     
     while True:    
         results[jlpt + str(i)] = session.query(Kanji).filter(Kanji.tags.like(u'%' + jlpt + str(i) + '%' )).count()  
         if i > 3 : break
         else: i = i + 1
     i = 1    
     while True:
         results[grade + str(i)] = session.query(Kanji).filter(Kanji.tags.like(u'%' + grade + str(i) + '%' )).count()
         if i > 9 : break
         else: i = i + 1
         
     results[u'user'] = session.query(Kanji).filter(Kanji.tags.like(u'user')).count()
         
     return results
예제 #27
0
def evaluate_functions(model, functions):
    """Executes the each of the SQLAlchemy functions specified in
    ``functions``, a list of dictionaries of the form described below, on the
    given model and returns a dictionary mapping function name (slightly
    modified, see below) to result of evaluation of that function.

    ``functions`` is a list of dictionaries of the form::

        {'name': 'avg', 'field': 'amount'}

    For example, if you want the sum and the average of the field named
    "amount"::

        >>> # assume instances of Person exist in the database...
        >>> f1 = dict(name='sum', field='amount')
        >>> f2 = dict(name='avg', field='amount')
        >>> evaluate_functions(Person, [f1, f2])
        {'avg__amount': 456, 'sum__amount': 123}

    The return value is a dictionary mapping ``'<funcname>__<fieldname>'`` to
    the result of evaluating that function on that field. If `model` is
    ``None`` or `functions` is empty, this function returns the empty
    dictionary.

    If a field does not exist on a given model, :exc:`AttributeError` is
    raised. If a function does not exist,
    :exc:`sqlalchemy.exc.OperationalError` is raised.

    """
    if not model or not functions:
        return {}
    processed = []
    funcnames = []
    for f in functions:
        # We retrieve the function by name from the SQLAlchemy ``func``
        # module and the field by name from the model class.
        #
        # If the specified function doesn't exist, this raises
        # OperationalError. If the specified field doesn't exist, this raises
        # AttributeError.
        funcobj = getattr(func, f['name'])
        field = getattr(model, f['field'])
        # Time to store things to be executed. The processed list stores
        # functions that will be executed in the database and funcnames
        # contains names of the entries that will be returned to the
        # caller.
        funcnames.append('{}__{}'.format(f['name'], f['field']))
        processed.append(funcobj(field))
    # evaluate all the functions at once and get an iterable of results
    evaluated = session.query(*processed).one()
    return dict(zip(funcnames, evaluated))
예제 #28
0
def reinsert_cards():
    if request.method == 'POST':
        # post. reinsert the given rowids
        now = datetime.now()
        reason = request.form["reason"]
        if not reason:
            raise Exception("reason required")

        # get the cards
        rids = []
        for key, val in request.form.items():
            if key.startswith("reinsert_"):
                rids.append(int(key.split("_")[1]))
        cards = InvCard.query.filter(InvCard.rowid.in_(rids)).order_by('name').all()

        # make sure we can insert them
        if any(card.inventory_status != "temporarily_out" for card in cards):
            raise Exception("card is not temporarily out")

        box_capacity = list(metadata.bind.execute(
            "select box,60 - count(*) as c from inv_cards where box not null and cast( box as int) != 0 group by box having c>0 order by c desc;"))

        # fill in each box with count cards
        i = 0
        fill_orders = fit_boxes(box_capacity, len(cards))
        fill_orders = sorted(fill_orders, key=lambda (box, count): int(box))

        for box, count in fill_orders:
            max_index = session.query(func.max(InvCard.box_index)).filter_by(box=box).one()[0]
            for card in cards[i:count + i]:
                max_index += 1
                card.box = box
                card.box_index = max_index
                card.inventory_status = 'present'
                InvLog(card=card, date=now, direction='added', reason=reason)
            i += count

        session.commit()

        # we're done. render the list.
        return render_template("results.html", cards=cards)

    else:
        # get the temporary_out cards to reinsert
        # it will be a list of ((date, reason), (cardlist)) tuples
        cards = InvCard.query.filter_by(inventory_status="temporarily_out")
        the_key = lambda c: (c.most_recent_log().date, c.most_recent_log().reason)
        outstanding_cards = groupby(sorted(cards, key=the_key), the_key)
        outstanding_cards = [(key, sorted(val, key=attrgetter('name'))) for key, val in outstanding_cards]
        return render_template("outstanding_cards.html", outstanding_cards=outstanding_cards)
예제 #29
0
def reinsert_cards():
	if request.method == 'POST':
		#post. reinsert the given rowids
		now = datetime.now()
		reason = request.form["reason"]
		if not reason:
			raise Exception("reason required")

		#get the cards
		rids=[]
		for key, val in request.form.items():
			if key.startswith("reinsert_"):
				rids.append(int(key.split("_")[1]))
		cards = InvCard.query.filter(InvCard.rowid.in_(rids)).order_by('name').all()

		#make sure we can insert them
		if any(card.inventory_status != "temporarily_out" for card in cards):
			raise Exception("card is not temporarily out")

		box_capacity = list(metadata.bind.execute("select box,60 - count(*) as c from inv_cards where box not null and cast( box as int) != 0 group by box having c>0 order by c desc;"))
		
		#fill in each box with count cards
		i=0
		fill_orders = fit_boxes(box_capacity, len(cards))
		fill_orders = sorted(fill_orders, key=lambda (box,count): int(box))

		for box, count in fill_orders:
			max_index = session.query(func.max(InvCard.box_index)).filter_by(box=box).one()[0]
			for card in cards[i:count+i]:
				max_index += 1
				card.box = box
				card.box_index = max_index
				card.inventory_status = 'present'
				InvLog(card=card,date=now,direction='added',reason=reason)
			i+=count

		session.commit()

		#we're done. render the list.
		return render_template("results.html", cards=cards)

	else:
		#get the temporary_out cards to reinsert
		#it will be a list of ((date, reason), (cardlist)) tuples
		cards = InvCard.query.filter_by(inventory_status = "temporarily_out")
		the_key = lambda c: (c.most_recent_log().date, c.most_recent_log().reason)
		outstanding_cards = groupby(sorted(cards,key=the_key),the_key)
		outstanding_cards = [(key, sorted(val, key=attrgetter('name'))) for key, val in outstanding_cards]
		return render_template("outstanding_cards.html",outstanding_cards=outstanding_cards)
예제 #30
0
def captures_to_db(captures, box_name):
    #given an iterable of captures and a box name,
    #save all the captured images to the database
    starting_index = session.query(func.max(InvCard.box_index))\
      .filter(InvCard.box==box_name).first()[0]
    if starting_index is None:
        starting_index = 0

    for i, img in enumerate(captures):
        as_png = cv.EncodeImage(".png", img).tostring()

        InvCard(box=box_name,
                box_index=starting_index + i,
                scan_png=as_png,
                recognition_status="scanned",
                inventory_status="present")

    session.commit()
예제 #31
0
def captures_to_db(captures, box_name):
    # given an iterable of captures and a box name,
    # save all the captured images to the database
    starting_index = session.query(func.max(InvCard.box_index)).filter(InvCard.box == box_name).first()[0]
    if starting_index is None:
        starting_index = 0

    for i, img in enumerate(captures):
        as_png = cv.EncodeImage(".png", img).tostring()

        InvCard(
            box=box_name,
            box_index=starting_index + i,
            scan_png=as_png,
            recognition_status="scanned",
            inventory_status="present",
        )

    session.commit()
예제 #32
0
 def addItemsToDb(self, min, max, exact=False, tag='user'):
     self.count = 0
     success = False
     
     items = self.frequency.getFrequencyRange(min, max, exact)
     
     now = datetime.now()
     for item in items:
         if session.query(Item).filter_by(item = item).count()  == 0:
             Item(item = item.lower(), tags = tag, next_quiz = now, leitner_grade = Leitner.grades.None.index, active = True, 
             current_session = False, been_in_session = 0)
             
             self.count = self.count + 1
             success = True
             try: 
                 session.commit()
             except IntegrityError:
                 session.rollback()
                 success = False
     return success
예제 #33
0
def _evalute_functions(model, functions):
    """Evalutes a query that executes functions

    If you pass a model and a list of functions to this func, it will
    execute them in the database and return a JSON string containing an
    object with all results evaluted.

    `model`

        An elixir model that functions are going to be executed agains.

    `functions`

        A list of functions in the following syntas: ``func:field``. For
        example, if you want the sum and the average of a field, you can
        pass something like this: ['sum:amount', 'avg:amount'].
    """
    processed = []
    funcnames = []
    for val in functions:
        funcname = val['name']
        fname = val['field']

        # So, now is the time to use a bit of dynamic blackmagic of
        # python. with the function name, we retrieve its object from
        # the sqlalchemy ``func`` func module. And with the field name,
        # we retrieve ti from the model class.
        funcobj = getattr(func, funcname)
        field = getattr(model, fname)

        # Time to store things to be executed. The processed list stores
        # functions that will be executed in the database and funcnames
        # contains names of the entries that will be returned to the
        # caller.
        processed.append(funcobj(field))
        funcnames.append('%s__%s' % (funcname, fname))

    # Ok, now is the time to execute it, pack in a JSON string and
    # return to the user.
    evaluted = session.query(*processed).one()
    return dumps(dict(zip(funcnames, evaluted)))
예제 #34
0
파일: website.py 프로젝트: Caele/card_scan
def move_cards():
	if request.method == 'POST':
		results = []

		now = datetime.now()
		new_box = request.form.items["new_box"]
		new_box_index = session.query(func.max(InvCard.box_index)).filter_by(box=new_box).one()[0]

		try:

			for key, val in request.form.items():
				match = re.match('move_(?P<num>\d+)', key)
				if not match: #if this isn't move_id
					continue
				if not val: #if the browser passed us an unchecked checkbox
					continue

				rid = int(match.group('num'))

				card = InvCard.query.filter_by(rowid=rid).one()
				if card.inventory_status != "present":
					raise Exception("can't move non-present card")

				results.append({
					'rowid': card.rowid,
					'set_name': card.set_name,
					'name': card.name,
					'box': card.box,
					'box_index': card.box_index})

				new_box_index += 1
				card.box = new_box
				card.box_index = new_box_index
			results = sorted(results, key = lambda r: (r['box'],r['box_index']))
			return render_template("results.html", cards=results)
		except Exception as e:
			session.rollback()
			raise e
예제 #35
0
def move_cards():
	if request.method == 'POST':
		results = []

		now = datetime.now()
		new_box = request.form.items["new_box"]
		new_box_index = session.query(func.max(InvCard.box_index)).filter_by(box=new_box).one()[0]

		try:

			for key, val in request.form.items():
				match = re.match('move_(?P<num>\d+)', key)
				if not match: #if this isn't move_id
					continue
				if not val: #if the browser passed us an unchecked checkbox
					continue

				rid = int(match.group('num'))

				card = InvCard.query.filter_by(rowid=rid).one()
				if card.inventory_status != "present":
					raise Exception("can't move non-present card")

				results.append({
					'rowid': card.rowid,
					'set_name': card.set_name,
					'name': card.name,
					'box': card.box,
					'box_index': card.box_index})

				new_box_index += 1
				card.box = new_box
				card.box_index = new_box_index
			results = sorted(results, key = lambda r: (r['box'],r['box_index']))
			return render_template("results.html", cards=results)
		except Exception as e:
			session.rollback()
			raise e
예제 #36
0
            elif re.search('a', answer):
                return  #abort the scan
            #default will retry

    captures_to_db(captures, boxnum)


if __name__ == '__main__':
    setup_all(True)

    cam = cv.CreateCameraCapture(0)
    scan_card.setup_windows()

    #main loop
    while True:
        #for now, name the next box as the largest integer box name, +1
        current_max_box = session.query(
            func.max(sqlalchemy.cast(InvCard.box,
                                     sqlalchemy.Integer))).first()[0]
        if current_max_box is None:
            #if there is no current box, just start at 1
            next_box = 1
        else:
            next_box = current_max_box + 1

        print "box to scan[%02d]: " % next_box,
        answer = raw_input().rstrip()
        if answer != "":
            next_box = answer
        capture_box(cam, next_box)
예제 #37
0
 def checkIfActive(self, criteria):
     kanji = session.query(Item).filter(Item.tags.like(u'%' + criteria + '%' )).first()
     if kanji is not None:
         return kanji.active
예제 #38
0
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""

import match_card
import cv
from models import InvCard
from elixir import setup_all, session
from sqlalchemy import distinct
import config

if __name__ == '__main__':
    setup_all(True)

    sets = [
        s[0] for s in session.query(distinct(InvCard.set_name)).filter(
            InvCard.set_name != 'PROMO').all()
    ]
    base_dir = config.base_magic_set_dir
    known = match_card.load_sets(base_dir, sets)
    cache = match_card.GradientCache(base_dir)
    print "all sets loaded!"

    cv.NamedWindow('debug')
    cv.StartWindowThread()
    match_card.match_db_cards(known, cache)
예제 #39
0
파일: DAO.py 프로젝트: joubu/CDL
 def videos(cls):
     try:
         from modele import Video
         return session.query(Video).all()
     except:
         return None
예제 #40
0
파일: DAO.py 프로젝트: joubu/CDL
 def categories_availables(cls):
     try:
         from modele import Config
         return session.query(Config).all()[-1].categories_availables
     except:
         return None
예제 #41
0
파일: DAO.py 프로젝트: joubu/CDL
 def category(cls, name):
     try:
         from modele import Category
         return session.query(Category).filter(Category.name==name).first()
     except:
         return None
예제 #42
0
파일: DAO.py 프로젝트: joubu/CDL
    def reload_config(cls):
        from modele import Config, Category
        dir_user = unicode(os.path.join(os.path.expanduser("~"), 'Canal_DL'))
        player = u'vlc'

        c = Config(dir_user, player)
        base_url_1 = u"http://service.canal-plus.com/video/rest/search/cplus/"
        base_url_2 = u"http://service.canal-plus.com/video/rest/getMEAs/cplus/"
        categories = {
            "pepites": {
                "code": u"PEPITES_SUR_LE_NET",
                "url": base_url_1 + u"pepites"
            },
            "guignols": {
                "code": u"LES_GUIGNOLS",
                "url": base_url_1 + u"guignols"
            },
            "grand": {
                "code": u"LE_GRAND_JOURNAL",
                "url": base_url_2 + u"39"
            },
            "groland": {
                "code": u"GROLAND",
                "url": base_url_2 + u"130"
            },
            "petit": {
                "code": u"LE_PETIT_JOURNAL",
                "url": base_url_1 + u"petit"
            },
            "jt": {
                "code": u"LE.JT.DE.CANAL",
                "url": base_url_2 + u"39"
            },
            "explorateurs": {
                "code": u"LES_NOUVEAUX_EXPLORATEURS",
                "url": base_url_1 + u"LES_NOUVEAUX_EXPLORATEURS"
            },
            "supplement": {
                "code": u"LE_SUPPLEMENT",
                "url": base_url_2 + u"1080"
            },
            "links": {
                "code": u"L_OEIL_DE_LINKS",
                "url": base_url_1 + u"L_OEIL_DE_LINKS"
            },
            "salut": {
                "code": u"SALUT_LES_TERRIENS",
                "url": base_url_1 + u"SALUT_LES_TERRIENS"
            },
            "zapping": {
                "code": u"ZAPPING",
                "url": base_url_2 + u"39"
            }
        }

        for k, v in categories.iteritems():
            c.categories_availables.append(
                Category(k, dir_user, v['code'], v['url'], create_path=True))

        petit = session.query(Category).filter(
            Category.name == u'petit').first()
        zapping = session.query(Category).filter(
            Category.name == u'zapping').first()
        c.categories.append(petit)
        c.categories.append(zapping)

        cls.commit()

        return c
예제 #43
0
파일: db.py 프로젝트: Xifax/suzu
 def checkIfActive(self, criteria):
     #FIXME: as of now, it just checks if there're are items like these
     kanji = session.query(Kanji).filter(Kanji.tags.like(u'%' + criteria + '%' )).first()
     if kanji is not None:
         return kanji.active
예제 #44
0
파일: db.py 프로젝트: Xifax/suzu
    def countItemsByTags(self):
#        results = {}
        jlpt = u'jlpt'
        grade = u'grade'
        return session.query(Kanji).filter(or_(Kanji.tags.like(u'%' + jlpt + '%' ), Kanji.tags.like(u'%' + grade + '%' ))).count()  
예제 #45
0
파일: DAO.py 프로젝트: joubu/CDL
 def player(cls):
     from modele import Config
     config = session.query(Config).all()[-1]
     return config.player
예제 #46
0
파일: DAO.py 프로젝트: joubu/CDL
 def categories_availables(cls):
     try:
         from modele import Config
         return session.query(Config).all()[-1].categories_availables
     except:
         return None
예제 #47
0
파일: DAO.py 프로젝트: joubu/CDL
 def videos(cls):
     try:
         from modele import Video
         return session.query(Video).all()
     except:
         return None
예제 #48
0
import match_card
import cv
from models import InvCard
from elixir import setup_all, session
from sqlalchemy import distinct


if __name__ == '__main__':
	setup_all()

	sets = [s[0] for s in session.query(distinct(InvCard.set_name)).filter(InvCard.set_name != 'PROMO').all()]
	base_dir = u'/home/talin/Cockatrice/cards/downloadedPics'
	known = match_card.load_sets(base_dir, sets)
	cache = match_card.GradientCache(base_dir)
	print "all sets loaded!"

	cv.NamedWindow('debug')
	cv.StartWindowThread()
	match_card.match_db_cards(known, cache)
예제 #49
0
파일: DAO.py 프로젝트: joubu/CDL
 def player(cls):
     from modele import Config
     config = session.query(Config).all()[-1]
     return config.player
예제 #50
0
        try:
            field = getattr(model, fieldname)
        except AttributeError, exception:
            exception.field = fieldname
            raise exception
        # Time to store things to be executed. The processed list stores
        # functions that will be executed in the database and funcnames
        # contains names of the entries that will be returned to the
        # caller.
        funcnames.append('%s__%s' % (funcname, fieldname))
        processed.append(funcobj(field))
    # Evaluate all the functions at once and get an iterable of results.
    #
    # If any of the functions
    try:
        evaluated = session.query(*processed).one()
    except OperationalError, exception:
        # HACK original error message is of the form:
        #
        #    '(OperationalError) no such function: bogusfuncname'
        original_error_msg = exception.args[0]
        bad_function = original_error_msg[37:]
        exception.function = bad_function
        raise exception
    return dict(zip(funcnames, evaluated))


class ModelView(MethodView):
    """Base class for :class:`flask.MethodView` classes which represent a view
    of an Elixir model.
예제 #51
0
		captures = scan_card.watch_for_card(cam)
		scan_card.save_captures(boxnum, captures)
		print "captured %d cards. is this correct?" % len(captures)
		answer = raw_input()
		print "got answer: ", answer
		if re.search('[yc]',answer):
			break #finish the function
		else:
			print "try editing captures_%02d to match" % boxnum
			answer = ""
			while not re.match('[cra]', answer):
				print "when done - (c)orrected? (r)etry scan? or (a)bort?"
				answer = raw_input()
			if re.search('c',answer):
				break
			elif re.search('r',answer):
				continue
			elif re.search('a',answer):
				return #abort the scan
			#default will retry

	scan_card.folder_to_db(boxnum)


if __name__ == '__main__':
	#main loop
	while True:
		next_box = session.query(func.max(sqlalchemy.cast(InvCard.box, sqlalchemy.Integer))).first()[0] + 1
		print "scanning %02d" % next_box
		capture_box(cam, next_box)