"""
# Exploring Views
"""
"""
- What does it mean exploring views???? The notion of view was shown in the example code but had nothing to do with the wrap up exercice.
- Name of the group participants missing
- THE LAST "FIGURE WITH THE "ARCHITECTURE" THAT IS NOT AN ARCHITECTURE IT IS THE PIPELINE IMPLEMENTED TO RUN THE EXPERIMENT
- You had to clean the pieces of code that had nothing to do with the experiment

"""
pip install dnspython
import pandas as pd
import json
import pymongo
from pymongo import MongoClient

import pprint
import urllib.parse

import timeit 
import ipywidgets as widgets
import threading 

import matplotlib.pyplot as plt
import seaborn as sns
client = MongoClient("mongodb+srv://geuser:melq.5491@bdegi.3pkrh.gcp.mongodb.net/gre_EMD?retryWrites=true&w=majority")
db = client.test
db = client['gre_EMD'] 
collection = db['gre10_depl']
collection1=db['gre10_mng']
collection2=db['gre10_pers']
collection3=db['gre10_traj']
db.list_collection_names()
collection.count_documents({})
collection.find_one()
"""
We can convert our entire collection of data into a pandas DataFrame with the comand below
"""
depl = pd.DataFrame(list(db.gre10_depl.find()))
"""
We can use command shape to the number of data samples in rows and in columns:
"""
depl.shape
"""
We use print(depl) to see our data
"""
print(depl)
"""
In our database the duree has format string so we change it into integer

"""
depl['duree'] = depl['duree'].astype(int)

"""
We do the same thing with "NO_PERS"
"""
depl['NO_PERS'] = depl['NO_PERS'].astype(int)
"""
We do the same thing with "NO_DEPL"
"""
depl['NO_DEPL'] = depl['NO_DEPL'].astype(int)
"""
# Introduction 
In this hands on, we used the collection **gre10_depl** of database gre_EMD. We focused on issues relating to the number of travellers, the number of deplacements, the trip duration and the areas travalled through (the resident zones). 

In this study, we used the following attributes : 
- NO_PERS : number of travellers in a trip 
- NO_DEPL: number of shifting in a trip 
- zoneorig : the zone where the trip began from  
- zoneres : the zone where the trip passed through
- zonedest : the destination of the trip 
- duree : trip duration  

"""
"""
# Lonely trip or group trip ?

"""
"""
We will examine the number of travallers in the trip in the follwong part. We call "group tours" if there are more than 5 (including 5) individuals on a journey.
"""
# View the number of traveller for the less crowed trip and the most crowded trip
print('There are',min(depl['NO_PERS']), 'travellers in the less crowded trip.')
print('There are',max(depl['NO_PERS']), 'traveller in the most crowded trip.')
print ('The average number of travaller is: ', depl['NO_PERS'].mean(), '.' )
print ('The median number of travaller is: ', depl['NO_PERS'].median(), '.' )
"""
On average, people traveled in pairs. The median here means that half of the people traveled alone or in pairs and more than 3 people traveled in the other half.
"""
# Groupe by number of travallers in a trip
nbPers=depl.groupby('NO_PERS').size()
print (nbPers)
# Delivery the data nbPers in table form
dfPers=pd.DataFrame(nbPers,columns=['counts'])

# Set the width and height of the figure 
plt.figure(figsize=(8,6))

# Bar chart showing number of residents having stayed in each zone
sns.barplot(x=dfPers.index, y=dfPers['counts'])

# Add title
plt.title("Number of trips taken by various numbers of individuals")

# Add label for vertical axis
plt.xlabel("Number of individuqls on a trip")

