Example #1
0
 def test_populate(self):
     populate()
     self.assertIsNotNone(User.objects.get(username="******"))
     self.assertIsNotNone(Leaderboard.objects.get(seed="test0", plays=4, challanges=0))
     lead=Leaderboard.objects.get(seed="test0", plays=4, challanges=0)
     usr=User.objects.get(username="******")
     self.assertIsNotNone(Score.objects.get(leaderboard=lead, user=usr, score=10))
Example #2
0
def runserver():
	import fs, optparse, daemon
	from os.path import join, exists
	from base import enable_logging
	from config import SiteConfig
	from populate import populate
	from cached import cache_expander, wipe_sitelists

	options, remainder = server_options_parser.parse_args()

	apply_site_dirs(remainder)
	enable_logging(options)
	config = SiteConfig(options)

	wipe_sitelists(config.active_domain)
	populate(cache_expander,config)
	if options.fork:
		pid = os.fork()
		if pid == 0: 
			# The Child Process
			with daemon.DaemonContext():
				start_server(site.PROJECT_DIR,"runserver",config)
		else:
			print "Forked a Daemon as", pid
	else:
		start_server(site.PROJECT_DIR,"runserver",config)
Example #3
0
def mainfct(document):
    path_to_docx = document
    document = Document(path_to_docx)

    tables = document.tables
    i = 0
    for table in tables:

        x = 0
        y = 0
        p = 0
        cell_counter = 0
        main_dict = {}
        # document.tables[i].cell(x,y).paragraphs[p].text != None

        while True:
            try:
                test_end = document.tables[i].cell(x, y).paragraphs[p].text
                p = 0
                while True:

                    try:
                        paragraphs = document.tables[i].cell(x, y).paragraphs

                        text = ""
                        for paragraph in paragraphs:
                            text = text + "\n" + paragraph.text
                            text = text.strip("\n")
                            p = p + 1
                        print text.encode("UTF-8")
                        filtered_dict2 = {}
                        if cell_counter > 0:
                            for k, v in parse_cell(text).items():
                                if v:
                                    filtered_dict2[k] = v
                        elif cell_counter == 0:
                            main_dict = parse_cell(text)
                        main_dict.update(filtered_dict2)
                        print main_dict
                        cell_counter = cell_counter + 1
                        if cell_counter == 3:
                            populate(main_dict)
                            cell_counter = 0
                            main_dict = {}
                        x = x + 1
                        print ("----------------y+1------------------")
                        p = 0
                    except IndexError:
                        x = 0
                        break

            except IndexError:
                break
            p = 0
            y = y + 1
            print ("-----------------------x+1----------------------------")
        i = i + 1

    print ("REACHED").encode("UTF-8")
Example #4
0
 def test_populate(self):
     populate()
     self.assertIsNotNone(User.objects.get(username="******"))
     self.assertIsNotNone(
         Leaderboard.objects.get(seed="test0", plays=4, challanges=0))
     lead = Leaderboard.objects.get(seed="test0", plays=4, challanges=0)
     usr = User.objects.get(username="******")
     self.assertIsNotNone(
         Score.objects.get(leaderboard=lead, user=usr, score=10))
Example #5
0
 def setUp(self):
     try:
         from populate import populate
         populate()
     except ImportError:
         print('The module populate_rango does not exist')
     except NameError:
         print('The function populate() does not exist or is not correct')
     except:
         print('Something went wrong in the populate() function :-(')
Example #6
0
    def test_population_script(self):
        populate.populate()
        restaurant = Restaurant.objects.get(name='Chow')
        self.assertEquals(restaurant.address,
                          '98 Byres Road, Glasgow, G12 8TB')

        food1 = Food.objects.get(name='Mushroom Curry')
        self.assertEquals(food1.vegetarian, True)

        food2 = Food.objects.get(name='Salmon Feast Set')
        self.assertEquals(food2.restaurant.name, 'Okome')
