コード例 #1
0
ファイル: image.py プロジェクト: ZijianYang/down
def images(pagenumber):
    """查询"""
    args = request.args
    tag = args.get("tag", None, type=str)
    if tag:
        tag = tag.split(" ")
    pagesize = args.get("pagesize", 10, type=int)
    score = args.get("score", 0, type=int)
    sort = args.get("sort", "score", type=str)
    pageindex = pagenumber - 1
    print('score:%s;tag:%s;pagesize:%s;pageindex:%s;sort: %s' %
          (score, tag, pagesize, pageindex, sort))
    if sort == "random":
        data = Store.FileHistoryRepository().getsradom(score, tag, pagesize)
    else:
        data = Store.FileHistoryRepository().getspage(score, tag, pageindex,
                                                      pagesize, sort)
    return jsonify({
        'items': [{
            'id': item.id,
            'url': item.filepath.replace("\\", "/"),
            'md5': item.md5,
            'score': item.remark1,
            'tags': item.remark2
        } for item in data["list"]],
        'total':
        data["total"]
    })
コード例 #2
0
ファイル: Store.py プロジェクト: CG3002-Design-Project/CG3002
def store_created(request):
    if (
        "address" in request.GET
        and request.GET["address"]
        and "city" in request.GET
        and request.GET["city"]
        and "country" in request.GET
        and request.GET["country"]
        and "region" in request.GET
        and request.GET["region"]
    ):
        address = request.GET["address"]
        city = request.GET["city"]
        country = request.GET["country"]
        if "city_state" in request.GET:
            city_state = request.GET["city_state"]
        else:
            city_state = city
        region = request.GET["region"]
    stores = Store.objects.all().order_by("-store_id")
    if not stores:
        id = 1
    else:
        id = stores[0].store_id + 1
    store = Store(store_id=id, address=address, city=city, country=country, state=city_state, region=region)
    store.save()
    stores = Store.objects.all()
    message = "Store has been successfully added"
    context = {"stores": stores, "message": message}
    return render(request, "view_stores.html", context)
コード例 #3
0
ファイル: cralwer.py プロジェクト: VinceNKB/PixivSpider
 def __init__(self):
     self.api = ByPassSniApi()
     self.api.require_appapi_hosts()
     # api.set_additional_headers({'Accept-Language':'en-US'})
     self.api.set_accept_language('en-us')
     self.error = []
     self.store = Store()
コード例 #4
0
ファイル: List_Stores.py プロジェクト: solzhen/techo-sodimac
	def add_store(self, name):
		if name.startswith('NOR'):
			if self.stores_norte[name] == 0:
				self.stores_norte[name] += 1
				self.norte_visited[name] = Store(name)
			else:
				self.stores_norte[name] += 1

		elif name.startswith('SUR'):
			if self.stores_sur[name] == 0:
				self.stores_sur[name] += 1
				self.sur_visited[name] = Store(name)
			else:
				self.stores_sur[name] += 1

		elif name.startswith('CEN'):
			if self.stores_centro[name] == 0:
				self.stores_centro[name] += 1
				self.centro_visited[name] = Store(name)
			else:
				self.stores_centro[name] += 1

		else:
			if self.stores_rm[name] == 0:
				self.stores_rm[name] += 1
				self.rm_visited[name] = Store(name)
			else:
				self.stores_rm[name] +=1
コード例 #5
0
def store_created(request):
    if 'address' in request.GET and request.GET[
            'address'] and 'city' in request.GET and request.GET[
                'city'] and 'country' in request.GET and request.GET[
                    'country'] and 'region' in request.GET and request.GET[
                        'region']:
        address = request.GET['address']
        city = request.GET['city']
        country = request.GET['country']
        if 'city_state' in request.GET:
            city_state = request.GET['city_state']
        else:
            city_state = city
        region = request.GET['region']
    stores = Store.objects.all().order_by('-store_id')
    if not stores:
        id = 1
    else:
        id = stores[0].store_id + 1
    store = Store(store_id=id,
                  address=address,
                  city=city,
                  country=country,
                  state=city_state,
                  region=region)
    store.save()
    stores = Store.objects.all()
    message = 'Store has been successfully added'
    context = {'stores': stores, 'message': message}
    return render(request, 'view_stores.html', context)
コード例 #6
0
ファイル: image.py プロジェクト: ZijianYang/down
def imagesbysection(star, end):
    """查询"""
    args = request.args
    tag = args.get("tag", None, type=str)
    if tag:
        tag = tag.split(" ")
    score = args.get("score", 0, type=int)
    sort = args.get("sort", "score", type=str)
    print('score:%s;tag:%s;star:%s;end:%s;sort: %s' %
          (score, tag, star, end, sort))
    if sort == "random":
        sectionlength = end - star
        data = Store.FileHistoryRepository().getsradom(score, tag,
                                                       sectionlength)
    else:
        data = Store.FileHistoryRepository().getsbysection(
            score, tag, star, end, sort)
    return jsonify({
        'items': [{
            'id': item.id,
            'url': item.filepath.replace("\\", "/"),
            'md5': item.md5,
            'score': item.remark1,
            'tags': item.remark2
        } for item in data["list"]],
        'total':
        data["total"]
    })
コード例 #7
0
ファイル: SSHStore.py プロジェクト: eugene-bright/buttersink
 def diff(self, toUUID, fromUUID, estimatedSize='None'):
     if estimatedSize == 'None':
         return Store.Diff(self.sink, self.vol(toUUID), self.vol(fromUUID))
     else:
         estimatedSize = int(float(estimatedSize))
         return Store.Diff(self.sink, self.vol(toUUID), self.vol(fromUUID),
                           estimatedSize, True)
コード例 #8
0
def Execute():
    a=Store.GetInt('a')
    b=Store.GetDouble('b')
    c=Store.GetString('c')
    print a
    print b
    print c
    return 1
コード例 #9
0
 def add():
     if (len(ReferenceNo.get()) != 0):
         Store.addRegRec(ReferenceNo.get(), DistributorName.get(), Date.get(), \
                         MobileNo.get(), ExpDate.get(), Medicine.get(), Amount.get(), \
                         Payment.get())
         storelist.delete(0, END)
         storelist.insert(END, (ReferenceNo.get(), DistributorName.get(), Date.get(), \
                                MobileNo.get(), ExpDate.get(), Medicine.get(), Amount.get(), \
                                Payment.get()))
コード例 #10
0
 def test_Store(self):
     p = Store.Product(1, "iPad", "Tablet", 1200.00, 25)
     s = Store.Store()
     s.add_product(p)
     self.assertIs(p.get_title(), "iPad")
     self.assertIs(p.get_description(), "Tablet")
     self.assertTrue(p.get_price(), 1200.00)
     self.assertNotEqual(p.get_quantity(), 19)
     self.assertEqual(s.searchStore("Ipad"), [1])
コード例 #11
0
	def __init__(self, *args):
		FtpServer.FlatFileSystem.__init__(self, *args)
		self.file_store = Store.Transaction(Config.file_store)
		self.cache = Store.Transaction(Config.cache_store)
		web.load()
		web.ctx.store = self.file_store
		web.ctx.cache = self.cache
		web.ctx.attachments = Store.Transaction(Config.attachment_store)
		web.ctx.printmode = False
		web.ctx.home = Config.canonical_base_url
コード例 #12
0
 def __init__(self, prefix, namespace, ontologies):
     self.prefix = prefix
     self.namespace = Namespace(namespace)
     self.store = Store()
     self.store.bind(prefix, namespace)
     self.store.bind("ao", str(AO))
     self.store.bind("pav", str(PAV))
     self.store.bind("dc", str(DC))
     self.ontologies = ontologies
     for k in ontologies:
         self.store.bind(k, ontologies[k])
コード例 #13
0
 def test_1(self):
     """This test is checking to make sure the checkout price is equal to 33.45 (since they are a premium member"""
     p1 = Store.Product("889", "Rodent of unusual size",
                        "when a rodent of the usual size just won't do",
                        33.45, 8)
     c1 = Store.Customer("Yinsheng", "QWF", True)
     myStore = Store.Store()
     myStore.add_product(p1)
     myStore.add_member(c1)
     myStore.add_product_to_member_cart("889", "QWF")
     result = myStore.check_out_member("QWF")
     self.assertEqual(result, 33.45)
