Esempio n. 1
0
def addPriceCardKingdom(ID):
    opener = AppURLopener()
    url = Get.getURL(5, ID)
    try:
        response = opener.open(url).read()
    except ValueError as e:
        return
    else:
        doc = lxml.html.document_fromstring(response)
        prices = doc.xpath("//span[@class='stylePrice']/text()")
        if prices != []:
            removedWhiteSpace = prices[0].replace(" ", "")
            removedNL = removedWhiteSpace.replace("\n", "")
            sendingPrice = removedNL.replace("$", "")
            if sendingPrice == "":
                prices = doc.xpath("//span[@class='salePrice']/text()")
                removedWhiteSpace = prices[0].replace(" ", "")
                removedNL = removedWhiteSpace.replace("\n", "")
                removedSale = removedNL.replace("Sale", "")
                sendingPrice = removedSale.replace("$", "")
            float(sendingPrice)
            oldPrice = Get.getPrice(5, ID)
            Get.addPrice(5, ID, sendingPrice)
            Get.updateHistoric1(ID)
            Get.updateHistoric2(5, oldPrice)
Esempio n. 2
0
def index():
    rewriting.FinalStats()
    form = InfoForm()
    
    dates = Get.GetDate()
    dates.insert(0,("--Choose a date--", "--Choose a date--"))
    dates.insert(1,("Last 3 days","Last 3 days"))
    dates.insert(2,("Last 7 days","Last 7 days"))

    form.date.choices = dates
    form.street.choices = [("--Choose station--", "--Choose station--")]
    form.pollutant.choices = [("--Choose pollutant--","--Choose pollutant--")]
    form.type.choices = [("--Choose type of data--", "--Choose type of data--")]

    if request.method == "POST":

        session["city"] = form.city.data
        session["street"] = form.street.data
        session["pollutant"] = form.pollutant.data
        session["date"] = form.date.data
        session["type"] = form.type.data
        FinalData = plot.GetFinalData(session["city"], session["street"],
                                     session["pollutant"], session["date"],
                                     session["type"])
        if FinalData == None:
            return render_template("plot.html", data = FinalData, url = 'static/images/newplot.png')
        else:
            return render_template("error.html", data = FinalData, url = 'static/images/newplot.png')

    return render_template("index.html", form = form )
Esempio n. 3
0
 def run(self):
     startime = time.time()
     while (time.time() - startime < self.T):
         for act in self.actList:
             if time.time() - startime > self.T:
                 return
             if act[0] == "GET":
                 self.__result.append(
                     Get.Get(act[1].strip(), act[2].strip()).submit())
             elif act[0] == "POST":
                 self.__result.append(
                     Post.Post(act[1].strip(), act[2].strip(),
                               act[3].strip()).submit())
             else:
                 if not act[1] == "-1":
                     time.sleep(int(act[1]))
                 else:
                     time.sleep(R.randint(0, 5))
     while True:
         if Global.mutex.acquire(5):
             # print self.i
             Global.result.append(self.__result)
             Global.mutex.release()
             break
         else:
             time.sleep(R.randint(0, 3))
Esempio n. 4
0
class InfoForm(FlaskForm):
    cities = [("--Choose your city--", "--Choose your city--")] + Get.GetCities()
    
    city = SelectField("Choose your city: ", choices = cities)
    street = SelectField("Choose your street: ", choices = [])
    pollutant = SelectField("Choose pollutant: ", choices = [])
    date = SelectField("Choose date: ", choices = [])
    type = SelectField("Choose type of data: ", choices = [])
Esempio n. 5
0
def look():
    '''
    Inspect your surroundings! Examine for clues!
    '''
    animaltext = ""
    if Get._checkexists(game.Vars()["animalname"]):
        animaltext = ''' You wonder if that $ANIMALNAME is friendly.'''
    print game.ParseText(game.Level().Look()+animaltext)