Example #7
0
def resize_for_new_nodes(new_total_nodes, k8s, cluster, test=False):
    """create new nodes to match new_total_nodes required
    only for scaling up"""
    if confirm(("Resizing up to: %d nodes" % new_total_nodes)):
        scale_logger.info("Resizing up to: %d nodes", new_total_nodes)
        if not test:
            cluster.add_new_node(new_total_nodes)
            wait_time = 130
            scale_logger.debug(
                "Sleeping for %i seconds for the node to be ready for populating", wait_time)
            time.sleep(wait_time)
            populate(k8s)
Example #8
0
def Checkdb(dbname):
    prgrm = 1
    if checkdb(dbname) is True: #Check the existance of the database (if exists or not)
        createdb(dbname) #Create the database
        session = connect(dbname) #Connect to the database

        createtables(dbname) #Create the tables
        populate(dbname, rawdata) #Populate the database

        finishTime = datetime.now() #End of the set up
        timeDetla = finishTime - startTime

        print('\n----------------------------------------------------')
        print("Setup is finished. Your database is now available.")
        print("The process was completed in : " + str(
            timeDetla.total_seconds()) + "s.") #Total time
        print('----------------------------------------------------\n')
        return prgrm
    else:
        print("Your database already exists.\n")
        print('Do you want to delete the tables to run the program anyway ?')
        print('1 = Delete the tables and recreate others.')
        print('Other integer: do not run the program\n')

        try:
            Choice = int(input('Your choice : '))
        except ValueError:
            print("The input is not right...\n")
            prgrm = 0
            return prgrm

        if Choice == 1:
            engine = db.create_engine(f'mysql+pymysql://{username}:{password}@{host}/{dbname}')
            connection = engine.connect() #Connect

            session = connect(dbname) #Connect to the database

            query = db.delete(Books)
            results = connection.execute(query) 

            populate(dbname, rawdata) #Populate the database with what we want
            return prgrm
        else : 
            prgrm = 0
            print('The program will not run')
            return prgrm

        print('----------------------------------------------------\n')
Example #9
0
    def __init__(self, remoteShell, domainAdmin="admin", domain=None):
        self.remoteShell = remoteShell
        self.uptoolPath = "/opt/quest/bin/uptool"     
        self.domainAdmin = domainAdmin
        self.defaultDomain = domain
        
        self.container = container.container(self.remoteShell, self.domainAdmin, self.defaultDomain) 
        self.create = upCreate.create(self.remoteShell, self.domainAdmin, self.defaultDomain)  
        self.delete = upDelete.delete(self.remoteShell, self.domainAdmin, self.defaultDomain) 
        self.depopulate = depopulate.depopulate(self.remoteShell, self.domainAdmin, self.defaultDomain) 
        self.list = upList.list(self.remoteShell, self.domainAdmin, self.defaultDomain) 
        self.membership = membership.membership(self.remoteShell, self.domainAdmin, self.defaultDomain) 
        self.migrate = migrate.migrate(self.remoteShell, self.domainAdmin, self.defaultDomain) 
        self.modify = modify.modify(self.remoteShell, self.domainAdmin, self.defaultDomain) 
        self.populate = populate.populate(self.remoteShell, self.domainAdmin, self.defaultDomain)

        isinstance(self.container, container.container)
        isinstance(self.create, upCreate.create)
        isinstance(self.delete, upDelete.delete)
        isinstance(self.depopulate, depopulate.depopulate)
        isinstance(self.list, upList.list)
        isinstance(self.membership, membership.membership)
        isinstance(self.migrate, migrate.migrate)
        isinstance(self.modify, modify.modify)
        isinstance(self.populate, populate.populate)
Example #10
0
    def setUp(self):
        try:
            from populate import populate
            populate()
        except ImportError:
            print('The module populate does not exist')
        except NameError:
            print('The function populate() does not exist or is not correct')
        except:
            print('Something went wrong in the populate() function')

        from django.contrib.auth import get_user_model
        User = get_user_model()
        testuser =  User.objects.create_user('testuser', '*****@*****.**', 'pass')
        from projects import models
        project = models.Project.objects.get(project_title="fake_title")
        pm = models.ProjectMember.objects.get_or_create(user=testuser, project=project, is_owner=True)