コード例 #14
0
 def test_2(self):
     """This test is checking to make sure the program is charging the extra 7% shipping cost for non-premium
     members"""
     p1 = Store.Product("889", "Rodent of unusual size",
                        "when a rodent of the usual size just won't do",
                        33.45, 8)
     c1 = Store.Customer("Yinsheng", "QWF", False)
     myStore = Store.Store()
     myStore.add_product(p1)
     myStore.add_member(c1)
     myStore.add_product_to_member_cart("889", "QWF")
     result = myStore.check_out_member("QWF")
     self.assertEqual(result, (33.45 * 1.07))
コード例 #15
0
ファイル: ButterStore.py プロジェクト: ceremcem/buttersink
    def measureSize(self, diff, chunkSize):
        """ Spend some time to get an accurate size. """
        self._fileSystemSync()

        sendContext = self.butter.send(
            self.getSendPath(diff.toVol),
            self.getSendPath(diff.fromVol),
            diff,
            showProgress=self.showProgress is not False,
            allowDryRun=False,
        )

        class _Measure(io.RawIOBase):
            def __init__(self, estimatedSize, showProgress):
                self.totalSize = None
                self.progress = progress.DisplayProgress(
                    estimatedSize) if showProgress else None

            def __enter__(self):
                self.totalSize = 0
                if self.progress:
                    self.progress.__enter__()
                return self

            def __exit__(self, exceptionType, exceptionValue, traceback):
                if self.progress:
                    self.progress.__exit__(exceptionType, exceptionValue,
                                           traceback)
                return False  # Don't supress exception

            def writable(self):
                return True

            def write(self, bytes):
                self.totalSize += len(bytes)
                if self.progress:
                    self.progress.update(self.totalSize)

        logger.info("Measuring %s", diff)

        measure = _Measure(diff.size, self.showProgress is not False)
        Store.transfer(sendContext, measure, chunkSize)

        diff.setSize(measure.totalSize, False)

        for path in self.getPaths(diff.toVol):
            path = self._fullPath(path) + Store.theInfoExtension

            with open(path, "a") as infoFile:
                diff.toVol.writeInfoLine(infoFile, diff.fromUUID,
                                         measure.totalSize)
コード例 #16
0
def ask_question():
    name = 'Colin'

    questions = Store.getQuestions()

    for q in questions:
        print str(q) + ": " + questions[q]
        input = sys.stdin.readline()
        input = int(input)
        print "You said " + str(input) + ". Saved? " + str(
            Store.storeResult(name=name, score=input, question_id=q))
        print "----------------"

    print "Thanks!! You've answered all the questions for now."
コード例 #17
0
ファイル: __init__.py プロジェクト: LeftyBC/moodlooker
def ask_question():
    name = 'Colin'

    questions = Store.getQuestions()

    for q in questions:
        print str(q) + ": " + questions[q]
        input = sys.stdin.readline()
        input = int(input)
        print "You said " + str(input) + ". Saved? " + str(Store.storeResult(name=name,score=input,question_id=q))
        print "----------------"


    print "Thanks!! You've answered all the questions for now."
コード例 #18
0
class JungleJamboree :
	
	
	def __init__ (self) :
		self._running = True
		self._display = None
		self._party = Party()
		self._turn = Turn ()
		self._store = Store ()

	def startGame (self) :
		self._party.setUpParty ()
		self._store.setUpStore ()
		self._store.menu (self._party)
コード例 #19
0
ファイル: ButterStore.py プロジェクト: JensErat/buttersink
    def measureSize(self, diff, chunkSize):
        """ Spend some time to get an accurate size. """
        self._fileSystemSync()

        sendContext = self.butter.send(
            self.getSendPath(diff.toVol),
            self.getSendPath(diff.fromVol),
            diff,
            showProgress=self.showProgress is not False,
            allowDryRun=False,
        )

        class _Measure(io.RawIOBase):

            def __init__(self, estimatedSize, showProgress):
                self.totalSize = None
                self.progress = progress.DisplayProgress(estimatedSize) if showProgress else None

            def __enter__(self):
                self.totalSize = 0
                if self.progress:
                    self.progress.__enter__()
                return self

            def __exit__(self, exceptionType, exceptionValue, traceback):
                if self.progress:
                    self.progress.__exit__(exceptionType, exceptionValue, traceback)
                return False  # Don't supress exception

            def writable(self):
                return True

            def write(self, bytes):
                self.totalSize += len(bytes)
                if self.progress:
                    self.progress.update(self.totalSize)

        logger.info("Measuring %s", diff)

        measure = _Measure(diff.size, self.showProgress is not False)
        Store.transfer(sendContext, measure, chunkSize)

        diff.setSize(measure.totalSize, False)

        for path in self.getPaths(diff.toVol):
            path = self._fullPath(path) + Store.theInfoExtension

            with open(path, "a") as infoFile:
                diff.toVol.writeInfoLine(infoFile, diff.fromUUID, measure.totalSize)
コード例 #20
0
	def __init__(self, surface):
		"Initialize variables, load images, set flags, and fonts"
		self.surface = surface
		self.bg = transform.scale(image.load("res/main_bg.jpg").convert(), (surface.get_width(), surface.get_height()))
		self.carImage = image.load("res/front_car.png")
		self.arrow_left = image.load("res/arrow_left.png")
		self.carImageSized = transform.scale(self.carImage, (150, 100))
		self.carX, self.carY = 437,290
		self.width = self.carImageSized.get_width()
		self.height = self.carImageSized.get_height()
		self.logo = image.load("res/logo_perspective.png")
		self.running = True
		self.rightMenu = image.load("res/menu_right.png")
		self.rightMenuX, self.rightMenuY = 1024, 768
		self.menuFont = font.Font("res/fonts/pricedown.ttf", 35)
		#menu options with color, rects, text, and action on click
		self.optionColors = [(255,255,255),(255,255,255),(255,255,255),(255,255,255),(255,255,255)]
		self.optionRects = [Rect(825,455,self.menuFont.size("Start Game")[0]+10,self.menuFont.size("Start Game")[1]),Rect(825,505,self.menuFont.size("Store")[0]+10,self.menuFont.size("Store")[1]),Rect(825,555,self.menuFont.size("Options")[0]+10,self.menuFont.size("Options")[1]),Rect(825,605,self.menuFont.size("Help")[0]+10,self.menuFont.size("Help")[1]),Rect(825,655,self.menuFont.size("About")[0]+10,self.menuFont.size("About")[1])]
		self.options = ["Start Game", "Store", "Help", "About"]
		self.optionResults = [self.levelRunning,self.storeRunning,self.setHelp,self.setAbout]
		self.store = Store(surface)
		self.level = Level(surface)
		self.about = Popup(surface, "About", ["Developed By Rikin Katyal", "ICS3U Final Project 2015", "Made Using Python and Pygame"])
		self.help = Popup(surface, "Help", ["Use arrow keys or WASD to move.", "Press Space for emergency break.", "Earn coins to spend in the store.", "Drive through obstacles and park", "in marked parking spot."])
		self.help.images([image.load("res/arrows.png"), image.load("res/wasd.png"), image.load("res/coin_medium.png")],[(310,456),(470,450),(660,475)])
		self.settings = Popup(surface, "Settings", ["Sound Effects (SFX)", "Music"])
		self.aboutRunning = False
		self.helpRunning = False
		self.settingsRunning = False
コード例 #21
0
 def test_3(self):
     p1 = Store.Product("889", "Rodent of unusual size",
                        "when a rodent of the usual size just won't do",
                        33.45, 8)
     description = p1.get_description()
     self.assertEqual(description,
                      "when a rodent of the usual size just won't do")