Esempio n. 6
0
def Search(Title):

    ScrollFramePosition = [ScreenSize[0]/2-20,ScreenSize[1]-100,ScreenSize[0]/2+10,50]# Width,Height,X,Y

    # Search from cached or web
    Prices, FinalSearchName, SearchedItems = Get.AvgPrice(None,Title,0,0,Title,0,AvgPriceDataBase1,ErrorsDataBase1,UPCDataBase1)

    FrameIndex = [str(a) for a in ImageWidgets]
    for ItemIndex in range(len(FrameIndex)):
        if('verticalscrolledframe' in FrameIndex[ItemIndex]):
            ImageWidgets[ItemIndex].destroy()

    # Place scrolled frame
    frame1 = VerticalScrolledFrame(MainWindow, height=ScrollFramePosition[1], width=ScrollFramePosition[0], bd=2, relief=SUNKEN)
    frame1.place(x=ScrollFramePosition[2], y=ScrollFramePosition[3])
    ImageWidgets.append(frame1)

    #Duplicate text from PackImageFromURL, Move to function
    Links = []
    def AddLinkToText(PositionInLinks,URL):
        Links[PositionInLinks].bind("<Button-1>", lambda e: OpenInBrowzer(URL))

    p = 0
    rowCount = 5

    Images = []
    for i in SearchedItems:
        Images.append(i[1])

    LoadImages(Images)

    for i in SearchedItems:
        if (i[1] != ""):
            ImageData = GetImageData(i[1], 500, 500)

            if ImageData == None: pass

            render = ImageTk.PhotoImage(ImageData)
            img = Label(frame1.interior, image=render)
            img.image = render

            # Create Image Widget
            ImageWidgets.append(img)
            img.grid(row=p * rowCount, column=0, rowspan=5)

        WrapLength = 400
        link1 = Label(frame1.interior, text=SimplifyString(str(i[2])), fg="blue", cursor="hand2", wraplength=WrapLength)
        link1.config(font=("Comic Sans MS", 15))
        ImageWidgets.append(link1)
        link1.grid(row=p * rowCount, column=1)
        Links.append(link1)
        AddLinkToText(p, i[0])

        link1 = Label(frame1.interior, text=SimplifyString(str(i[3])), wraplength=WrapLength)
        link1.config(font=("Comic Sans MS", 15))
        link1.grid(row=p * rowCount + 1, column=1)

        p = p + 1
def on_off():
    hardware_status = Get.get_Status()
    if hardware_status["pomp_status"]:
        GPIO.output(RELAIS_1_GPIO, GPIO.HIGH)
    elif hardware_status["pomp_status"] == False:
        GPIO.output(RELAIS_1_GPIO, GPIO.LOW)
    if hardware_status["lamp_status"]:
        GPIO.output(RELAIS_2_GPIO, GPIO.HIGH)
    elif hardware_status["lamp_status"] == False:
        GPIO.output(RELAIS_2_GPIO, GPIO.LOW)
Esempio n. 8
0
def type(date):
    types = Get.GetType(date)
    typeList = []

    for type in types:
        typeObj = {}
        typeObj["id"] = type[0]
        typeObj["name"] = type[1]
        typeList.append(typeObj)

    return jsonify({"types": typeList})
Esempio n. 9
0
def pollutant(street):
    pollutants = Get.GetPollutant1(street)
    pollutants.insert(0,("--Choose pollutant--", "--Choose pollutant--"))
    pollutantList = []

    for pollutant in pollutants:
        pollutantObj = {}
        pollutantObj["id"] = pollutant[0]
        pollutantObj["name"] = pollutant[1]
        pollutantList.append(pollutantObj)

    return jsonify({"pollutants": pollutantList})
Esempio n. 10
0
def street(city):
    streets = Get.GetStreets(city)
    streets.insert(0,("--Choose street--", "--Choose street--"))
    streetList = []

    for street in streets:
        streetObj = {}
        streetObj["id"] = street[0]
        streetObj["name"] = street[1]
        streetList.append(streetObj)

    return jsonify({"streets": streetList})
Esempio n. 11
0
def eat(thing):
    strthing = str(thing)
    if not strthing in game.Inventory():
        print game.ParseText(
            '''If it's not in your inventory you can't eat it! What are you gonna do, 
scarf it off the floor, $PLAYERNAME? For serious.''')
        return
    print game.ParseText(text[strthing])
    if strthing in deadly:
        game.Restart()
    if strthing in win:
        game.Win()
    Get.RemoveFromInventory(thing)
Esempio n. 12
0
 def run(self):
     startime = time.time()
     gt = Get.Get(self.url, self.path)
     while (time.time() - startime < self.T):
         self.__result.append(gt.submit())
     while True:
         if Global.mutex.acquire(5):
             # print self.i
             Global.result.append(self.__result)
             Global.mutex.release()
             break
         else:
             time.sleep(R.randint(0, 3))
Esempio n. 13
0
def addPriceAbuGames(ID):
    opener = AppURLopener()
    url = Get.getURL(4, ID)
    try:
        response = opener.open(url).read()
    except ValueError as e:
        return
    else:
        doc = lxml.html.document_fromstring(response)
        prices = doc.xpath("//td[@class='itementry']/text()")
        sendingPrice = prices[1].replace("$", "")
        float(sendingPrice)
        oldPrice = Get.getPrice(4, ID)
        Get.addPrice(4, ID, sendingPrice)
        Get.updateHistoric1(ID)
        Get.updateHistoric2(4, oldPrice)
Esempio n. 14
0
def addPriceTrollAndToad(ID):
    opener = AppURLopener()
    url = Get.getURL(2, ID)
    try:
        response = opener.open(url).read()
    except ValueError as e:
        return
    else:
        doc = lxml.html.document_fromstring(response)
        prices = doc.xpath("//div[@class='priceSection']/text()")
        sendingPrice = prices[0].replace("$", "")
        float(sendingPrice)
        oldPrice = Get.getPrice(2, ID)
        Get.addPrice(2, ID, sendingPrice)
        Get.updateHistoric1(ID)
        Get.updateHistoric2(2, oldPrice)