# Add label for vertical axis
plt.ylabel("Number of trips ")
# Compute the rates
lonelyTrip =depl[(depl.NO_PERS >= 1)&(depl.NO_PERS <= 2)]
groupTrip =depl[(depl.NO_PERS >= 5)]
print ('The rate of individuals traveling alone or in pairs ', int(len(lonelyTrip)/float(len(depl))*100), '%.' )
print ('The rate of group trip: ', int(len(groupTrip)/float(len(depl))*100), '%.' )
"""
# Number of deplacement
"""
print('The minimum number of deplacement in our database is', min(depl['NO_DEPL']), '.')
print('The maximum number of deplacement in our database is', max(depl['NO_DEPL']), '.')
print ('The average of the number of deplacement is: ', depl['NO_DEPL'].mean(), '.' )
print ('The median of the number of deplacement is: ', depl['NO_DEPL'].median(), '.' )
"""
We can notice that on average, the trips in the database are composed of 3.2 deplacements.
"""
# Group by each number of deplacement
nbDepl=depl.groupby('NO_DEPL').size()
print (nbDepl)
"""
We can notice that the more the number of deplacement increases, the less the number of trips composed of these deplacements decreases. For example, only 2 trips have 22 deplacements whereas 14831 trips have one deplacement
"""
# Show nbDepl in table form
dfNoDepl=pd.DataFrame(nbDepl,columns=['counts'])

# Sort by 'counts' in descending order 
print(dfNoDepl.sort_values(by = 'counts',ascending = False, inplace = False))
noDpl1 =depl[(depl.NO_DEPL == 1)]
noDpl1.shape # return a tuple showing the dimensionality of the dataframe NoDpl1
noDpl2 =depl[(depl.NO_DEPL == 2)]
noDpl2.shape # return a tuple showing the dimensionality of the dataframe NoDpl2
noDpl3 =depl[(depl.NO_DEPL == 3)]
noDpl3.shape # return a tuple showing the dimensionality of the dataframe NoDpl3
noDpl7 =depl[(depl.NO_DEPL == 7)]
noDpl7.shape # return a tuple showing the dimensionality of the dataframe NoDpl7
noDpl10 =depl[(depl.NO_DEPL == 10)]
noDpl10.shape # return a tuple showing the dimensionality of the dataframe NoDpl10
print ('The rate of trips having 1 deplacement: ', int(len(noDpl1)/float(len(depl))*100), '%.' )
print ('The rate of people having 2 deplacements: ', int(len(noDpl2)/float(len(depl))*100), '%.' )
print ('The rate of people having 3 deplacements: ', int(len(noDpl3)/float(len(depl))*100), '%.' )
print ('The rate of people having 7 deplacements: ', int(len(noDpl7)/float(len(depl))*100), '%.' )
print ('The rate of people having 10 deplacements: ', int(len(noDpl10)/float(len(depl))*100), '%.' )

"""
As noticed before, the rates of trips which have done one or two deplacements are the highest, 23%. From 10 deplacements, the rate is only 0%.
"""
# Set the width and height of the figure 
plt.figure(figsize=(14,6))

# Bar chart showing the number of trips according to the number of deplacement 
sns.barplot(x=dfNoDepl.index, y=dfNoDepl['counts'])

# Add title
plt.title("Numbers of trips having x deplacements")

# Add label for vertical axis
plt.xlabel("Number of deplacements")

# Add label for vertical axis
plt.ylabel("Number of trips")

"""
On this graph, we can see indeed that the number of deplacement 1 has the highest number of trips. And step by step, it decreases.
"""
groupZoneOrig = depl[["zoneorig", "NO_DEPL"]].groupby('zoneorig').mean()
groupZoneOrig
print('The maximum mean of number of deplacement in trips from origine zone is', groupZoneOrig.max(), '.')
print('The minimum mean of number of deplacement in trips from origine zones is', groupZoneOrig.min(), '.')
"""
With this table, we can see what is for each origine zone, the mean of the number of deplacement of trips. To see which origine zones have the maximum or the minimum mean, we filter data by the values found before.
"""
groupZoneOrig[groupZoneOrig['NO_DEPL'] == 13.0]
groupZoneOrig[groupZoneOrig['NO_DEPL'] == 1.0]
"""
Here we can notice that it is the trips from the zone 128051 which have the most deplacements, in average 13 deplacements. Maybe, this zone is far enough from destination zones, that’s why the trips from there have more deplacements. On the contrary, trips from the zones 601005, 601016, 603006, 801002, 804051 and 806003 make only on average 1 deplacement. We can assume that these zones are near destination zones.
"""
groupZoneDest = depl[["zonedest", "NO_DEPL"]].groupby('zonedest').mean()
groupZoneDest
print('The maximum mean of number of deplacement in trips to destination zones is', groupZoneDest.max(), '.')
print('The minimum mean of number of deplacement in trips to destination zones is', groupZoneDest.min(), '.')
groupZoneDest[groupZoneDest['NO_DEPL'] == 12.0]
"""
So there is in average 12 deplacements to the destination zone 128051
"""
groupZoneDest[groupZoneDest['NO_DEPL'] == 1.0]
"""
So there are on average 12 deplacements in the trips to the destination zone 128051. We can notice that it is the same zone which has the maximum mean of number of deplacements of trips from origine zones. We can conclude that this zone is far away from the other zones, that’s why there are many deplacements to do in trips from this zone or to this zone.
"""
"""
# Duration
"""
# Statistics of trip duration
dur_mean = depl['duree'].mean()
dur_median = depl['duree'].median()
dur_var = dur_mean = depl['duree'].var()
dur_std = dur_mean = depl['duree'].std()