コード例 #22
0
ファイル: Dict.py プロジェクト: gustavodsf/java_projects
    def addWordDict(self, word, idSource, generateID, typeWord):
        idWord = None
        idWordHasTxt = 0
        with self.semaWord:
            generateID.incrementIdWordHasTxt()
            idWordHasTxt = generateID.getIdWordHasTxt()

        #import pdb; pdb.set_trace()
        if word in self.wordDict.keys():
            self.wordDict[word].qtd += 1
            idWord = self.wordDict[word].id
        else:
            with self.semaWord:
                generateID.incrementIdWord()
                idWord = generateID.getIdWord()
                while idWord in self.usedWordId:
                    generateID.incrementIdWord()
                    idWord = generateID.getIdWord()
                self.usedWordId[idWord] = True
                s = Store.Store()
                s.qtd = 1
                s.id = idWord
                s.type = typeWord
                self.wordDict[word] = s
        self.convenioDAO.savePalavraHasOrigem(idWordHasTxt, idSource, idWord)
コード例 #23
0
ファイル: tag.py プロジェクト: ZijianYang/down
def tag(tag):
    """查询"""
    data = Store.TagRepository().gets(tag)
    return jsonify([{
        'tag': item.tag,
        'count': item.count,
    } for item in data])
コード例 #24
0
 def urldetail(self, html, ruledetails, resulturls):
     """处理详情信息"""
     values = {}
     for ruledetail in ruledetails:
         if ruledetail["Type"] == "Fix":
             values[ruledetail["Key"]] = ruledetail["Value"]
         elif ruledetail["Type"] == "Regex":
             regex = ruledetail["Regex"]
             pattern = re.compile(regex)
             regexvalues = pattern.findall(html)
             values[ruledetail["Key"]] = regexvalues
     i = 0 # 循环计数
     for resulturl in resulturls:
         urldetails = []
         for (key, value) in values.items():
             typestr = [f for f in ruledetails if f["Key"] == key][0]["Type"]
             if typestr == "Fix":
                 urldetailvalue = value
             elif typestr == "Regex":
                 urldetailvalue = value[i]
             urldetail = Store.Entity.UrlDetail(key, urldetailvalue)
             urldetails.append(urldetail)
         Store.UrlDetailRepository().adds(resulturl, urldetails)
         print("处理详情数据:%s" % (resulturl))
         i = i + 1
コード例 #25
0
 def handlerooturl(self, downconfig, validationdata=True):
     """处理RootUrl"""
     # 没有上层处理,对rooturl进行下载和数据保存,不做处理
     print("处理RootUrl:", end=" ")
     rooturl = downconfig.rooturl
     rooturlinfo = Store.UrlRepository().getsbykeyrequesturl(
         self.key, rooturl).first()
     if not rooturlinfo or not validationdata:
         filepath = Tool.DownHelper.star(self.filedirpath, rooturl)
         rootrule = downconfig.rule("RootUrl")
         url = Store.Entity.Url(rootrule["RuleNo"], filepath, rooturl,
                                rooturl)
         Store.UrlRepository().add(self.key, url)  #根处理特殊源和结果是一个
         print("处理完毕")
     else:
         print("已存在数据,继续")
コード例 #26
0
class PooledDBO:
    """ Class controlling access to DB handles

    We implement a pool of connection threads. This gives us both worlds - the advantage of reusing connection handles without running the risk of exhausting them, as well as the ability to issue multiple simultaneous queries from different threads.

    @cvar DBH: A store containing cached database connection objects
    @cvar lock: an array of unique locks that each thread must hold before executing new SQL
    @ivar temp_tables: A variable that keeps track of temporary tables so they may be dropped when this object gets gc'ed
    """
    temp_tables = []
    transaction = False
    ## This stores references to the pools
    DBH = Store.Store(max_size=10)

    def get_dbh(self, case):
        try:
            pool = self.DBH.get(case)
        except KeyError:
            pool = Pool(case)
            self.DBH.put(pool, key=case)

        self.dbh = pool.get()

        ## Ensure the tz is properly reset before handing out dbh:
        c = self.dbh.cursor()
        try:
            c.execute("select value from meta where property ='TZ' limit 1")
            row = c.fetchone()
            if row:
                c.execute(db_expand('set time_zone = %r', row['value']))
        except Exception, e:
            pass
コード例 #27
0
ファイル: SSHStore.py プロジェクト: eugene-bright/buttersink
    def _fillVolumesAndPaths(self, paths):
        """ Fill in paths.

        :arg paths: = { Store.Volume: ["linux path",]}
        """
        for (volDict, volPaths) in self._client.fillVolumesAndPaths():
            vol = Store.Volume(**volDict)
            paths[vol] = volPaths
コード例 #28
0
 def parse_value_display_str(self, value_display_str):
     print(value_display_str)
     split_value_display_str = Store.multi_dim_split(
         ['Current Balance: $ ', '   View Details'], value_display_str)
     print('split_value_display_str: ', split_value_display_str)
     value_str = split_value_display_str[1]
     print('value_str: ', value_str)
     return float(value_str)
コード例 #29
0
 def test_product(self):
     """ Test creating a product. """
     item = Store.Product(100,"Mango","Fruit",5,100 )
     self.assertAlmostEqual(item.get_title(),"Mango")
     self.assertAlmostEqual(item.get_description() , "Fruit" )
     self.assertAlmostEqual(item.get_price(),5)
     self.assertNotEqual(item.get_quantity_available(),99)
     self.assertIsNotNone(item)
コード例 #30
0
ファイル: ButterStore.py プロジェクト: ceremcem/buttersink
    def receiveVolumeInfo(self, paths):
        """ Return Context Manager for a file-like (stream) object to store volume info. """
        path = self.selectReceivePath(paths)
        path = path + Store.theInfoExtension

        if Store.skipDryRun(logger, self.dryrun)("receive info to %s", path):
            return None

        return open(path, "w")
コード例 #31
0
ファイル: NavStoreParser.py プロジェクト: nandub/yammer
 def do_img(self, attrs):
   src= self.getAtt(attrs, 'src')
   srcreal= self.getAtt(attrs, 'srcreal')
   if srcreal is not None:
     uo= urllib.urlopen(srcreal)
     fp= Store.storeopen(srcreal, self._root, 'w')
     fp.write(uo.read())
     uo.close()
     fp.close()
コード例 #32
0
ファイル: ButterStore.py プロジェクト: JensErat/buttersink
    def receiveVolumeInfo(self, paths):
        """ Return Context Manager for a file-like (stream) object to store volume info. """
        path = self.selectReceivePath(paths)
        path = path + Store.theInfoExtension

        if Store.skipDryRun(logger, self.dryrun)("receive info to %s", path):
            return None

        return open(path, "w")
コード例 #33
0
ファイル: SSHStore.py プロジェクト: smoofra/buttersink
    def send(self, diff):
        """ Return Context Manager for a file-like (stream) object to send a diff. """
        if Store.skipDryRun(logger, self.dryrun)("send %s", diff):
            return None

        (diffTo, diffFrom) = self.toArg.diff(diff)
        self._client.send(diffTo, diffFrom)

        progress = DisplayProgress(diff.size) if self.showProgress is True else None
        return _SSHStream(self._client, progress)
コード例 #34
0
ファイル: NavStoreParser.py プロジェクト: nandub/yammer
 def fixReferences(self, attrs):
   newattrs= []
   for a,v in attrs:
     if (a == 'href' or a == 'src') and v.find(':') < 0:
       v= self.fixRef(v)
       if a == 'src':
         newattrs.append(('srcreal', v))
         v= Store.storeurl(v, self._root, self._httpRoot)
     newattrs.append((a, v))
   return newattrs
コード例 #35
0
ファイル: SSHStore.py プロジェクト: AmesCornish/buttersink
    def send(self, diff):
        """ Return Context Manager for a file-like (stream) object to send a diff. """
        if Store.skipDryRun(logger, self.dryrun)("send %s", diff):
            return None

        (diffTo, diffFrom) = self.toArg.diff(diff)
        self._client.send(diffTo, diffFrom)

        progress = DisplayProgress(diff.size) if self.showProgress is True else None
        return _SSHStream(self._client, progress)
