from src.models.pooling.Model_opts import *

from src.data.RawPlaces365Data import name_raw_places
from src.data.IndoorOutdoorData import name_io
from src.data.CocoDefaultData import name_coco_default
from src.data.ActivityData import name_activity
from src.data.DaytimeData import name_daytime
from src.data.LocationData import name_loc
from src.data.SUNattributesData import name_sun
from src.data.TimezoneData import name_timezone
from submissions.runs.run_base import run_on_dev
from submissions.runs.run_base import run_on_test

opts = {
    opt_model: {
        opt_use_seg: True,
        opt_subm_imgs_per_day: 0,
        opt_subm_imgs_per_day_only_on_recall: False,
        opt_comp_method: comp_method_datamax,
        opt_comp_use_weights: True,
        opt_query_src: query_src_desc,
        opt_use_tokenclustering: False,
        opt_optimize_labels: True,
    },

    opt_segmentation: {
        opt_img_selection: img_selection_first,
        opt_repr_selection: repr_selection_first,
        opt_s1_min_imgs: 2,
        opt_merge_dist: 15,
        opt_s1_threshold: 23000,
    },

    opt_data: {

        name_activity: {
            opt_weight: 1,
            opt_threshold: 0,
            opt_use_idf: False,
            opt_idf_boosting_threshold: 0,
            opt_intensify_factor_m: 1,
            opt_intensify_factor_p: 1,
            opt_ceiling: False,
        },

        name_coco_default: {
            opt_weight: 1,
            opt_threshold: 0.9,
            opt_use_idf: False,
            opt_idf_boosting_threshold: 0,
            opt_intensify_factor_m: 1,
            opt_intensify_factor_p: 1,
            opt_ceiling: False,
        },

        name_daytime: {
            opt_weight: 1,
            opt_threshold: 0,
            opt_use_idf: False,
            opt_idf_boosting_threshold: 0,
            opt_intensify_factor_m: 1,
            opt_intensify_factor_p: 1,
            opt_ceiling: False,
        },

        name_loc: {
            opt_weight: 1,
            opt_threshold: 0,
            opt_use_idf: False,
            opt_idf_boosting_threshold: 0,
            opt_intensify_factor_m: 1,
            opt_intensify_factor_p: 1,
            opt_ceiling: False,
        },

        name_raw_places: {
            opt_weight: 1,
            opt_threshold: 0,
            opt_use_idf: False,
            opt_idf_boosting_threshold: 0,
            opt_intensify_factor_m: 1,
            opt_intensify_factor_p: 1,
            opt_ceiling: True,
        },

        name_io: {
            opt_weight: 1,
            opt_threshold: 0,
            opt_use_idf: False,
            opt_idf_boosting_threshold: 0,
            opt_intensify_factor_m: 3,
            opt_intensify_factor_p: 3,
            opt_ceiling: False,
        },

        name_sun: {
            opt_weight: 1,
            opt_threshold: 0,
            opt_use_idf: False,
            opt_idf_boosting_threshold: 0,
            opt_intensify_factor_m: 1,
            opt_intensify_factor_p: 1,
            opt_ceiling: False,
        },

        name_timezone: {
            opt_weight: 1,
            opt_threshold: 0,
            opt_use_idf: False,
            opt_idf_boosting_threshold: 0,
            opt_intensify_factor_m: 1,
            opt_intensify_factor_p: 1,
            opt_ceiling: False,
        },
    },
}

if __name__ == "__main__":
    run_on_dev(opts)
    run_on_test(opts)


# -*- coding: utf-8 -*-

from datetime import datetime
from pytz import timezone

import babel
from odoo import api, fields, models, tools, _
from datetime import date, datetime, time, timedelta
from odoo.exceptions import UserError
from odoo.osv import expression