print ('Statistics of trip duration: mu:',dur_mean,', median:',dur_median,', var:',dur_var,', std:',dur_std)
# Duration distinction between lonely trips and group trips
dur_lonelyTrip_mean = lonelyTrip['duree'].mean()
dur_groupTrip_mean = groupTrip['duree'].mean()

print ('The average duration of lonely trip is: ', dur_lonelyTrip_mean, '.' )
print ('The average duration of group trip is: ', dur_groupTrip_mean, '.' )
"""
**Longest trip and shortest trip**
"""
# The longest road

s = depl[["duree","zoneorig","zonedest"]]
indexmax = depl["duree"].idxmax()
print(s.loc[[indexmax]])
# The shortest road

indexmin = depl["duree"].idxmin()
print(s.loc[[indexmin]])
"""
# Resident zone

"""
# Groupe by resident zone 
nbZoneRes=depl.groupby('zoneres').size()
print (nbZoneRes)
# show total nomber of resident zone 
print('Totally, there are', nbZoneRes.size, 'resident zones where the trips passed through.')
# View nbZoneRes in table form
dfZoneRes=pd.DataFrame(nbZoneRes,columns=['counts'])

# Sorting in descending order by 'counts' 
print(dfZoneRes.sort_values(by = 'counts',ascending = False, inplace = False))
"""
Much of trips traveled through these 3 zones : zone 1, zone2 and zone 3. From the calculation above, we found that there are 20735 items for zone 1, 17799 items for zone 2 and 10845 items for zone3. The fewest trips passing through the zone 54 (only 2 trips).
"""
zoneRes1 =depl[(depl.zoneres == '1')]
zoneRes1.shape # return a tuple showing the dimensionality of the dataframe zoneRes1
zoneRes2 =depl[(depl.zoneres == '2')]
zoneRes2.shape # return a tuple showing the dimensionality of the dataframe zoneRes2
zoneRes3 =depl[(depl.zoneres == '3')]
zoneRes3.shape # return a tuple showing the dimensionality of the dataframe zoneRes3
print ('The rate of trips passing through the zone 1: ', int(len(zoneRes1)/float(len(depl))*100), '%.' )
print ('The rate of trips  passing through the zone 2: ', int(len(zoneRes2)/float(len(depl))*100), '%.' )
print ('The rate of trips  passing through the zone 3: ', int(len(zoneRes3)/float(len(depl))*100), '%.' )
# Set the width and height of the figure 
plt.figure(figsize=(14,6))

# Bar chart showing number of trips passing through the x zone
sns.barplot(x=dfZoneRes.index, y=dfZoneRes['counts'])

# Add title
plt.title("Numbers of trips passing through the x zone")

# Add label for vertical axis
plt.xlabel("Resident Zone")

# Add label for vertical axis
plt.ylabel("Number of trips")
"""
# Destination
"""
"""
we will study in the following section the destination zone for people having stayed in zone 1. Have people staying in zone 1 gone to the same destination or not? Is it possible that the resident zone 1 is a must-see location for certain given destination?
"""
# Groupe by destination zone
nbZoneDest=zoneRes1.groupby('zonedest').size()

# View nbZoneDest data in table form
dfZoneDest=pd.DataFrame(nbZoneDest,columns=['counts'])

