def xtest_multiple_contacts(): """ Handle response of multiple contacts found """ s = Vendor.get("WhitePages", config={"api_key": "1234"}) lookup_result = s._parse(JSON_GOOD) assert len(lookup_result.contacts) == 2 assert lookup_result.contacts[0] == {"firstname": "Bob", "lastname": "Smith"} assert lookup_result.contacts[1] == {"firstname": "Sally", "lastname": "Jones"}
def test_multiple_contacts(): """ Handle response of multiple contacts found """ s = Vendor.get("pacificeast", config={"public": True, "account_id": "1234", "env": "dev"}) lookup_result = s._parse(XML_MULTIPLE_CONTACTS) assert len(lookup_result.contacts) == 2 assert lookup_result.contacts[0] == {"firstname": "Bob", "lastname": "Smith"} assert lookup_result.contacts[1] == {"firstname": "Sally", "lastname": "Jones"}
def main (args, app): for plugin in Vendor.FromConfig(app.config): if args.name == plugin.name: plugin.remove(app.config) app.config.save( ) print ('removed', plugin.format_url( )) break
def get(self): ctl = self.request.get('CTL') sender = self.request.get('SENDER') receiver = self.request.get('RECEIVER') content = self.request.get('CONTENT') vendor = Vendor() if ctl == '102': sender = Mail() sender.send(sender, vendor.parse(receiver), receiver, content) self.response.out.write("Done sending mail! " + str(sender) + " " + str(receiver) + " " + str(content)) elif ctl == '103': self.response.out.write(str(sender) + " ") self.response.out.write(vendor.parse(receiver) + " ") self.response.out.write(str(receiver) + " ") self.response.out.write(str(content))
def test_rad_result(): """ Ensure that RAD result is parsed correctly """ s = Vendor.get("pacificeast", config={"public": True, "account_id": "1234", "env": "dev"}) lookdown_result = s._parse_lookdown(XML_RAD_RESULT) assert len(lookdown_result.contacts) == 3 assert lookdown_result.contacts[0] == XML_RAD_RESULTS[0] assert lookdown_result.contacts[1] == XML_RAD_RESULTS[1] assert lookdown_result.contacts[2] == XML_RAD_RESULTS[2] """
def get_waterfall(pce_id=None, pce_env=None, whitepages_key=None): """ Create the lookup waterfall Args: None Returns: [{}]: list of dicts with keys name (str), config (dict) where name is the name of a Vendor provider and config is the associated configuration """ waterfall = [ #Vendor.get("mock", config={}), Vendor.get("PacificEast", config={"public": False, "account_id": pce_id, "env": pce_env}), Vendor.get("PacificEast", config={"public": True, "account_id": pce_id, "env": pce_env}), Vendor.get("WhitePages", config={"api_key": whitepages_key}), ] return waterfall
def create_user(self, first_name=None, last_name=None, user_type=None): # Went with Factory Method, but addomg new types breaks Open/Closed # I saw examples instantiating with globals() but doesn't seem like # good practice if user_type == 'Employee': return Employee(first_name, last_name, user_type) if user_type == 'Vendor': return Vendor(first_name, last_name, user_type) if user_type == 'Contractor': return Contractor(first_name, last_name, user_type) return BaseUser(first_name, last_name, user_type)
def main(args, app): vendor = Vendor(args.name, path=args.path) try: module = vendor.get_module() vendor.add_option('module', module.__name__) vendor.store(app.config) app.config.save() print "added", vendor.format_url() except (ImportError), e: print e print """{name:s} doesn't seem to be an importable python module If it is a python module, try using --path to influence PYTHONPATH """.format(name=args.name)
def predict(receipt): ## predict vendor vendor = Vendor(receipt.rawText, receipt.lines) vendor.run() receipt.ruleBasedPrediction['vendor'] = vendor._result ## predict tax rate taxRate = TaxRate(receipt.rawText, receipt.lines, receipt.graph, receipt.words) taxRate.run() receipt.ruleBasedPrediction['tax_rate'] = taxRate._result ## predict total price totalPrice = TotalPrice(receipt.rawText, receipt.lines) totalPrice.run() receipt.ruleBasedPrediction['total_price'] = totalPrice._result ## predict date date = Date(receipt.rawText, receipt.lines) date.run() receipt.ruleBasedPrediction['date'] = date._result ## predict currency currency = Currency(receipt.rawText) currency.run() receipt.ruleBasedPrediction['currency'] = currency._result ## predict address address = Address(receipt.linesText) address.run() receipt.ruleBasedPrediction['address'] = address._result ## predict products products = Products(receipt.rawText, receipt.lines, receipt.linesText) products.run() receipt.ruleBasedPrediction['products'] = products._result
def matcher(buyerPref, sellerPref): matchBuyer = {} matchSeller = {} #set up buyers and sellers for buyer in buyerPref.keys(): matchBuyer[buyer] = Customer(buyerPref[buyer]) for seller in sellerPref.keys(): matchSeller[seller] = Vendor(sellerPref[seller]) for seller in matchSeller.keys(): nowSeller = matchSeller[seller] counter = 1 while not nowSeller.matched: for cust in nowSeller.prefs: nowSeller.visited.append(cust) nowCust = matchBuyer[cust] if not nowCust.full: nowCust.addMatch(seller) nowSeller.addMatch(cust) elif nowCust.full: if nowCust.isPref(seller): if nowCust.full: delSeller = nowCust.removeNonPref() matchSeller[delSeller].removeMatch() nowCust.addMatch(seller) nowSeller.removeMatch() nowSeller.addMatch(cust) else: break #now look through other buyers for cust in matchBuyer.keys(): nowCust = matchBuyer[cust] if cust not in nowSeller.visited: if not nowCust.full: nowCust.addMatch(seller) former = nowSeller.removeMatch(self) matchBuyer[former].removeMatch(seller) nowSeller.addMatch(cust) #print results for k in matchBuyer.keys(): matchBuyer[k].seeAttr for k in matchSeller.keys(): matchSeller[k].seeAttr
def test_config(): """ Ensure that the config is properly parsed """ # Create an instance of the vendor s = Vendor.get("pacificeast", config={"public": True, "account_id": "1234", "env": "dev"}) with patch("vendor_pacificeast.requests.post") as mock_post: # Configure the mock object mock_post.result.status_code = 200 mock_post.result.text = XML_NO_RESULT # Call lookup to ensure that the config passes properly to requests s.lookup("3105550000") assert mock_post.called assert mock_post.call_count == 1 assert "<cus:accountID>1234</cus:accountID>" in mock_post.call_args[1]["data"]
def main (args, app): vendor = Vendor(args.name, path=args.path) try: module = vendor.get_module( ) vendor.add_option('module', module.__name__) vendor.store(app.config) app.config.save( ) print "added", vendor.format_url( ) except (ImportError), e: print e print """{name:s} doesn't seem to be an importable python module If it is a python module, try using --path to influence PYTHONPATH """.format(name=args.name)
def vendor_add(self, name, shortTitle=None, slug=None, description=None, logo=None, country=None, city=None, address=None, ordering=None, publish=True): vendor = Vendor( name=name, shortTitle=shortTitle, slug=slug, description=description, logo=logo, country=country, city=city, address=address, ordering=ordering, publish=publish) if vendor not in self.vendors: self.vendors.append(vendor)
def test_contact_found(): """ Handle response of contact found """ s = Vendor.get("WhitePages", config={"api_key": "1234"}) lookup_result = s._parse(JSON_GOOD) assert lookup_result.success == True assert len(lookup_result.contacts) == 1 assert lookup_result.contacts[0] == { "firstname": None, "lastname": "Whitepages", "formatted_addr": "Seattle WA 98115", "address": None, "city": "Seattle", "state": "WA", "country": "US", "zip": "98115", "geocoded": True, "geo_accuracy": "PostalCode", "latitude": 47.6851, "longitude": -122.2926 }
def test_no_name(): """ Handle response of address but no name """ s = Vendor.get("WhitePages", config={"api_key": "1234"}) lookup_result = s._parse(JSON_NO_NAME) assert lookup_result.success == True assert len(lookup_result.contacts) == 1 assert lookup_result.contacts[0] == { "firstname": None, "lastname": None, "formatted_addr": "Mineola NY 11501", "address": None, "city": "Mineola", "state": "NY", "country": "US", "zip": "11501", "geocoded": True, "geo_accuracy": "PostalCode", "latitude": 40.7469, "longitude": -73.6388 }
def test_best_location(): """ Handle response of address but no name """ s = Vendor.get("WhitePages", config={"api_key": "1234"}) lookup_result = s._parse(JSON_BEST_LOCATION) assert lookup_result.success == True assert len(lookup_result.contacts) == 1 log.debug(lookup_result.contacts) assert lookup_result.contacts[0] == { "firstname": "Bob", "lastname": "Bobson", "formatted_addr": "3434 Bubble Ct, Anytown CA 01234-4444", "address": "3434 Bubble Ct", "city": "Anytown", "state": "CA", "country": "US", "zip": "01234-4444", "geocoded": True, "geo_accuracy": "RoofTop", "latitude":24.688217, "longitude":-106.167145, }
def get_vendor_names (conf): return [vendor.name for vendor in Vendor.FromConfig(conf)]
from vendor import Vendor MOCKVENDORS = ( Vendor('Dough factore',1,"Seolina") Vendor('Farm PRoduce',24,"Country Rd.") Vendor("Cocoa World",45,'First boulevard') )
from vendor import Vendor from vend_adapter import VendAdapter MOCKVENDORS = (VendAdapter(Vendor('Dough Factory', 1, 'Semolina Court')), VendAdapter(Vendor('Farm Produce', 14, 'Country Rd.')), VendAdapter(Vendor('Cocoa World', 53, 'Tropical Blvd.')))
def main(): vendor = Vendor() vendor.start()
def main(args, app): for plugin in Vendor.FromConfig(app.config): if args.name in ['*', plugin.name]: print(args.format(plugin))
def main(): """ Do it """ # Parse the command line args parser = argparse.ArgumentParser(description="Phone Lookup") # What to do parser.add_argument("--lookup", action="store_true", help="Perform phone lookup") parser.add_argument("--geocode", action="store_true", help="Perform geocoding") parser.add_argument("--server", action="store_true", help="Perform reverse address serving") # Server params parser.add_argument("--server_sid", type=str, help="sid for server") parser.add_argument("--server_token", type=str, help="token for server") # Which geocoder to use parser.add_argument("--geocoder", type=str, default="mock", help="Which geocoder ('mock' or 'google')") # Vendor params parser.add_argument("--pce_id", type=str, help="PacificEast Account ID/Key") parser.add_argument("--pce_env", type=str, help="PacificEast environment ('dev' or 'prod')") parser.add_argument("--wp_key", type=str, help="WhitePages API Key") parser.add_argument("--runall", action="store_true", help="Run all numbers without prompting") args = parser.parse_args() # Perform actions if not (args.lookup or args.geocode or args.server): log.warn("No actions specified. Use '--lookup' and/or '--geocode' or '--server' to do something.") elif args.server and (args.lookup or args.geocode): log.warn("Cannot use '--server' with '--lookup' or '--geocode'.") elif args.server: # Use normal SIGINT handling signal.signal(signal.SIGINT, signal.SIG_DFL) # Run the server if args.pce_id: vendors = [ Vendor.get("PacificEast", config={"public": False, "account_id": args.pce_id, "env": args.pce_env}), ] else: vendors = [ Vendor.get("mock", config={}), ] # Configure and run the Pyramid app server.serve(vendors, sid=args.server_sid, token=args.server_token) else: # Load the number data and perform the lookups log.debug("Loading numbers.json") numbers = load_numbers("numbers.json") ############ # Lookups if args.lookup: log.info("Performing lookups") # Get the waterfall waterfall = get_waterfall( pce_id=args.pce_id, pce_env=args.pce_env, whitepages_key=args.wp_key) do_lookups(numbers, waterfall, "numbers.json", runall=args.runall) ############ # Geocoding if args.geocode: log.info("Performing geocoding") geocoder = Geocoder.get(args.geocoder, config={}) do_geocoding(numbers, geocoder, "numbers.json", runall=args.runall)
from vendor import Vendor MOCKVENDORS = ( Vendor('Dough Factory', 1, 'Semolina Court'), Vendor('Farm Produce', 14, 'Country Rd.'), Vendor('Cocoa World', 53, 'Tropical Blvd.') )
from vendor_adapter import VendorAdapter from vendor import Vendor MOCKVENDOR = ( VendorAdapter(Vendor("Fabryka czekolady", 34, 'Polna')), VendorAdapter(Vendor("Farma", 13, "Leśna")), VendorAdapter(Vendor("Świat cynamonu", 53, "Słoneczna")), )
from vendor import Vendor from weather import Weather from customer import Customer from money import Money from supplies import Supplies from lemonade import Lemonade vendor = Vendor() today = Weather() cash = Money() supplies = Supplies() lemonade = Lemonade() customer = Customer() def main(): day = 0 play_time = today.get_play_duration() weekdays = today.get_weekday_list(play_time) while day < play_time: cash.show_status() today.get_forecast() vendor.show_list_buy(supplies, cash, vendor) cash.show_status() lemonade.make_lemonade(supplies.lemons, supplies.sugar, supplies.ice, supplies.cups) vendor.set_price() customer.get_customers(vendor.price, cash, today.weather_score, supplies, vendor, lemonade) supplies.subtract_supplies(lemonade.sold_lemonade()) cash.show_earnings() for each_day in weekdays: weekdays.remove(weekdays[0])
def test_no_result(): """ Handle response of no contacts found """ s = Vendor.get("pacificeast", config={"public": True, "account_id": "1234", "env": "dev"}) lookup_result = s._parse(XML_NO_RESULT) assert lookup_result.success == False
from user import User from vendor import Vendor from utils import RSA from cryptography.fernet import Fernet # Standard from datetime import datetime import jsonpickle from secrets import choice from random import random ## SCENARIO 4 # Players bank = Bank() vendor = Vendor() user = User() symmetric_key = Fernet.generate_key() user.set_session_key(symmetric_key) user.send_session_key_to(bank, RSA.encrypt(bank.public_key, symmetric_key)) coins = 7 user_credits_message = jsonpickle.encode({ 'Coins' : coins }).encode('utf-8') user_encrypted_message = Fernet(user.session_key).encrypt(user_credits_message) response = user.send_message_to(bank, user_encrypted_message) print('[MAIN] Response:', response)
#!/usr/bin/python from sys import argv from vendor import Vendor if len(argv) > 1: drupal_id = int(argv[1]) if len(argv) > 2: path = argv[2] else: path = '/var/www/fuelwonk' vendor = Vendor(drupal_id, path) vendor.phone() print vendor.yelp_id
def get_vendor_map (conf): vendors = { } for vendor in Vendor.FromConfig(conf): vendors[vendor.name] = vendor return vendors
from vendor import Vendor MOCKVENDORS = ( Vendor('Fabryka Czekolady', 34, 'Polna'), Vendor('Farma', 13, 'Leśna'), Vendor('Świat cynamonu', 53, 'Słoneczna'), )
def get_plugins (conf): return Vendor.FromConfig(conf)
from customer import Customer from store import Store from vendor import Vendor from time import sleep c = Customer() v = Vendor() sleep(1) s = Store() msg, sig = c.get("public_key") s.register_loyalty_card(msg, sig) resp = c.get("send_history") s.make_purchase(*resp, [("apples", 1)]) resp = c.get("") s.check_balance(*resp) resp = c.get("spend_num_points") s.spend_points(*resp) print(v.get_dp_counting_queries([["apples"]]))