Example #1
0
 def __init__(self, array1, array2, populacao, fitness, estadoInicial):
     self.array1 = array1
     self.array2 = array2
     self.populacao = populacao
     self.fitness = fitness
     self.estadoInicial = estadoInicial
     self.check = Check()
Example #2
0
class Reproducao(object):
    def __init__(self, array1, array2, populacao, fitness, estadoInicial):
        self.array1 = array1
        self.array2 = array2
        self.populacao = populacao
        self.fitness = fitness
        self.estadoInicial = estadoInicial
        self.check = Check()

    def reproduzirFilho1(self):
        filho = self.array1[0:4]
        for i in self.array2:
            if i not in filho:
                filho.append(i)
        if randint(0, 100) > 20:
            filho = Mutacao(filho).Mutacao()

        self.populacao.append(filho)
        self.fitness.append(self.check.fitness(filho, self.estadoInicial))

    def reproduzirFilho2(self):
        filho = self.array2[0:4]
        for i in self.array1:
            if i not in filho:
                filho.append(i)
        if randint(0, 100) > 20:
            filho = Mutacao(filho).Mutacao()

        self.populacao.append(filho)
        self.fitness.append(self.check.fitness(filho, self.estadoInicial))
Example #3
0
    def test_email_error(self):
        msg = "Send $5 to John Snow {0}{1}"
        no_rparen = Check(
            msg.format('([email protected]', ' for The Night Watch'))
        no_lparen = Check(
            msg.format('[email protected])', ' for The Night Watch'))
        valid_no_for1 = Check(msg.format('([email protected])', None))
        valid_no_for2 = Check(msg.format('([email protected]).', None))
        valid_for = Check(
            msg.format('([email protected])', ' for The Night Watch'))

        self.assertTrue(no_rparen.errors)
        self.assertEqual(no_rparen.errors, ["Invalid email", self.format_msg])

        self.assertTrue(no_lparen.errors)
        self.assertEqual(no_lparen.errors,
                         ["Invalid name", "Invalid email", self.format_msg])

        self.assertFalse(valid_no_for1.errors)
        self.assertEqual(valid_no_for1.email, '*****@*****.**')

        self.assertFalse(valid_no_for2.errors)
        self.assertEqual(valid_no_for2.email, '*****@*****.**')

        self.assertFalse(valid_for.errors)
        self.assertEqual(valid_for.email, '*****@*****.**')
Example #4
0
def incoming_sms():
    """Send a dynamic reply to an incoming text message"""
    # Get the message the user sent our Twilio number
    body = request.values.get('Body', None)

    # Start our TwiML response
    resp = MessagingResponse()

    # Determine the right reply for this message
    if body:
        sms_check = Check(body)
        if not sms_check.errors:
            response = send_check(sms_check)
            if response.status_code == 201:
                resp.message("The check was sent.")
            else:
                print("Checkbook.io API response info:")
                print(body)
                print(response.text)
                print(sms_check.checkbook_post_data())
                print(response.status_code)
                resp.message("API call was not successful.")
        else:
            print("Message parsing errors:")
            print(sms_check.errors)
            resp.message("Check is not valid." + str(sms_check.errors))

    return str(resp)