class HrPayslip(models.Model):
    _inherit = 'hr.payslip'

    settlement = fields.Boolean(string='Settlement')
    settlemen_date = fields.Date(string='Settlemen date', readonly=True, required=False,
        default=lambda self: fields.Date.to_string(date.today().replace(day=1)), states={'draft': [('readonly', False)]})
    reason_liquidation = fields.Selection([
            ('1', 'TERMINACIÓN DE CONTRATO'),
            ('2', 'SEPARACIÓN VOLUNTARIA'),
            ('3', 'ABANDONO DE EMPLEO'),
            ('4', 'DEFUNCIÓN'),
            ('7', 'AUSENTISMOS'),
            ('8', 'RESICIÓN DE CONTRATO'),
            ('9', 'JUBILACIÓN'),
            ('A', 'PENSIÓN'),
            ('5', 'CLAUSURA'),
            ('6', 'OTROS'),
            ],
            string='Reason for liquidation',
            required=False,
            states={'draft': [('readonly', False)]})
    agreement_employee = fields.Boolean(string='Agreement with the employee')
    amount_agreement = fields.Float('Amount of the agreement', required=False)
    indemnify_employee = fields.Boolean(string='Indemnify the employee')
    compensation_20 = fields.Boolean(string='I will pay the compensation of 20 days per year worked?')

    previous_contract_date = fields.Date('Previous Contract Date', related="contract_id.previous_contract_date", help="Start date of the previous contract for antiquity.")
    date_start = fields.Date('Start Date', required=True, default=fields.Date.today,
        help="Start date of the contract.", related="contract_id.date_start")
    date_end = fields.Date('End Date',
        help="End date of the contract", related="contract_id.date_end")
    years_antiquity = fields.Integer(string='Antiquity', related="contract_id.years_antiquity")
    days_rest = fields.Integer(string='Días de antiguedad ultimo año', related="contract_id.days_rest")
    type_contract = fields.Selection(string='Tipo de contrato', related="contract_id.type_id.type")

    @api.onchange('complete_name')
    def _compute_complete_name(self):
        for name in self:
            complete_name = name.name
            if name.last_name:
                complete_name += ' ' + name.last_name
            if name.last_name:
                complete_name += ' ' + name.mothers_last_name
            name.complete_name = complete_name

    @api.onchange('indemnify_employee','agreement_employee')
    def _compute_complete_name(self):
        for settlement in self:
            if settlement.indemnify_employee:
                settlement.agreement_employee = False
                settlement.amount_agreement = 0
            else:
                settlement.compensation_20 = False
            if settlement.agreement_employee:
                settlement.indemnify_employee = False
                settlement.compensation_20 = False
            else:
                settlement.amount_agreement = 0

    @api.multi
    def print_settlement_report(self):
        payroll_dic = {}
        data={
            'payroll_data':payroll_dic
            }
        return self.env.ref('payroll_mexico.action_report_settlement_template').report_action(self, {})

class HrPayrollStructure(models.Model):
    _inherit = 'hr.payroll.structure'

    settlement = fields.Boolean(string='Settlement structure?')
    payroll_type = fields.Selection([
            ('ordinary_payroll', 'Ordinary Payroll'),
            ('extraordinary_payroll', 'Extraordinary Payroll')],
            string='Payroll Type',
            required=True,)


from __numutil import *
from __regutil import *
from __asmutil import *
from __gencom  import *
import random,math,itertools

def gen_word_in_memory(A,total_bytes):
    A(".data")
    A(f"word_arrary: .byte ")
    string = ""
    for x in range(total_bytes):
       A(str(numutil.sign8(x)) + ',')

def my_gen1(A,au):
    for i in range(32):
        au.li(reg_list[i],0)

    address_base = 0x10010000
    byte_count = 2**2
    def convert_adddress(count):
        return address_base + count

    def get_random_offset(conut):
        addr = convert_adddress(conut)
        offset = numutil.s16()
        return addr - offset, offset

    for i in range(5000):
        base,off = get_random_offset(numutil.below(byte_count))
        value = numutil.u32()
        regs = regutil.get_random( k = 3)
        au.li(regs[0],value)
        au.li(regs[1],base)
        A(f"swr {regs[1]},{off}({regs[1]})")
        A(f"lwr {regs[2]},{off}({regs[1]})")

    def gen_random_lwr():
        base,off = get_random_offset(numutil.below(byte_count))
        regs = regutil.get_random( k = 2)
        au.li(regs[0],base)
        A(f"lwr {regs[1]},{off}({regs[0]})")
        return regs[1]

    for i in range(5000):
        reg0 = gen_random_lwr()
        reg1 = gen_random_lwr()
        regs = regutil.get_random( k = 2)
        A(f"addu {regs[1]},{reg0},{reg1}")
        base,off = get_random_offset(numutil.below(byte_count))
        au.li(regs[0],base)
        A(f"swr {regs[1]},{off}({regs[0]})")

    au.check_and_exit()
    gen_word_in_memory(A,byte_count)
    return ["mars","-d"]

r = gen('lwr_swr')
r.gen(my_gen1)


from pylab import *
import sys,scipy,random