コード例 #36
0
ファイル: image.py プロジェクト: ZijianYang/down
def image(imageid):
    """查询"""
    data = Store.FileHistoryRepository().getbyid(imageid)
    return jsonify({
        'id': data.id,
        'url': data.filepath.replace("\\", "/"),
        'md5': data.md5,
        'score': data.remark1,
        'tags': data.remark2
    } if data else {})
コード例 #37
0
ファイル: Triplify.py プロジェクト: bioinformatics-ua/ann2rdf
 def __init__(self, prefix, namespace, ontologies):
     self.prefix = prefix
     self.namespace = Namespace(namespace)
     self.store = Store()
     self.store.bind(prefix, namespace)
     self.store.bind("ao", str(AO))
     self.store.bind("pav", str(PAV))
     self.store.bind("dc", str(DC))
     self.ontologies = ontologies
     for k in ontologies:
         self.store.bind(k, ontologies[k])
コード例 #38
0
 def test_5(self):
     """This test is making sure the 'None' is being returned when trying to get a product from an ID that
     doesn't exist"""
     p1 = Store.Product("889", "Rodent of unusual size",
                        "when a rodent of the usual size just won't do",
                        33.45, 8)
     p2 = Store.Product("888", "Bird of unusual size",
                        "when a bird of the usual size just won't do",
                        25.98, 10)
     p3 = Store.Product("887", "Cat of unusual size",
                        "when a cat of the usual size just won't do", 50.55,
                        5)
     p4 = Store.Product("886", "A Dog", "woof woof", 60.75, 12)
     myStore = Store.Store()
     myStore.add_product(p1)
     myStore.add_product(p2)
     myStore.add_product(p3)
     myStore.add_product(p4)
     result = myStore.get_product_from_id('900')
     self.assertEqual(result, None)
コード例 #39
0
  def test_partialBadWordNotRejected(self):
    shortUrl = ShortUrlClass(shortenedUrlRepository=Store.ShortenedUrlRepositoryClass(appObj=appObj))

    testCodes = ["12fuc"]

    with patch("Logic.shortCodeGenerator.getObscureURLStringFromSequence", side_effect=testCodes) as mock_gen:
      mm = MagicMock()
      mm.getObjectJSON.return_value=None, None, None, None, None
      url = shortUrl.getShortUrl(storeConnection=mm)
      self.assertEqual(url, "12fuc")
    self.assertEqual(len(url), CODELENGTH)
コード例 #40
0
  def test_badwordWillNotBeGenerated(self):
    shortUrl = ShortUrlClass(shortenedUrlRepository=Store.ShortenedUrlRepositoryClass(appObj=appObj))

    testCodes = ["fuck5", "sH1it", "shit5", "sh1t5", "5h1t4", "12ok5"]

    with patch("Logic.shortCodeGenerator.getObscureURLStringFromSequence", side_effect=testCodes) as mock_gen:
      mm = MagicMock()
      mm.getObjectJSON.return_value=None, None, None, None, None
      url = shortUrl.getShortUrl(storeConnection=mm)
      self.assertEqual(url, "12ok5")
    self.assertEqual(len(url), CODELENGTH)
コード例 #41
0
ファイル: SSHStore.py プロジェクト: AmesCornish/buttersink
    def receive(self, diff, paths):
        """ Return Context Manager for a file-like (stream) object to store a diff. """
        path = self.selectReceivePath(paths)
        path = self._relativePath(path)

        if Store.skipDryRun(logger, self.dryrun)("receive to %s", path):
            return None

        (diffTo, diffFrom) = self.toArg.diff(diff)
        self._client.receive(path, diffTo, diffFrom)

        progress = DisplayProgress(diff.size) if self.showProgress is True else None
        return _SSHStream(self._client, progress)
コード例 #42
0
ファイル: Butter.py プロジェクト: AmesCornish/buttersink
    def send(self, targetPath, parent, diff, showProgress=True, allowDryRun=True):
        """ Return context manager for stream to send a (incremental) snapshot. """
        if parent is not None:
            cmd = ["btrfs", "send", "-p", parent, targetPath]
        else:
            cmd = ["btrfs", "send", targetPath]

        if Store.skipDryRun(logger, self.dryrun and allowDryRun)("Command: %s", cmd):
            return None

        process = subprocess.Popen(
            cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=DEVNULL)
        _makeNice(process)

        return _Reader(process, process.stdout, targetPath, diff, showProgress)
コード例 #43
0
ファイル: Game.py プロジェクト: stan3971/JungleJamboree
	def __init__(self) :
		"""sets running to true, and creates a party and begins setting
		 up a pygame display """
		self._running = True
		self._display = None
		self._party = Party()
		self._turn = Turn()
		self._store = Store ()
		self._store.setUpStore ()
		self._party.setUpParty () 
		self._state = "Start"
		self._width = 800
		self._height = 600
		self._size = (self._width, self._height)
		pygame.init()
		pygame.font.init()
		self._display = pygame.display.set_mode(self._size)
		self._myFont1 = pygame.font.Font('freesansbold.ttf', 15)
		self._myFont2 = pygame.font.Font('freesansbold.ttf', 25)
		self._myFont3 = pygame.font.Font('freesansbold.ttf', 12)
		pygame.display.set_caption('Jungle Jamboree')
コード例 #44
0
ファイル: NavStoreParser.py プロジェクト: nandub/yammer
  def __init__(self, page):
    htmllib.HTMLParser.__init__(self, formatter.NullFormatter())

    # turn on elements that weren't in HTML 2
    for f in newhtmlelements.split():
      self.setifnot('start_' + f, self.fake_start)
      self.setifnot('end_' + f, self.fake_end)
    for f in newhtmlelementsempty.split():
      self.setifnot('do_' + f, self.fake_start)

    self._page= page
    self._httpRoot= page._httpRoot
    self._root= page.root()
    self._ofp= Store.storeopen(page.url(), self._root, 'w')
    self._anchors= {}
    self._forms= {}
    self._frames= {}
    self._siteRoot= page.siteRoot()
    self._url= page.url()
    self.feed(page.body())
    self.close()
コード例 #45
0
ファイル: Butter.py プロジェクト: AmesCornish/buttersink
    def receive(self, path, diff, showProgress=True):
        """ Return a context manager for stream that will store a diff. """
        directory = os.path.dirname(path)

        cmd = ["btrfs", "receive", "-e", directory]

        if Store.skipDryRun(logger, self.dryrun)("Command: %s", cmd):
            return None

        if not os.path.exists(directory):
            os.makedirs(directory)

        process = subprocess.Popen(
            cmd,
            stdin=subprocess.PIPE,
            stderr=subprocess.PIPE,
            stdout=DEVNULL,
        )
        _makeNice(process)

        return _Writer(process, process.stdin, path, diff, showProgress)
コード例 #46
0
ファイル: TestSuite.py プロジェクト: nandub/yammer
 def createPage(self, pagetests, url, postargs=None, forceget=0):
   self._id += 1
   id= self._id
   t= self.createSubpage(url, postargs, forceget)
   testpage= Store.storeurl(t.url(), self._root + str(self._id),
     self._httproot)
   self._navFrame.write("""
     <a target="case" href="%(testpage)s">Test: %(id)s</a>
     <ul>
     """ % locals())
   if pagetests.__doc__ is not None:
     lines= pagetests.__doc__.split('\n')
     for line in lines:
       self._navFrame.write("""
         <li>%(line)s""" % locals())
   self._navFrame.write("</ul>")
   try:
     next= pagetests(t)
     self._navFrame.write("<b>passed</b><hr>\n")
     return next
   except TestFailed.TestFailed, args:
     msg= args[0]
     self._navFrame.write("<b>FAILED</b>: %(msg)s<hr>\n" % locals())
     return None