Example #5
0
    def rsizerCreate(self):
        '''
        ###################################
        # rSizer Description Text
        #
        ## globals itemInfo, itemNumber
        ####################################
        '''
        self.logger.log_info(self.rsizerCreate.__name__,"THIS IS A MESSAGE in rsizerCreate")
        self.descriptionTextField = wx.TextCtrl(self.mainPanel, size=(300, 500),
                                         style=wx.TE_MULTILINE | wx.TE_RICH2)

        results = Check(self)
        description = results.description()
        self.descriptionTextField.AppendText(description)
        
        
        ####work in progress####
        self.descriptionTextField.Bind(wx.EVT_TEXT, self.eventsHandler.onDescriptionTextField)

        
        
        self.rSizer = wx.BoxSizer(wx.HORIZONTAL)
        self.rSizer.Add(self.descriptionTextField, 0, wx.ALL, 5)
        # Create Lbls/Text
        self.saveDescriptionTextBtn = wx.Button(self.mainPanel, label='Save Current')
        self.saveDescriptionTextBtn.Bind(wx.EVT_BUTTON,
                                self.eventsHandler.onSaveCurrentTextBtn)
        # self.currentBoxLbl = wx.StaticText(self.mainPanel, label='Current Box')
        # self.currentBoxText = wx.TextCtrl(self.mainPanel, size=(40,-1))
        # self.currentConditionLbl = wx.StaticText(self.mainPanel, label='Condition 1-5')
        self.currentConditionText = wx.TextCtrl(self.mainPanel, size=(40,-1))
        self.currentConditionText.Bind(wx.EVT_TEXT, self.eventsHandler.onCurrentConditionText)
        self.currentConditionNotesLbl = wx.StaticText(self.mainPanel, label='Condition Notes')
        self.currentConditionNotesText = wx.TextCtrl(self.mainPanel, size=(120,40), style=wx.TE_MULTILINE)
        self.currentDateListedLbl = wx.StaticText(self.mainPanel, label='Date Listed')
        self.currentDateListedText = wx.TextCtrl(self.mainPanel, size=(60,-1))
        self.currentDateListedText.Bind(wx.EVT_TEXT, self.eventsHandler.onDateListedText)

        self.currentTitleLbl = wx.StaticText(self.mainPanel, label='Title')
        self.currentTitleText = wx.TextCtrl(self.mainPanel, size=(300,60), style=wx.TE_MULTILINE)
        self.currentTitleText.Bind(wx.EVT_TEXT, self.eventsHandler.onCurrentTitleText)
        # Create rSizerCurrentItemSizer add lbl/text
        self.rSizerCurrentItemSizer = wx.BoxSizer(wx.VERTICAL)
        self.rSizerCurrentItemSizer.Add(self.saveDescriptionTextBtn, 0, wx.ALL, 5)
        # self.rSizerCurrentItemSizer.Add(self.currentBoxLbl, 0, wx.ALL, 5)
        # self.rSizerCurrentItemSizer.Add(self.currentBoxText, 0, wx.ALL, 5)
        # self.rSizerCurrentItemSizer.Add(self.currentConditionLbl, 0, wx.ALL, 5)
        # self.rSizerCurrentItemSizer.Add(self.currentConditionText, 0, wx.ALL, 5)
        self.rSizerCurrentItemSizer.Add(self.currentConditionNotesLbl, 0, wx.ALL, 5)
        self.rSizerCurrentItemSizer.Add(self.currentConditionNotesText, 0, wx.ALL, 5)
        self.rSizerCurrentItemSizer.Add(self.currentDateListedLbl, 0, wx.ALL, 5)
        self.rSizerCurrentItemSizer.Add(self.currentDateListedText, 0, wx.ALL, 5)
        self.rSizerCurrentItemSizer.Add(self.currentTitleLbl, 0, wx.ALL, 5)
        self.rSizerCurrentItemSizer.Add(self.currentTitleText, 0, wx.ALL, 5)
        self.rSizer.Add(self.rSizerCurrentItemSizer)
        self.rSizer.Hide(self.rSizerCurrentItemSizer,recursive=True)

        return
Example #6
0
 def __init__(self, vuls, proxy=False):
     self.vuls = vuls
     self.size = 6
     self.proxy = proxy
     self.check = False
     self.check = Check()
     self.load()
     self.lock = Lock()
     self.pool = ThreadPool(self.size)
Example #7
0
 def test_valid_check(self):
     msg = "Send $5 to John Snow ([email protected]) for The Night Watch"
     expected = {
         "name": 'John Snow',
         "recipient": '*****@*****.**',
         "amount": 5.0,
         "description": "The Night Watch"
     }
     c = Check(msg)
     self.assertEqual(c.checkbook_post_data(), expected)
Example #8
0
    def heuristic(self):
        number_squares = 0
        checker = Check(self.initState.board)

        for i in range(self.initState.size):
            if sum(self.initState.board[i]) == 0:
                for j in range(self.initState.size):
                    if checker.checkALL(i, j):
                        number_squares += 1

        return number_squares
Example #9
0
    def expand(self):
        nextStates = []

        checker = Check(self.initState.board)

        for i in range(self.initState.size):
            for j in range(self.initState.size):
                if checker.checkALL(i, j):
                    nextState = copy.deepcopy(self)
                    nextState.setVal(i, j, 1)
                    nextStates.append(nextState)
        return nextStates