########DEFINE THE IFNETCLASS#########
class PyIFNetClass():
	########DEFINE A DEFAULT ConnectionsTRUCTOR#########
	def __init__(self,**kwargs):
		####update parameters with the specified ones
		items=kwargs.items();
		for k in xrange(len(items)):
			self[items[k][0]]=items[k][1];
		####add specific or from all parameters
		self.setFromSharedAttributes(**{'Attributes':[]});

	####SET CONNECT#####
	def setConnectionsProperties(self,**kwargs):
		getattr(self,'set'+self['ID'])(**kwargs);

	####SET onePopPREDICT
	def setOnePopPred(self,**kwargs):
		#get the name of the pop
		namePop=PyToolsClass.getKeyWhere(NeuronGroups,'ConnectionType','I')[0];
		#set command
		NeuronGroups[namePop]['IsCommanded']=True;
		#set connectivity
		self.Connections['Fast']={'all':{'SynapticGatesNumber':0,'setMethod':'Pred'},'Units':{namePop+'-'+namePop:{'IsConnected':True,'IsSparsed':False}}};
		self.Connections['Slow']={'all':{'SynapticGatesNumber':1,'setMethod':'Pred'},'Units':{namePop+'-'+namePop:{'IsConnected':True,'IsSparsed':False}}};

	####SET EIPREDICT
	def setEIPred(self,**kwargs):
		#get the name of the NeuronGroups
		namePopE=PyToolsClass.getKeyWhere(NeuronGroups,'ConnectionType','E')[0];
		namePopI=PyToolsClass.getKeyWhere(NeuronGroups,'ConnectionType','I')[0];

		#set command and connectivity
		self.Connections['Fast']={'all':{'SynapticGatesNumber':0,'setMethod':'Pred'},'Units':{}};
		self.Connections['Slow']={'all':{'SynapticGatesNumber':1,'setMethod':'Pred'},'Units':{}};
		isIntegrator=True;
		for prePop in [namePopE,namePopI]:
			NeuronGroups[prePop]['IsCommanded']=True;
			for postPop in [namePopE,namePopI]:
				self.Connections['Fast']['Units'][postPop+'-'+prePop]={'IsConnected':True,'IsSparsed':False};
				self.Connections['Slow']['Units'][postPop+'-'+prePop]={'IsConnected':False,'IsSparsed':False};
				#check if it is an integrator network
				if (np.dot(np.dot(NeuronGroups[postPop].Gamma.T,(self.A+NeuronGroups[postPop].lambdaD[0])),NeuronGroups[prePop].Gamma)<0.).all():
					isIntegrator=False;
		#configure I to not be commanded
		NeuronGroups[namePopI]['IsCommanded']=False;
		#configure E-E to not be fast connected
		self.Connections['Fast'][namePopE+'-'+namePopE]=False;
		#configure the slow connectivity for the specific function
		if isIntegrator:
			self.Connections['Slow']['Units'][namePopE+'-'+namePopE]={'IsConnected':True,'IsSparsed':False};
		else:
			self.Connections['Slow']['Units'][namePopE+'-'+namePopI]={'IsConnected':True,'IsSparsed':False};

	####SET EIPREDICT
	def setEIEIPred(self,**kwargs):
		#get the name of the NeuronGroups
		namesPopE=PyToolsClass.getKeyWhere(NeuronGroups,'ConnectionType','E');
		namesPopI=PyToolsClass.getKeyWhere(NeuronGroups,'ConnectionType','I');
		typesPop=np.concatenate((np.array(['E' for i in xrange(len(namesPopE))]),np.array(['I' for i in xrange(len(namesPopI))])))
		namesPop=np.concatenate((namesPopE,namesPopI));

		#set command and connectivity
		for prePop in NeuronGroups.keys():
			#set command
			if NeuronGroups[prePop]['ConnectionType']=='E':
				NeuronGroups[prePop]['IsCommanded']=True;
			else:
				NeuronGroups[prePop]['IsCommanded']=False;

		#look if integrator or diffentiator case
		isIntegrator=True;
		for prePop in NeuronGroups.keys():
			for postPop in NeuronGroups.keys():
				#same EI group
				if NeuronGroups[prePop]['group']==NeuronGroups[postPop]['group']:
					if (np.dot(np.dot(NeuronGroups[postPop].Gamma.T,(self.A+NeuronGroups[postPop].lambdaD[0])),NeuronGroups[prePop].Gamma)<0.).all():
						isIntegrator=False;

		#build connectivity
		self.Connections['Fast']={'all':{'SynapticGatesNumber':0,'setMethod':'Pred'},'Units':{}};
		self.Connections['Slow']={'all':{'SynapticGatesNumber':1,'setMethod':'Pred'},'Units':{}};
		for prePop in NeuronGroups:
			for postPop in NeuronGroups:
				#same EI group
				if NeuronGroups[prePop]['group']==NeuronGroups[postPop]['group']:
					if NeuronGroups[postPop]['ConnectionType']+'-'+NeuronGroups[prePop]['ConnectionType']=='E-E':
						#fast
						self.Connections['Fast']['Units'][postPop+'-'+prePop]={'IsConnected':False,'IsSparsed':False};
						#slow
						if isIntegrator:
							self.Connections['Slow']['Units'][postPop+'-'+prePop]={'IsConnected':True,'IsSparsed':False};
						else:
							self.Connections['Slow']['Units'][postPop+'-'+prePop]={'IsConnected':False,'IsSparsed':False};
					elif NeuronGroups[postPop]['ConnectionType']+'-'+NeuronGroups[prePop]['ConnectionType']=='E-I':
						#fast
						self.Connections['Fast'][postPop+'-'+prePop]=={'IsConnected':True,'IsSparsed':False};
						#slow
						if isIntegrator:
							self.Connections['Slow']['Units'][postPop+'-'+prePop]={'IsConnected':False,'IsSparsed':False};
						else:
							self.Connections['Slow']['Units'][postPop+'-'+prePop]={'IsConnected':True,'IsSparsed':False};
					else:
						#fast
						self.Connections['Fast']['Units'][postPop+'-'+prePop]={'IsConnected':True,'IsSparsed':False};
						#slow
						self.Connections['Slow']['Units'][postPop+'-'+prePop]={'IsConnected':False,'IsSparsed':False};
				#different group
				else:
					if NeuronGroups[postPop]['ConnectionType']+'-'+NeuronGroups[prePop]['ConnectionType']=='E-E':
						#fast
						self.Connections['Fast']['Units'][postPop+'-'+prePop]={'IsConnected':True,'IsSparsed':False};
						#slow
						if isIntegrator:
							self.Connections['Slow']['Units'][postPop+'-'+prePop]={'IsConnected':False,'IsSparsed':False};
						else:
							self.Connections['Slow']['Units'][postPop+'-'+prePop]={'IsConnected':True,'IsSparsed':False};
					elif NeuronGroups[postPop]['ConnectionType']+'-'+NeuronGroups[prePop]['ConnectionType']=='E-I':
						#fast
						self.Connections['Fast']['Units'][postPop+'-'+prePop]={'IsConnected':False,'IsSparsed':False};
						#slow
						if isIntegrator:
							self.Connections['Slow']['Units'][postPop+'-'+prePop]={'IsConnected':True,'IsSparsed':False};
						else:
							self.Connections['Slow']['Units'][postPop+'-'+prePop]={'IsConnected':False,'IsSparsed':False};
					else:
						#fast
						self.Connections['Fast']['Units'][postPop+'-'+prePop]={'IsConnected':False,'IsSparsed':False};
						#slow
						self.Connections['Slow']['Units'][postPop+'-'+prePop]={'IsConnected':False,'IsSparsed':False};

	##################################
	#######SIMULATION CONTROL######

	################################
	##INIT VariableArrayS
	def initVariableArrays(self,**kwargs):
		pass;

	################################
	####BUILD SHORTCUTS
	def setShortCuts(self,**kwargs):
		##build the queries
		AliasQueries=self.getSelfAliasQueries(**
									{
										#'locals':locals
										'StructureName':"self.__dict__",
										'Aliases':
										#shortcuts to VariableArray Parent Objects
										[
											{'AliasName':Alias[0],'AliasedVariablePathArray':Alias[1]} for Alias in [
															['Runom',['SimulatedRunomChild']],
															['Commandom',['SimulatedCommandomChild']],
															['Sensom',['SimulatedSensomChild']],
															['Populems',['SimulatedPopulomChild','Populems']],
															['Connectems',['SimulatedConnectomChild','Connectems']]
														]
														#+
														#[
														#	[VariablePathArray[1],VariablePathArray[0]+['VariableArrays','Units',VariablePathArray[1]]] for VariablePathArray in [
															#					[[],'dV'],
															#					[[],'V'],
															#					[[],'MuExt'],
															#					[['SimulatedInputChild'],'Gamma'],
															#					[['NetParent','SimulatedCommandomChild'],'c']
															#					]
														#]
										]
									}
								);
		##build the aliases
		for AliasQuery in AliasQueries:
			exec(AliasQuery);

	################################
	####INIT SIMULATION
	def initSimulation(self,**kwargs):

		###########################
		##determine which childrend takes part to the simulation
		#self.setList(**{});
		#self.setList
		##set SimulatedChildren
		self.setTaggedChildrenStructure(**kwargs['Tasks'][0]['kwargs']);

		"""
		##parse deeper SimulatedChildren
		self.doTasksToFirstChildrenWithFirstChildControllers(**
								{
								   'Tasks':kwargs['Tasks'],
								   'IsParsing':True
							   }
							);
		###########################
		##initSimulation for this object and all simulated children

		##Init VariableArrays
		self.initVariableArrays();
		self.doTasksToTaggedChildrenWithTaggedChildControllers(**
								{
									'Tags':['Simulated','Child'],
								    'Tasks':
										   [
												 {
													 'Function':'initVariableArrays',
													 'kwargs':
													 {
													}
												 }
											],
								    'IsParsing':True
							   }
							);

		##Set Shortcuts Aliases
		self.setShortCuts();
		self.doTasksToTaggedChildrenWithTaggedChildControllers(**
								{
									'Tags':['Simulated','Child'],
								    'Tasks':
										   [
												 {
													 'Function':'setShortCuts',
													 'kwargs':
													 {
													}
												 }
											],
								    'IsParsing':True
							   }
							);

		##Set Shortcuts Aliases
		self.doTasksToTaggedChildrenWithTaggedChildControllers(**
								{
									'Tags':['Simulated','Child'],
								    'Tasks':
										   [
												 {
													 'Function':'initSimulation',
													 'kwargs':
													 {
													}
												 }
											],
								    'IsParsing':True
							   }
							);

		##initMonitor
		#self.initMonitor();
		self.doTasksToTaggedChildrenWithTaggedChildControllers(**
								{
									'Tags':['Simulated','Child'],
								    'Tasks':
										   [
												 {
													 'Function':'initMonitor',
													 'kwargs':
													 {
													}
												 }
											],
								    'IsParsing':True
							   }
							);
		"""
		##Say that init is done
		self['IsInitSimulation']=True;

	def thresJ(self,J):
		return [min,max][(int)((1.+self.extJ_temp)/2.)](J,0.);

	###RUN SIMULATION##
	def runSimulation(self,**kwargs):

		##define default IsInitSimulation
		if self.__dict__.has_key('IsInitSimulation')==False:
			print('WARNING : PyIFNetClass run Simulation has to define first IsInitSimulation');
			return 0;

		##Check The simulation was initiated
		if self['IsInitSimulation']:

			##Print who is running
			print('runSimulation PyIFNetClass, initSimulation is True for : %s : ...running start! '%(self['ID']));

			##Init Time
			self['Time']=self['Runom']['StartTime'];

			##Loop on Time
			for self['TimeIdx'] in xrange(self['Runom']['TimeStepsNumber']):

				"""
				##Do the Commandom Methods
				if self['Commandom']!=None:
					##call the OneStepTime Routine
					self['Commandom'].runOneStepTime();

				##Do the Sensom Methods
				if self['Sensom']!=None:
					##call the OneStepTime Routine
					self['Sensom'].runOneStepTime();

				##Loop on the Populems
				for self['PopulemIdx'] in xrange(len(self['Populems']['Units'])):
					#set the Object
					self['Populem']=self['Populems']['Units'][self['PopulemIdx']];
					#call the OneStepTime Routine
					self['Populem'].runOneStepTime();

				##Loop on the Connectems
				for self['ConnectemIdx'] in xrange(len(self['Connectems']['Units'])):
					#set the Object
					self['Connectem']=self['Connectems']['Units'][self['ConnectemIdx']];
					#call the OneStepTime Routine
					self['Connectem'].runOneStepTime();
				"""

				#runOneStep to all SimulatedThingoms
				self.doTasksToTaggedChildrenWithTaggedChildControllers(**
								{
									'Tags':['Simulated','Child'],
								    'Tasks':
										   [
												 {
													 'Function':'runOneStepTime',
													 'kwargs':
													 {
													}
												 }
											],
								    'IsParsing':True
							   }
							);

				#Advance Time
				self['Time']+=self['Runom']['TimeStep'];
				self['Runom']['VariableArrays']['Units']['t']['InstantaneousValues'][0,self['TimeIdx']]=self['Time']

			################################
			####PRINT WHO IS RUNNING
			print('runSimulation PyIFNetClass, Simulation is Done for : %s : ...running stop! '%(self['ID']));

		else:
			pass;
			#print('WARNING : runSimulation PyIFNetClass, initSimulation is False for this : %s'%(self['ID']));