Example #11
0
 def setUp(self):
     print "asdfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
     for item in model.__dict__.values():
         if inspect.isclass(item) and issubclass(item,
             sqlobject.SQLObject) and item != sqlobject.SQLObject \
             and item != InheritableSQLObject:
             item.dropTable(ifExists=True)
     testutil.DBTest.setUp(self)
     self.objs = populate()
Example #12
0
def populateserver():
	import fs, optparse
	from os.path import join, exists
	from base import enable_logging
	from config import SiteConfig
	from populate import populate, save_expander
	from cached import cache_expander, wipe_sitelists

	options, remainder = populate_options_parser.parse_args()

	apply_site_dirs(remainder)
	enable_logging(options)
	config = SiteConfig(options)

	if config["output"]:
		populate(save_expander,config)
	else:
		wipe_sitelists(config.active_domain)
		populate(cache_expander,config)
 def test_standard_case(self):
     """Checks method runs correctly under typical inputs."""
     db = populate.populate()
     nat_environment = {
         c.C_BIDEN: 30,
         c.C_WARREN: 30,
         c.C_SANDERS: 20,
         c.C_BUTTIGIEG: 20,
         "confidence": 0.5
     }
     candidates = [c.C_BIDEN, c.C_WARREN, c.C_SANDERS, c.C_BUTTIGIEG]
     primary_calendar = db.get_primary_calendar()
     result = ps.simulate(db, nat_environment, candidates, primary_calendar)
     self.assertNotEqual(result.winner, None)
 def test_no_candidates(self):
     """Tests the case where there are no candidates provided."""
     db = populate.populate()
     nat_environment = {
         c.C_BIDEN: 30,
         c.C_WARREN: 30,
         c.C_SANDERS: 20,
         c.C_BUTTIGIEG: 20,
         "confidence": 0.5
     }
     candidates = []
     primary_calendar = db.get_primary_calendar()
     with self.assertRaises(ValueError):
         result = ps.simulate(db, nat_environment, candidates,
                              primary_calendar)
 def test_negative_support(self):
     """Tests the case where one candidate has negative national support."""
     db = populate.populate()
     nat_environment = {
         c.C_BIDEN: 40,
         c.C_WARREN: 31,
         c.C_SANDERS: 31,
         c.C_BUTTIGIEG: -2,
         "confidence": 0.5
     }
     candidates = [c.C_BIDEN, c.C_WARREN, c.C_SANDERS, c.C_BUTTIGIEG]
     primary_calendar = db.get_primary_calendar()
     with self.assertRaises(ValueError):
         result = ps.simulate(db, nat_environment, candidates,
                              primary_calendar)
Example #16
0
def populate_command():
    populate.populate()
    print('Populated the database.')
Example #17
0
from merge import mergesort
from merge import mergesort_time
from quick import quicksort
from counting import countingsort
from radix import radixsort
from shell import shellsort

#utils
from populate import populate
import time

v100 = list(range(0, 100))
v1000 = list(range(0, 1000))
v10000 = list(range(0, 10000))

v100 = populate(v100)
v1000 = populate(v1000)
v10000 = populate(v10000)


def time_execute_shellsort_v100():

    before = time.time()
    shellsort(v100)
    after = time.time()
    total = ((after - before) * 1000)

    print("time shellsort (100 elements) = %0.4f" % total)