Example #10
0
    def test_general_error(self):
        msg = "send $5 to John Snow ([email protected]) for The Night Watch"
        expected = ['Start message with "Send"', self.format_msg]
        c = Check(msg)

        self.assertTrue(c.errors)
        self.assertEqual(c.errors, expected)
Example #11
0
    def test_name_error(self):
        msg = "Send $5 toJohn Snow ([email protected]) for The Night Watch"
        expected = ["Invalid name", self.format_msg]
        c = Check(msg)

        self.assertTrue(c.errors)
        self.assertEqual(c.errors, expected)
Example #12
0
    def test_amount_error_general(self):
        msg = "Send 5 to John Snow ([email protected]) for The Night Watch"
        expected = ['Invalid amount.', self.format_msg]
        c = Check(msg)

        self.assertTrue(c.errors)
        self.assertEqual(c.errors, expected)
    def __init__(self,ipadd,fm_path,session=None):
        self.class_name = 'Update'
        self.ls = LogShow(self.class_name)
        if isinstance(ipadd, str):
            self.ip = ipadd
        else:
            self.ip = str(ipadd)
        if not Check.checkIP(self.ip):
            self.ls.log_print('warn', self.ip + ' is not valuable!', '__init__')
        if isinstance(fm_path, str):            
            self.firmware_path = fm_path
        else:
            self.firmware_path = str(fm_path)

        self.url_update = 'http://' + self.ip + '/service/system/firmware_upgrade/full_update'
        self.url_status = 'http://' + self.ip + '/service/system/task/status'
        self.url_update_new = 'http://' + self.ip + '/service/system/system_upgrade'
        self.url_restore = 'http://' + self.ip + '/service/system/restore'
        self.url_stop = 'http://' + self.ip + '/service/system/stop'
        self.url_start = 'http://' + self.ip + '/service/system/start'
        
        self.login = LogIn(self.ip)
        if session is None:
            self.Login()
        else:
            self.session = session
Example #14
0
    def test_amount_error_not_number(self):
        msg = "Send $five to John Snow ([email protected]) for The Night Watch"
        expected = ['Amount is not a number.', self.format_msg]
        c = Check(msg)

        self.assertTrue(c.errors)
        self.assertEqual(c.errors, expected)
Example #15
0
	def __init__(self , path):
		self.estadoInicial = [1,2,3,4,5,6,7,8]
		self.tamanhoPopulacao = 40
		self.variacao = [4,14]  
		self.morte = 0.40 
		self.morteLimite = self.morte * self.tamanhoPopulacao
		self.path = path
		self.arquivo = Arquivo()
		self.linha = []
		self.coluna = []

		self.populacao=[]
		self.fitness=[]
		self.melhorResultado = False
		self.check = Check()

		self.executavel()
Example #16
0
    def test_invalid_check(self):
        msg = "send 5 to John Snow [email protected]) for armor."
        expected = [
            'Start message with "Send"', 'Invalid amount.', 'Invalid name',
            'Invalid email', self.format_msg
        ]
        c = Check(msg)

        self.assertTrue(c.errors)
        self.assertEqual(c.errors, expected)
Example #17
0
    def test_amount_error_is_number(self):
        msg = "Send {0} to John Snow ([email protected]) for The Night Watch"
        expected = [
            'Amount can only have two decimal places.', self.format_msg
        ]

        no_dec = Check(msg.format('$500'))
        extra_zeros = Check(msg.format('$5.20000'))
        frac = Check(msg.format('$5.123'))

        self.assertFalse(no_dec.errors)
        self.assertEqual(no_dec.amount, 500)

        self.assertFalse(extra_zeros.errors)
        self.assertEqual(extra_zeros.amount, 5.20)

        self.assertTrue(frac.errors)
        self.assertEqual(frac.errors, expected)
        self.assertEqual(frac.amount, None)
Example #18
0
    def __init__(self, ipadd, session=None):
        self.class_name = 'GetVersion'
        self.ls = LogShow(self.class_name)

        if isinstance(ipadd, str):
            self.ip = ipadd
        else:
            self.ip = str(ipadd)
        if not Check.checkIP(self.ip):
            self.ls.log_print('warn', self.ip + ' is not valuable', '__init__')
        self.webcontroller = WebController(self.ip, session)