import wave,time
from pyaudio import PyAudio, paInt16

framerate = 16000  # 采样率
num_samples = 2000  # 采样点
channels = 1  # 声道
sampwidth = 2  # 采样宽度2bytes
FILEPATH = 'speech.wav'

def save_wave_file(filepath, data):
    wf = wave.open(filepath, 'wb')
    wf.setnchannels(channels)
    wf.setsampwidth(sampwidth)
    wf.setframerate(framerate)
    wf.writeframes(b''.join(data))
    wf.close()

# 录音
def my_record():
    pa = PyAudio()
    # 打开一个新的音频stream
    stream = pa.open(format=paInt16, channels=channels,
                     rate=framerate, input=True, frames_per_buffer=num_samples)
    my_buf = []  # 存放录音数据

    t = time.time()
    print('正在录音...')

    while time.time() < t + 4:  # 设置录音时间（秒）
        # 循环read，每次read 2000frames
        string_audio_data = stream.read(num_samples)
        my_buf.append(string_audio_data)
    print('录音结束.')
    save_wave_file(FILEPATH, my_buf)
    stream.close()
my_record()


import pandas as pd
import seaborn as sns
import matplotlib
import matplotlib.pyplot as plt

df = pd.read_csv('vehicles.csv')
print('pycharm')
print(df.columns)
sns_plot = sns.lmplot(df.columns[0], df.columns[1], data=df, fit_reg=False)
sns_plot.axes[0,0].set_ylim(0,)
sns_plot.axes[0,0].set_xlim(0,)
sns_plot.savefig("scaterplot_vehicle.png",bbox_inches='tight')
plt.show()