time_execute_shellsort_v100()
Example #18
0
def Checkdb(dbname):
    prgrm = 1  #Default value for the program to run
    if checkdb(
            dbname
    ) is True:  #Check the existance of the database (if exists or not)
        """
        The database does not exist: we need to create it from scratch and populate it
        """
        createdb(dbname)  #Create the database
        session = connect(dbname)  #Connect to the database

        createtables(dbname)  #Create the tables
        populate(dbname, rawdata)  #Populate the database

        finishTime = datetime.now()  #End of the set up
        timeDetla = finishTime - startTime

        print('\n----------------------------------------------------')
        print("Setup is finished. Your database is now available.")
        print("The process was completed in : " +
              str(timeDetla.total_seconds()) +
              "s.")  #Total time for the database's setup
        print('----------------------------------------------------\n')
        return prgrm
    else:
        print("Your database already exists.\n")
        print('Here are the tables and their columns that exists : ')

        engine = db.create_engine(
            f'mysql+pymysql://{username}:{password}@{host}/{dbname}')
        connection = engine.connect()  #Connect
        session = connect(dbname)  #Connect to the database

        metadata = MetaData(bind=engine)

        m = MetaData()
        m.reflect(engine)
        listtable = []
        for table in m.tables.values():  #Create a list
            listtable.append(table.name)
            print("\nTable name: ", table.name, "\n")
            for column in table.c:
                print("Column name: ", column.name)

        print('\nDo you want to see what is inside a specific table ? ')
        print('1 = You want to see inside a table.')
        print('Other integer : do not show anything\n')

        try:
            choice = int(input('Your choice : '))
        except ValueError:
            print(
                '\nThe input is not right. We will consider you do not want to see anything\n'
            )
            choice = 0

        if choice == 1:
            print(
                '\nYou asked to see what is inside a table. Which one do you want to see ? \n'
            )
            try:
                tablechosen = choosetable()
            except ValueError:
                print('\nPlease write a valid input (string)')
                tablechosen = choosetable()

            try:
                existingtable = listtable.index(tablechosen)
            except ValueError:
                print("You did not entered a valid table name...")
                print("Please write a valid one now\n")
                tablechosen = choosetable()
            else:
                print(
                    pd.DataFrame(
                        connection.execute(
                            "SELECT * FROM {}".format(tablechosen))))

        else:
            pass

        print(
            '\nDo you want to add the data that does not exist (without deleting the previously existing one ?'
        )
        print('1 = You want to add the data and run the program')
        print('Other integer : Do not do anything. The program will stop\n')

        try:
            Choice = int(input('Your choice : '))
        except ValueError:
            print(
                "The input is not right... We will consider you do not want the program to run.\n"
            )
            prgrm = 0
            return prgrm

        if Choice == 1:

            # Create a code that add the data from the jason file
            # if it does not exist in the table

            with open('data.json') as f:
                data_json = json.load(f)

            for data in data_json:
                if not Books.objects.filter(Title=data['Title']).exists:
                    data = Books(Title=data['Title'],
                                 Author=data['Author'],
                                 ReadOrNot='0')
                    data.save()
                    print(
                        f"Added to the database:  {data.Title} \ (TITLE {data.Title}). "
                    )
                else:
                    print(
                        f'This book already exists: \ {Books.objects.get(Title = data["Title"]).Title} (TITLE: {data["Title"]}).'
                    )

            return prgrm  #The program will run properly

        else:
            prgrm = 0
            print('The program will not run')
            return prgrm
# Date: Thu 25 Jul 2019 17:23:15 CEST
# Author: Nicolas Flandrois

from sqlalchemy.orm import sessionmaker, query
from connection import connect, createdb, checkdb
from datetime import datetime
from createtables import createtables
from populate import populate

startTime = datetime.now()
print("Setup in progress. Please wait.")
dbname = 'ocpizza'
rawdata = 'data.json'

if checkdb(dbname) is True:
    createdb(dbname)
    session = connect(dbname)

    createtables(dbname)
    populate(dbname, rawdata)

    finishTime = datetime.now()
    timeDetla = finishTime - startTime

    print("Setup is finished. Your database is now available.")
    print("The process was completed in : " + str(timeDetla.total_seconds()) +
          "s.")

else:
    print("Your database already exists.")
Example #20
0
def populate_db_tests():
    populate(MONGO_DATABASE_TESTS, MONGO_HOST, MONGO_PORT)