Example #19
0
def Game(Master, Player_lst, Turn, Rule_set):
    from Check import Check
    from Move import Move
    from Play import Play
    while True:
        m = Move(Master, Player_lst, Turn)  #Client
        if Play(m, Master, Player_lst,
                Turn) == True:  #Checks wether move is valid
            break
    while True:
        Rules = Check(Master, Rule_set)
        if Rules != -1:
            if '+' in Rules:  #can send back to Move()
                Applier('+')
            elif '0' in Rules:
                Applier('0')
            elif '*' in Rules:
                Applier('*')
            elif '1' in Rules:  #Can't Play draws a card
                Applier('1')
        elif Rules == -1:
            return
    def __init__(self, ipadd, username="******", password="******"):

        self.class_name = "Sftp"
        self.ls = LogShow(self.class_name)

        if isinstance(ipadd, str):
            self.ip = ipadd
        else:
            self.ip = str(ipadd)
        if not Check.checkIP(self.ip):
            self.ls.log_print('warn', self.ip + 'is not the valuable ip!',
                              '__init__')

        if isinstance(username, str):
            self.username = username
        else:
            self.username = str(username)
        if isinstance(password, str):
            self.password = password
        else:
            self.username = str(password)

        self.Connect()
Example #21
0
    def __init__(self, ip, port=21, bufsize=1024, username=None, password=None):
        self.class_name = "Ftp"
        self.ls = LogShow(self.class_name)
        if not Check.checkIP(ip):
            self.ls.log_print('warn', ip + ' is not valuable !')
        
        self.ip = ip
        
        if username is not None:
            self.username = username
        else:
            self.username = '******'
        
        if password is not None:
            self.password = password
        else:
            self.password = None

        self.port = (int)port
        self.bufsize = (int)bufsize

        if not hasattr(self,'ftp'):
            self.ftp = FTP()
        self.Connect()
Example #22
0
 def get_all_checks(self):
     checks = []
     for check_id in self.__get_all_checks_ids():
         checks.append(Check(check_id))
     return checks
Example #23
0
	def __init__(self, data):
		all_d = data.split('\t', 1)
		self.id = all_d[0]
		self.first_treat = False
		self.treament_line = False
		self.Check_list = [Check(all_d[1])]
Example #24
0
from Check import Check
from Patient import Patient

f = open('data.txt', 'r+')
title = f.readline()
his = f.read()
target = "铂"

p_list = {}
for line in his.split('\n'):
	id = line.split('\t', 1)[0]
	if id not in p_list.keys():
		P = Patient(line)
		p_list[id] = P
	else:
		C = Check(line.split('\t', 1)[1])
		p_list[id].Check_list.append(C)

for key,value in p_list.items():
	#print value.id
	for record in value.Check_list:
		#print record.Treat
		if value.first_treat == False:
			if record.Treat != "None":
				#first treatment
				value.first_treat = True
				if '+' in record.Treat:
					t_ct = 0
					medinces = record.Treat.split('+')
					for m in medinces:
						if target in m:
Example #25
0
class FetchContentSF:
    '''
    获取漏洞内容 包括 漏洞名称 CVE号  类型 最早公开时间  受影响的软件或系统 漏洞起因 安全建议  原始信息来源
    '''
    def __init__(self, vuls, proxy=False):
        self.vuls = vuls
        self.size = 6
        self.proxy = proxy
        self.check = False
        self.check = Check()
        self.load()
        self.lock = Lock()
        self.pool = ThreadPool(self.size)

    def load(self):
        error_times = 0
        LOG.pprint('+', 'load cncert cookie', GREEN)
        while error_times < 3:
            code = self.check.load()
            if code:
                break
            LOG.pprint('-', 'load cncert cookie failed, load again', RED)
        LOG.pprint('+', 'load cncert cookie success', GREEN)

    def setThreadSize(self, size):
        self.size = size

    def setCookie(self, cookie):
        self.cookie = cookie
        self.check = True

    def fetch(self):

        res = self.pool.map(self.fetchALL, self.vuls)
        self.pool.close()
        self.pool.join()

        return res

    def fetchALL(self, url):

        info = self._fetchInfo(url)
        info['url'] = url
        flag = info.has_key('CVE') and 'N-A' not in info['CVE']
        code = -1000
        if flag:
            if self.lock.acquire(1):
                code = self.check.check(info['CVE'])
                self.lock.release()
            if code == -1:
                LOG.pprint('-', '无法获取CNCERT cookie,请查看是否可以正常访问网站', RED)
                self.pool.terminate()
                sys.exit(0)
        try:
            if flag and info['CVE'] in CVEDB:
                LOG.pprint("-", "已存在CVE漏洞库中 " + url + ", 不载入,请人工确认", RED)
            elif flag and code > 0:
                LOG.pprint("-", "已存在CNCERT漏洞库中 " + url + ", 不载入", RED)
            elif flag and code == 0:
                discuss = self._fetchDiscussion(url)
                exploit = self._fetchExploit(url)
                solution = self._fetchSolution(url)
                company = self._fetchReferences(url)
                references = {'references': url}
                LOG.pprint("+", "fetch " + url + " details done", GREEN)
                return dict(
                    dict(
                        dict(dict(dict(info, **discuss), **exploit),
                             **solution), **references), **company)
            else:
                LOG.pprint("-", "不存在CVE " + url + ", 不载入,请人工确认", RED)
        except KeyboardInterrupt:
            LOG.pprint('+', 'user stop', GREEN)
            self.pool.terminate()
            sys.exit(0)

    def _fetchInfo(self, url):
        url = url + "/info"
        HTTPCONTAINER.setHeaders(HEADERS)
        r = HTTPCONTAINER.get(url, self.proxy)

        pattern = re.compile(
            r'\s*<td>\s*<span class="label">([\s\S]+?):</span>\s*</td>\s*<td>\s*([\s\S]*?)\s*</td>'
        )
        results = pattern.findall(r.content)
        res = {}
        for line in results:
            if line[0] == 'CVE':
                if line[1] == "":
                    res['CVE'] = "N-A-" + str(int(random.random() * 1000))
                else:
                    res['CVE'] = line[1][:13]
            elif line[0] == 'Vulnerable':
                res['Vulnerable'] = '\t'.join(line[1].split('\t'))
                res['Vulnerable'] = '\n'.join(res['Vulnerable'].split('\n'))
                res['Vulnerable'] = (' '.join(
                    res['Vulnerable'].split())).replace('<br/>', '\n')
                res['Vulnerable'] = re.sub('<[^<]+?>', '', res['Vulnerable'])
                pattern = re.compile(r'\s*([\S\s]+?)\s[0-9]{1}[\s\S]*?\n')
                product = list(set(pattern.findall(res['Vulnerable'])))
                res['product'] = "##".join(product).replace('+', '').strip()
                # print res['Vulnerable']
            else:
                res[line[0]] = re.sub('<[^<]+?>', '', line[1])
        return res

    def _fetchReferences(self, url):
        '''
        获取解决方案中的url
        获取厂商名
        :param url:
        :return:
        '''
        url += "/references"
        HTTPCONTAINER.setHeaders(HEADERS)
        r = HTTPCONTAINER.get(url, self.proxy)
        content = r.content[r.content.index('<li class="here"><a href='):]
        #正则匹配
        pattern = re.compile(
            r'<li><a href="([\s\S]+?)">([\s\S]+?)</a>\s*\([\s\S]+?\)\s*<br/></li>'
        )
        results = pattern.findall(content)
        data = {"company": "", "solutionUrl": "", "companyUrl": ""}
        max = 0
        for result in results:
            if "Homepage" in result[1] or "Home Page" in result[1]:
                data['company'] = result[1].strip("Homepage").strip(
                    "Home Page").strip()
                data['companyUrl'] = result[0]
            else:
                if max < len(result[1].strip()):
                    data['solutionUrl'] = result[0]
                    max = len(result[1].strip())

        return data

    def _fetchDiscussion(self, url):
        url = url + "/discuss"
        HTTPCONTAINER.setHeaders(HEADERS)
        r = HTTPCONTAINER.get(url, self.proxy)
        pattern = re.compile(
            r'<div id="vulnerability">\s*<span class="title">([\s\S]*?)</span><br/><br/>\s*([\s\S]*?)\s*</div>'
        )
        results = pattern.findall(r.content)[0]
        temp = results[1].replace('<br/>', '')
        temp = ' '.join(temp.split())
        return {"title": results[0], "discuss": temp}

    def _fetchExploit(self, url):
        url = url + "/exploit"
        HTTPCONTAINER.setHeaders(HEADERS)
        r = HTTPCONTAINER.get(url, self.proxy)
        pattern = re.compile(
            r'<div id="vulnerability">\s*<span class="title">[\s\S]*?</span><br/><br/>\s*([\s\S]*?)\s*</div>'
        )
        res = pattern.findall(r.content)
        temp = res[0].replace('<br/>', '')
        temp = ' '.join(temp.split())
        return {"exploit": temp}

    def _fetchSolution(self, url):
        url = url + "/solution"
        HTTPCONTAINER.setHeaders(HEADERS)
        r = HTTPCONTAINER.get(url, self.proxy)

        pattern = re.compile(r'<b>Solution:</b><br/>\s*([\s\S]*?)\s*</div>')
        res = pattern.findall(r.content)
        temp = res[0].replace('<br/>', '')
        temp = ' '.join(temp.split())
        if "":
            pass
        return {"solution": temp}