sns_plot2 = sns.distplot(df['Current fleet'], bins=20, kde=False, rug=True).get_figure()
plt.show()
sns_plot2.savefig("current_fleet.png",bbox_inches='tight')

sns_plot3 = sns.distplot(df['New Fleet'].dropna(), bins=20, kde=False, rug=True).get_figure()
plt.show()
sns_plot3.savefig("new_fleet.png",bbox_inches='tight')


from tkinter import *
from Response import Response
from tkinter import messagebox
class Questionnaire(Frame):
# GUI Setup
    def __init__ (self, master):
# Initialise Questionnaire Class
        Frame.__init__(self, master)
        self.grid()
        self.createProgSelect()
        self.createTeamExpQuest()
        self.createProblems()
        self.createComments()
        self.createButtons()
    def createProgSelect(self):
        # Create widgets to select a degree programme from a list
        lblProg = Label(self, text='Degree Programme:', font=('MS', 8,'bold'))
        lblProg.grid(row=0, column=0, columnspan=2, sticky=NE)
        self.listProg = Listbox(self, height= 3)
        scroll = Scrollbar(self, command= self.listProg.yview)
        self.listProg.configure(yscrollcommand=scroll.set)
        self.listProg.grid(row=0, column=2, columnspan=2, sticky=NE)
        scroll.grid(row=0, column=4, sticky=W)
        for item in ["CS", "CS with", "BIS", "SE", "Joints",""]:
            self.listProg.insert(END, item)
            self.listProg.selection_set(END)
    def createTeamExpQuest(self):
        lblStrAgr = Label(self, text = 'Strongly \n Agree', font=('MS', 8,'bold'))
        lblStrAgr.grid(row=3, column= 4, rowspan=2)
        lblStrAgr = Label(self, text = 'Partly \n Agree', font=('MS', 8,'bold'))
        lblStrAgr.grid(row=3, column= 5, rowspan=2)
        lblStrAgr = Label(self, text = 'Partly \n Disagree', font=('MS', 8,'bold'))
        lblStrAgr.grid(row=3, column= 6, rowspan=2)
        lblStrAgr = Label(self, text = 'Strongly \n Disagree', font=('MS', 8,'bold'))
        lblStrAgr.grid(row=3, column= 7, rowspan=2)

        self.varQ1 = IntVar()
        R1Q1 = Radiobutton(self, variable=self.varQ1, value=4)
        R1Q1.grid(row=5, column= 4)
        R2Q1 = Radiobutton(self, variable= self.varQ1, value=3)
        R2Q1.grid(row=5, column= 5)
        R3Q1 = Radiobutton(self, variable= self.varQ1, value=2)
        R3Q1.grid(row=5, column= 6)
        R4Q1 = Radiobutton(self, variable= self.varQ1, value=1)
        R4Q1.grid(row=5, column= 7)

        lblStrAgr = Label(self, text = 'Team experience:', font=('MS', 8,'bold'))
        lblStrAgr.grid(row=3, column= 3, rowspan=1)

        lblStrAgr = Label(self, text = '1. Our team worked together efficiently?', font=('MS', 8))
        lblStrAgr.grid(row=5, column= 3, rowspan=1)

        self.varQ2 = IntVar()
        R1Q2 = Radiobutton(self, variable=self.varQ2, value=4)
        R1Q2.grid(row=6, column= 4)
        R2Q2 = Radiobutton(self, variable= self.varQ2, value=3)
        R2Q2.grid(row=6, column= 5)
        R3Q2 = Radiobutton(self, variable= self.varQ2, value=2)
        R3Q2.grid(row=6, column= 6)
        R4Q2 = Radiobutton(self, variable= self.varQ2, value=1)
        R4Q2.grid(row=6, column= 7)

        lblStrAgr = Label(self, text = '2. Our team produced good quality products?', font=('MS', 8))
        lblStrAgr.grid(row=6, column= 3, rowspan=1)

        self.varQ3 = IntVar()
        R1Q3 = Radiobutton(self, variable=self.varQ3, value=4)
        R1Q3.grid(row=7, column= 4)
        R2Q3 = Radiobutton(self, variable= self.varQ3, value=3)
        R2Q3.grid(row=7, column= 5)
        R3Q3 = Radiobutton(self, variable= self.varQ3, value=2)
        R3Q3.grid(row=7, column= 6)
        R4Q3 = Radiobutton(self, variable= self.varQ3, value=1)
        R4Q3.grid(row=7, column= 7)

        lblStrAgr = Label(self, text = '3. Our team produced good quality products?', font=('MS', 8))
        lblStrAgr.grid(row=7, column= 3, rowspan=1)

    def createProblems(self):
        #Create Widgets to show Problems experienced
        lblProb1 = Label(self, text='Problems:', font=('MS', 8,'bold'))
        lblProb1.grid(row=8, column = 0)
        lblProb2 = Label(self, text='Our team often experienced the ' +
        'following problems (choose all that apply):')
        lblProb2.grid(row=8, column = 1, columnspan=6, sticky=W)

        self.varCB1 = IntVar()
        CB1 = Checkbutton(self, text=" Poor Communication", variable=self.varCB1)
        CB1.grid(row=9, column=0, columnspan=4, sticky=W)
        self.varCB2 = IntVar()
        CB1 = Checkbutton(self, text=" Lack of distinction", variable=self.varCB2)
        CB1.grid(row=10, column=0, columnspan=4, sticky=W)
        self.varCB3 = IntVar()
        CB1 = Checkbutton(self, text=" Disagreement among teammates", variable=self.varCB3)
        CB1.grid(row=11, column=0, columnspan=4, sticky=W)

        self.varCB4 = IntVar()
        CB4 = Checkbutton(self, text=" Members missing meetings", variable=self.varCB4)
        CB4.grid(row=9, column=4, columnspan=4, sticky=W)
        self.varCB5 = IntVar()
        CB5 = Checkbutton(self, text=" Members not contributing", variable=self.varCB5)
        CB5.grid(row=10, column=4, columnspan=4, sticky=W)
        self.varCB6 = IntVar()
        CB6 = Checkbutton(self, text=" Members not motivated", variable=self.varCB6)
        CB6.grid(row=11, column=4, columnspan=4, sticky=W)
    def createComments(self):
        self.txtComment = Text(self, height=3,width=40)
        scroll = Scrollbar(self, command=self.txtComment.yview)
        self.txtComment.configure(yscrollcommand=scroll.set)
        self.txtComment.grid(row=12, column=2,columnspan=5, sticky=E)
        scroll.grid(row=12, column=7, sticky=W)

        self.entName = Entry(self)
        self.entName.grid(row=15, column=2, columnspan=2, sticky=E)

        lblCmnt = Label(self, text='Comments about \n teamwork', font=('MS', 8,'bold'))
        lblCmnt.grid(row=12, column = 2,rowspan = 2, sticky = E)
        lblCmnt = Label(self, text='Name (optional)', font=('MS', 8,'bold'))
        lblCmnt.grid(row=15, column = 2)
    def createButtons(self):
        butSubmit = Button(self, text='Submit',font=('MS', 8,'bold'))
        butSubmit['command']=self.storeResponse #Note: no () after the method
        butSubmit.grid(row=16, column=2, columnspan=2)

        butClear = Button(self, text='Clear',font=('MS', 8,'bold'))
        butClear['command']=self.clearResponse #Note: no () after the method
        butClear.grid(row=16, column=4, columnspan=2)

        #butViewResults = Button(self, text='View Results',font=('MS', 8,'bold'))
        #butViewResults['command']=self. #Note: no () after the method
        #butClear.grid(row=16, column=4, columnspan=2)
    def clearResponse(self):
        self.listProg.selection_clear(0,END)
        self.listProg.selection_set(END)
        self.varQ1.set(0)
        self.varQ2.set(0)
        self.varQ3.set(0)
        self.varCB1.set(0)
        self.varCB2.set(0)
        self.varCB3.set(0)
        self.varCB4.set(0)
        self.varCB5.set(0)
        self.varCB6.set(0)
        self.entName.delete(0, END)
        self.txtComment.delete(1.0, END)
    def storeResponse(self):
        index = self.listProg.curselection()[0]
        strProg = str(self.listProg.get(index))
        strMsg=""
        if strProg == "":
            strMsg = "You need to select a Degree Programme. "
        if (self.varQ1.get()== 0) or (self.varQ2.get() == 0) or (self.varQ3.get() == 0):
            strMsg = strMsg + "You need to answer all Team Experience Questions"
        if strMsg == "":
            import shelve
            db = shelve.open('responsedb')
            responseCount = len(db)
            Ans = Response(str(responseCount+1), strProg,
            self.varQ1.get(), self.varQ2.get(), self.varQ3.get(),
            self.varCB1.get(), self.varCB2.get(), self.varCB3.get(),
            self.varCB4.get(), self.varCB5.get(), self.varCB6.get(),
            self.txtComment.get(1.0,END), self.entName.get())
            db[Ans.respNo] = Ans
            db.close
            messagebox.showinfo("Questionnaire", "Questionnaire Submitted")
            self.clearResponse()
        else:
            messagebox.showwarning("Entery error", strMsg)