Esempio n. 15
0
def main(argv):
    try:
        if len(sys.argv) < 3:
            if sys.argv[1] == "-h" or sys.argv[1] == "--help":
                usage()
                sys.exit()
            else:
                clierror()
                sys.exit(2)
        else:
            if sys.argv[2] != "1" and sys.argv[2] != "2":  # check the input
                clierror()
                sys.exit(2)
            else:
                opts, args = getopt.getopt(argv, "so:pc",
                                           ["show", "ofile=", "post", "copy"])

        lyrics = Get.getlyrics(sys.argv[1], sys.argv[2])

    except getopt.GetoptError:
        print("error: missing a mandatory option.Use -h or --help for help")
        sys.exit(2)

    for opt, arg in opts:
        if opt in ("-s", "--show"):
            print(lyrics)
        elif opt in ("-o", "--ofile"):
            out.out(arg, lyrics)
        elif opt in ("-p", "--post"):
            try:
                for i in range(0, 100):
                    input(i + 1)
                    Post.post("♬" +
                              lyrics.splitlines()[i][11:].replace(" ", ""))
                    print("♬" + lyrics.splitlines()[i][11:].replace(" ", ""))
            except:
                print("输出完成")
        elif opt in ("-c", "--copy"):
            try:
                for i in range(1, 100):
                    Copy.inputtxt("♬" +
                                  lyrics.splitlines()[i][11:].replace(" ", ""))
                    print(lyrics.splitlines()[i][11:].replace(" ", ""))
                    input(i + 1)
            except:
                print("输出完成")
def addPriceToyWiz(ID):
    opener = AppURLopener()
    url = Get.getURL(3, ID)
    try:
        response = opener.open(url).read()
    except ValueError as e:
        return
    else:
        doc = lxml.html.document_fromstring(response)
        prices = doc.xpath("//span[@class='price price--withoutTax']/text()")
        if prices != []:
            stockCheck = doc.xpath(
                "//p[@class='alertBox-column alertBox-message']/span/text()")
            if (stockCheck == []):
                removedWhiteSpace = prices[0].replace(" ", "")
                removedNL = removedWhiteSpace.replace("\n", "")
                removedTab = removedNL.replace("\t", "")
                sendingPrice = removedTab.replace("$", "")
                float(sendingPrice)
                oldPrice = Get.getPrice(3, ID)
                Get.addPrice(3, ID, sendingPrice)
                Get.updateHistoric1(ID)
                Get.updateHistoric2(3, oldPrice)
Esempio n. 17
0
def addPriceTCGPlayer(ID):
    #get(site, cardID)
    opener = AppURLopener()
    url = Get.getURL(1, ID)
    try:
        response = opener.open(url).read()
    except ValueError as e:
        return
    else:
        doc = lxml.html.document_fromstring(response)
        prices = doc.xpath("//td[@class='priceGuidePricePointData']/text()")
    # doc = lxml.html.document_fromstring(check(url))
    # prices = doc.xpath("//td[@class='priceGuidePricePointData']/text()")
    if prices != []:
        if prices[0] == "N/A":
            sendingPrice = prices[1].replace("$", "")
        else:
            sendingPrice = prices[0].replace("$", "")
        float(sendingPrice)
        oldPrice = Get.getPrice(1, ID)
        #print(oldPrice)
        Get.addPrice(1, ID, sendingPrice)
        Get.updateHistoric1(ID)
        Get.updateHistoric2(1, oldPrice)