# Sorting in descending order by 'counts'
print(dfZoneDest.sort_values(by = 'counts',ascending = False, inplace = False).head())
"""
From the above data, the top 5 zones where people having stayed in zone 1 are : 101001, 131001, 137001, 128001, 140001.
"""
"""
In next part we want to know how many people will go to the same destination, so we group by zone destination and calcul the sum of the people in each zone destination
"""
group = depl[["zonedest","NO_PERS"]].groupby('zonedest')['NO_PERS'].sum()
group
"""
Here, for each zone origin we can know all the reachable zone destinations and the duration between 2 zones
"""
group2 = depl[["zoneorig","zonedest","duree"]].groupby(['zoneorig', 'zonedest'])['duree'].min()
group2.head()
"""
![Wrap-up.png](attachment:Wrap-up.png)
"""
"""
t
"""
"""
## Releases
"""
start_time = timeit.default_timer()
# Creates a client for the primary sandbox from cluster host cluster0-nlbcx.mongodb.net
client = MongoClient("mongodb://adminUser:xpass@cluster0-shard-00-00-nlbcx.mongodb.net:27017/?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin")

db = client.test 
db = client['stackoverflow-dump-view']
collection = db['viewModel-view']

view = collection.find_one() # json file, can be browsed as a dictionary

#print (view['releaseViewList'][0].keys())
viewRel0=view['releaseViewList'][0]
viewRel1=view['releaseViewList'][1]
viewRel2=view['releaseViewList'][2]
"""
### First Release View
"""
viewRel0
"""
### Second Release View
"""
viewRel1
"""
### Third Release View
"""
viewRel2
minValue0=viewRel0['attributeDescList'][0]['minValue'];print(minValue0)
maxValue0=viewRel0['attributeDescList'][0]['maxValue'];print(maxValue0)
mean0=viewRel0['attributeDescList'][0]['mean'];print(mean0)
median0=viewRel0['attributeDescList'][0]['median'];print(median0)
nullValue0=viewRel0['attributeDescList'][0]['nullValue'];print(nullValue0)
name0=viewRel0['attributeDescList'][0]['name'];print(name0)
count0=viewRel0['attributeDescList'][0]['count'];print(count0)
"""
### Number of Null Values per release
"""
nullsRel0=[]
for i in viewRel0['attributeDescList']:
    nullsRel0.append(sum(i['nullValue']))

nullsRel1=[]
for i in viewRel1['attributeDescList']:
    nullsRel1.append(sum(i['nullValue']))

nullsRel2=[]
for i in viewRel2['attributeDescList']:
    nullsRel2.append(sum(i['nullValue']))
import matplotlib.pyplot as plt 

# line 1 points 
x = ['Votes','Posts','Comments','Badges','Users']
y1 = nullsRel0
# plotting the line 1 points 
plt.plot(x, y1, label = "Jan01-18")

# line 2 points 
y2 = nullsRel1
# plotting the line 1 points 
plt.plot(x, y2, label = "Jan02-18")

# line 3 points 
y3 = nullsRel2
# plotting the line 1 points 
plt.plot(x, y3, label = "Jan03-18")

# naming the x axis 
plt.xlabel('dataset') 
# naming the y axis 
plt.ylabel('null values') 
# giving a title to my graph 
plt.title('Number of null values per release') 

# show a legend on the plot 
plt.legend() 

# function to show the plot 
plt.show() 
"""
### Number of Items per release
"""
countRel0=[]
for i in viewRel0['attributeDescList']:
    countRel0.append(i['count'])

countRel1=[]
for i in viewRel1['attributeDescList']:
    countRel1.append(i['count'])

countRel2=[]
for i in viewRel2['attributeDescList']:
    countRel2.append(i['count'])
import matplotlib.pyplot as plt 

# line 1 points 
x = ['Votes','Posts','Comments','Badges','Users']
y1 = countRel0
# plotting the line 1 points 
plt.plot(x, y1, label = "Jan01-18")

# line 2 points 
y2 = countRel1
# plotting the line 1 points 
plt.plot(x, y2, label = "Jan02-18")

# line 3 points 
y3 = countRel2
# plotting the line 1 points 
plt.plot(x, y3, label = "Jan03-18")

# naming the x axis 
plt.xlabel('dataset') 
# naming the y axis 
plt.ylabel('count') 
# giving a title to my graph 
plt.title('Count of items per release') 

# show a legend on the plot 
plt.legend() 