#Main
root = Tk()
root.title("Teamwork Questionnaire")
app = Questionnaire(root)
root.mainloop()


#Hassan kaous
#gui for messaging

from Tkinter import *

class MainDisplay(Frame):
    def __init__(self):
        Frame.__init__(self)
        self.master.title("Messenger")
        self.grid(sticky = W+E+N+S)
        self._label = Label(self, text = "Mainwindow")
        self._label.grid(row = 1, column = 1)
        self._messageArea= Text

def main():
    MainDisplay().mainloop()

main()


#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import sys

try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

with open('requirements.txt', 'r') as f:
    requires = f.readlines()

readme = ''
history = ''
tests_require = []

setup(
    name='travis',
    version = '0.1dev',
    description='a test repo for travis-ci',
    long_description=readme + '\n\n' + history,
    author='Luke Thomas Mergner',
    author_email='lmergner@gmail.com',
    url='https://github.com/lmergner/travis',
    packages=[
        'travis',
    ],
    install_requires=requires,
    license="BSD",
    zip_safe=False,
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'License :: OSI Approved :: BSD License',
        'Natural Language :: English',
        'Programming Language :: Python :: 2.7',
    ],
    test_suite='tests',
    tests_require=tests_require,
)


SHIFT_VAL = 3  # defining the shift count
ENCRYPT_ME = "hello world"  # must be lower case