Example #21
0
def update_unschedulable(number_unschedulable,
                         nodes,
                         k8s,
                         calculate_priority=None):
    """Attempt to make sure given number of
    nodes are blocked, if possible; 
    return number of nodes newly blocked; negative
    value means the number of nodes unblocked

    calculate_priority should be a function
    that takes a node and return its priority value
    for being blocked; smallest == highest
    priority; default implementation uses get_pods_number_on_node

    CRITICAL NODES SHOULD NOT BE INCLUDED IN THE INPUT LIST"""

    assert number_unschedulable >= 0
    number_unschedulable = int(number_unschedulable)

    scale_logger.info(
        "Updating unschedulable flags to ensure %i nodes are unschedulable",
        number_unschedulable)

    if calculate_priority == None:
        # Default implementation based on get_pods_number_on_node
        def calculate_priority(node):
            return k8s.get_pods_number_on_node(node)

    schedulable_nodes = []
    unschedulable_nodes = []

    priority = []

    # Analyze nodes status and establish blocking priority
    for count in range(len(nodes)):
        if nodes[count].spec.unschedulable:
            unschedulable_nodes.append(nodes[count])
        else:
            schedulable_nodes.append(nodes[count])
        priority.append((calculate_priority(nodes[count]), count))

    # Attempt to modify property based on priority
    toBlock = []
    toUnBlock = []

    heapq.heapify(priority)
    for _ in range(number_unschedulable):
        if len(priority) > 0:
            _, index = heapq.heappop(priority)
            if nodes[index] in schedulable_nodes:
                toBlock.append(nodes[index])
        else:
            break
    for _, index in priority:
        if nodes[index] in unschedulable_nodes:
            toUnBlock.append(nodes[index])

    __update_nodes(k8s, toBlock, True)
    scale_logger.debug("%i nodes newly blocked", len(toBlock))
    __update_nodes(k8s, toUnBlock, False)
    scale_logger.debug("%i nodes newly unblocked", len(toUnBlock))
    if (len(toBlock) != 0 or len(toUnBlock) != 0) and (
            len(toBlock) != len(toUnBlock)) and not k8s.test:
        slack_logger.info("%i nodes newly blocked, %i nodes newly unblocked",
                          len(toBlock), len(toUnBlock))
    if len(toUnBlock) != 0:
        populate(k8s)

    return len(toBlock) - len(toUnBlock)
Example #22
0
 def setUp(self):
     populate()
     up = UserProfile()
     up.user = User.objects.create_user('a', 'b', 'c')
     up.save()
     self.client.login(username='******', password='******')
Example #23
0
def mainfct(document):
	path_to_docx = document
	document = Document(path_to_docx)

	tables = document.tables
	i = 0
	for table in tables:

		x = 0
		y = 0
		p = 0
		cell_counter = 0
		main_dict={}
	#document.tables[i].cell(x,y).paragraphs[p].text != None



		while True:
			try:
				test_end = document.tables[i].cell(x,y).paragraphs[p].text
				p=0	
				while True:

					try:
						paragraphs = document.tables[i].cell(x,y).paragraphs
						
						text=""
						for paragraph in paragraphs:
							text = text +'\n'+ paragraph.text
							text = text.strip('\n')
							p = p+1
						print text.encode('UTF-8')
						filtered_dict2 = {}
						if cell_counter > 0:
							for k, v in parse_cell(text).items():
							    if v:
	        						filtered_dict2[k] = v
						elif cell_counter ==0:
							main_dict = parse_cell(text)
						main_dict.update(filtered_dict2)
						print main_dict
						cell_counter = cell_counter + 1
						if cell_counter == 3:
							populate(main_dict)
							cell_counter = 0
							main_dict={}
						x=x+1
						print ("----------------y+1------------------")
						p=0
					except IndexError:
						x=0
						break
				

			except IndexError:
				break
			p=0
			y = y + 1
			print ("-----------------------x+1----------------------------")
		i = i + 1

	print ("REACHED").encode('UTF-8')
Example #24
0
 def setUp(self):
     populate.populate()
     self.user = User.objects.create_user('john', '*****@*****.**', 'johnpassword')
     self.user.save()
     self.client.force_login(self.user)
Example #25
0
def populate_tables():
    from populate import populate
    populate()