Esempio n. 18
0
	def GetAnswer(self):
		buffer = Utils.FileOpener()
		send = Put(self.__socket, self.address, self.port)
		errors = Errors(self.address, self.port)
		data_rec = Structure(self.request)
		file = None
		blk_num = 0
		connect = True
		print("Filename : " + self.filename)
		filename = self.filename.split('/')
		if 1 == len(filename):
			self.filename = filename[0]
		else:
			self.__send__error__(0x02, errors, "access violation")
			connect = False
		if self.mode == WRITE_REQUEST:
			send.send_ack(0)
			file = buffer.openfile(self.path + self.filename, 'wb+')
		elif self.mode == READ_REQUEST:
			file = buffer.openfile(self.path + self.filename, 'rb')
		if file is None:
			if self.mode == WRITE_REQUEST:
				"""--------------------------------------------------------------------------------------------------"""
				"""                                           access violation                                       """
				"""--------------------------------------------------------------------------------------------------"""
				self.__send__error__(0x02, errors, "access violation")
				connect = False
			if self.mode == READ_REQUEST:
				"""--------------------------------------------------------------------------------------------------"""
				"""                                           file not found                                         """
				"""--------------------------------------------------------------------------------------------------"""
				self.__send__error__(0x01, errors, "unable to read file : " + self.filename)
				connect = False
		restart = False
		write_err = False
		opcode = 0x04
		init = False
		while connect:
			init = False
			recv = Get(self.mode, self.__socket, self.address, self.port)
			if self.mode == READ_REQUEST:
				"""--------------------------------------------------------------------------------------------------"""
				"""                                           send file                                              """
				"""--------------------------------------------------------------------------------------------------"""
				if not restart and opcode == ACK:
					blk = buffer.readfile()
					blk_num += 1
				if opcode == READ_REQUEST and blk_num == 1:
					"""----------------------------------------------------------------------------------------------"""
					"""                                         resend init ack                                      """
					"""----------------------------------------------------------------------------------------------"""
					rand = randint(0, 100)
					if rand >= self.average:
						send.send_content(blk_num, blk)
					init = True
					data, addr = self.__socket.recvfrom(PACKET_SIZE)
					self.port = addr[1]
					send.port = addr[1]
					opcode = struct.unpack("!h", data[0:2])[0]
				if opcode == ACK and not init:
					"""----------------------------------------------------------------------------------------------"""
					"""                                        send next block or lost block                         """
					"""----------------------------------------------------------------------------------------------"""
					rand = randint(0, 100)
					if rand >= self.average or len(blk) < DATA_SIZE:
						send.send_content(blk_num, blk)
						restart = False
					else:
						restart = True
					"""----------------------------------------------------------------------------------------------"""
					"""                                        recv ack                                              """
					"""----------------------------------------------------------------------------------------------"""
					data, addr = self.__socket.recvfrom(PACKET_SIZE)
					self.port = addr[1]
					send.port = addr[1]
					opcode = struct.unpack("!h", data[0:2])[0]
					structure = data_rec.get_ack_struct(data)
					if structure.block == blk_num:
						"""------------------------------------------------------------------------------------------"""
						"""                                      block matching                                      """
						"""------------------------------------------------------------------------------------------"""
						restart = False
					elif structure.block > blk_num:
						"""------------------------------------------------------------------------------------------"""
						"""                                      block not matching                                  """
						"""------------------------------------------------------------------------------------------"""
						rand = randint(0, 100)
						if rand >= self.average:
							self.__send__error__(0x04, errors, 'invalid id : ' + structure.block)
						restart = True
					else:
						restart = True
				else:
					restart = True
				if len(blk) < DATA_SIZE:
					timer = Timeout(5.0, self.__socket)
					"""----------------------------------------------------------------------------------------------"""
					"""                                       final blk                                              """
					"""----------------------------------------------------------------------------------------------"""
					while connect:
						try:
							max_exceed = timer.start_timer()
							if -1 == max_exceed:
								print("closing connection")
								connect = False
							else:
								data, addr = self.__socket.recvfrom(PACKET_SIZE)
								opcode = struct.unpack("!h", data[0:2])[0]
								if opcode == ACK:
									if struct.unpack('!h', data[2:4])[0] == blk_num:
										connect = False
										print("True " + str(blk_num) + " " + str(data[2:4]))
									else:
										print("False " + str(blk_num) + " " + str(data[2:4]))
										connect = True
								elif opcode == READ_REQUEST or opcode == WRITE_REQUEST:
									return (data, addr)
								else:
									send.send_content(blk_num, blk)
									connect = True
						except socket.timeout:
							connect = False
			elif self.mode == WRITE_REQUEST:
				"""--------------------------------------------------------------------------------------------------"""
				"""                                           recv file                                              """
				"""--------------------------------------------------------------------------------------------------"""
				data, addr = self.__socket.recvfrom(PACKET_SIZE)
				self.port = addr[1]
				send.port = addr[1]
				timer = Timeout(5.0, self.__socket)
				opcode = struct.unpack("!h", data[0:2])[0]
				if opcode == WRITE_REQUEST and blk_num == 0:
					"""----------------------------------------------------------------------------------------------"""
					"""                                         resend ack                                           """
					"""----------------------------------------------------------------------------------------------"""
					send.send_ack(0)
				elif opcode == DATA:
					"""----------------------------------------------------------------------------------------------"""
					"""                                       recv next data                                         """
					"""----------------------------------------------------------------------------------------------"""
					structure = data_rec.get_data_struct(data)
					if structure.block == blk_num + 1:
						self.port = addr[1]
						"""------------------------------------------------------------------------------------------"""
						"""                                      block matching                                      """
						"""------------------------------------------------------------------------------------------"""
						if not restart:
							write = buffer.writefile(structure.data)
							if write < len(structure.data):
								self.__send__error__(0x03, errors, "disk full")
								connect = False
								write_err = True
							else:
								write_err = False
						blk_num += 1
						rand = randint(0, 100)
						if rand >= self.average or len(structure.data) < DATA_SIZE:
							if not write_err:
								send.port = addr[1]
								send.send_ack(structure.block)
							restart = False
						else:
							rand = randint(0, 100)
							if rand >= self.average:
								self.__send__error__(0x04, errors, "invalid transfer id : " + structure.block)
							restart = True
					else:
						"""------------------------------------------------------------------------------------------"""
						"""                                      block not matching                                  """
						"""------------------------------------------------------------------------------------------"""
						self.__send__error__(0x04, errors, "wrong block id for file: " + self.filename)
						restart = True
				else:
					"""----------------------------------------------------------------------------------------------"""
					"""                                          other error                                         """
					"""----------------------------------------------------------------------------------------------"""
					self.__send__error__(0x05, errors, "Operation not permitted during transfer:" + opcode)
					connect = False
				if len(structure.data) < DATA_SIZE and opcode == DATA:
					"""----------------------------------------------------------------------------------------------"""
					"""                                       final ack                                              """
					"""----------------------------------------------------------------------------------------------"""
					while connect:
						try:
							max_exceed = timer.start_timer()
							if -1 == max_exceed:
								print("closing connection")
								connect = False
							else:
								data, addr = self.__socket.recvfrom(PACKET_SIZE)
								opcode = struct.unpack("!h", data[0:2])[0]
								if opcode == ACK:
									if struct.unpack("!h", data[2:4])[0] == blk_num:
										print("True " + str(blk_num) + " " + str(data[2:4]))
										connect = False
									else:
										print("False " + str(blk_num) + " " + str(data[2:4]))
										connect = True
								elif opcode == READ_REQUEST or opcode == WRITE_REQUEST:
									return data, addr
								else:
									send.send_ack(blk_num)
									connect = True
						except socket.timeout:
							connect = False
			else:
				self.__send__error__(0x05, errors, "Operation not permitted :" + str(self.mode))
				connect = False
		return None, None