encrypted = ""

for c in ENCRYPT_ME:
    encrypted_letter = ord(c) + SHIFT_VAL
    encrypted += chr((encrypted_letter % 26)+ord("a"))

print("Plain text:", ENCRYPT_ME)

print("Encrypted text:", encrypted)

Easy Challenges/Challenge #3 [easy]/challenge_3.py


from sqlalchemy.orm import Session

from .models import Message

class RecorderMiddleare:

    def __init__(self, conn):
        self.conn = conn

    def process_input(self, input_event):
        m = Message(
            user_id=input_event.user_id,
            channel_id=input_event.channel,
            message=input_event.message,
        )
        session = Session(bind=self.conn)
        session.add(m)
        session.commit()


from selenium.webdriver.common.by import By
import time

class CMHelper():
    global warning_text
    warning_text = "This app was built for an older version of Android and may not work properly. " \
               "Try checking for updates, or contact the developer."

    def __init__(self, app):
        self.app = app
        self.driver = self.app.driver

    def warning(self):
        assert warning_text in self.driver.find_element_by_id('android:id/message').text
        print("I assert")
        self.driver.find_element_by_id('android:id/button1').click()
        print("I click OK")

    def add_contact(self):
        time_of_wait = 0
        for i in range(200):
            if self.driver.find_elements_by_id('com.example.android.contactmanager:id/addContactButton')==[]:
                time.sleep(1)
                time_of_wait +=1
            else:
                print(time_of_wait)
        self.driver.find_element_by_id('com.example.android.contactmanager:id/addContactButton').click()
        print("I click Add button")

    def contact_name_edit_text_selectable(self, text):
        print('input '+str(text)+' in Name field')
        self.driver.find_element_by_id('com.example.android.contactmanager:id/contactNameEditText').send_keys(text)