Example #26
0
    for i in range(0, len(list_of_config)):
        print("CONFIG OF DOC -", count, ":-", list_of_config[i], "\n")
        count = count + 1
    aggregated_config = {}
    for j in range(0, len(list_of_config)):
        config_j = list_of_config[j]
        data_merge(aggregated_config, config_j)
        print("Config Of Document ", j, "is MERGED!!")
    print("\n Aggregated CONFIG is :- ", aggregated_config, "\n")

    data_merge(aggregated_config, config_from_outside)

    for i in range(0, fake_documents_count):
        fake_doc_i = cp.deepcopy(aggregated_config)
        for key, value in fake_doc_i.items():
            val = pl.populate(value)
            fake_doc_i[key] = val
        fake_docs_list.append(fake_doc_i)

    count = 0
    for i in range(0, len(fake_docs_list)):
        print("Fake DOC -", count, ":-", fake_docs_list[i], "\n")
        count = count + 1
    c = "in-3"
    mydb = client['Output']
    mycollection = mydb[col]
    for i in range(0, len(fake_docs_list)):
        mycollection.insert_one(fake_docs_list[i])

mydb = client['Output']
colls = mydb.collection_names()
"""Probabilistic model of the 2020 Democratic Primary."""

import populate
import database
import simulate.primary_simulation as ps
import analyse.plot as plot

# Define constants.
NUM_SIMULATIONS = 1000

# Carry out the simulations.
results = []
for simulation in range(NUM_SIMULATIONS):

    # Create a clean database containing required information.
    db = populate.populate()

    # Initialise other variables.
    base_nat_environment = db.get_nat_primary_environment()
    candidates = db.get_primary_candidates()

    # Set up to iterate through the primary calendar.
    primary_calendar = db.get_primary_calendar()

    result = ps.simulate(db, base_nat_environment, candidates,
                         primary_calendar)
    results.append(result)

# Analyse and present the results.
plot.winners_pie_chart(results)
plot.most_delegates_pie_chart(results)
Example #28
0
 def setUpClass(cls):
     cls.conn = get_connection()
     cls.cur = cls.conn.cursor()
     init_db(cls.cur)
     populate(cls.cur)
     cls.conn.commit()
Example #29
0
 def setUp(self):
     populate.populate()
     self.credentials = {
         'username': '******',
         'password': '******'}
     User.objects.create_user(**self.credentials)
Example #30
0
def index(request):
    display_array = json.dumps(populate.populate())
    print display_array
    return render(request, 'index.html',{'data_for_site' : display_array})
Example #31
0
def setup(count):
    """Empties the collection and populates with `count` number of documents.
    """
    dbinit.init_collection()
    populate.populate(count)
Example #32
0
 def setUp(self):
     populate(MONGO_DATABASE_TESTS, MONGO_HOST, MONGO_PORT)
Example #33
0
def populate():
    import populate
    populate.populate(saidb)
Example #34
0
app.config.from_object('config')

# Define the database object which is imported by modules and controllers
db = SQLAlchemy(app)

# Sample HTTP error handling
@app.errorhandler(404)
def not_found(error):
    return render_template('404.html'), 404

# Import a module / component using its blueprint handler variable
from app.module_authentication.controllers import mod_auth
from app.module_schedule.controllers import mod_schedule

#import models
from app.module_authentication import models
from app.module_schedule import models

# Register blueprints
app.register_blueprint(mod_auth)
app.register_blueprint(mod_schedule)

# Define and populate the database
from populate import populate

if(os.path.exists(BASE_DIR + '/app.db')):
    print "Database already populated."
else:
    db.create_all()
    populate()