Example #26
0
 def Check(self):
     EdkLogger.quiet("Checking ...")
     EccCheck = Check()
     EccCheck.Check()
     EdkLogger.quiet("Checking  done!")
#!/usr/bin/env python

import sys
import os
import commands
from Check import Check
 
if __name__ == "__main__":
    

    launcher = Check()
    launcher.inspectSingleIpsec(sys.argv[4])    
    launcher.run('ipsec')

    launcher.closeDatabase()
    
    '''
    ## remove lock file
    lock_file_name = 'checksrunning.lock'
    os.remove(lock_file_name)
    '''
Example #28
0
from Roots import Roots
from Roots import Discriminant
from Check import Check

a = input("введите a")
b = input("введите b")
c = input("введите c")

my_check = Check(a, b, c)

if my_check.check_values():
    my_dis = Discriminant(a, b, c)
    print(my_dis.get_discriminant())
    my_roots = Roots(a, b, my_dis.get_discriminant())
    print(my_roots.get_roots())
else:
    print("Введите числа")
Example #29
0
    'host': '192.168.6.133',
    'httpport': '80',
    'sshport': '22',
    'sshuser': '******',
    'sshpass': '******',
    'htmlDict': {
        '/index.php': [
            'MD5',
            '2decodebeauty',
        ],
        '/index.php?page=phpcom': ['phpcom', 'decodebeauty', 'basiccompress']
    },
    'CmdDict': {
        'ls -l  /var/www/html/logs': [
            u'total 4\n',
            u'-rwxr-xr-x 1 www-data www-data 40 Aug 28 15:28 logfile.php\n'
        ],
        'ls /var/www/html/': [
            u'action.php\n', u'config.php\n', u'error.php\n', u'favicon.ico\n',
            u'index.php\n', u'library\n', u'logs\n', u'md5.php\n',
            u'normaliz.php\n', u'phpcom.php\n', u'static\n', u'uploadfile\n',
            u'views\n'
        ]
    },
}