コード例 #47
0
class Menu():
	#initialize pygame
	init()
	def __init__(self, surface):
		"Initialize variables, load images, set flags, and fonts"
		self.surface = surface
		self.bg = transform.scale(image.load("res/main_bg.jpg").convert(), (surface.get_width(), surface.get_height()))
		self.carImage = image.load("res/front_car.png")
		self.arrow_left = image.load("res/arrow_left.png")
		self.carImageSized = transform.scale(self.carImage, (150, 100))
		self.carX, self.carY = 437,290
		self.width = self.carImageSized.get_width()
		self.height = self.carImageSized.get_height()
		self.logo = image.load("res/logo_perspective.png")
		self.running = True
		self.rightMenu = image.load("res/menu_right.png")
		self.rightMenuX, self.rightMenuY = 1024, 768
		self.menuFont = font.Font("res/fonts/pricedown.ttf", 35)
		#menu options with color, rects, text, and action on click
		self.optionColors = [(255,255,255),(255,255,255),(255,255,255),(255,255,255),(255,255,255)]
		self.optionRects = [Rect(825,455,self.menuFont.size("Start Game")[0]+10,self.menuFont.size("Start Game")[1]),Rect(825,505,self.menuFont.size("Store")[0]+10,self.menuFont.size("Store")[1]),Rect(825,555,self.menuFont.size("Options")[0]+10,self.menuFont.size("Options")[1]),Rect(825,605,self.menuFont.size("Help")[0]+10,self.menuFont.size("Help")[1]),Rect(825,655,self.menuFont.size("About")[0]+10,self.menuFont.size("About")[1])]
		self.options = ["Start Game", "Store", "Help", "About"]
		self.optionResults = [self.levelRunning,self.storeRunning,self.setHelp,self.setAbout]
		self.store = Store(surface)
		self.level = Level(surface)
		self.about = Popup(surface, "About", ["Developed By Rikin Katyal", "ICS3U Final Project 2015", "Made Using Python and Pygame"])
		self.help = Popup(surface, "Help", ["Use arrow keys or WASD to move.", "Press Space for emergency break.", "Earn coins to spend in the store.", "Drive through obstacles and park", "in marked parking spot."])
		self.help.images([image.load("res/arrows.png"), image.load("res/wasd.png"), image.load("res/coin_medium.png")],[(310,456),(470,450),(660,475)])
		self.settings = Popup(surface, "Settings", ["Sound Effects (SFX)", "Music"])
		self.aboutRunning = False
		self.helpRunning = False
		self.settingsRunning = False

	def render(self, down):
		"Main function to render menu"
		mx, my = mouse.get_pos()
		mb = mouse.get_pressed()
		self.pressed = key.get_pressed()
		# blit menu if not store adn not level
		if not self.store.isRunning() and not self.level.isRunning():
			self.surface.blit(self.bg, (0,0))
			self.width += 16
			self.height += 12
			self.carY += 6
			self.carX -= 8
			self.carImageSized = transform.scale(self.carImage, (self.width, self.height))
			#blit logo and move car down road
			if self.carY > 320:
				self.surface.blit(self.logo, (512-100,380))
			if self.carY < 768:
				self.surface.blit(self.carImageSized, (self.carX, self.carY))
			else:
				self.surface.blit(self.rightMenu, (self.rightMenuX, self.rightMenuY))
				if self.rightMenuX >= 590:
					self.rightMenuX -= 30
				if self.rightMenuY >= 350:
					self.rightMenuY -= 30
				if self.rightMenuX <= 590 and self.rightMenuY <= 350:
					for r in range(len(self.options)):
						# draw.rect(self.surface, (255,255,0), self.optionRects[r])
						if self.optionRects[r].collidepoint((mx,my)) and not self.aboutRunning and not self.helpRunning:
							self.optionColors[r] = (0,0,0)
							if mb[0]:
								self.optionResults[r]()
						else:
							self.optionColors[r] = (255,255,255)
						self.surface.blit(self.menuFont.render(self.options[r], 1, self.optionColors[r]), (830, 450+(r*50)))
		#blit store instead of menu
		elif self.store.isRunning():
			self.store.render(down)
		#blit level screen instead of menu
		elif self.level.isRunning():
			self.level.render()
		#if level is chosen, end menu screen
		if self.level.choseLevel:
			self.running = False
		#about popup
		if self.aboutRunning:
			self.about.render()
			self.aboutRunning = self.about.isRunning()
		#help popup
		elif self.helpRunning:
			self.help.render()
			self.helpRunning = self.help.isRunning()

	def isRunning(self):
		"Check if menu is running"
		return self.running

	def notRunning(self):
		"Stop running menu"
		self.running = False

	def storeRunning(self):
		"Check if store is running"
		self.store.running = True

	def levelRunning(self):
		"Check if level screen is running"
		self.level.running = True

	def setAbout(self):
		"Start about popup"
		self.aboutRunning = True

	def setHelp(self):
		"Start help popup"
		self.helpRunning = True