Esempio n. 19
0
def use(thinga, thingb):
    stra = str(thinga)
    strb = str(thingb)
    if stra == strb:
        print game.ParseText(
            "You think you're being clever, $PLAYERNAME, but you're not.")
        return
    if not stra in game.Inventory():
        print game.ParseText(
            "Yo, $PLAYERNAME, that's not in your inventory. Soz and all that.")
        return
    if not thingb in game.Vars() or strb in game.Inventory():
        print game.ParseText(
            "Yeah, that's not a thing that exists either in the world or in your inventory. So, no."
        )
        return
    if stra == "sword":
        if strb == "cyberogres":
            if "llama" in game.Inventory():
                print game.ParseText(
                    '''You mount the llama. Your mighty steed charges the cyberogres, 
killing one with a blow from its hooves. You slay the second with a slash of your cybersword. You are victorious!'''
                )
                game.Win()
            elif "t-rex" in game.Inventory():
                print game.ParseText(
                    '''You mount the t-rex and raise your sword towards you foes. 
It charges them down, swallowing them both with a mighty gulp. You are victorious!'''
                )
                game.Win()
            else:
                print game.ParseText(
                    '''You brandish your cybersword. The cyberogres pop into a fighting stance.
You slash at the first cyberogre, slaying them with a mighty blow. The second one comes up behind you and 
crushes your skull. You needed that skull! Man.''')
                game.Restart()
            return
        if strb == "player":
            print game.ParseText("Uh, you stab yourself. OK.")
            game.Restart()
        if strb == "llama":
            print game.ParseText(
                '''Why would you... uh, whatever. You stab the llama and it dies. Monster.'''
                + modstr)
            Get.RemoveFromInventory(thingb)
            return
        if strb == "t-rex":
            print game.ParseText(
                '''You brandish the sword at the t-rex. The t-rex is having none of that and eats you.'''
            )
            game.Restart()
    if stra == "llama":
        if strb == "cyberogres":
            print game.ParseText(
                '''The cyberogres rip the llama in two. "LLAAAAAMAAAAAA!" you cry, distraught. '''
                + modstr)
            return
        if strb == "sword":
            print game.ParseText(
                '''The llama looks at the sword, but doesn't quite understand how that might work.'''
            )
            return
        if strb == "t-rex":
            print game.ParseText('''The t-rex eats the llama. Monster.''' +
                                 modstr)
            Get.RemoveFromInventory(thinga)
            return
        if strb == "player":
            print game.ParseText('''The llama licks you. Ew. Ew.''')
            return
        if strb == "haxsnax":
            print game.ParseText('''The llama eats the haxsnax. Yum.''')
            Get.RemoveFromInventory(thingb)
            return
    if stra == "cyberogres":
        if strb == "player":
            print game.ParseText(
                '''The cyberogres are angry at being trapped in your inventory and murder you. So.'''
            )
            game.Restart()
        if strb == "haxsnax":
            print "The cyberogres eat your haxsnax! Oh no!"
            Get.RemoveFromInventory(thingb)
            return
        if strb == "sword":
            print game.ParseText(
                "So you decide to give two dangerous cyberogres your only weapon. Whatever, it's your adventure."
            )
            Get.RemoveFromInventory(thingb)
            return
    if stra == "t-rex":
        if strb == "llama":
            use(thingb, thinga)
            return
        if strb == "haxsnax":
            print game.ParseText(
                "The t-rex chomps down the haxsnax. It is hungry no more! Success. Cybersuccess."
            )
            Get.RemoveFromInventory(thingb)
            thinga.Hungry(False)
            return
        if strb == "sword":
            print game.ParseText(
                "The t-rex's arms are too small to use the sword. Alas.")
            return
        if strb == "cyberogres":
            print game.ParseText(
                "The t-rex eats the cyberogres. This is incredibly grizzly to watch, but, uh, victory, I guess?"
            )
            game.Win()
    if stra == "haxsnax":
        if strb == "llama" or strb == "t-rex" or strb == "cyberogres":
            use(thingb, thinga)
            return
        if strb == "player":
            print game.ParseText('''Cyberlicious! You eat the haxsnax.''')
            Get.RemoveFromInventory(thingb)
            return
    if stra == "player":
        use(thingb, thinga)
        return

    # Default failure text
    game.ParseText(
        '''You know what, I can't be bothered to make up an interaction between those things, so no, you can't do that.'''
    )