CC = Check(obj['awdname'], obj['host'])
CC.CheckHttp(obj['httpport'], obj['htmlDict'])
CC.Login(obj['sshport'], obj['sshuser'], obj['sshpass'])
CC.CheckCmd(obj['CmdDict'])
print CC.exe("sss")
Example #30
0
    def rsizerCreate(self):
        '''
        ###################################
        # rSizer Description Text
        #
        ## globals itemInfo, itemNumber
        ####################################
        '''
        self.logger.log_info(self.rsizerCreate.__name__,
                             "THIS IS A MESSAGE in rsizerCreate")
        self.descriptionTextField = wx.TextCtrl(self.mainPanel,
                                                size=(300, 500),
                                                style=wx.TE_MULTILINE
                                                | wx.TE_RICH2)

        results = Check(self)
        description = results.description()
        self.descriptionTextField.AppendText(description)

        self.descriptionTextField.Bind(
            wx.EVT_TEXT, self.eventsHandler.onDescriptionTextField)

        self.rSizer = wx.BoxSizer(wx.HORIZONTAL)
        self.rSizer.Add(self.descriptionTextField, 0, wx.ALL, 5)
        self.currentTitleLbl = wx.StaticText(self.mainPanel, label='Title')
        self.currentTitleText = wx.TextCtrl(self.mainPanel,
                                            size=(300, 60),
                                            style=wx.TE_MULTILINE)
        self.currentTitleText.Bind(wx.EVT_TEXT,
                                   self.eventsHandler.onCurrentTitleText)

        # self.currentBoxLbl = wx.StaticText(self.mainPanel, label='Current Box')
        # self.currentBoxText = wx.TextCtrl(self.mainPanel, size=(40,-1))
        self.currentConditionLbl = wx.StaticText(self.mainPanel,
                                                 label='Condition 1-5')
        self.currentConditionText = wx.TextCtrl(self.mainPanel, size=(40, -1))
        self.currentConditionText.Bind(
            wx.EVT_TEXT, self.eventsHandler.onCurrentConditionText)
        # Issue #19
        self.currentAuctionIncludesLbl = wx.StaticText(
            self.mainPanel, label='Auction Includes')
        self.currentAuctionIncludesText = wx.TextCtrl(self.mainPanel,
                                                      size=(120, 40),
                                                      style=wx.TE_MULTILINE)
        self.currentAuctionIncludesText.Bind(
            wx.EVT_TEXT, self.eventsHandler.onCurrentAuctionIncludesText)
        self.currentConditionNotesLbl = wx.StaticText(self.mainPanel,
                                                      label='Condition Notes')
        self.currentConditionNotesText = wx.TextCtrl(self.mainPanel,
                                                     size=(120, 40),
                                                     style=wx.TE_MULTILINE)
        self.currentConditionNotesText.Bind(
            wx.EVT_TEXT, self.eventsHandler.onCurrentConditionNotesText)
        self.currentDateListedLbl = wx.StaticText(self.mainPanel,
                                                  label='Date Listed')
        self.currentDateListedText = wx.TextCtrl(self.mainPanel, size=(60, -1))
        self.currentDateListedText.Bind(wx.EVT_TEXT,
                                        self.eventsHandler.onDateListedText)
        # Create Lbls/Text
        self.saveDescriptionTextBtn = wx.Button(self.mainPanel,
                                                label='Save Current')
        self.saveDescriptionTextBtn.Bind(
            wx.EVT_BUTTON, self.eventsHandler.onSaveCurrentTextBtn)

        # Create rSizerCurrentItemSizer add lbl/text
        self.rSizerCurrentItemSizer = wx.BoxSizer(wx.VERTICAL)
        self.rSizerCurrentItemSizer.Add(self.currentTitleLbl, 0, wx.ALL, 5)
        self.rSizerCurrentItemSizer.Add(self.currentTitleText, 0, wx.ALL, 5)
        self.rSizerCurrentItemSizer.Add(self.currentAuctionIncludesLbl, 0,
                                        wx.ALL, 5)
        self.rSizerCurrentItemSizer.Add(self.currentAuctionIncludesText, 0,
                                        wx.ALL, 5)
        self.rSizerCurrentItemSizer.Add(self.currentConditionLbl, 0, wx.ALL, 5)
        self.rSizerCurrentItemSizer.Add(self.currentConditionText, 0, wx.ALL,
                                        5)
        self.rSizerCurrentItemSizer.Add(self.currentConditionNotesLbl, 0,
                                        wx.ALL, 5)
        self.rSizerCurrentItemSizer.Add(self.currentConditionNotesText, 0,
                                        wx.ALL, 5)
        self.rSizerCurrentItemSizer.Add(self.currentDateListedLbl, 0, wx.ALL,
                                        5)
        self.rSizerCurrentItemSizer.Add(self.currentDateListedText, 0, wx.ALL,
                                        5)
        self.rSizerCurrentItemSizer.Add(self.saveDescriptionTextBtn, 0, wx.ALL,
                                        5)
        self.rSizer.Add(self.rSizerCurrentItemSizer)
        self.rSizer.Hide(self.rSizerCurrentItemSizer, recursive=True)

        return
Example #31
0
    # Get values from second project.
    event_2 = "acute_arm_1"
    instance_2 = None

    othtreti, othtreti_hidden = getEntryLR(record_id, event_2, instance_2, "othtreti", records_list[1], record_id_map_list[1], metadata_list[1], form_repetition_map_list[1])
    ster, ster_hidden = getEntryLR(record_id, event_2, instance_2, "ster", records_list[1], record_id_map_list[1], metadata_list[1], form_repetition_map_list[1])
    acyclo, acyclo_hidden = getEntryLR(record_id, event_2, instance_2, "acyclo", records_list[1], record_id_map_list[1], metadata_list[1], form_repetition_map_list[1])    

    if (vstetiol == '1'):
        if (othtreti == '') or ((ster == '') and (not ster_hidden)) or ((acyclo == '') and (not acyclo_hidden)):
            element_bad = True

    return element_bad