コード例 #48
0
ファイル: Game.py プロジェクト: cs360f14/JungleJamboree
class Game :

	def __init__(self) :
		"""sets running to true, and creates a party and begins setting
		 up a pygame display """
		 
		self._running = True
		self._display = None
		self._party = Party()
		self._turn = Turn()
		self._store = Store ()
		self._store.setUpStore ()
		self._party.setUpParty () 
		self._state = "Start"
		self._width = 800
		self._height = 600
		self._size = (self._width, self._height)
		pygame.init()
		pygame.font.init()
		self._display = pygame.display.set_mode(self._size)
		self._myFont1 = pygame.font.Font('freesansbold.ttf', 15)
		self._myFont2 = pygame.font.Font('freesansbold.ttf', 25)
		self._myFont3 = pygame.font.Font('freesansbold.ttf', 12)
		pygame.display.set_caption('Jungle Jamboree')
	
	def on_loop (self):
		""" main game loop that is executed while the game is running"""
		
		self._display.blit(imgStart, (0,0))
		self._display.blit(start, (400,400))
		while(True):
			mouse = pygame.mouse.get_pos()
			for event in pygame.event.get():
				"""allows you to see what the last input was in 
				the geany output window. un comment the line 
				below for testing """
			   #print event 

				#called when you hit the X
				if event.type == QUIT:
					pygame.quit()
					sys.exit()
					
				if self._party.checkPartyDead () :
					self._state == "GameOver"
					self.gameOver (event)
					
				if self._state == "GameOver":
					self.gameOver (event)
					
				elif self._state == "Start":
					self.startButton (mouse, event)
															
				elif self._state == "Store":
					self.store (mouse, event)
										
				elif self._state == "Home":
					self.home (mouse, event)
									
				elif self._state == "Inventory":
					self.inventory (mouse, event)
					
				elif self._state == "Party":
					self.party (mouse, event)
					
				elif self._state == "Forage":
					self.forage (mouse, event)
					
				elif self._state == "Travel":
					self.travel (mouse, event)
					pass

			#the update for the screen		
			pygame.display.update()
			
	def startButton (self, mouse, event) :
		""" from the opening screen, the start button takes the user
			to the store """
			
		if event.type == MOUSEBUTTONDOWN:
			if self.checkMouse (mouse, 395, 460, 395, 415) :
				self._state = "Store"
				
	def travel (self, mouse, event) :
		""" when the user decides to travel, the turn is updated
			and returned back to the home screen """
		
		self._display.blit(imgTravel, (0, 0))
		self._display.blit(leave1, (20, 550))
		self._turn.updateTurn(self._party, self._display)
		pygame.display.update()
		
		waitEvent = pygame.event.wait()
			
		while not (waitEvent.type == MOUSEBUTTONDOWN and  \
		self.checkMouse (mouse, 20, 60, 550, 570)) :
			mouse = pygame.mouse.get_pos()	
			waitEvent = pygame.event.wait()
			
		self._state = "Home"	
							
	def store (self, mouse, event) :
		""" store menu where the user may buy, sell, and trade items """
		
		self._display.blit(imgStore, (0, 0))
		self._display.blit(leave1, (20, 550))
		self._store.menu (self._party, self._display, mouse, event)
		option = self._store.getItemSelection(mouse, event)
		if event.type == MOUSEBUTTONDOWN:
			if self.checkMouse (mouse, 20, 60, 550, 570) :
				self._state = "Home"
							
	def home (self, mouse, event) :
		""" main home screen where the user can select from the options
			store, forage, inventory, party, and travel """
			
		self.displayHome (mouse, event)
		if event.type == MOUSEBUTTONDOWN:
			if self.checkMouse (mouse, 8, 95, 380, 405) :
				self._state = "Store"
		
		if event.type == MOUSEBUTTONDOWN:
			if self.checkMouse (mouse, 8, 160, 410, 435) :
				self._state = "Forage"
				
		if event.type == MOUSEBUTTONDOWN:
			if self.checkMouse (mouse, 8, 160, 440, 465) :
				self._state = "Inventory"
				
		if event.type == MOUSEBUTTONDOWN:
			if self.checkMouse (mouse, 8, 95, 470, 500) :
				self._state = "Party"
				
		if event.type == MOUSEBUTTONDOWN:			
			if self.checkMouse (mouse, 8, 95, 500, 535) :
				self._state = "Travel"
	
	def displayHome (self, mouse, event) :
		""" displays images for the home screen (background and party
			members) """
		
		self._display.blit(imgJungle, (0, 0))
		explorersDead = []
		for person in self._party.generatePerson():
			explorersDead.append(person.getHealthTitle ())
		if not explorersDead[0] == "Dead":	
			self._display.blit(imgPerson1, (281, 400))
		if not explorersDead[1] == "Dead":
			self._display.blit(imgPerson2, (386, 407))
		if not explorersDead[2] == "Dead":
			self._display.blit(imgPerson3, (200, 380))
		if not explorersDead[3] == "Dead":
			self._display.blit(imgPerson4, (145, 400))
		if not explorersDead[4] == "Dead":
			self._display.blit(imgPerson5, (563, 440))
		self._display.blit(store, (10, 380))
		self._display.blit(forage, (10, 410))
		self._display.blit(inventory, (10, 440))
		self._display.blit(party, (10, 470))
		
		travelFont = self._myFont2.render("TRAVEL", 1, (255,255,255))	
		self._display.blit(travelFont, (10, 500))
		self._turn.displayMenu(self._party, self._display)
		
	def forage (self, mouse, event) :
		""" forage option that displays the foraging screen. 
			if the party has not yet foraged this turn,
			they may forage. returns back to home screen """
			
		self._display.blit(imgForage, (0, 0))
		self._display.blit(leave1, (750, 575))
		self._turn.forageEvent(self._party, self._display)
		
		pygame.display.update()
		
		waitEvent = pygame.event.wait()
			
		while not (waitEvent.type == MOUSEBUTTONDOWN and  \
		self.checkMouse (mouse, 750, 800, 550, 600)):
			mouse = pygame.mouse.get_pos()	
			waitEvent = pygame.event.wait()

		self._state = "Home"
	
	def inventory (self, mouse, event) :
		""" inventory screen that displays the party inventory """
		
		self._display.blit(imgInventory, (0, 0))
		self._display.blit(leave2, (20, 550))
		self._party.getInventory().displayInventory(mouse, event, \
		self._display)

		if event.type == MOUSEBUTTONDOWN:
			if self.checkMouse (mouse, 20, 60, 550, 570) :
				self._state = "Home"

	def checkMouse (self, mouse, left, right, top, bottom):
		""" checks the mouse location """
		
		isIn = False
		if mouse[0]	> left and mouse[0] < right \
		and mouse[1] > top and mouse[1] < bottom :
			isIn = True
		return isIn

		
	def party (self, mouse, event):
		""" holds party information throughout the game and displays """
		
		explorers = []
		explorersStatus = []
		explorersHealth = []
		for person in self._party.generatePerson():
			explorers.append(testGame._myFont2.render(person.getName(), 1, (0,0,0)))
			explorersStatus.append(testGame._myFont2.render(person.getHealthTitle (), 1, (0,0,0)))
			explorersHealth.append(testGame._myFont2.render(str(person.getHealth ()), 1, (0,0,0)))

		self._display.blit(imgParty, (0, 0))
		self._display.blit(imgPerson1, (15, 15))
		self._display.blit(explorers[0], (100, 30))
		self._display.blit(explorersStatus[0], (100, 55))
		self._display.blit(explorersHealth[0], (100, 80))
		self._display.blit(imgPerson2, (15, 215))
		self._display.blit(explorers[1], (100, 230))
		self._display.blit(explorersStatus[1], (100, 255))
		self._display.blit(explorersHealth[1], (100, 280))
		self._display.blit(imgPerson3, (15, 415))
		self._display.blit(explorers[2], (100, 430))
		self._display.blit(explorersStatus[2], (100, 455))
		self._display.blit(explorersHealth[2], (100, 480))
		self._display.blit(imgPerson4, (400, 15))
		self._display.blit(explorers[3], (490, 30))
		self._display.blit(explorersStatus[3], (490, 55))
		self._display.blit(explorersHealth[3], (490, 80))
		self._display.blit(imgPerson5, (400, 215))
		self._display.blit(explorers[4], (490, 230))
		self._display.blit(explorersStatus[4], (490, 255))
		self._display.blit(explorersHealth[4], (490, 280))
		self._display.blit(leave1, (750, 575))
		if event.type == MOUSEBUTTONDOWN:
			if self.checkMouse (mouse, 750, 800, 550, 600) :
				self._state = "Home"
		
	def gameOver (self, event):
		""" once the game has ended (every party member has died),
			opens the game over screen """
		
		self._display.blit(imgGameOver, (0, 0))
		self._turn.displayEnd(self._party, self._display)
		mouse = pygame.mouse.get_pos()	
		print "Game Over"
		pygame.display.update ()
		waitEvent = pygame.event.wait()
		
		while not (waitEvent.type == QUIT) :
			mouse = pygame.mouse.get_pos()	
			waitEvent = pygame.event.wait()
		
		pygame.quit()
		sys.exit()
