def __init__(self, player_details, canvas): self.players = [ Player(name, order, is_human) for (order, (name, is_human)) in enumerate(player_details) ] self.tiles = Tiles() self.locations = Locations(self) self.active_tile = None self.active_target = None self.mode = GameMode.SELECTING_TILE self.canvas = canvas self.source = [] self.target = [] # TODO: Move fonts into Settings or separate fonts module? self.small_floor_tile_scores_font = pygame.font.SysFont( 'Arial', Settings.floor_tile_scores_font_size) self.large_floor_tile_scores_font = pygame.font.SysFont( 'Arial', int(Settings.floor_tile_scores_font_size * Settings.player_area_multiplier)) self.button_font = self.large_floor_tile_scores_font # TODO: Move this in with the ButtonLocation? x, y = Settings.player_area_location multiplier = Settings.player_area_multiplier x += Settings.pattern_area_width * multiplier x += 2 * Settings.tile_width * multiplier width = 3 * Settings.tile_width * multiplier y += (Settings.area_height - Settings.tile_height * 1.9) * multiplier height = Settings.tile_height * multiplier self.locations.all.append( ButtonLocation(self, x, y, width, height, 'Continue', 'confirm'))
def delete_location(): if request.method == 'POST': address = request.form['location-address'] location_instance = Locations() location_instance.delete_location(address) return redirect('/locations') else: return render_template('delete_location.html')
def add_new_location(): if request.method == 'POST': address = request.form['location-address'] type = request.form['location-type'] hours = request.form['location-hours'] manager = request.form['location-manager'] location_instance = Locations() location_instance.add_location(address, type, hours, manager) return redirect('/locations') else: return render_template('add_new_location.html')
def test_specific_10000047_with_new_crsecsturl_field(self): xml_string = get_string("fixtures/large-test-file.xml") root = ET.fromstring(xml_string) accreditations = Accreditations(root) kisaims = KisAims(root) locations = Locations(root) xml_string = get_string( "fixtures/one_inst_one_course_with_crsecsturl.xml") root = ET.fromstring(xml_string) institution = get_first(root.iter("INSTITUTION")) raw_inst_data = xmltodict.parse( ET.tostring(institution))["INSTITUTION"] ukprn = raw_inst_data["UKPRN"] course = get_first(institution.findall("KISCOURSE")) raw_course_data = xmltodict.parse(ET.tostring(course))["KISCOURSE"] locids = get_locids(raw_course_data, ukprn) expected_course_doc = json.loads( get_string("fixtures/one_inst_one_course_with_crsecsturl.json")) course_doc = get_course_doc( accreditations, locations, locids, raw_inst_data, raw_course_data, kisaims, ) course_doc = remove_variable_elements(course_doc) self.assertEqual(expected_course_doc, course_doc)
def __init__(self, management_cert_path, subscription_id, management_key_path=None): """Initialise the various API interfaces. Note that management_key_path is not required (except for Python 2.5), as the key can be included in the certificate chain file. The OpenSSL command line can create an appropriate PEM file like so: openssl pkcs12 -in azure.pfx -out azure.pem -nodes """ from hostedservices import HostedServices, ServiceConfiguration from storageaccounts import StorageAccounts from locations import Locations self.service_api = HostedServices(management_cert_path, subscription_id, management_key_path) self.ServiceConfiguration = ServiceConfiguration self.storage_api = StorageAccounts(management_cert_path, subscription_id, management_key_path) self.location_api = Locations(management_cert_path, subscription_id, management_key_path) self._sme = ServiceManagementEndpoint(management_cert_path, subscription_id, management_key_path) self.WASMError = WASMError self.get_operation_status = self._sme.get_operation_status self.request_done = self._sme.request_done self.wait_for_request = self._sme.wait_for_request for op in self.service_api.get_wasm_ops(): setattr(self, op.__name__, op) for op in self.storage_api.get_wasm_ops(): setattr(self, op.__name__, op) for op in self.location_api.get_wasm_ops(): setattr(self, op.__name__, op)
def render(offers, query): locations = Locations.fromOffers(offers) mapPoints = GoogleMapPoints.fromLocations(locations) mapCenter = OnlineView.getMapCenter(query.city) mapZoom = 12 # this should be evaluated to ensure best map look offerPage = OnlineView.getOfferPage(mapPoints, mapCenter, mapZoom, query.numRooms, query.maxPrice, query.whereabouts) HttpResponse.renderPage(offerPage.getHtml())
def create_course_docs(xml_string): """Parse HESA XML passed in and create JSON course docs in Cosmos DB.""" # TODO Investigate writing docs to CosmosDB in bulk to speed things up. cosmosdb_client = utils.get_cosmos_client() logging.info( "adding ukrlp data into memory ahead of building course documents" ) enricher = UkRlpCourseEnricher() logging.info( "adding subject data into memory ahead of building course documents" ) subject_enricher = SubjectCourseEnricher() collection_link = utils.get_collection_link( "AzureCosmosDbDatabaseId", "AzureCosmosDbCoursesCollectionId" ) # Import the XML dataset root = ET.fromstring(xml_string) # Import accreditations, common, kisaims and location nodes accreditations = Accreditations(root) kisaims = KisAims(root) locations = Locations(root) course_count = 0 for institution in root.iter("INSTITUTION"): raw_inst_data = xmltodict.parse(ET.tostring(institution))[ "INSTITUTION" ] ukprn = raw_inst_data["UKPRN"] for course in institution.findall("KISCOURSE"): raw_course_data = xmltodict.parse(ET.tostring(course))["KISCOURSE"] locids = get_locids(raw_course_data, ukprn) course_doc = get_course_doc( accreditations, locations, locids, raw_inst_data, raw_course_data, kisaims, ) enricher.enrich_course(course_doc) subject_enricher.enrich_course(course_doc) cosmosdb_client.CreateItem(collection_link, course_doc) course_count += 1 logging.info(f"Processed {course_count} courses")
def __init__(self, management_cert_path, subscription_id): from hostedservices import HostedServices, ServiceConfiguration from storageaccounts import StorageAccounts from locations import Locations self.service_api = HostedServices(management_cert_path, subscription_id) self.ServiceConfiguration = ServiceConfiguration self.storage_api = StorageAccounts(management_cert_path, subscription_id) self.location_api = Locations(management_cert_path, subscription_id) self._sme = ServiceManagementEndpoint(management_cert_path, subscription_id) self.WASMError = WASMError self.get_operation_status = self._sme.get_operation_status self.request_done = self._sme.request_done self.wait_for_request = self._sme.wait_for_request for op in self.service_api.get_wasm_ops(): setattr(self, op.__name__, op) for op in self.storage_api.get_wasm_ops(): setattr(self, op.__name__, op) for op in self.location_api.get_wasm_ops(): setattr(self, op.__name__, op)
def create_post(user): if not user: return 403, "Forbiden" if request.method == "GET": return render_template("post.html", locations=Locations.all(), user=user) if request.method == "POST": post_data = request.form if post_data == None: return "Bad request", 400 f = request.files['image'] filename = secure_filename(str(uuid.uuid1())) f.save("static/images/submitted/{}".format(filename)) values = (None, post_data["title"], filename, post_data["size"], post_data["price"], post_data["bed_count"], post_data["location_id"], post_data["available_from"], post_data["available_to"], post_data["description"], user.user_id) post = Post(*values) post.save() return redirect(url_for("create_post"))
def test_with_large_file(self): xml_string = get_string("fixtures/large-test-file.xml") root = ET.fromstring(xml_string) accreditations = Accreditations(root) kisaims = KisAims(root) locations = Locations(root) for institution in root.iter("INSTITUTION"): raw_inst_data = xmltodict.parse( ET.tostring(institution))["INSTITUTION"] ukprn = raw_inst_data["UKPRN"] for course in institution.findall("KISCOURSE"): raw_course_data = xmltodict.parse( ET.tostring(course))["KISCOURSE"] locids = get_locids(raw_course_data, ukprn) course_doc = get_course_doc( accreditations, locations, locids, raw_inst_data, raw_course_data, kisaims, ) self.assertTrue("institution_id" in course_doc)
def testLocations(self): offer1 = {'address' : 'Wielicka 9', 'longlatt' : [51, 11], 'title' : 'Mieszkanie dwupokojowe'} offer2 = {'address' : 'Wielicka 9', 'longlatt' : [51, 11], 'title' : 'Mieszkanie trzypokojowe'} offer3 = {'address' : 'Sarego 12', 'longlatt' : [53, 13], 'title' : 'Garsoniera wysoki standard'} offers = [offer1, offer2, offer3] locations = Locations.fromOffers(offers) self.assertTrue(locations.has_key('Wielicka 9'), "Locations does not contain required address") self.assertEquals(2, len(locations['Wielicka 9']['offers']), "Should be 2 offers at this location") self.assertEquals([51, 11], locations['Wielicka 9']['longlatt']) self.assertEquals('Mieszkanie dwupokojowe', locations['Wielicka 9']['offers'][0]['title']) self.assertEquals('Mieszkanie trzypokojowe', locations['Wielicka 9']['offers'][1]['title']) self.assertTrue(locations.has_key('Sarego 12'), "Locations does not contain required address") self.assertEquals(1, len(locations['Sarego 12']['offers']), "Should be 1 offer at this location") self.assertEquals([53, 13], locations['Sarego 12']['longlatt']) self.assertEquals('Garsoniera wysoki standard', locations['Sarego 12']['offers'][0]['title'])
class WASM(object): """Class exposing Windows Azure Service Management operations. Using WASM ---------- >>> import pyazure >>> pa = pyazure.PyAzure(management_cert_path=MANAGEMENT_CERT, ... subscription_id=SUBSCRIPTION_ID) >>> 'Anywhere Asia' in pa.wasm.list_locations() True >>> request_id = pa.wasm.create_storage_account('pyazuretest','doctest', ... 'anywhere us', 'Here is my description, not great is it?') >>> pa.wasm.wait_for_request(request_id) True >>> (pa.wasm.get_operation_status(request_id) == ... {'HttpStatusCode': '200', 'Status': 'Succeeded'}) True >>> request_id = pa.wasm.create_storage_account( ... 'pyazuretestwithaverylongname','doctest','anywhere us') Traceback (most recent call last): ... ValueError: ('pyazuretestwithaverylongname', 'name must be between 3 and 24 characters in length and use numbers and lower-case letters only.') >>> 'pyazuretest' in pa.wasm.list_storage_accounts() True >>> pa.wasm.create_service('pyazuretest','create service doctest', ... 'anywhere europe') True >>> 'pyazuretest' in pa.wasm.list_services() True >>> pa.wasm.create_service('pyazuretest','create service doctest', ... 'anywhere europe') Traceback (most recent call last): ... WASMError: (409, 'ConflictError', 'The specified DNS name is already taken.') >>> pa.wasm.create_service('pyazuretest','create service doctest' * 10, ... 'anywhere europe') # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: ('create service doctest...', 'label exceeds 100 char limit') >>> pa.wasm.get_service_properties('pyazuretest') # doctest: +ELLIPSIS ... # doctest: +NORMALIZE_WHITESPACE OrderedDict([('Url', 'http...'), ('ServiceName', 'pyazuretest'), ('HostedServiceProperties', OrderedDict([('Description', ''), ('Location', 'Anywhere Europe'), ('Label', 'create service doctest')]))]) >>> pa.wasm.delete_service('pyazuretest') True >>> pa.wasm.delete_storage_account('pyazuretest') True >>> pa.wasm.delete_storage_account('pyazuretest') Traceback (most recent call last): ... WASMError: (404, 'ResourceNotFound', 'The requested storage account was not found.') """ def __init__(self, management_cert_path, subscription_id): from hostedservices import HostedServices, ServiceConfiguration from storageaccounts import StorageAccounts from locations import Locations self.service_api = HostedServices(management_cert_path, subscription_id) self.ServiceConfiguration = ServiceConfiguration self.storage_api = StorageAccounts(management_cert_path, subscription_id) self.location_api = Locations(management_cert_path, subscription_id) self._sme = ServiceManagementEndpoint(management_cert_path, subscription_id) self.WASMError = WASMError self.get_operation_status = self._sme.get_operation_status self.request_done = self._sme.request_done self.wait_for_request = self._sme.wait_for_request for op in self.service_api.get_wasm_ops(): setattr(self, op.__name__, op) for op in self.storage_api.get_wasm_ops(): setattr(self, op.__name__, op) for op in self.location_api.get_wasm_ops(): setattr(self, op.__name__, op)
def locations(): location_instance = Locations() data = location_instance.get_locations() return render_template('locations.html', locations=data)
def locations(self): # cached list of data center locations for deployments if not self._locations: self._locations = list(Locations(self.cert, self.sub_id, self.key).list_locations()) return self._locations
from rooms import Rooms from seeds import Seeds from engine import Engine from curses_ui import UI from clock import Clock from autotracker import Autotracker if __name__ == '__main__': parser = argparse.ArgumentParser(description='Zebbo Probability Engine') parser.add_argument('--autotrack', dest='autotrack', action='store_true', default=False) parser.add_argument('--clock', dest='clock', action='store_true', default=False) args = parser.parse_args() items = Items.read('items.json') locations = Locations.read('locations.json') geography = Geography.read(locations, 'geography.json') rooms = Rooms.read('rooms.json') seeds = Seeds.read(items, locations, 'seeds.json') engine = Engine(items, locations, geography, rooms, seeds) if args.clock: clock = Clock() else: clock = None if args.autotrack: autotracker = Autotracker(engine, clock) poll = autotracker.poll else: poll = lambda: None
def setUp(self): xml_string = get_string("fixtures/course_with_locations.xml") root = ET.fromstring(xml_string) self.locations = Locations(root)
class Window(QMainWindow): def __init__(self): QMainWindow.__init__(self) self.resize(800, 600) self.setWindowTitle('Diaboli Ex') home = os.path.expanduser('~') self.worldPath = os.path.join(home, '.diaboli-ex.json') self.cwd = CWD self.local = LOCAL if os.path.isfile(self.worldPath): world = json.load(open(self.worldPath, 'r')) if 'version' not in world: world['version'] = '0.0.0' if semver.compare(VERSION, world['version']) > 0: v1 = world['version'].split('.') v0 = VERSION.split('.') if v0[0] != v1[0] or v0[1] != v1[1]: self.initNewWorld() world = json.load(open(self.worldPath, 'r')) else: self.initNewWorld() world = json.load(open(self.worldPath, 'r')) world['launches'] += 1 world['version'] = VERSION self.world = AttrDict(world) self.saveWorld() if self.local: self.achievements = json.load(open(os.path.join(CWD, 'data', 'achievements.json'), 'r', encoding='utf8')) else: self.achievements = requests.get(BASE_URL + 'data/achievements.json').json() self.tabs = QTabWidget() self.view = QWebView(self) self.view.page().mainFrame().javaScriptWindowObjectCleared.connect(self.injectObjects) if DEBUG: self.showEditor() else: self.setCentralWidget(self.view) self.createContext() self.loadWorld() def createContext(self): def link(action, *args): if args: text = args[-1] else: text = '' if action.split('.')[0] == 'main': script = 'app' action = action.split('.')[1] else: script = 'currentLocation' script += '.%s(%s)' % (action, ','.join(["'%s'" % a for a in args[:-1]])) if args: args = '/' + '/'.join(args[:-1]) else: args = '' script = ('$("a[href=\'%s%s\']").on("click", function(e)' % (action, args)) + \ '{e.preventDefault();%s;' % (script) + \ '$("a[href=\'" + e.target + "\']").addClass("visited");return false;})' return '<a href=\'%s%s\'>%s</a><script>$(document).ready(function(){%s});</script>' % ( action, args, text, script ) def action(action, *args): # a = link(action, *args) script = 'currentLocation.%s(%s);' % (action, ",".join(["'%s'" % a for a in args])) script = '<script>$(document).ready(function(){%s});</script>' % script return script def achieve(aid): return action('achieve', aid) def checkpoint(label): return action('checkpoint', label) def show(block, text): return link('main.showBlock', block, text) def disable(*names): script = '' for name in names: if '.' not in name: self.displayedBlocks.append(name) name = 'showBlock/%s' % name script += '$("a[href=\'%s\']")' % name script += '.addClass("disabled").attr("href", "#");' script = '<script>%s</script>' % script return script def set(section, key, value): if section == 'player': self.world[section][key] = value elif section == 'location': self.world.locations[self.world.currentLocation][key] = value return '<!--//-->' def progress(): return round((self.world.showed_blocks / META['total_blocks']) * 100) self.context = { 'world': self.world, 'link': link, 'show': show, 'disable': disable, 'set': set, 'action': action, 'achieve': achieve, 'checkpoint': checkpoint, 'VERSION': VERSION, 'META': META, 'progress': progress } def showEditor(self): self.updateEditor() self.timer = QTimer() self.timer.timeout.connect(self.updateEditor) self.timer.start(1000) self.editor = QTextEdit() editPanel = QWidget() editPanel.setLayout(QVBoxLayout()) editPanel.layout().addWidget(self.editor) buttonPanel = QWidget() buttonPanel.setLayout(QHBoxLayout()) self.applyButton = QPushButton('Apply') self.applyButton.clicked.connect(self.applyWorld) self.reloadButton = QPushButton('Apply && Reload') self.reloadButton.clicked.connect(self.reloadWorld) buttonPanel.layout().addWidget(self.applyButton) buttonPanel.layout().addWidget(self.reloadButton) editPanel.layout().addWidget(buttonPanel) self.tabs.addTab(self.view, 'Game') self.tabs.addTab(editPanel, 'Editor') self.view.page().settings().setAttribute( QWebSettings.DeveloperExtrasEnabled, True ) self.setCentralWidget(self.tabs) def initNewWorld(self): with open(self.worldPath, 'w') as wf: json.dump({ "player": {}, 'locations': {}, 'achievements': [], 'persons': {}, 'launches': 0, 'checkpoint': '', 'version': VERSION, 'showed_blocks': 0 }, wf) def updateEditor(self): text = json.dumps(self.world, indent=4) if text != self.editor.toPlainText() and not self.editor.hasFocus(): self.editor.setText(text) def saveWorld(self): json.dump( self.world, open(self.worldPath, 'w'), indent=4 ) def applyWorld(self): try: world = json.loads(self.editor.toPlainText()) with open(self.worldPath, 'w') as f: f.write(self.editor.toPlainText()) except Exception as e: print(e) return self.world = AttrDict(world) def reloadWorld(self): self.applyWorld() self.loadWorld() def loadWorld(self): self.locations = Locations(self, BASE_URL, self.world, BasicLocation) if 'currentLocation' not in self.world: self.loadPage('data/menu.html') else: self.goTo(self.world.currentLocation) def goTo(self, location): self.locations.load(location) def loadPage(self, path, context=None): self.displayedBlocks = [] if 'currentLocation' in self.world: if self.world.currentLocation in self.world.locations: self.context['location'] = self.world.locations[ self.world.currentLocation ] else: self.context['location'] = {} self.context['player'] = self.world.player self.template = env.get_template(path) if context is None: context = {} context.update(self.context) self.injectObjects() content = self.template.render(context) # self.view.setContent(content, "text/html; charset=utf-8") self.view.setHtml(content) def injectObjects(self): self.view.page().mainFrame().addToJavaScriptWindowObject('app', self) if hasattr(self, 'currentLocation'): self.view.page().mainFrame().addToJavaScriptWindowObject('currentLocation', self.currentLocation) self.view.page().mainFrame().evaluateJavaScript('console.log(app)') @pyqtSlot() def play(self): self.locations.load('first') @pyqtSlot() def finish(self): if self.world.launches == 1: self.world['achievements'].append('one_launch') context = { "done": [], "last": [] } for aid, a in self.achievements.items(): if aid in self.world.achievements: context['done'].append(a) else: context['last'].append(a) self.loadPage('finish.html', context=context) @pyqtSlot() def exit(self): sys.exit() @pyqtSlot() def restart(self): achievements = self.world.achievements self.initNewWorld() world = json.load(open(self.worldPath, 'r')) world['achievements'] = achievements self.world = AttrDict(world) self.saveWorld() self.loadWorld() @pyqtSlot() def update(self): url = BASE_URL if sys.platform == 'win32': os.startfile(url) elif sys.platform == 'darwin': subprocess.Popen(['open', url]) else: try: subprocess.Popen(['xdg-open', url]) except OSError: print('Please open a browser on: %s' % url) @pyqtSlot(str) def showBlock(self, block): self.context['player'] = self.world.player self.world['showed_blocks'] += 1 if block in self.displayedBlocks: return else: self.displayedBlocks.append(block) html = ''.join( self.template.blocks[block]( self.template.new_context(self.context) ) ).replace('"', '\\"').replace("'", "\\'").replace('\n', '') script = '$("#visible").append("%s");' % html.strip() self.view.page().mainFrame().evaluateJavaScript(script) script = '$("a[href=\'main.show/%s\']").addClass("visited");' % block # self.view.setContent('<script>%s</script>' % script, "text/html; charset=utf-8") self.view.page().mainFrame().evaluateJavaScript(script) self.view.page().mainFrame().setScrollBarValue( Qt.Vertical, self.view.page().mainFrame().scrollBarMaximum(Qt.Vertical) )
class WASM(object): """Single class that conveniently exposes Windows Azure Service Management operations from those implemented and explicitly exposed by the individual service wrappers. Using WASM ---------- >>> import pyazure >>> pa = pyazure.PyAzure(management_cert_path=MANAGEMENT_CERT, ... subscription_id=SUBSCRIPTION_ID, management_key_path=MANAGEMENT_KEY) >>> 'Anywhere Asia' in pa.wasm.list_locations() True >>> request_id = pa.wasm.create_storage_account('pyazuretest','doctest', ... 'anywhere us', 'Here is my description, not great is it?') >>> pa.wasm.wait_for_request(request_id) True >>> (pa.wasm.get_operation_status(request_id) == ... {'HttpStatusCode': 200, 'Status': 'Succeeded'}) True >>> request_id = pa.wasm.create_storage_account( ... 'pyazuretestwithaverylongname','doctest','anywhere us') Traceback (most recent call last): ... ValueError: ('pyazuretestwithaverylongname', 'name must be between 3 and 24 characters in length and use numbers and lower-case letters only.') >>> 'pyazuretest' in pa.wasm.list_storage_accounts() True >>> pa.wasm.create_service('pyazuretest','create service doctest', ... 'anywhere europe') True >>> 'pyazuretest' in pa.wasm.list_services() True >>> pa.wasm.create_service('pyazuretest','create service doctest', ... 'anywhere europe') Traceback (most recent call last): ... WASMError: (409, 'ConflictError', 'The specified DNS name is already taken.') >>> pa.wasm.create_service('pyazuretest','create service doctest' * 10, ... 'anywhere europe') # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: ('create service doctest...', 'label exceeds 100 char limit') >>> pa.wasm.get_service_properties('pyazuretest') # doctest: +ELLIPSIS ... # doctest: +NORMALIZE_WHITESPACE OrderedDict([('Url', 'http...'), ('ServiceName', 'pyazuretest'), ('HostedServiceProperties', OrderedDict([('Description', ''), ('Location', 'Anywhere Europe'), ('Label', 'create service doctest')]))]) >>> pa.wasm.delete_service('pyazuretest') True >>> pa.wasm.delete_storage_account('pyazuretest') True >>> pa.wasm.delete_storage_account('pyazuretest') Traceback (most recent call last): ... WASMError: (404, 'ResourceNotFound', 'The requested storage account was not found.') """ def __init__(self, management_cert_path, subscription_id, management_key_path=None): """Initialise the various API interfaces. Note that management_key_path is not required (except for Python 2.5), as the key can be included in the certificate chain file. The OpenSSL command line can create an appropriate PEM file like so: openssl pkcs12 -in azure.pfx -out azure.pem -nodes """ from hostedservices import HostedServices, ServiceConfiguration from storageaccounts import StorageAccounts from locations import Locations self.service_api = HostedServices(management_cert_path, subscription_id, management_key_path) self.ServiceConfiguration = ServiceConfiguration self.storage_api = StorageAccounts(management_cert_path, subscription_id, management_key_path) self.location_api = Locations(management_cert_path, subscription_id, management_key_path) self._sme = ServiceManagementEndpoint(management_cert_path, subscription_id, management_key_path) self.WASMError = WASMError self.get_operation_status = self._sme.get_operation_status self.request_done = self._sme.request_done self.wait_for_request = self._sme.wait_for_request for op in self.service_api.get_wasm_ops(): setattr(self, op.__name__, op) for op in self.storage_api.get_wasm_ops(): setattr(self, op.__name__, op) for op in self.location_api.get_wasm_ops(): setattr(self, op.__name__, op)
# # if count == 100: # # break # #print(count) # # except Exception as ex: # print(ex, ex.message) # count += 1 # continue # # print("Complete!") count = 0 diff_count = 0 classifier = Classifier() analyser = IndicoSentimentAnalyser() locations = Locations() with open(temp_file, 'rb') as fp: reader = csv.reader(fp) with open(chinese_file, 'wb') as op: writer = csv.writer(op) writer.writerow(['Date', 'Location', 'Country', 'Text', 'Sentiment']) for row in reader: tweet_text = row[12] location = row[3] date = row[7] country = locations.get_country(location=location) try:
from post import Post from user import User from locations import Locations from werkzeug.utils import secure_filename from basic_authentication import ( get_password_hash, verify_password, generate_token, verify_token, require_login ) app = Flask(__name__) location_titles = ['Sofia', 'Bansko', 'Shumen', ] Locations.drop() for title in location_titles: location = Locations(*(None, title)) location.save() @app.route("/index.html") @require_login def homepage(user): return render_template("index.html", user=user) @app.route("/login.html", methods=["GET", "POST"]) def login(): if request.method == "GET": return render_template("login.html")
app.add_route("/api/v1/users/{userId}/permissionvalidation", ValidateLocationPermissions(db)) app.add_route("/api/v1/users/{userId}/mqttauth", MqttUserToken()) app.add_route("/api/v1/users/{userId}/locations", UserLocations(db, mqttclient)) app.add_route("/api/v1/users/{userId}/weather", Weather()) app.add_route("/api/v1/users/{userId}/sunschedule", SunSchedule()) app.add_route("/api/v1/users/{userId}/sensors", UserSensors(db)) app.add_route("/api/v1/users/{userId}/permissions/{shareId}", LocationPermission(db)) app.add_route("/api/v1/users/{userId}/bitcoin/current", BitcoinCurrent()) app.add_route("/api/v1/users/{userId}/bitcoin/historical", BitcoinHistorical()) app.add_route("/api/v1/users/{userId}/bitcoin", BitcoinPrice()) app.add_route("/api/v1/users/{userId}/firebasetoken", FirebaseUserToken(db)) app.add_route("/api/v1/users/{userId}/locations/{locationId}", Locations(db, mqttclient)) app.add_route( "/api/v1/users/{userId}/locations/{locationId}/devices", LocationDevices(db, mqttclient), ) app.add_route("/api/v1/users/{userId}/locations/{locationId}/ordersensors", OrderSensors(db)) app.add_route( "/api/v1/users/{userId}/locations/{locationId}/permissions", LocationsPermissions(db), ) app.add_route("/api/v1/users/{userId}/locations/{locationId}/rooms", LocationRooms(db)) app.add_route("/api/v1/users/{userId}/locations/{locationId}/rooms/{roomId}", LocationRoom(db)) app.add_route(
def loadWorld(self): self.locations = Locations(self, BASE_URL, self.world, BasicLocation) if 'currentLocation' not in self.world: self.loadPage('data/menu.html') else: self.goTo(self.world.currentLocation)
def secondsToMin(time_seconds): #show 2 decimal places print("{:.2f}".format(time_seconds / 60) + " minutes") # look for end key in the computed-short graph def searchShortest(key, computed_map): if key in computed_map: return computed_map[key] mapData = process_csv("distances.csv") hsuMap = Graph() location = Locations() for i in location._locations: hsuMap.add_vertex(i) for items in mapData: # change last element in list to a float (for adding purposes) items[2] = float(items[2]) # each element in list becomes an argument for paramter hsuMap.connect_vertex(*items) print("** HSU Transit Time Calculator **") print("TIER 1") start = input("Enter starting location: ")
from flask import Flask, render_template, request, redirect, url_for from locations import Locations from forms import AddLocationForm app = Flask(__name__) app.config['SECRET_KEY'] = 'SECRET_PROJECT' visit = Locations() categories = {"recommended": "Recommended", "tovisit": "Places To Go", "visited": "Visited!!!", } UP_ACTION = "\u2197" DEL_ACTION = "X" @app.route("/<category>", methods=["GET", "POST"]) def locations(category): locations = visit.get_list_by_category(category) ## Check the request for form data and process if request.method == "POST": [(name, action)] = request.form.items() if action == UP_ACTION: visit.moveup(name) elif action == DEL_ACTION: visit.delete(name) ## Return the main template with variables return render_template("locations.html", category=category, categories=categories, locations=locations, add_location=AddLocationForm())
def detect(haystack): location = Locations.detect(haystack) if location != None: location["country"] = pycountry.countries.get( alpha2=location["code"]).name return location
class Game: def __init__(self, player_details, canvas): self.players = [ Player(name, order, is_human) for (order, (name, is_human)) in enumerate(player_details) ] self.tiles = Tiles() self.locations = Locations(self) self.active_tile = None self.active_target = None self.mode = GameMode.SELECTING_TILE self.canvas = canvas self.source = [] self.target = [] # TODO: Move fonts into Settings or separate fonts module? self.small_floor_tile_scores_font = pygame.font.SysFont( 'Arial', Settings.floor_tile_scores_font_size) self.large_floor_tile_scores_font = pygame.font.SysFont( 'Arial', int(Settings.floor_tile_scores_font_size * Settings.player_area_multiplier)) self.button_font = self.large_floor_tile_scores_font # TODO: Move this in with the ButtonLocation? x, y = Settings.player_area_location multiplier = Settings.player_area_multiplier x += Settings.pattern_area_width * multiplier x += 2 * Settings.tile_width * multiplier width = 3 * Settings.tile_width * multiplier y += (Settings.area_height - Settings.tile_height * 1.9) * multiplier height = Settings.tile_height * multiplier self.locations.all.append( ButtonLocation(self, x, y, width, height, 'Continue', 'confirm')) @property def selected(self): return self.source + self.target @property def number_of_players(self): return len(self.players) def draw_background(self): self.canvas.fill((0, 0, 0)) def show_scores(self): for player in self.players: player.show_score(self) def draw(self): self.draw_background() self.locations.draw() self.show_scores() pygame.display.flip() @property def selected_type(self): if not self.source: return None return self.source[0].content.tile_type @property def clicked_location(self): result = self.locations.find(*pygame.mouse.get_pos()) if result is not None: return result return None def select_source_tile(self, location): self.source = [] if type(location) == FactoryLocation: for i in self.locations.all: if type(i) == FactoryLocation: if i.factory_id == location.factory_id and i.content.tile_type == location.content.tile_type: self.source.append(i) elif type(location) == CentreLocation: for i in self.locations.all: if type(i) == CentreLocation and i.content: if i.content.tile_type == location.content.tile_type: self.source.append(i) self.mode = GameMode.SELECTING_TARGET def select_target_row(self, location): self.target = [] for i in self.locations.all: if type(i) is not PatternLocation or i.player_id is not 0: continue if i.row == location.row: self.target.append(i) self.mode = GameMode.AWAITING_CONFIRMATION def sort_centre(self): centre_locations = self.locations.filter(location_type=CentreLocation) centre_pieces = [ l.content for l in centre_locations if l.content is not None ] centre_pieces.sort(key=lambda x: x.tile_type.colour) for location in centre_locations: location.content = None for i in range(len(centre_pieces)): centre_locations[i].content = centre_pieces[i] def move_pieces(self): self.target.sort(key=lambda x: -x.column) free_target = [t for t in self.target if not t.content] for i in range(min(len(free_target), len(self.source))): free_target[i].content = self.source[i].content self.source[i].content = None # TODO: Refactor - lots of duplication from code just above source = [s for s in self.source if s.content] free_target = [ t for t in self.locations.all if isinstance(t, FloorLocation) and not t.content and t.player_id == 0 ] free_target.sort(key=lambda x: x.column) for i in range(min(len(free_target), len(source))): free_target[i].content = source[i].content source[i].content = None if type(self.source[0]) == FactoryLocation: centre_locations = self.locations.filter( location_type=CentreLocation, is_free=True, sort_by='cell_id') factory_locations = self.locations.filter( location_type=FactoryLocation, factory_id=self.source[0].factory_id) to_move_to_centre = [l for l in factory_locations if l.content] for i, location in enumerate(to_move_to_centre): centre_locations[i].content = location.content location.content = None if to_move_to_centre: self.sort_centre() # TODO: Move to separate function to reset mode? self.mode = GameMode.SELECTING_TILE self.source = [] self.target = [] def confirm_movement(self): self.move_pieces() def process_mouse_click(self): location = self.clicked_location if location is None or not location.can_click: return if isinstance(location, FactoryLocation): self.select_source_tile(location) return if isinstance(location, PatternLocation): self.select_target_row(location) return if isinstance(location, ButtonLocation) and location.action == 'confirm': self.move_pieces() def new_tiles(self): for location in self.locations.filter(location_type=FactoryLocation): if not location.content: location.content = self.tiles.random_tile() def points_for_range(self, h_range, v_range): result = 0 for x in h_range: for y in v_range: if self.locations.filter(location_type=WallLocation, column=x, row=y)[0].content is None: return result result += 1 return result def points_for_wall_location(self, location): h_points = self.points_for_range(range(location.column - 1, -1, -1), [location.row]) + \ self.points_for_range(range(location.column + 1, 5), [location.row]) if h_points: h_points += 1 v_points = self.points_for_range([location.column], range(location.row - 1, -1, -1)) + \ self.points_for_range([location.column], range(location.row + 1, 5)) if v_points: v_points += 1 result = max(1, h_points + v_points) # print(location.column, location.row, h_points, v_points) return result def score(self): for player in self.players: pattern_locations = self.locations.filter( location_type=PatternLocation, player_id=player.order) wall_locations = self.locations.filter(location_type=WallLocation, player_id=player.order) for row in range(5): source_locations = [ l for l in pattern_locations if l.row == row and l.content ] if len(source_locations) != row + 1: continue tile_type = source_locations[0].content.tile_type target_location = [ l for l in wall_locations if l.row == row and l.tile_type == tile_type ][0] player.points += self.points_for_wall_location(target_location) target_location.content = source_locations[0].content source_locations[0].content = None for location in source_locations[1:]: location.content.location = Location.DISCARD_PILE location.content = None for location in self.locations.filter(location_type=FloorLocation): if location.content: location.content.location = Location.DISCARD_PILE location.content = None self.new_tiles()
__author__ = 'Gaurav-PC' import csv from locations import Locations indian_file = "F:\\SOIC Courses\\Big Data\\Final Project\\Cuisine-Dataset\\locations\\indian_with_date.csv" italian_file = "F:\\SOIC Courses\\Big Data\\Final Project\\Cuisine-Dataset\\locations\\italian_with_date.csv" mideast_file = "F:\\SOIC Courses\\Big Data\\Final Project\\Cuisine-Dataset\\locations\\mideast_with_date.csv" out_file = "F:\\SOIC Courses\\Big Data\\Final Project\\Cuisine-Dataset\\locations\\final\\italy\\italian_cuisine_final.csv" location = Locations() with open(italian_file, 'rb') as fp: reader = csv.reader(fp) with open(out_file, 'wb') as op: writer = csv.writer(op) writer.writerow(['Date', 'Location', 'Country', 'Text', 'Sentiment']) count = 0 for row in reader: if count == 0: count += 1 continue loc = row[1] country = location.get_country(loc) final = [row[0], loc, country, row[2], row[3]] writer.writerow(final) count += 1 print("Done [" + str(count) + "] ...")