# function to show the plot 
plt.show() 
elapsed = timeit.default_timer() - start_time
"""
### Execution time
"""
print ("execution time: " + str(elapsed) + " s")
#------------------------------------------------------------------ Q1 --------------------------------------------------------------------#
btn1=widgets.ToggleButton(value=False,description='Activate',disabled=False,button_style='info',tooltip='',icon='',visibility = 'visible')
#timeLbl1=widgets.Text(value='0',description='',disabled=True)
q1 = widgets.RadioButtons(options=['January 1rst 2018', 'January 2nd 2018', 'January 3rd 2018'],value=None,description='Release:',disabled=True)
#------------------------------------------------------------------------------------------------------------------------------------------#
#------------------------------------------------------------------ Q2 --------------------------------------------------------------------#
btn2=widgets.ToggleButton(value=False,description='Activate',disabled=False,button_style='info',tooltip='',icon='',visibility = 'visible')
#timeLbl2=widgets.Text(value='0',description='',disabled=True)
q2 = widgets.RadioButtons(options=['January 1rst 2018', 'January 2nd 2018', 'January 3rd 2018'],value=None,description='Release:',disabled=True)
#------------------------------------------------------------------------------------------------------------------------------------------#
#------------------------------------------------------------------ Q3 --------------------------------------------------------------------#
btn3=widgets.ToggleButton(value=False,description='Activate',disabled=False,button_style='info',tooltip='',icon='',visibility = 'visible')
#timeLbl3=widgets.Text(value='0',description='',disabled=True)
q3 = widgets.RadioButtons(options=['January 1rst 2018', 'January 2nd 2018', 'January 3rd 2018'],value=None,description='Release:',disabled=True)
#------------------------------------------------------------------------------------------------------------------------------------------#
#------------------------------------------------------------------ Q4 --------------------------------------------------------------------#
btn4=widgets.ToggleButton(value=False,description='Activate',disabled=False,button_style='info',tooltip='',icon='',visibility = 'visible')
#timeLbl4=widgets.Text(value='0',description='',disabled=True)
q4 = widgets.Dropdown(options=['Id','PostTypeId','AcceptedAnswerId','ParentId','CreationDate','DeletionDate','Score','ViewCount','Body','OwnerUserId','OwnerDisplayName','LastEditorUserId','LastEditorDisplayName','LastEditDate','LastActivityDate','Title','Tags','AnswerCount','CommentCount','FavoriteCount','ClosedDate','CommunityOwnedDate'],
    value=None,description='Attribute:',disabled=True,)
#------------------------------------------------------------------------------------------------------------------------------------------#
#------------------------------------------------------------------ Q5 --------------------------------------------------------------------#
btn5=widgets.ToggleButton(value=False,description='Activate',disabled=False,button_style='info',tooltip='',icon='',visibility = 'visible')
#timeLbl5=widgets.Text(value='0',description='',disabled=True)
drop_options = [['--','Id','UserId','Name','Date','Class','TagBased'],
                ['--','Id','PostId','Score','Text','CreationDate','UserDisplayName','UserId'],
               ['--','Id','PostTypeId','AcceptedAnswerId','ParentId','CreationDate','DeletionDate','Score','ViewCount','Body','OwnerUserId','OwnerDisplayName','LastEditorUserId','LastEditorDisplayName','LastEditDate','LastActivityDate','Title','Tags','AnswerCount','CommentCount','FavoriteCount','ClosedDate','CommunityOwnedDate'],
               ['--','Id','Reputation','CreationDate','DisplayName','LastAccessDate','WebsiteUrl','Location','AboutMe','Views','UpVotes','DownVotes','ProfileImageUrl','EmailHash','AccountId'],
               ['--','Id','PostId','VoteTypeId','UserId','CreationDate','BountyAmount']]
children = [widgets.Dropdown(options=name,description='',value=None) for name in drop_options]
tab = widgets.Tab()
tab.children = children
items=['Badges', 'Comments', 'Posts', 'Users', 'Votes']
for i in range(len(items)):
    tab.set_title(i, items[i])