Esempio n. 20
0
 def GetAnswer(self, mode):
     recv = Get(mode, self.__socket, self.address, self.port)
     timeout = True
     timer = self.timer
     reply = None
     connect = True
     message_id = -1
     buffer = Utils.FileOpener()
     errors = Errors(self.address, self.port)
     file = False
     if mode == READ_REQUEST:
         mode = 0x03
         file = buffer.openfile(self.output_file, 'wb+')
         if None == file:
             self.__send__error__(0x02, errors, "access violation")
     elif mode == WRITE_REQUEST:
         mode = 0x01
         message_id = 0
         while timeout:
             timeout = False
             try:
                 exceed = timer.start_timer()
                 if exceed == -1:
                     self.__socket.close()
                     print("no ack for write request received")
                     return
                 reply = recv.get_ack()
                 if type(reply) is tuple:
                     if errors.is_critical(reply[0], reply[1]):
                         errors.print_error()
                         timer.cancel_timer()
                         self.__socket.close()
                         return
                     else:
                         errors.print_error()
                         timeout = True
                         timer.cancel_timer()
             except socket.timeout:
                 rand = randint(0, 100)
                 if rand >= self.average:
                     self.__socket.sendto(self.request_packed,
                                          (self.address, self.port))
                 timeout = True
         file = buffer.openfile(self.input_file, 'rb')
         if None == file:
             self.__send__error__(0x01, errors, "file not found")
     if None == file:
         self.__socket.close()
         return
     restart = False
     while connect:
         if mode == 0x01:
             """ send file """
             get = Get(WRITE_REQUEST, self.__socket, self.address,
                       self.port)
             send = Put(self.__socket, self.address, self.port)
             if not restart:
                 data = buffer.readfile()
                 message_id += 1
             rand = randint(0, 100)
             if rand >= self.average:
                 send.send_content(message_id, data)
             if len(data) < DATA_SIZE:
                 connect = False
             try:
                 restart = False
                 max_exceed = timer.start_timer()
                 if -1 == max_exceed:
                     print("connection lost")
                     break
                 reply = get.get_ack()
                 if type(reply) is tuple:
                     if errors.is_critical(reply[0], reply[1]):
                         errors.print_error()
                         break
                     else:
                         restart = True
                         max_exceed = timer.restart_timer()
                         if -1 == max_exceed:
                             print("connection lost")
                             break
                         self.__send__error__(0x04, errors,
                                              "id invalid " + str(reply[0]))
                         errors.print_error()
                         connect = True
                 else:
                     timer.cancel_timer()
                     if reply != message_id:
                         self.__send__error__(0x04, errors,
                                              "invalid id" + str(reply))
                         errors.print_error()
                         connect = True
                         restart = True
             except socket.timeout:
                 connect = True
                 restart = True
         elif mode == 0x03:
             """ get file """
             send = Put(self.__socket, self.address, self.port)
             get = Get(READ_REQUEST, self.__socket, self.address, self.port)
             try:
                 max_exceed = timer.start_timer()
                 if -1 == max_exceed:
                     print("connection lost")
                     break
                 reply = get.get_content()
                 if get.error:
                     if errors.is_critical(reply[0], reply[1]):
                         errors.print_error()
                         break
                     else:
                         restart = True
                         max_exceed = timer.restart_timer()
                         if -1 == max_exceed:
                             print("connection lost")
                             break
                 else:
                     if len(reply[1]) < DATA_SIZE:
                         connect = False
                     timer.cancel_timer()
                     if buffer.writefile(reply[1]) < len(reply[1]):
                         self.__send__error__(0x03, errors, "disk full")
                         break
             except socket.timeout:
                 restart = True
             if not restart:
                 message_id += 1
             rand = randint(0, 100)
             if message_id == 0 and restart:
                 if rand >= self.average:
                     self.__socket.sendto(self.request_packed,
                                          (self.address, self.port))
             else:
                 if rand >= self.average:
                     send.send_ack(message_id)
             if not connect:
                 final_ack = False
                 while not final_ack:
                     try:
                         exceed = timer.start_timer()
                         if exceed == -1:
                             break
                         content = recv.get_content()
                         rand = randint(0, 100)
                         if rand >= self.average:
                             send.send_ack(message_id)
                     except socket.timeout:
                         final_ack = True
     self.__socket.close()
     return