コード例 #49
0
ファイル: Triplify.py プロジェクト: bioinformatics-ua/ann2rdf
class Triplify:

    def __init__(self, prefix, namespace, ontologies):
        self.prefix = prefix
        self.namespace = Namespace(namespace)
        self.store = Store()
        self.store.bind(prefix, namespace)
        self.store.bind("ao", str(AO))
        self.store.bind("pav", str(PAV))
        self.store.bind("dc", str(DC))
        self.ontologies = ontologies
        for k in ontologies:
            self.store.bind(k, ontologies[k])

    def normalize(self, normalization):

        # For each ao:Annotation in the store get its ao:hasTopic property.
        '''
        topics = self.store.graph.objects(None, AO.hasTopic)
        for topic in topics:
            for value in self.store.graph.objects(topic, RDFS.label):
                norm_values = normalization.do_request(value)
                for norm_value in norm_values:

                    # try to convert 'GO:0005623' -> 'http://purl.org/obo/owl/GO#0005623'
                    if ':' in norm_value:
                        split = norm_value.split(':')
                        p = split[0].lower()
                        i = split[1].lower()
                        prefix = normalization.query_prefix_cc(p)
                        print prefix
                        if p in prefix:
                            self.store.bind(p, prefix[p])
                            self.store.add((topic, DC.related, URIRef(prefix[p]+i)))
                        else:
                            self.store.add((topic, DC.related, Literal(norm_value)))
                    else:

                    if str(norm_value).startswith('http'):
                        self.store.add((topic, DC.related, URIRef(norm_value)))
                    else:
                        self.store.add((topic, DC.related, Literal(norm_value)))
        '''

        annotations = self.store.graph.subjects(RDF.type, AO.Annotation)
        for annotation in annotations:
            contexts = self.store.graph.objects(annotation, AO.context)
            for context in contexts:
                for exact in self.store.graph.objects(context, AO.exact):
                    norm_values = normalization.normalize(exact)
                    for norm_value in norm_values:
                        if str(norm_value).startswith('http'):
                            self.store.add((annotation, AO.hasTopic, URIRef(norm_value)))
                        else:
                            self.store.add((annotation, AO.hasTopic, Literal(norm_value)))

    def process(self, annotations):

        # self.store.load('http://purl.org/ao/')

        counter = 0
        for annotation in annotations:

            counter += 1
            sys.stdout.write('\rTRIPLIFY: '+str(counter))
            sys.stdout.flush()

            # generate a unique id for the annotation set
            # b_id = BNode()
            b_id = '_' + annotation.hash

            # annotation
            ann_id = URIRef(self.namespace + annotation.id + b_id)
            self.store.add((ann_id, RDF.type, AO.Annotation))

            # context
            if annotation.context is not None:
                ann_context = URIRef(self.namespace + annotation.context.id + b_id)
                self.store.add((ann_context, RDF.type, AO.TextSelector))
                self.store.add((ann_context, AO.exact, Literal(annotation.context.exact)))
                for o in annotation.context.offset:
                    self.store.add((ann_context, AO.offset, Literal(o, datatype=XSD.integer)))
                for r in annotation.context.range:
                    self.store.add((ann_context, AO.range, Literal(r, datatype=XSD.integer)))
                self.store.add((ann_id, AO.context, ann_context))

            # tag
            for tag in annotation.tags:
                if str(tag).startswith('http'):
                    self.store.add((ann_id, AO.body, URIRef(tag)))
                else:
                    self.store.add((ann_id, AO.body, Literal(tag)))

            # topic
            for topic in annotation.topics:
                if str(topic).startswith('http'):
                    self.store.add((ann_id, AO.hasTopic, URIRef(topic)))
                elif ":" in str(topic):
                    split = topic.split(':')
                    k = split[0]
                    v = split[1]
                    if k in self.ontologies.keys():
                        self.store.add((ann_id, AO.hasTopic, URIRef(Namespace(self.ontologies[k])+v)))
                    else:
                        self.store.add((ann_id, AO.hasTopic, Literal(topic)))
                else:
                    self.store.add((ann_id, AO.hasTopic, Literal(topic)))

            # relations
            for relation in annotation.relations:
                ann_target = URIRef(self.namespace + relation.annotation + b_id)
                # if relation is not specified generalize one
                if relation.relation:
                    ann_relation = URIRef(self.namespace + relation.relation)
                else:
                    ann_relation = DC.related
                self.store.add((ann_id, ann_relation, ann_target))

            # source
            if annotation.source is not None:
                ann_source = URIRef(self.namespace + annotation.source.id)
                self.store.add((ann_source, RDF.type, PAV.SourceDocument))
                self.store.add((ann_source, DC.description, Literal(annotation.source.text)))
                self.store.add((ann_source, DC.identifier, Literal(annotation.source.id)))
                if annotation.source.retrievedFrom is not None:
                    self.store.add((ann_source, PAV.retrievedFrom, Literal(annotation.source.retrievedFrom)))
                if annotation.source.accessedOn is not None:
                    self.store.add((ann_source, PAV.sourceAccessedOn, Literal(annotation.source.accessedOn)))
                self.store.add((ann_id, AO.onSourceDocument, ann_source))

    # apply mappings available on the config file
    def map(self, mappings):
        tags = mappings['tags']
        relations = mappings['properties']

        for tag in tags:
            tag_to_remove = tag['if']
            tag_to_add = tag['then']
            for s in self.store.graph.subjects(AO.body, Literal(tag_to_remove)):
                self.store.remove((s, AO.body, Literal(tag_to_remove)))
                self.store.add((s, AO.body, Literal(tag_to_add)))

        for rel in relations:
            rel_to_remove = rel['if']
            rel_to_add = rel['then']
            rel_to_remove = URIRef(self.namespace + rel_to_remove)
            if str(rel_to_add).startswith('http'):
                rel_to_add = URIRef(rel_to_add)
            else:
                rel_to_add = URIRef(self.namespace + rel_to_add)
            for s, o in self.store.graph.subject_objects(rel_to_remove):
                self.store.remove((s, rel_to_remove, o))
                self.store.add((s, rel_to_add, o))

    def close(self):
        self.store.close()

    def show(self):
        s = self.store.serialize('turtle')
        logging.debug(s)

    def save_rdf(self, output):
        filename = output + '.rdf'
        s = self.store.serialize('xml')
        write_file(filename, s)
        logging.info('\nStore saved at: ' + filename)

    def save_ttl(self, output):
        filename = output + '.ttl'
        s = self.store.serialize('turtle')
        write_file(filename, s)
        logging.info('\nStore saved at: ' + filename)
コード例 #50
0
	def __init__ (self) :
		self._running = True
		self._display = None
		self._party = Party()
		self._turn = Turn ()
		self._store = Store ()
コード例 #51
0
ファイル: R305_api.py プロジェクト: girish946/python3-R305
def write():

    
    #first finger scan
    setBaud()    
    data = genImg.getHeader()
    ser.write(bytearray(data));
    time.sleep(1)
    s = ser.read(ser.inWaiting())
    print([hex(c) for c in s])
    genImg.parse(s)
    # generate character file of the finger image.
    setBaud()
    data = Img2Tz.getHeader(0x01)
    ser.write(bytearray(data));
    time.sleep(1)
    s = ser.read(ser.inWaiting())
    print([hex(c) for c in s])
    Img2Tz.parse(s)


    #second finger scan.
    setBaud()    
    data = genImg.getHeader()
    ser.write(bytearray(data));
    time.sleep(1)
    s = ser.read(ser.inWaiting())
    print([hex(c) for c in s])
    genImg.parse(s)
    #generate character file of the finger image.
    setBaud()
    data = Img2Tz.getHeader(0x02)
    ser.write(bytearray(data));
    time.sleep(1)
    s = ser.read(ser.inWaiting())
    print([hex(c) for c in s])
    Img2Tz.parse(s)


    #create RegModel
    setBaud()    
    data = RegModel.getHeader()
    ser.write(bytearray(data));
    time.sleep(1)
    s = ser.read(ser.inWaiting())
    print([hex(c) for c in s])
    RegModel.parse(s)
    #getTemplateNumber
    setBaud()    
    data = TemplateNum.getHeader()
    ser.write(bytearray(data));
    time.sleep(1)
    s = ser.read(ser.inWaiting())
    print([hex(c) for c in s])
    num = TemplateNum.parse(s)
    print ("recived template Number is "+ str(num))

    """
    setBaud()    
    data = DeleteAll.getHeader()
    ser.write(bytearray(data));
    time.sleep(1)
    s = ser.read(ser.inWaiting())
    print([hex(ord(c)) for c in s])
    print(DeleteAll.parse(s))"""

    
    setBaud()    
    data = Store.getHeader(0x01,int(num)+1 )
    print([hex(int(c)) for c in data])
    ser.write(bytearray(int(x) for x in data));
    time.sleep(1)
    s = ser.read(ser.inWaiting())
    print([hex(c) for c in s])
    print ( len(s))
    Store.parse(s)

     #getTemplateNumber
    setBaud()    
    data = TemplateNum.getHeader()
    ser.write(bytearray(data));
    time.sleep(1)
    s = ser.read(ser.inWaiting())
    print([hex(c) for c in s])
    num = TemplateNum.parse(s)
    print( "recived template Number is "+ str(num))    
コード例 #52
0
ファイル: main.py プロジェクト: redify/Projects
"""
Manage video rentals and controls when videos are checked out, due to return, 
overdue fees and for added complexity create a summary of those accounts which are overdue for contact.
"""

import Store

the_store = Store.store()

the_store.createAccount('bob')
the_store.createAccount('timmy')
the_store.createAccount('greg')

the_store.createMovie('timbucktoo')
the_store.createMovie('star trek 3')
the_store.createMovie('villia')

the_store.checkMovie('timmy', 'villia')