#print "************************SKIPPING CHECK '"+name+"' FOR TEST************************"
checklist.append(Check(name, description, report_forms, inter_project, whole_row_check, check_invalid_entries, inter_record, inter_row, specify_fields, target_fields, rowConditions, fieldConditions, checkFunction))
del name, description, inter_project, whole_row_check, check_invalid_entries, inter_record, inter_row, specify_fields, target_fields, rowConditions, fieldConditions, checkFunction


#### Check: In VIPS II, Interview, if family history of stroke <45 is yes (fhstrkyng=1), then in IPSS, Other Child and Neonatal Risk Factors, stroke < 50 years of age should also be yes (hstroke=1).
name = "fam_hist_stroke_consistent"
description = 'In VIPS II, Interview, if family history of stroke <45 is yes (fhstrkyng=1), then in IPSS, Other Child and Neonatal Risk Factors, stroke < 50 years of age should also be yes (hstroke=1).'
report_forms = True
inter_project = True
whole_row_check = False
check_invalid_entries = False
inter_record = False
inter_row = True
specify_fields = True
target_fields = ['fhstrkyng'] # list target fields in the first project only; only links to these fields will be generated.
Example #32
0
class AlgoritmoGenetico(object):

	def __init__(self , path):
		self.estadoInicial = [1,2,3,4,5,6,7,8]
		self.tamanhoPopulacao = 40
		self.variacao = [4,14]  
		self.morte = 0.40 
		self.morteLimite = self.morte * self.tamanhoPopulacao
		self.path = path
		self.arquivo = Arquivo()
		self.linha = []
		self.coluna = []

		self.populacao=[]
		self.fitness=[]
		self.melhorResultado = False
		self.check = Check()

		self.executavel()

	def imprimeMatriz(self , matriz):
		print("------Matriz inicial-------")
		for i in range(len(matriz)):
			linha = matriz[i]
			print(linha)

	def executavel(self):
		S0 = self.arquivo.getMatrizArquivo(self.path)
		self.imprimeMatriz(S0)
		for i in range(0 , self.tamanhoPopulacao):
			self.populacao.append([1,2,3,4,5,6,7,8])
			a = 0
			while a < randint(self.variacao[0] , self.variacao[1]):
				a += 1
				self.populacao[i] = Mutacao(self.populacao[i]).Mutacao()

			fitness_final = self.check.fitness(self.populacao[i] , self.estadoInicial)	
			self.fitness.append(fitness_final)
		maxi = 0
		geracao = 1

		while maxi != 8:
 
		    morto = 0
		    x = 0
		    while morto < self.morteLimite:
		        for i in range(0 , self.tamanhoPopulacao):
		            try:
		                if self.fitness[i] == x:
		                    self.populacao.pop(i)
		                    self.fitness.pop(i)
		                    morto += 1

		                if morto == self.morteLimite:
		                    break
		            except:
		                break
		        x += 1
		 
		        filhos = 0 
		        cpop = len(self.populacao)-1 

		        while filhos < morto:
		            reproducao = Reproducao(self.populacao[randint(0,cpop)],self.populacao[randint(0,cpop)] , self.populacao , self.fitness , self.estadoInicial)
		            reproducao.reproduzirFilho1()
		            reproducao.reproduzirFilho2()
		            filhos += 2 

		        geracao += 1

		        maxi = 0
		        for i in range(0 , self.tamanhoPopulacao):
		            if self.fitness[i] > maxi:
		                maxi = self.fitness[i]
		                if maxi == 8:
		                	print("Algoritmo Genetico")
		                	self.printarMatricial(self.populacao[i])
		                	self.melhorResultado = True
		                	break
		        if self.melhorResultado == True:
		            break

	def printarMatricial(self , vetor):
		for i in range(8):
			valor = vetor[i]
			for j in range(8):
				if j == valor:
					self.coluna.append(1)
				else:           
					self.coluna.append(0)
			self.linha.append(self.coluna)
			self.coluna = []
		for i in range(8):
			print(self.linha[i])