def format_trips_row(row): result = {} result["bicycleID"] = row[0] result["startDate"] = helpers.format_date(row[1]) result["startTime"] = helpers.format_time(row[1]) result["startStation"] = row[2] result["endingDate"] = helpers.format_date(row[3]) result["endingTime"] = helpers.format_time(row[3]) result["endingStation"] = row[4] return result
def test_validate_tickets(self): customer = requests.post("http://localhost:8080/api/customers", params=self.customer1).json() show1 = data.create_show("Tony Carreira", "31/10/2014", 22.50, 100) product1 = data.create_product("Cafe Expresso", "coffee", 2.3) product2 = data.create_product("Pipocas", "popcorn", 5.3) payload = { "customerID": customer["id"], "showID": show1["id"], "pin": int(customer["pin"]), "quantity": 3 } helpers.format_date(datetime.date.today()) requests.post("http://localhost:8080/api/tickets", params=payload) # START # Get purchased tickets tickets = requests.get("http://localhost:8080/api/tickets", params={"customerID": customer["id"]}).json() tickets_ids = [] for tick in tickets[:2]: tickets_ids.append(tick["id"]) tickets_string = ",".join(tickets_ids) # Test that the tickets are valid validation_params = {"customerID": customer["id"], "tickets": tickets_string} answer = requests.get("http://localhost:8080/api/validateTickets", params=validation_params) self.assertEqual(answer.status_code, 200) # Test that the status changed to used tickets = requests.get("http://localhost:8080/api/tickets", params={"customerID": customer["id"]}).json() results = list(filter(lambda ticket: ticket["id"] in tickets_ids and ticket["status"] == "used", tickets)) self.assertTrue(len(results) == 2) # Test that used tickets can't be validated again answer = requests.get("http://localhost:8080/api/validateTickets", params=validation_params) self.assertEqual(answer.status_code, 400) # END data.delete_tickets(show1["id"], customer["id"]) data.delete_customer(customer["id"]) data.delete_show(show1["id"]) data.delete_product(product1["id"]) data.delete_product(product2["id"]) data.delete_transactions(customer["id"]) data.delete_vouchers(customer["id"])
def test_get_auctions(self): photo = Upload('images/monalisa.jpeg') auction_doc = { "name": "Quadro Mona Lisa", "minimum_bid": "4230", "photo": photo } self.app.post("/api/auctions", params=auction_doc) photo = Upload('images/thescream.jpeg') auction_doc = { "name": "The Scream", "minimum_bid": "10000", "photo": photo } self.app.post("/api/auctions", params=auction_doc) # Test that the auctions are retrieved auctions = self.app.get("/api/auctions") now = helpers.format_date(datetime.datetime.now()) self.assertTrue(len(auctions.json) >= 2) results1 = list(filter(lambda auction: auction["name"] == "Quadro Mona Lisa" and auction["minimum_bid"] == 4230 and "photo_id" in auction and auction["date"] == now and "id" in auction, auctions.json)) self.assertTrue(len(results1) == 1) results = list(filter(lambda auction: auction["name"] == "The Scream" and auction["minimum_bid"] == 10000 and "photo_id" in auction and auction["date"] == now and "id" in auction, auctions.json)) self.assertTrue(len(results) == 1) #Test that the image from Mona Lisa can be retrieved photo_id = results1[0]["photo_id"] result = self.app.get("/api/photos/" + photo_id) image_bytes = open('images/monalisa.jpeg', "rb").read() self.assertTrue(result.body == image_bytes)
def get_versions(): try: versions = get_cache_item('versions') except: json = requests.get( 'http://s3.amazonaws.com/Minecraft.Download/versions/versions.json' ).json() set_cache_item('versions', json) versions = {} versions['time'] = time() versions['value'] = json output = {} output['status'] = 'success' output['versions'] = [] output['time'] = versions['time'] versions = versions['value'] bykey = {} for version in versions['versions']: v = {} v['id'] = version['id'] v['time'] = version['time'] v['niceTime'] = format_date(version['time']) v['type'] = version['type'] output['versions'].append(v) bykey[version['id']] = version['time'] output['latest'] = {} for version in versions['latest']: output['latest'][version] = {} output['latest'][version]['id'] = versions['latest'][version] output['latest'][version]['time'] = bykey[versions['latest'][version]] output['latest'][version]['niceTime'] = format_date( bykey[versions['latest'][version]]) return jsonify(output)
def get_versions(): try: versions = get_cache_item('versions') except: json = requests.get( 'http://s3.amazonaws.com/Minecraft.Download/versions/versions.json').json() set_cache_item('versions', json) versions = {} versions['time'] = time() versions['value'] = json output = {} output['status'] = 'success' output['versions'] = [] output['time'] = versions['time'] versions = versions['value'] bykey = {} for version in versions['versions']: v = {} v['id'] = version['id'] v['time'] = version['time'] v['niceTime'] = format_date(version['time']) v['type'] = version['type'] output['versions'].append(v) bykey[version['id']] = version['time'] output['latest'] = {} for version in versions['latest']: output['latest'][version] = {} output['latest'][version]['id'] = versions['latest'][version] output['latest'][version]['time'] = bykey[versions['latest'][version]] output['latest'][version]['niceTime'] = format_date( bykey[versions['latest'][version]]) return jsonify(output)
def _print_common_content(self, ptr, vehicle): helmets = vehicle.get("helmets", 0) checkin = vehicle.get("check_in", "") ci_str = helpers.format_date(checkin) ptr.set(align='center', width=1, height=1) if helmets > 0: ptr.text(config.HELMETS_TEXT + ": " + str(helmets) + "\n") ptr.text("\n") ptr.text(config.CI_TEXT + ci_str)
def get_auctions(self): cursor = self.db.auctions.find() results = [] for doc in cursor: doc["id"] = str(doc["_id"]) doc["photo_id"] = str(doc["photo_id"]) doc["date"] = helpers.format_date(doc["date"]) del doc["_id"] results.append(doc) return results
def remove_timetable(data, context): date = format_date(get_monday()) key = client.key(kind, date) query = client.query(kind=kind) query.add_filter('__key__', '<', key) query.keys_only() results = query.fetch() for entity in results: client.delete(entity.key) print('Removed timetables successfully') return
def get_active_by_EFEAT(efeat_num): """ Return the details of a ticket by EFEAT#### """ if len(efeat_num) != 4: return INVALID_EFEAT_ENTERED efeat_dict = {} experiences = get_experiences() found = False for exp in experiences: experience_name = exp["experience_name"] if efeat_num in experience_name: found = True efeat_dict["Test Name"] = experience_name efeat_dict["Launch Date"] = format_date(exp["start_time"]) efeat_dict["Link"] = create_external_link(experience_name, exp["id"]) if found: return json.dumps(efeat_dict, indent=0)[2:-2] return NO_RESULTS_FOUND
def get(self, image_key=None): if not image_key: return self.error(404) image = AvatarImage.get(image_key) if not image: return self.error(404) sz = self.request.get("sz") if sz == "cc_32": data = image.data_cc_32 elif sz == "cc_60": data = image.data_cc_60 else: data = image.data if not data: return self.error(404) self.response.headers["Content-Type"] = "image/png" self.response.headers["Cache-control"] = "public, max-age=%s" % image_max_age self.response.headers["Expires"] = format_date(datetime.now() + timedelta(days=365)) self.response.out.write(data)
def _print_checkout_info(self, ptr, vehicle): checkout = vehicle.get("check_out", "") co_str = helpers.format_date(checkout) ptr.text(config.CO_TEXT + co_str)
def created(self): try: return format_date(self.created_at) except: return None
def actived(self): try: return format_date(self.active) except: return None
def updated(self): try: return format_date(self.updated_at) except: return None
def test_buy_tickets(self): customer = requests.post("http://localhost:8080/api/customers", params=self.customer1).json() show1 = data.create_show("Tony Carreira", "31/10/2014", 22.50, 100) product1 = data.create_product("Cafe Expresso", "coffee", 2.3) product2 = data.create_product("Pipocas", "popcorn", 5.3) payload = { "customerID" : customer["id"], "showID" : show1["id"], "pin" : int(customer["pin"]), "quantity" : 3 } today_date = helpers.format_date(datetime.date.today()) # Buy tickets valid answer = requests.post("http://localhost:8080/api/tickets", params=payload) self.assertEqual(answer.status_code, 200) #Buy tickets invalid payload["quantity"] = 99 answer = requests.post("http://localhost:8080/api/tickets", params=payload) self.assertEqual(answer.status_code, 400) # Check if available tickets are updated answer = requests.get("http://localhost:8080/api/shows").json() results = list(filter(lambda show: show["name"] == "Tony Carreira" and show["price"] == 22.50 and show["seats"] == 100 and show["date"] == "31/10/2014" and show["available"] == 97, answer)) self.assertTrue(len(results) == 1) # Get purchased tickets tickets = requests.get("http://localhost:8080/api/tickets", params={"customerID": customer["id"]}).json() results = list(filter(lambda ticket: "id" in ticket and "seat" in ticket and ticket["status"] == "unused" and ticket["date"] == today_date and ticket["showID"] == show1["id"] and ticket["name"] == "Tony Carreira" and ticket["date_show"] == "31/10/2014", tickets)) self.assertTrue(len(results) == 3) # Get vouchers vouchers = requests.get("http://localhost:8080/api/vouchers", params={"customerID": customer["id"]}).json() results = list(filter(lambda voucher: "id" in voucher and (voucher["product"] == "coffee" or voucher["product"] == "popcorn") and voucher["discount"] == 1 and voucher["status"] == "unused", vouchers)) self.assertTrue(len(results) == 3) # Check that the transactions were recorded get_params = {"customerID": customer["id"]} transactions = requests.get("http://localhost:8080/api/transactions", params=get_params).json() results = list(filter(lambda transaction: transaction["date"] == today_date and transaction["amount"] == 67.5 and "3" in transaction["description"] and "Tony Carreira" in transaction["description"], transactions)) self.assertTrue(len(results) == 1) #Buy tickets for free discount vouchers payload["quantity"] = 5 answer = requests.post("http://localhost:8080/api/tickets", params=payload) self.assertEqual(answer.status_code, 200) vouchers = requests.get("http://localhost:8080/api/vouchers", params={"customerID": customer["id"]}).json() results = list(filter(lambda voucher: "id" in voucher and (voucher["product"] == "all" or voucher["product"] == "popcorn" or voucher["product"] == "coffee") and (voucher["discount"] == 1 or voucher["discount"] == 0.05) and voucher["status"] == "unused", vouchers)) self.assertTrue(len(vouchers) == 9) data.delete_tickets(show1["id"], customer["id"]) data.delete_customer(customer["id"]) data.delete_show(show1["id"]) data.delete_product(product1["id"]) data.delete_product(product2["id"]) data.delete_transactions(customer["id"]) data.delete_vouchers(customer["id"])
def scrap_source0(self): self.driver.get('https://devpost.com/hackathons') el = self.driver.find_element_by_xpath( '//*[@id="container"]/div/div/div/div[1]/div[2]/a') while el.is_displayed(): if el.text == "": break el.click() timeout.sleep(1) html = self.driver.page_source soup = BeautifulSoup(html, 'html.parser') rows = list( soup.select( "#container > div > div > div > div.results > div.challenge-results > div" )) print("got rows") titles = [] locations = [] preview = [] # descriptions = [] time = [] refs = [] source = "https://devpost.com/hackathons" for row in rows: temp_title = row.find("h2", {"class": "title"}) temp_location = row.find("p", {"class": "challenge-location"}) temp_preview = row.find("p", {"class": "challenge-description"}) temp_time = row.find("span", {"class": "value date-range"}) temp_ref = row.find("a", href=True)['href'].encode('ascii', 'ignore') if hasattr(temp_title, "text"): titles.append(temp_title.text.strip().encode( 'ascii', 'ignore')) else: titles.append("") if hasattr(temp_location, "text"): locations.append(temp_location.text.strip().encode( 'ascii', 'ignore')) else: locations.append("") if hasattr(temp_preview, "text"): preview.append(temp_preview.text.strip().encode( 'ascii', 'ignore')) else: preview.append("") if hasattr(temp_time, "text"): time.append( helpers.format_date(temp_time.text.strip().encode( 'ascii', 'ignore'))) else: time.append("") refs.append(temp_ref) print("got data") i = 0 data = [None] * len(titles) while i < len(data): data[i] = Object() data[i].title = titles[i].decode("utf-8") data[i].location = locations[i] data[i].preview = preview[i] #data[i].description = descriptions[i].encode('ascii', 'ignore') data[i].time = time[i] data[i].ref = refs[i] data[i].area = "" data[i].source = source i = i + 1 dbtools.insert_data(data) print("transferred data to database handler")
class MeterPoint: # Text name that identifies a data file, database, or historian # where meter data points are to be stored. A default is provided, # but a meaningful filename should be used. today = date.today() dateFile = 'MP' + format_date(today) # DESCRIPTION description = '' # The measurement point datum that was collected during the last # reading update. This measurement must be of the measurement type # and measurement unit specified by object properties. The # measurement took place at the last update datetime. If needed # these measurements should be saved to a database or historian. lastMeasurement = None # (1, 1) # Datetime of the last meter reading. This time is used with # the measurement interval to determine when the meter should be # read. lastUpdate = datetime.utcnow() # Constant time interval between readings. This and the last # measurement time are used to schedule the next meter reading. measurementInterval = timedelta(hours=1) # See MeasurementType enumeration. Property being metered. measurementType = MeasurementType.Unknown # See MeasurementUnit enumeration. Allowed units of measure. This # formulation is currently simplified by allowing only a limited # number of measurement units. These are not necessarily the raw # units; it should be the proper converted units. measurementUnit = MeasurementUnit.Unknown # NAME name = '' def __init__(self): pass def read_meter(self, obj): # Read the meter point at scheduled intervals # # MeterPoints are updated on a schedule. Properties have been defined to # keep track of the time of the last update and the interval between # updates. # # While this seems easy, meters will be found to be diverse and may use # diverse standards and protocols. Create subclasses and redefine this # function as needed to handle unique conditions. print('Made it to MeterPoint.read_meter() for ' + obj.name) def store(self): """ Store last measurement into historian The default approach here could be to append a text record file. If the file is reserved for one meterpoint, little or no metadata need be repeated in records. Minimum content should be reading time and datum. Implementers will be found to have diverse practices for historians. """ print('Made it to store() function in ' + self.name + ' targeting database ' + self.dataFile) # Open a simple text file for appending # Append the formatted, paired last measurement time and its datum with open(self.dataFile, "a") as myfile: myfile.write("{},{};".format(format_ts(self.lastUpdate), self.lastMeasurement))