Example #35
0
def nn_submit():
    body = request.get_json()

    data = [
        body['age'] / 100,
        body['high_risk_exposure_occupation'],
        body['high_risk_interactions'],
        body['diabetes'],
        body['chd'],
        body['htn'],
        body['cancer'],
        body['asthma'],
        body['copd'],
        body['autoimmune_dis'],
        body['smoker'],
        minMaxTemp(body['temperature']),
        minMaxPulse(body['pulse']),
        body['labored_respiration'],
        body['cough'],
        body['fever'],
        body['sob'],
        body['diarrhea'],
        body['fatigue'],
        body['headache'],
        body['loss_of_smell'],
        body['loss_of_taste'],
        body['runny_nose'],
        body['muscle_sore'],
        body['sore_throat']
    ]

    junk0 = [0 for i in range(25)]
    junk1 = [1 for i in range(25)]

    columns = ['age',
               'high_risk_exposure_occupation', 'high_risk_interactions', 'diabetes',
               'chd', 'htn', 'cancer', 'asthma', 'copd', 'autoimmune_dis', 'smoker',
               'temperature', 'pulse', 'labored_respiration', 'cough', 'fever', 'sob',
               'diarrhea', 'fatigue', 'headache', 'loss_of_smell', 'loss_of_taste',
               'runny_nose', 'muscle_sore', 'sore_throat']
    binary_features = ['diabetes', 'chd', 'htn', 'cancer', 'asthma', 'copd', 'autoimmune_dis', 'high_risk_exposure_occupation', 'high_risk_interactions', 'smoker', 'labored_respiration', 'cough',
                       'fever', 'sob', 'diarrhea', 'fatigue', 'headache', 'loss_of_smell', 'loss_of_taste', 'runny_nose', 'muscle_sore', 'sore_throat']

    df = pd.DataFrame([data, junk0, junk1], columns=columns)

    for col in binary_features:
        df[col] = df[col] * 1

    dummy_cols = list(set(df[binary_features]))
    df = pd.get_dummies(df, columns=dummy_cols)
    df = df.drop(index=[1,2])
    predictions = model.predict(df)
    data.append(predictions[0][0].item())
    data.insert(0, counter())
    with open('user.csv', 'w') as f_object:
        writer_object = writer(f_object)
        writer_object.writerow(['id','age',
               'high_risk_exposure_occupation', 'high_risk_interactions', 'diabetes',
               'chd', 'htn', 'cancer', 'asthma', 'copd', 'autoimmune_dis', 'smoker',
               'temperature', 'pulse', 'labored_respiration', 'cough', 'fever', 'sob',
               'diarrhea', 'fatigue', 'headache', 'loss_of_smell', 'loss_of_taste',
               'runny_nose', 'muscle_sore', 'sore_throat','prediction'])
        writer_object.writerow(data)
        f_object.close()
    populate()
    return {'prediction': predictions[0][0].item()}
Example #36
0
 def setUpClass(cls):
     cls.conn = get_connection()
     cls.cur = cls.conn.cursor()
     init_db(cls.cur)
     populate(cls.cur)
     cls.conn.commit()
Example #37
0
from app.controllers.shows_on_date_route import ShowsOnDateRoute
from app.controllers.show_seating_route import ShowSeatingRoute
from app.controllers.seat_reserved_route import SeatReservedRoute
from app.controllers.reservation_route import ReservationRoute

# add route controllers to routes
base_uri = '/api'

api.add_resource(ApiLoginRoute, base_uri + '/access')
api.add_resource(DatesRoute, base_uri + '/dates')
api.add_resource(MovieRoute, base_uri + '/movie')
api.add_resource(MovieListRoute, base_uri + '/movies/all')
api.add_resource(MoviesOnDateRoute, base_uri + '/movies/date')
api.add_resource(ShowsOnDateRoute, base_uri + '/shows/date')
api.add_resource(ShowSeatingRoute, base_uri + '/show/seating')
api.add_resource(ReservationRoute, base_uri + '/reservations')
api.add_resource(SeatReservedRoute, base_uri + '/seat/reserved')
api.add_resource(RegistrationRoute, base_uri + '/registration')
'''
@app.route('/')
def index():
    return render_template('index.html')  # renders parameter in templates folder
'''

db.create_all()

# populate database and add the admin
from populate import populate
with app.app_context():
    populate(db)
Example #38
0
def populate_ep():
    populate(es)
    return 'Done populate!\n'