q5=tab
#------------------------------------------------------------------------------------------------------------------------------------------#
#------------------------------------------------------------------ Q6 --------------------------------------------------------------------#
btn6=widgets.ToggleButton(value=False,description='Activate',disabled=False,button_style='info',tooltip='',icon='',visibility = 'visible')
#timeLbl6=widgets.Text(value='0',description='',disabled=True)
q6= widgets.RadioButtons(options=['Yes', 'No'],value=None,description='',disabled=False)
#------------------------------------------------------------------------------------------------------------------------------------------#
#------------------------------------------------------------------ Q7 --------------------------------------------------------------------#
btn7=widgets.ToggleButton(value=False,description='Activate',disabled=False,button_style='info',tooltip='',icon='',visibility = 'visible')
#timeLbl7=widgets.Text(value='0',description='',disabled=True)
children2 = [widgets.Dropdown(options=name,value=None) for name in drop_options]
tab2 = widgets.Tab()
tab2.children = children2
for i in range(len(items)):
    tab2.set_title(i, items[i])
q7=tab2
#------------------------------------------------------------------------------------------------------------------------------------------#

#------------------------------------------------------- Effort questions -----------------------------------------------------------------#
effortW = []
for e in range(7):
    effortW.append(widgets.ToggleButtons(options=['Low', 'Regular', 'High'],description='Select Effort:',disabled=False,value=None))  

timeLblW = []
for t in range(7):
    timeLblW.append(widgets.Text(value='0',description='',disabled=True))  
    
# Timer function    
# btn - receive a button object
# lbl - receive a label object
#    we use lbl.value to get timer value
# q - receive a multiple option object
#    we use q.value to get answered value
def timer(btn,lbl,q):        

    cnt =int(lbl.value)   
    on=btn.value 
    desc=q.description

    if desc!='Submitted':
        if on==True:      
            threading.Timer(1, timer, [btn,lbl,q]).start()
            cnt = cnt+1                        
            lbl.value = str(cnt)
            btn.description='Submit answer'
            q.disabled=False

        elif on==False:
            threading.Timer(1, timer, [btn,lbl,q]).start()
            btn.description='Activate'
            q.disabled=True

        else:
            None

    if cnt!=0 and btn.description=='Activate':
        threading.Timer(1, timer, [btn,lbl,q]).start()
        q.description='Submitted'
        btn.visibility='hidden'
        btn.description='--'
        btn.disbled=True  

def timerTab(btn,lbl,q):        

    cnt=int(lbl.value)   
    on=btn.value 
    desc=q.children[0].description

    if desc!='Submitted':
        if on==True:      
            threading.Timer(1, timerTab, [btn,lbl,q]).start()
            cnt = cnt+1                        
            lbl.value = str(cnt)
            btn.description='Submit answer'
            for i in range(len(q.children)):
                q.children[i].disabled=False

        elif on==False:
            threading.Timer(1, timerTab, [btn,lbl,q]).start()
            btn.description='Activate'
            for i in range(len(q.children)):
                q.children[i].disabled=True

        else:
            None

    if cnt!=0 and btn.description=='Activate':
        threading.Timer(1, timerTab, [btn,lbl,q]).start()
        for i in range(len(q.children)):
            q.children[i].description='Submitted'
        btn.visibility='hidden'
        btn.description='--'
        btn.disbled=True                        