the_store.dumpAccountInfo('timmy')
コード例 #53
0
ファイル: Game.py プロジェクト: stan3971/JungleJamboree
class Game :

	def __init__(self) :
		"""sets running to true, and creates a party and begins setting
		 up a pygame display """
		self._running = True
		self._display = None
		self._party = Party()
		self._turn = Turn()
		self._store = Store ()
		self._store.setUpStore ()
		self._party.setUpParty () 
		self._state = "Start"
		self._width = 800
		self._height = 600
		self._size = (self._width, self._height)
		pygame.init()
		pygame.font.init()
		self._display = pygame.display.set_mode(self._size)
		self._myFont1 = pygame.font.Font('freesansbold.ttf', 15)
		self._myFont2 = pygame.font.Font('freesansbold.ttf', 25)
		self._myFont3 = pygame.font.Font('freesansbold.ttf', 12)
		pygame.display.set_caption('Jungle Jamboree')
	
	def on_loop (self):
		self._display.blit(imgStart, (0,0))
		self._display.blit(start, (400,400))
		while(True):
			mouse = pygame.mouse.get_pos()
			for event in pygame.event.get():
				#allows you to see what the last input was in the geany output window
				print event

				#called when you hit the X
				if event.type == QUIT:
					pygame.quit()
					sys.exit()
					
				if self._party.checkPartyDead () :
					self._state == "GameOver"
					self.gameOver ()
					
				if self._state == "GameOver":
					self.gameOver ()
					
				elif self._state == "Start":
					self.startButton (mouse, event)
															
				elif self._state == "Store":
					self.store (mouse, event)
										
				elif self._state == "Home":
					self.home (mouse, event)
									
				elif self._state == "Inventory":
					self.inventory (mouse, event)
					
				elif self._state == "Party":
					self.party (mouse, event)
					
				elif self._state == "Forage":
					self.forage (mouse, event)
					
				elif self._state == "Travel":
					self.travel (mouse, event)
					pass

			#the update for the screen		
			pygame.display.update()
			
	def startButton (self, mouse, event) :
		if event.type == MOUSEBUTTONDOWN:
			if self.checkMouse (mouse, 395, 460, 395, 415) :
				self._state = "Store"
				
	def travel (self, mouse, event) :
		self._display.blit(imgTravel, (0, 0))
		self._display.blit(leave1, (20, 550))
		self._turn.updateTurn(self._party, self._display)
		pygame.display.update()
		
		waitEvent = pygame.event.wait()
			
		while not (waitEvent.type == MOUSEBUTTONDOWN and  \
		self.checkMouse (mouse, 20, 60, 550, 570)) :
			mouse = pygame.mouse.get_pos()	
			waitEvent = pygame.event.wait()
			
		self._state = "Home"	
							
	def store (self, mouse, event) :
		self._display.blit(imgStore, (0, 0))
		self._display.blit(leave1, (20, 550))
		self._store.menu (self._party, self._display, mouse, event)
		option = self._store.getItemSelection(mouse, event)
		if event.type == MOUSEBUTTONDOWN:
			if self.checkMouse (mouse, 20, 60, 550, 570) :
				self._state = "Home"
							
	def home (self, mouse, event) :

		self.displayHome (mouse, event)
		if event.type == MOUSEBUTTONDOWN:
			if self.checkMouse (mouse, 8, 95, 380, 405) :
				self._state = "Store"
		
		if event.type == MOUSEBUTTONDOWN:
			if self.checkMouse (mouse, 8, 160, 410, 435) :
				self._state = "Forage"
				
		if event.type == MOUSEBUTTONDOWN:
			if self.checkMouse (mouse, 8, 160, 440, 465) :
				self._state = "Inventory"
				
		if event.type == MOUSEBUTTONDOWN:
			if self.checkMouse (mouse, 8, 95, 470, 500) :
				self._state = "Party"
				
		if event.type == MOUSEBUTTONDOWN:			
			if self.checkMouse (mouse, 8, 95, 500, 535) :
				self._state = "Travel"
	
	def displayHome (self, mouse, event) :
		self._display.blit(imgJungle, (0, 0))
		explorersDead = []
		for person in self._party.generatePerson():
			explorersDead.append(person.getHealthTitle ())
		if not explorersDead[0] == "Dead":	
			self._display.blit(imgPerson1, (281, 400))
		if not explorersDead[1] == "Dead":
			self._display.blit(imgPerson2, (386, 407))
		if not explorersDead[2] == "Dead":
			self._display.blit(imgPerson3, (200, 380))
		if not explorersDead[3] == "Dead":
			self._display.blit(imgPerson4, (145, 400))
		if not explorersDead[4] == "Dead":
			self._display.blit(imgPerson5, (563, 440))
		self._display.blit(store, (10, 380))
		self._display.blit(forage, (10, 410))
		self._display.blit(inventory, (10, 440))
		self._display.blit(party, (10, 470))
		
		travelFont = self._myFont2.render("TRAVEL", 1, (255,255,255))	
		self._display.blit(travelFont, (10, 500))
		self._turn.displayMenu(self._party, self._display)
		"""		
		dayString = "DAY:  " + str(self._turn.getDay())
		day = self._myFont2.render(dayString, 1, (255,255,255))	
		self._display.blit(day, (300, 270))
		
		disString = "DISTANCE:  " + str(self._turn.getDistance())
		distance = self._myFont2.render(disString, 1, (255,255,255))	
		self._display.blit(distance, (300, 300))
		
		foodString = "FOOD AMOUNT:  " + str(self._party.getFood())
		food = self._myFont2.render(foodString, 1, (255,255,255))	
		self._display.blit(food, (300, 330))
		"""				
	def forage (self, mouse, event) :
		self._display.blit(imgForage, (0, 0))
		self._display.blit(leave1, (750, 575))
		self._turn.forageEvent(self._party, self._display)
		if event.type == MOUSEBUTTONDOWN:
			if self.checkMouse (mouse, 750, 800, 550, 600) :
				self._state = "Home"
		
	def inventory (self, mouse, event) :
		self._display.blit(imgInventory, (0, 0))
		self._display.blit(leave2, (20, 550))
		self._party.getInventory().displayInventory(mouse, event, \
		self._display)

		if event.type == MOUSEBUTTONDOWN:
			if self.checkMouse (mouse, 20, 60, 550, 570) :
				self._state = "Home"

	def checkMouse (self, mouse, left, right, top, bottom):
		isIn = False
		if mouse[0]	> left and mouse[0] < right \
		and mouse[1] > top and mouse[1] < bottom :
			isIn = True
		return isIn

		
	def party (self, mouse, event):
		explorers = []
		explorersStatus = []
		explorersHealth = []
		for person in self._party.generatePerson():
			explorers.append(testGame._myFont2.render(person.getName(), 1, (0,0,0)))
			explorersStatus.append(testGame._myFont2.render(person.getHealthTitle (), 1, (0,0,0)))
			explorersHealth.append(testGame._myFont2.render(str(person.getHealth ()), 1, (0,0,0)))

		self._display.blit(imgParty, (0, 0))
		self._display.blit(imgPerson1, (15, 15))
		self._display.blit(explorers[0], (100, 30))
		self._display.blit(explorersStatus[0], (100, 55))
		self._display.blit(explorersHealth[0], (100, 80))
		self._display.blit(imgPerson2, (15, 215))
		self._display.blit(explorers[1], (100, 230))
		self._display.blit(explorersStatus[1], (100, 255))
		self._display.blit(explorersHealth[1], (100, 280))
		self._display.blit(imgPerson3, (15, 415))
		self._display.blit(explorers[2], (100, 430))
		self._display.blit(explorersStatus[2], (100, 455))
		self._display.blit(explorersHealth[2], (100, 480))
		self._display.blit(imgPerson4, (400, 15))
		self._display.blit(explorers[3], (490, 30))
		self._display.blit(explorersStatus[3], (490, 55))
		self._display.blit(explorersHealth[3], (490, 80))
		self._display.blit(imgPerson5, (400, 215))
		self._display.blit(explorers[4], (490, 230))
		self._display.blit(explorersStatus[4], (490, 255))
		self._display.blit(explorersHealth[4], (490, 280))
		self._display.blit(leave1, (750, 575))
		if event.type == MOUSEBUTTONDOWN:
			if self.checkMouse (mouse, 750, 800, 550, 600) :
				self._state = "Home"
		
	def gameOver (self):
		self._display.blit(imgGameOver, (0, 0))
		self._turn.displayEnd(self._party, self._display)
		mouse = pygame.mouse.get_pos()	
		print "Game Over"
		pygame.display.update ()
		waitEvent = pygame.event.wait()
		
		while not (waitEvent.type == MOUSEBUTTONDOWN ) :
			mouse = pygame.mouse.get_pos()	
			waitEvent = pygame.event.wait()