Esempio n. 21
0
def get(thing):
    '''
    Get the thing. Get it! Put it in your inventory.
    '''
    Get.get(thing)
Esempio n. 22
0
def Analisis(ItemsList):
    OutOfCalls = 0
    global MaxCalls
    driver = None

    UPCDataBase = TinyDB(
        os.path.dirname(os.path.dirname(__file__)) + "/DataBase/LinkToUPC")
    ShippingDataBase = TinyDB(
        os.path.dirname(os.path.dirname(__file__)) +
        "/DataBase/LinkToShipping")
    AvgPriceDataBase = TinyDB(
        os.path.dirname(os.path.dirname(__file__)) +
        "/DataBase/LinkToAvgPrice")
    ErrorsDataBase = TinyDB(
        os.path.dirname(os.path.dirname(__file__)) + "/Logs/Errors")
    WebDriverPath = os.path.dirname(
        os.path.dirname(__file__)) + '/Drivers/chromedriver.exe'

    TotalCount = len(ItemsList)  # Total Count of items to search

    if (MaxCalls == 0):  # No maximum call count
        CallCount = len(ItemsList)
    elif MaxCalls > len(ItemsList):  # More calls than items
        CallCount = len(ItemsList)
    else:  # Call count is limited by Maximum calls
        CallCount = MaxCalls

    LastCycle = time.time() * 2  # Record cycle time for time predictions
    RecordedCycleTime = []  # Initilize empty time per cycle array
    for Item in range(CallCount):  # For every item
        CycleTime = time.time(
        ) - LastCycle  # Calculate time it took for last item to be analized
        RecordedCycleTime.append(CycleTime)  # Keep track of number

        # If more than 300 numbers remove the first number in the list, or if the first number is negative and there is more than one number
        if (len(RecordedCycleTime) > 300
                or (RecordedCycleTime[0] < 0 and len(RecordedCycleTime) >= 2)):
            RecordedCycleTime = RecordedCycleTime[1:len(RecordedCycleTime)]

        # Calculate expected time remaining in mins
        ExpectedTimeRemaining = statistics.mean(RecordedCycleTime) * (
            TotalCount - Item) / 60
        LastCycle = time.time()  # Record start time for analysis

        # Get Item information
        ItemSearchKeywords = ItemsList[Item]['SearchKeywords']
        ItemURL = ItemsList[Item]['viewItemURL'][0]
        ItemTitle = ItemsList[Item]['title'][0]
        ItemUPC = Get.UPC(ItemURL, UPCDataBase)
        ItemPrice = ItemsList[Item]['sellingStatus'][0][
            'convertedCurrentPrice'][0]['__value__']
        ItemShippingType = ItemsList[Item]['shippingInfo'][0]['shippingType'][
            0]
        try:
            ItemPicture = ItemsList[Item]['pictureURLSuperSize'][0]
        except:
            try:
                ItemPicture = ItemsList[Item]['galleryURL'][0]
            except:
                ItemPicture = ""
        ItemName = ItemsList[Item]['title'][0]

        #Display stuff
        sys.stdout.write("\rSearching %d" % Item + " of %d" % TotalCount +
                         " " +
                         "Minutes Remainging: %.2f" % ExpectedTimeRemaining +
                         " " + str(ItemTitle) + " ")
        sys.stdout.flush()

        #Calculating Endtime of listing
        ItemEndTime = ItemsList[Item]['listingInfo'][0]['endTime'][0]
        Year = int(ItemEndTime[0:4])
        Month = int(ItemEndTime[5:7])
        Dayy = int(ItemEndTime[8:10])
        Hour = int(ItemEndTime[11:13])
        Minute = int(ItemEndTime[14:16])
        dt = datetime.datetime(Year, Month, Dayy, Hour, Minute, 0)
        UnixEndingStamp = time.mktime(dt.timetuple())

        if (float(UnixEndingStamp) <
                time.time()):  # Item auction end time has passed
            print('Auction ended already for: ' + str(ItemURL))

        # Get shipping on items where shipping changes for different places
        if ItemShippingType == 'Calculated' or ItemShippingType == 'CalculatedDomesticFlatInternational' or ItemShippingType == 'FreePickup':
            ItemShipping, driver = Get.Shipping(ItemURL, driver,
                                                ShippingDataBase,
                                                WebDriverPath)
        else:
            try:
                ItemShipping = ItemsList[Item]['shippingInfo'][0][
                    'shippingServiceCost'][0]['__value__']
            except:
                continue

        global Lot
        Prices, FinalSearchName, SearchedItems = Get.AvgPrice(
            ItemURL,
            ItemTitle,
            OutOfCalls,
            float(ItemPrice) + float(ItemShipping),
            ItemSearchKeywords,
            float(UnixEndingStamp),
            AvgPriceDataBase,
            ErrorsDataBase,
            UPCDataBase,
            ImageURL=ItemPicture)

        if ('Multi Item Auction Found' in FinalSearchName):
            Info = [
                float(ItemPrice) + float(ItemShipping),
                str(ItemURL),
                str(False)
            ]
            Lot.append(Info)  # Store item info in Lot variable and in GUI
            Logs.Write("Found Lot Item: " + str(Info))
            AddToGUI(ItemName, FinalSearchName,
                     str(float(ItemPrice) + float(ItemShipping)), "",
                     ItemPicture, ItemURL, [])

        if (FinalSearchName == None
                or ItemTitle == None):  # Issues getting specific item names
            print("Error: 24, None type")
            print(FinalSearchName)
            print(ItemTitle)
            print(ItemURL)
            Logs.Write("Error: 24, None type " + str(FinalSearchName) + " " +
                       str(ItemTitle) + " " + str(ItemURL) + " " +
                       str(ItemPrice) + " " + str(ItemShipping))
            continue

        if (Prices == -2):  #Out of calls
            OutOfCalls = 1
            continue

        if Prices == -1 or Prices == None:  # Error finding avg price
            continue

        if ItemSearchKeywords in SpecificProductSearch:  # If item needs to be evaluated by Specific Product Search
            global SpecificProductDiscount
            SearchingForDiscount = SpecificProductDiscount  # Use Specific Product discount
            # If ending soon, and within discount range
            if (float(Prices) * SearchingForDiscount > float(ItemPrice) +
                    float(ItemShipping)) and UnixEndingStamp < time.time(
                    ) + EndingSoon and ItemURL not in [
                        ItemInfo[2] for ItemInfo in OutputSpecific
                    ]:
                OutputSpecific.append([
                    float(ItemPrice) + float(ItemShipping),
                    float(Prices),
                    str(ItemURL),
                    str(FinalSearchName),
                    str(SearchingForDiscount),
                    str(ItemSearchKeywords)
                ])
                AddToGUI(ItemName, FinalSearchName,
                         str(float(ItemPrice) + float(ItemShipping)), Prices,
                         ItemPicture, ItemURL, SearchedItems)
                Logs.Write("Found Discounted Specific Search Item" + str([
                    float(ItemPrice) + float(ItemShipping),
                    float(Prices),
                    str(ItemURL),
                    str(FinalSearchName),
                    str(ItemSearchKeywords)
                ]))
        else:  # Use normal discount
            SearchingForDiscount = Discount

            if (float(Prices) * SearchingForDiscount > float(ItemPrice) +
                    float(ItemShipping)) and UnixEndingStamp < time.time(
                    ) + EndingSoon and ItemURL not in [
                        ItemInfo[2] for ItemInfo in Output
                    ]:
                Output.append([
                    float(ItemPrice) + float(ItemShipping),
                    float(Prices),
                    str(ItemURL),
                    str(FinalSearchName),
                    str(SearchingForDiscount),
                    str(ItemSearchKeywords)
                ])
                AddToGUI(ItemName, FinalSearchName,
                         str(float(ItemPrice) + float(ItemShipping)), Prices,
                         ItemPicture, ItemURL, SearchedItems)
                Logs.Write("Found Discounted Item" + str([
                    float(ItemPrice) + float(ItemShipping),
                    float(Prices),
                    str(ItemURL),
                    str(FinalSearchName),
                    str(ItemSearchKeywords)
                ]))

    try:
        driver.Quit()  # Close driver after complete
    except:
        print('drive.Quit Failed')
Esempio n. 23
0
partition = "Atlantic"
prefix = "http://espn.go.com"

total = soup.find_all("div",class_=re.compile("^span-2"))
for  part in total:
	partition = part.find("h4").string
	#print partition
	temp = part.find("ul" ,class_="medium-logos")
	teamAll = temp.find_all("li")
	for team in teamAll:
		#get Roster
		name =  team.h5.string
		print name
		u4 = team.find("a",href=re.compile("^http://espn.go.com/nba/team/_/name/"))
		url4 = u4['href']
		postfix = url4.split("/name")[1]

		u1= team.find("a", text = "Roster")
		url1 = prefix+u1['href']
		#Get.getRoster(name, url1)

		#get Match
		u2 = team.find("a", text = "Schedule")
		url2 = prefix+u2['href']
		#if(cmp(name,"Boston Celtics")==0 or cmp(name,"Brooklyn Nets")==0 or cmp(name,"New York Knicks")==0):
		#	print "pass"
		#else:
		if(cmp(name,"Los Angeles Clippers")==0):
			Get.getMatch(name, postfix,url2)
		else:
			print "pass"
Esempio n. 24
0
def get(thing):
    '''
    Get the thing. Get it! Put it in your inventory.
    '''
    Get.get(thing)