"""
# Tasks
"""
"""
## Q1. Which is the release with best quality? (less missing, nulls and default values)
"""
timeLblW[0]
btn1
q1
"""
January 2nd 2018
"""
timer(btn1,timeLblW[0],q1)
"""
### Q1.1 Effort to answer the question
"""
effortW[0]
"""
Effort : regular

"""
"""
## Q2. Which release has the most number of records?
"""
timeLblW[1]
btn2
q2
"""
January 3rd 2018 
"""
timer(btn2,timeLblW[1],q2)
"""
### Q2.1 Effort to answer the question
"""
effortW[1]
"""
Effort : low
"""
"""
## Q3. Which is the release where _UpVote_ attribute from _Users_ item is more spread?
"""
timeLblW[2]
btn3
q3
"""
January 3rd 2018 

"""
timer(btn3,timeLblW[2],q3)
"""
### Q3.1 Effort to answer the question
"""
effortW[2]
"""
Effort : high
"""
"""
## Q4. Which attribute from _Posts_ item can be used to compute answers' popularity and author's reputation (started answered and authors)
"""
timeLblW[3]
btn4
q4
"""
ViewCount 

"""
timer(btn4,timeLblW[3],q4)
"""
### Q4.1 Effort to answer the question
"""
effortW[3]
"""
Effort : low

"""
"""
## Q5. Which is/are the attribute(s) that can be used to identify the most trendy topic addressed in the release?
"""
timeLblW[4]
btn5
q5
"""
* Badges : TagBased 
* Comments : Score 
* Posts : ViewCount 
* Users : Views 
* Votes : BountyAmount

"""
timerTab(btn5,timeLblW[4],q5)
"""
### Q5.1 Effort to answer the question
"""
effortW[4]
"""
Effort : low
"""
"""
## Q6 Will missing, null, and default values bias observation of trends?
"""
timeLblW[5]
btn6
q6
"""
Yes

"""
timer(btn6,timeLblW[5],q6)
"""
### Q6.1 Effort to answer the question
"""
effortW[5]
"""
Effort : low
"""
"""
## Q7. Choose the attributes that can be used as sharging keys to fragment the release using a hash based and an interval based strategy
"""
timeLblW[6]
btn7
timerTab(btn7,timeLblW[6],q7)
q7
"""
* Badges : TagBased
* Comments : Score 
* Posts : View count 
* Users : Views
* Votes : BountyAmount

"""
"""
### Q7.1 Effort to answer the question
"""
effortW[6]
"""
Effort : regular
"""
"""
## Get Match Results
"""
# collect user effort 
userEffortL = []
for e in effortW:
    userEffortL.append(e.value) 
        
# collect time from answers
qtimeL=[]
for t in timeLblW:
    qtimeL.append(int(t.value))

# tuple for answers
qans1=q1.options[2]
qans2=q2.options[0]
qans3=q3.options[1]
qans4=q4.options[3]
qans5=[q5.children[0].options[3],q5.children[1].options[0],q5.children[2].options[5],q5.children[3].options[5],q5.children[4].options[0]]
qans6=q6.options[0]
qans7=[q7.children[0].options[3],q7.children[1].options[0],q7.children[2].options[5],q7.children[3].options[5],q7.children[4].options[0]]
qans = [qans1,qans2,qans3,qans4,qans5,qans6,qans7]

scoreL = [0.0]*7

if q1.value == qans1: scoreL[0]=1 
if q2.value == qans2: scoreL[1]=1 
if q3.value == qans3: scoreL[2]=1 
if q4.value == qans4: scoreL[3]=1 

if qans5[0] == q5.children[0].value: scoreL[4]=scoreL[4] + 0.2
if qans5[1] == q5.children[1].value: scoreL[4]=scoreL[4] + 0.2
if qans5[2] == q5.children[2].value: scoreL[4]=scoreL[4] + 0.2
if qans5[3] == q5.children[3].value: scoreL[4]=scoreL[4] + 0.2
if qans5[4] == q5.children[4].value: scoreL[4]=scoreL[4] + 0.2

if q6.value ==qans6: scoreL[5]=1

if qans7[0] == q7.children[0].value: scoreL[6]=scoreL[6] + 0.2
if qans7[1] == q7.children[1].value: scoreL[6]=scoreL[6] + 0.2
if qans7[2] == q7.children[2].value: scoreL[6]=scoreL[6] + 0.2
if qans7[3] == q7.children[3].value: scoreL[6]=scoreL[6] + 0.2
if qans7[4] == q7.children[4].value: scoreL[6]=scoreL[6] + 0.2
        
# calculated effort
calcEffortL = []
maxcEffort = 100
for i in range(0,len(scoreL)):
    if scoreL[i] == 0: 
        calcEffortL.append(maxcEffort)
    else:
        if int(qtimeL[i]) > 300: qtimeL[i] = 300 # 5 min limit
        tmp=int(qtimeL[i])/scoreL[i]
        calcEffortL.append((tmp*100)/1800)            
import csv
# qid | time | score | user_effort | calculated_effort | execution_time (cpu)
header=['qid', 'score', 'time', 'user_effort', 'calculated_effort', 'execution_time'] 
qid=list(range(1,8))
elapsedL = [elapsed]*7

rows = zip(qid,scoreL,qtimeL,userEffortL,calcEffortL,elapsedL)

with open("../results/match2.csv", mode="w") as f:
    #writer = csv.writer(f, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
    writer = csv.writer(f, delimiter=',')
    writer.writerow(header)
    for row in rows:
        writer.writerow(row)