Пример #1
0
    def buscaListaMotivosDivergencia(self):
        banco = BANCO()

        try:
            c = banco.conexao.cursor()
            c.execute('''SELECT 
                             DESCRICAO
                         FROM 
                             MOTIVOS_DIVERGENCIAS
                         ORDER BY
                             DESCRICAO
                       ''')

            linhas = c.fetchall()

            for linha in linhas:
                self.listaMotivos.append(linha[0])

            c.close()

            return self.listaMotivos
        except Exception as e:
            logger.logError(
                "Ocorreu um erro na busca dos motivos    -    Details: {}".
                format(str(e)))
Пример #2
0
    def __init__(self):
        diretorio = os.path.dirname(os.path.abspath(__file__))
        configFile = cfgprsr.ConfigParser()

        configFile.read(diretorio + '/config.ini')
        self.printer_type = configFile['PRINTER']['tipo']
        self.printer_device = configFile['PRINTER']['dispositivo']
        self.printer_vid = int(configFile['PRINTER']['vid'], 16)
        self.printer_pid = int(configFile['PRINTER']['pid'], 16)
        self.printer_baudrate = int(configFile['PRINTER']['baudrate'])
        self.printer_timeout = int(configFile['PRINTER']['timeout'])
        self.printer_parity = configFile['PRINTER']['parity']

        try:
            if self.printer_type.lower() == 'serial':
                self.printer = Serial(devfile=self.printer_device,
                                  baudrate=int(self.printer_baudrate),
                                  timeout=int(self.printer_timeout),
                                  parity=self.printer_parity)

                self.printer.open()
            elif self.printer_type.lower() == 'usb':
                self.printer = Usb(idVendor=self.printer_vid,
                                   idProduct=self.printer_pid)

            self.printer.codepage = 'CP860'


        except Exception as e:
            logger.logError("Erro ao comunicar com a impressora.    -    Details: {}".format(str(e)))
Пример #3
0
    def RegistraOrdenacaoNoBanco(self):
        try:
            self.DefinePrioridades()
        except Exception as e:
            logger.logError(
                "Erro ao definir as prioridades no algoritmo de Priorização de PDS.    -    Details: {}"
                .format(str(e)))

        self.lco.sort_values('PRIORIDADE').to_sql('tempTabelaOrdenada',
                                                  self.connLocal,
                                                  if_exists='replace',
                                                  index=False)

        curLocal = self.connLocal.cursor()

        curLocal.execute("""
                            UPDATE
                                PDS
                            SET
                                PRIORIDADE = (SELECT 
                                                  PRIORIDADE 
                                              FROM 
                                                  tempTabelaOrdenada TEMP
                                              WHERE
                                                  TEMP.PK_RCQ = PDS.PK_RCQ);"""
                         )

        curLocal.execute("DROP TABLE tempTabelaOrdenada;")

        self.connLocal.commit()

        curLocal.close()
        self.connLocal.close()
Пример #4
0
    def buscaPD(self, ID):
        banco = BANCO()

        try:
            curDados = banco.conexao.cursor()
            curDados.execute('''SELECT
                                    PDS.*, 
                                    COALESCE(CORES.DESCRICAO, 'SEM COR'),
                                    COALESCE(CORES.PRIMARIA, '#000000'),
                                    COALESCE(CORES.SECUNDARIA, '#000000'),
                                    COALESCE(CORES.COR_TEXTO, '#FFFFFF')
                                FROM
                                    PDS
                                LEFT JOIN
                                    CORES ON (CORES.PK_CRS = PDS.COR) 
                                WHERE
                                    PK_RCQ = "{}"
                             '''.format(str(ID)))

            self.dadosPD = curDados.fetchone()

            return "Busca feita com sucesso!"

        except Exception as e:
            return "Ocorreu um erro na busca do PD"
            logger.logError(
                "Ocorreu um erro na busca do PD    -    Details: {}".format(
                    str(e)))
Пример #5
0
    def DefineRankeamento(self):
        try:
            self.ExtraiTerminais()
        except Exception as e:
            logger.logError(
                "Erro ao extrair os terminais da lista de PDs para priorização dos PDs.    -    Details: {}"
                .format(str(e)))

        self.ranking = pd.DataFrame()
        vol = pd.Series([])

        for t in self.terminais:
            q = 0
            for a in ('ACABAMENTO_1', 'ACABAMENTO_2'):
                q += self.lco[self.lco[a] == t].sum()['QTD']

            vol[len(vol)] = q

        self.ranking['ACABAMENTO'] = self.terminais
        self.ranking['Volume'] = vol

        self.ranking = self.ranking.join(self.apl.set_index('ACABAMENTO'),
                                         on='ACABAMENTO')                  \
                                   .fillna('Z')                            \
                                   .sort_values(['APLICAVEL', 'Volume'],
                                                ascending=[False, False])  \
                                   .reset_index(drop=True)
Пример #6
0
    def tomaTempoEvento(self, FK_ID, FK_TTM, FK_USU, MAQ):
        try:
            banco = BANCO()
            agora = dt.now()

            cur = banco.conexao.cursor()

            cur.execute(
                """INSERT INTO TEMPOS (
                                DATA,
                                FK_ID,
                                FK_TTM,
                                FK_USU,
                                MAQUINA)
                            VALUES
                                (datetime(?),
                                ?,
                                ?,
                                ?,
                                ?)
                                """, (agora, FK_ID, FK_TTM, FK_USU, MAQ))

            banco.conexao.commit()
        except Exception as e:
            logger.logError(
                "Erro ao tomar tempo de Evento    -    Details: {}".format(
                    str(e)))
Пример #7
0
    def marketOrder(self, type, asset, currency):
        try:
            currentAmount = self.getAmountOfItem(asset + currency)
            print("current amount of %s%s: %f \n" %
                  (asset, currency, currentAmount))

            change = self.resetToEquilibrium_Market(currentAmount, asset,
                                                    currency)
            # orderSize = self.bank.update(change)
            orderSize = self.getMaxAmountToUse(asset, currency) * 0.4
            if type == self.buyText:
                result = self.marketBuy(
                    orderSize,
                    asset,
                    currency,
                    note='Going long.. Previous round trip profit')
            else:
                if type == self.sellText:
                    result = self.marketSell(orderSize,
                                             asset,
                                             currency,
                                             note='Going short')
            self.attemptsLeft = self.attemptsTotal
            return True
        except:
            tb = traceback.format_exc()
            logger.logError(tb)
            if self.attemptsLeft == 0:
                self.attemptsLeft = self.attemptsTotal
                return None
            sleep(self.delayBetweenAttempts)
            self.connect()
            self.attemptsLeft = self.attemptsLeft - 1
            self.marketOrder(type, asset, currency)
Пример #8
0
def verifyParam(name, value, inf_bound, sup_bound):
    if value < inf_bound or value > sup_bound:
        logError(
            '[PGCYCL]: Error, {} must be in the range [{},{}], given : {}'.
            format(name, inf_bound, sup_bound, value), True, True)
        exit(2)
    else:
        return value
Пример #9
0
def InsertDomainWrapper(domainArray, InScopeId):
    curInScope = models.InScope(InScopeId)
    newDomains = returnNewDomainsArrayInScopeObject(domainArray, curInScope)
    # Check Internet
    if dnsCheck.checkInternet():
        for domain in newDomains:
            mysqlfunc.insertDomain(domain, InScopeId)
    else:
        print '[-] Internet Check failed'
        logger.logError('[-] Internet check failed: ' + ', '.join(newDomains))
Пример #10
0
    def __init__(self):
        try:
            self.conexao = sqlite3.connect(diretorio + '/database/DADOS.db')
        except Exception as e:
            logger.logError(
                "Erro ao conectar ao banco de dados local.    -    Details: {}"
                .format(str(e)))

            #        self.conexao.text_factory = lambda x: str(x, 'cp1252')
            self.createTable()
Пример #11
0
    def OrdenaLista(self):
        try:
            self.RegistraOrdenacaoNoBanco()
        except Exception as e:
            logger.logError(
                "Erro ao registrar a lista já priorizada no banco de dados local.    -    Details: {}"
                .format(str(e)))

        # self.ExibeResultados()

        if not self.headless:
            self.master.destroy()
Пример #12
0
 def ImportaAplicaveis(self):
     try:
         self.apl = pd.read_sql_query(
             """
                                          SELECT
                                              *
                                          FROM
                                              APLICAVEL;
                                      """, self.connLocal)
     except Exception as e:
         logger.logError(
             "Erro ao ler a tabela APLICAVEL do banco de dados local.    -    Details: {}"
             .format(str(e)))
Пример #13
0
    def registraAlteracoes(self):
        if self.virtualNumPadVisible:
            self.popUpVNumPad.destroy()
            self.virtualNumPadVisible = False

        self.mensagemMenu.set(
            "Por favor aguarde enquanto as configurações são salvas")
        self.master.update()

        self.configFile.set('DEFAULT', 'maquina', str(self.cboMaquina.get()))
        self.configFile.set('DEFAULT', 'filtralista',
                            str(self.varLoadMode.get()))
        self.configFile.set('DEFAULT', 'maqautomatica',
                            str(self.varMaqAuto.get()))

        if self.varLoadMode.get() == 'True':
            self.configFile.set('DEFAULT', 'ordens',
                                '({})'.format(str(self.entryNrListas.get())))

        else:
            self.configFile.set('DEFAULT', 'limite horizonte',
                                str(self.scrLimiteHorizonte.get()))
            self.configFile.set('DEFAULT', 'limitediariocircuitos',
                                str(self.scrLimiteCircuitos.get()))

        with open(self.diretorio + '/config.ini', 'w') as configfile:
            self.configFile.write(configfile)

        try:
            import atualiza_bdlocal
            atualiza_bdlocal.AtualizaBancoLocal()
            priori.AlgoritmoSeparacao(headless=True)

            self.parent.limpaTela()
            self.parent.montaTelaPrincipal()
            self.master.destroy()
        except Exception as e:
            self.configFile.set('DEFAULT', 'filtralista', 'False')

            with open(self.diretorio + '/config.ini', 'w') as configfile:
                self.configFile.write(configfile)

            self.mensagemMenu.set('Erro. Verifique as configurações')
            self.lblMsgMenu['fg'] = 'red'

            logger.logError(
                "Erro ao salver as configurações do Menu.    -    Details: {}".
                format(str(e)))
Пример #14
0
    def buscaLista(self):
        banco = BANCO()

        if self.maquinaAutomatica == 'True':
            strOrdenacao = """ORDER BY
                                  PDS.PRIORIDADE,
                                  BITOLA,
                                  (SELECT SUM([QTD_PD_REQ]) FROM PDS P where P.CABO = PDS.CABO GROUP BY CABO) DESC,
                                  MEDIDA DESC"""
        else:
            strOrdenacao = """ORDER BY
                                  BITOLA,
                                  (SELECT SUM([QTD_PD_REQ]) FROM PDS P where P.CABO = PDS.CABO GROUP BY CABO) DESC,
                                  MEDIDA DESC"""

        try:
            c = banco.conexao.cursor()

            if self.filtaLista == 'True':
                c.execute('''SELECT
                               *
                             FROM
                               PDS
                             WHERE
                               PDS."QTD_PD_REQ" > PDS.QTD_CORTADA
                          ''' + strOrdenacao)
            else:
                c.execute('''SELECT
                               *
                             FROM
                               PDS
                             WHERE
                               PDS.MAQUINA = "%s" AND
                               PDS."QTD_PD_REQ" > PDS.QTD_CORTADA
                          ''' % self.maquina + strOrdenacao)

            self.lista = c.fetchall()

            c.close()

            return "Busca feita com sucesso!"

        except Exception as e:
            return "Ocorreu um erro na busca do PD"
            logger.logError(
                "Ocorreu um erro na busca do PD    -    Details: {}".format(
                    str(e)))
Пример #15
0
    def limitBuy(self,
                 price,
                 asset,
                 currency,
                 orderQuantity,
                 orderId=None,
                 note=None):
        result = None

        openOrder = self.orderOpen(orderId)
        if openOrder and orderQuantity != 0:
            try:
                result = self.market.Order.Order_amend(orderID=orderId,
                                                       price=price).result()
                logger.logOrder(
                    self.marketName, 'Limit', price, asset, currency,
                    orderQuantity,
                    str(note) + ' amend for order: ' + str(orderId))
            except Exception as e:

                if e.response.status_code == 400:
                    logger.logError('LIMIT AMEND ERROR')
                    orderQuantity = self.quantityLeftInOrder(
                        orderId, orderQuantity)
                    if orderQuantity != 0:
                        openOrder = False
                else:
                    logger.logError('UNKNOWN LIMIT ERROR: ' + str(e))
                    raise e

        if not openOrder and orderQuantity != 0:
            result = self.market.Order.Order_new(
                symbol=asset + currency,
                orderQty=orderQuantity,
                ordType="Limit",
                price=price,
                execInst='ParticipateDoNotInitiate').result()
            logger.logOrder(self.marketName, 'Limit', price, asset, currency,
                            orderQuantity, note)
        if result is not None:
            tradeInfo = result[0]
            for key, value in tradeInfo.items():
                if key == "orderID":
                    newOrderId = (key + ": {0}".format(value))
                    return newOrderId[9:]
        else:
            return None
Пример #16
0
def upload_file(file_name, s3=s3, acl="public-read"):
    bucket_name = os.environ.get('TGM_BUCKET_NAME')
    #opens file, reads it, and uploads it to the S3 bucket.
    try:
        with open(file_name, 'rb') as data:
            s3.upload_fileobj(data,
                              bucket_name,
                              file_name,
                              ExtraArgs={
                                  "ACL": acl,
                                  "ContentType": file_name.split(".")[-1]
                              })
    except:
        logError('ERROR_S3_UPLOAD of ' + file_name)

    file_url = "https://s3.ap-south-1.amazonaws.com/" + bucket_name + "/" + file_name
    return file_url
Пример #17
0
    def Definicoes(self):
        try:
            self.diretorio = os.path.dirname(os.path.abspath(__file__))
            self.configFile = cfgprsr.ConfigParser()
            self.configFile.read(self.diretorio + '/config.ini')
            self.maquina = self.configFile['DEFAULT']['maquina']
        except Exception as e:
            logger.logError(
                "Erro ao ler as variáveis de ambiente.    -    Details: {}".
                format(str(e)))

        try:
            self.connLocal = BANCO().conexao
        except Exception as e:
            logger.logError(
                "Erro ao conectar ao banco de dados Local para priorização dos PDs.    -    Details: {}"
                .format(str(e)))
Пример #18
0
    def limitOrderStatus(self, orderID, triesLeft=None):
        if triesLeft == None:
            triesLeft = 1
        if orderID == None:
            return False
        filter = '{"orderID": "' + orderID + '"}'
        res = self.market.Order.Order_getOrders(filter=filter).result()

        try:
            res = res[0][0]
            status = res['ordStatus']
        except:
            if triesLeft != 0:
                sleep(1)
                return self.limitOrderStatus(orderID)
            triesLeft = triesLeft - 1
            logger.logError('--- ORDER LIST ERROR ---')

        return res
Пример #19
0
def memTest(logNum, server, session, command):
    try:
        if command is None: return
        session.sendline(command)
        session.prompt()
        lines = session.before.decode()
        for line in lines.splitlines():
            print('{:4d}\t{:15s}\t{:16.5f}\t{}'.format(logNum, server,
                                                       time.time(), line))
            if 'ERROR' in line:
                logMessage = 'MemTest Failed {} {}'.format(line, command)
                logger.logError(logNum, server, logMessage)
    except Exception as ex:
        template = "An exception of type {0} occurred. Arguments:\n{1!r}"
        message = template.format(type(ex).__name__, ex.args)
        print(message)
        logger.logError(logNum, server, message)
        print('Command Failed {:4d}\t{:15s}\t{:16.5f}\t{}'.format(
            logNum, server, time.time(), command))
Пример #20
0
    def botaoLogin(self):
        global idUsuario, nomeUsuario

        banco = BANCO()
        cur = banco.conexao.cursor()

        usr = self.user.get()
        pwd = self.password.get()
        pwdbco = None

        try:
            cur.execute(""" SELECT
                                    PK_USU,
                                    NOME,
                                    SENHA
                                FROM
                                    USUARIOS
                                WHERE
                                    NOME = "%s"
                            """ % usr)

            dadosUsuario = cur.fetchone()
            idUsuario = dadosUsuario[0]
            nomeUsuario = dadosUsuario[1]
            pwdbco = dadosUsuario[2]

            if pwdbco == pwd:
                self.lblMensagem["text"] = "Login OK"
                loginRoot.destroy()

            else:
                self.lblMensagem["text"] = "Senha incorreta"
                logger.logError(
                    "Tentativa de Login inválida    -    Details: Senha incorreta para usuario '{}'"
                    .format(str(usr)))

        except:
            self.lblMensagem["text"] = "Usuário não encontrado"
            logger.logError(
                "Tentativa de Login inválida    -    Details: Usuário '{}' não encontrado"
                .format(str(usr)))
Пример #21
0
 def ImportaLista(self):
     try:
         self.lco = pd.read_sql_query(
             """
                                      SELECT 
                                          PK_RCQ, 
                                          [QTD_PD_REQ] - [QTD_CORTADA] AS "QTD",
                                          [ACABAMENTO_1],
                                          [ACABAMENTO_2],
                                          PRIORIDADE
                                      FROM 
                                          PDS
                                      WHERE
                                          [QTD_PD_REQ] - [QTD_CORTADA] > 0 AND
                                          MAQUINA = '%s';    
                                      """ % self.maquina,
             self.connLocal).fillna('Vazio')
     except Exception as e:
         logger.logError(
             "Erro ao importar a lista de PDs para priorização de PDs.    -    Details: {}"
             .format(str(e)))
Пример #22
0
def Subfinder(InScopeObject):
    # Remove the wildcard
    print '[+] Starting Subfinder on: ' + InScopeObject.ScopeText
    # Takes -d for domain && -o for name of the output file
    outputFileLoc = variables.tempFolder + 'subfinder.temp'
    # Remove the files between
    subprocess.call('rm ' + outputFileLoc, shell=True)
    subprocess.call(variables.goBin + 'subfinder -d %s -o %s > /dev/null' %
                    (InScopeObject.ScopeText[2:], outputFileLoc),
                    shell=True)
    try:
        domainsOutput = subprocess.check_output('cat ' + outputFileLoc,
                                                shell=True)
        newDomains = parsingSqlData.returnNewDomainsArrayInScopeObject(
            filter(None, domainsOutput.split('\n')), InScopeObject)
        # Check Internet

        if dnsCheck.checkInternet():
            print '[*] Internet seems to be successs in responses'
            print '[*] \tStarting insert newDomains'
            # Need to wrap this so it's faster
            pool = ThreadPool(50)
            insertDomainInScopeId = partial(
                mysqlfunc.insertDomain, domainRangeId=InScopeObject.InScopeId)
            pool.map(insertDomainInScopeId, newDomains)
            #for domain in newDomains:
            #+	mysqlfunc.insertDomain(domain, InScopeObject.InScopeId)
        else:
            print '[-] Internet Check failed'
            logger.logError('[-] Internet check failed: ' +
                            ', '.join(newDomains))

    except OSError, e:
        if e[0] == 2:
            print '[-] Subfinder errored out: By the fact that the output file does not exist\n'
            pdb.set_trace()
        else:
            print '[-] Subfinder errored out: Weird error... debug in InScopeTextTasks >> subfinder function'
            pdb.set_trace()
Пример #23
0
    def __init__(self):
        try:
            self.global_database_dsn = configFile['GLOBAL_DATABASE']['dsn']
            self.global_database_user = configFile['GLOBAL_DATABASE']['user']
            self.global_database_password = configFile['GLOBAL_DATABASE'][
                'password']
            self.global_database_charset = configFile['GLOBAL_DATABASE'][
                'charset']
        except Exception as e:
            logger.logError(
                "Erro ao ler as variáveis de ambiente.    -    Details: {}".
                format(str(e)))

        try:
            self.conexao = fdb.connect(dsn=self.global_database_dsn,
                                       user=self.global_database_user,
                                       password=self.global_database_password,
                                       charset=self.global_database_charset)
        except Exception as e:
            logger.logError(
                "Erro ao abrir a conexão com o banco global (Delphus).    -    Details: {}"
                .format(str(e)))
def pullTransactionData():
    if not os.path.exists(path):
        logger.logError("Path (%s) doesnt exist. Creating new path'" % path)
        try:
            os.mkdir(path)
            if not os.path.exists(path):
                logger.logError("Path (%s) creation failed. Exiting" % path)
                sys.exit(1)
            else:
                logger.logthis("Path created")
        except FileExistsError:
            logger.logError("Folder (%s) already exists" % path)
    filename = path+"transactions_" + time.strftime("%d%m%Y") + ".csv"
    url = "https://shapeshift.io/recenttx/50"
    r = requests.get(url)
    if r.status_code is 200:
        transactions = json.loads(r.text)
        logger.logthis(str("Picked up " + str(len(transactions)) + " transactions."))
        logger.logthis("parsing")
        if not os.path.isfile(filename):
            logger.logthis("File not found, creating new one")
            csvFile = open(filename, "w+")
            csvWriter = csv.writer(csvFile, delimiter=",")
            csvWriter.writerow(["timestamp", "curIn", "curOut", "amount", "txid"])
            csvFile.close()
        else:
            logger.logthis("Appending to existing file")
        # to ensure we dont have duplicates
        inMemCSV = []
        csvFile = open(filename, "r")
        for row in csv.reader(csvFile):
            inMemCSV.append(row)
        csvFile.close()
        dupcount = 0
        with open(filename, "a") as csvFile:
            csvWriter = csv.writer(csvFile, delimiter=",")
            for tx in transactions:
                row =[str(tx['timestamp']), str(tx['curIn']), str(tx['curOut']), str(tx['amount']), str(tx['txid'])]
                if row in inMemCSV:
                    # duplicate found
                    dupcount += 1
                    continue
                csvWriter.writerow(row)
            csvFile.close()
        logger.logthis("Found "+str(dupcount)+" duplicates, Wrote " + str(len(transactions)-dupcount)+ " to file")
        logger.logthis("All transactions have been written to a file")
        logger.logthis("Complete, closing")
    else:
        logger.logthis("Error when pulling the data")
        logger.logthis(str("Status code" + str(r.status_code)))
Пример #25
0
def addNewTask(args):
    #####
    # Var initialization
    #####

    index = 0  # Index of the first optional arg
    arg = 0  # Current argument

    data = {
        'command': '',
        'minute': 0,
        'hour': 0,
        'frequency': '0',
        'day': '0',
        'month': '0'
    }

    args_length = len(args)

    if args_length < 3:
        printUsage()

    else:
        data.update({'command': args[index]})
        file = open(FBATCH, 'a')
        try:
            index += 1
            minute = verifyParam('minute', int(args[index]), 0, 59)
            data.update({'minute': minute})
            index += 1
            hour = verifyParam('hour', int(args[index]), 0, 23)
            data.update({'hour': hour})
            index += 1

            if index < args_length:
                arg = args[index]
            else:
                arg = '-d'

            index += 1

            if arg == '-d' or arg == '--daily':
                data.update({'frequency': 'daily'})

            elif arg == '-w' or arg == '--weekly':
                day = verifyParam('day of the week', args[index], 1, 7)
                data.update({'frequency': 'weekly', 'day': day})

            elif arg == '-m' or arg == '--monthly':
                day = verifyParam('day', (args[index]), 1, 31)
                data.update({'frequency': 'monthly', 'day': day})

            elif arg == '-y' or arg == '--yearly':
                month = verifyParam('month', int(args[index]), 1, 12)
                index += 1
                day = verifyParam('day', int(args[index]), 1, 31)
                data.update({
                    'frequency': 'yearly',
                    'day': day,
                    'month': month
                })

            else:
                printUsage()

            content = writeToFBatch(**data)
            if os.stat(FBATCH).st_size != 0:
                content = '\n' + content
            file.write(content)
            file.flush()
            logInfo(
                '[PGCYCL]: Added command "{command}" will be executed at : {hour}:{minute} on a {frequency} basis'
                .format(**data), True)

        except IndexError:
            logError(
                '[PGCYCL]: Error : No value behind parameter : {}'.format(arg),
                True, True)
            exit(2)

        except ValueError:
            logError(
                '[PGCYCL]: Parameter {} needs integer value, given {}'.format(
                    arg, args[index]), True, True)
            exit(2)

        finally:
            file.close()
Пример #26
0
def deleteTask():
    tasks = listAllTasks(True)
    lines = listAllTasks(False)
    tasks_count = len(lines)

    if tasks_count == 0:
        logError(
            '[PGCYCL]: No tasks in fbatch file for the moment, add some first',
            True, False)
        exit(0)

    print(tasks)
    print('Give id of the tasks you which to delete (q to exit) ')
    index = getinput()

    if index == 'q' or index == '' or index == 'exit':
        logInfo('[PGCYCL]: User aborted deletion', True)
        exit(0)

    try:
        index = int(index)

    except ValueError:
        logError('[PGCYCL]: Id invalid, given "{}"'.format(index), True, True)
        exit(1)

    if index > tasks_count:
        logError(
            '[PGCYCL]: Id not found, "{}" given, only {} tasks'.format(
                index, tasks_count), True, True)
        exit(1)

    elif 0 < index <= tasks_count:
        line = lines[index - 1]
        output = 'Deleting tasks {} :\n'.format(index)
        output += 'Minute\tHour\tDay\tMonth\tFrequency\tCommand\n'
        output += line
        output += '\nAre you sure ? (y/N) '

        try:
            print(output)
            answer = getinput()

            if not answer or answer == 'n':
                logInfo("User aborted deletion", True)
                exit(0)

            elif answer == 'y':
                lines.pop(index - 1)
                last = len(lines) - 1
                lines[last] = lines[last].rstrip()

                # Resets file content
                open(FBATCH, 'w').close()

                fbatch_file = open(FBATCH, 'a')
                lines = ''.join(lines)
                fbatch_file.write(lines)
                fbatch_file.close()
                logInfo('[PGCYCL]: Recurrent task deleted successfully', True)

        except SyntaxError:
            logError('[PGCYCL]: Error : Answer invalid', True, True)
            exit(1)

    else:
        logError('[PGCYCL]: Id not valid', True, True)
        exit(1)
Пример #27
0
argv = sys.argv

if len(argv) >= 2:

    param = argv[1]

    if param == 'help' or param == '-h' or param == '?':
        printUsage()

    if param == 'list':
        print(useSemaphore(listAllTasks, True, False))

    elif param == 'add':
        useSemaphore(addNewTask, argv[2:], True)

    elif param == 'del':
        useSemaphore(deleteTask, None, True)

    else:
        logError('[PGCYCL]: Command not found', True, True)
        printUsage()
'''
deleteTask()
addNewTask(['command', 5, 39, '-d'])
addNewTask(['echo test', 7, 42, '-w', 3])
addNewTask(['error', 12, 1, '-m', 21])
addNewTask(['exit(1)', 3, 34, '-y', 9, 5])
addNewTask(['drop database', 23, 6])
'''
Пример #28
0
    def origem(self):
        try:
            conGlobal = banco.GLOBAL_DATABASE().conexao
        except Exception as e:
            logger.logError("Erro na conexao com o banco de dados de origem!    -    Details: {}".format(str(e)))


        if self.filtraLista == 'True':
            try:
                dadosOrigem = pd.read_sql_query("""SELECT
                                                       *
                                                   FROM
                                                       PDS_PENDENTES_CORTE_COR
                                                   WHERE
                                                       "NR_ORDEM_CORTE" in {}
                                                   ORDER BY
                                                       "DATA_ENTREGA",
                                                       "CABO";
                                                """.format(self.ordensCorte),
                                                conGlobal)

                self.dadosLimitados = dadosOrigem

                self.aplicavelOrigem = pd.read_sql_query("""SELECT 
                                                              PRO.COD_FABRIC as "ACABAMENTO",
                                                              PRO.APLICAVEL 
                                                            FROM 
                                                              PRODUTOS PRO
                                                            WHERE
                                                              PRO.FK_CAD != 13;
                                                         """,
                                                         conGlobal)
            except Exception as e:
                logger.logError("Erro na obtenção dos dados de origem!    -    Details: {}".format(str(e)))
        else:
            try:
                dadosOrigem = pd.read_sql_query("""SELECT 
                                                    * 
                                                FROM 
                                                    PDS_PENDENTES_CORTE_COR
                                                WHERE
                                                    "DATA_ENTREGA" <= CURRENT_DATE + %i AND
                                                    "MAQUINA" = '%s'
                                                ORDER BY
                                                    "DATA_ENTREGA",
                                                    "CABO";
                                                """ % (int(self.limiteHorizonte),
                                                           self.maquina),
                                                conGlobal)

                dadosOrdenados = dadosOrigem.sort_values(
                    by='DATA ENTREGA').reset_index(drop=True)

                qtdAcumulada = pd.Series(dadosOrdenados['QTD_PD_REQ'].cumsum())

                self.dadosLimitados = dadosOrdenados[:qtdAcumulada.where(qtdAcumulada <= int(self.limiteCircuitos)).idxmax(skipna=True)]

                self.aplicavelOrigem = pd.read_sql_query("""SELECT 
                                                         PRO.COD_FABRIC as "ACABAMENTO",
                                                         PRO.APLICAVEL 
                                                       FROM 
                                                         PRODUTOS PRO
                                                       WHERE
                                                         PRO.FK_CAD != 13;
                                                    """, conGlobal)

            except Exception as e:
                logger.logError("Erro na obtenção dos dados de origem!    -    Details: {}".format(str(e)))

        self.origem2destino()
Пример #29
0
    def registraCorteNoBanco(self, ID, qtdCortadaEmPecas, qtdCortadaEmMetros):
        try:
            try:
                conOrigem = GLOBAL_DATABASE().conexao
                curOrigem = conOrigem.cursor()
            except Exception as e:
                logger.logError(
                    "Erro no metodo: pd.registraCorteNoBanco() -> Erro na conexão com o banco de dados de origem!    -    Details: {}"
                    .format(str(e)))
                return False

            try:
                id_array = ID.split('|')
                requisicao = id_array[0]
                corte = id_array[1]
                quantidade = id_array[2]

                curOrigem.execute(
                    "EXECUTE PROCEDURE ATUALIZA_IQC({}, {}, {}, {})".format(
                        str(requisicao), str(corte), str(quantidade),
                        str(qtdCortadaEmMetros)))
            except Exception as e:
                logger.logError(
                    "Erro no metodo: pd.registraCorteNoBanco() -> Erro ao tentar transmissao para o Banco de dados Global!    -    Details: {}"
                    .format(str(e)))
                return False

            try:
                bancoLocal = BANCO()
                curLocal = bancoLocal.conexao.cursor()
            except Exception as e:
                logger.logError(
                    "Erro no metodo: pd.registraCorteNoBanco() -> Erro na conexão com o banco de dados local!    -    Details: {}"
                    .format(str(e)))
                return False

            try:
                query = """ 
                            UPDATE
                                PDS
                            SET
                                QTD_CORTADA = {}
                            WHERE
                                PK_RCQ = '{}';
                        """.format(str(qtdCortadaEmPecas), str(ID))

                curLocal.execute(query)
            except Exception as e:
                logger.logError(
                    "Erro no metodo: pd.registraCorteNoBanco() -> Erro ao tentar transmissao para o Banco de dados Local!    -    Details: {}"
                    .format(str(e)))
                return False

            try:
                conOrigem.commit()
                bancoLocal.conexao.commit()
                conOrigem.close()
                bancoLocal.conexao.close()

                return True
            except Exception as e:
                logger.logError(
                    "Erro ao commitar registro de corte nos bancos!    -    Details: {}"
                    .format(str(e)))

        except Exception as e:
            logger.logError(
                "Erro ao registrar o corte nos bancos!    -    Details: {} ".
                format(str(e)))
            return False
Пример #30
0
    def followingLimitOrder(self,
                            type,
                            asset,
                            currency,
                            orderQuantity,
                            restricted=True,
                            initial_price=None,
                            orderID=None,
                            note=None):
        try:

            asset = self.interpretType(asset)
            currency = self.interpretType(currency)
            type = self.interpretType(type)

            previousLimitPrice = None
            initialPrice = initial_price
            if initialPrice == None:
                initialPrice = self.getCurrentPrice(asset, currency)
                previousLimitPrice = initialPrice

            while self.isInRange(type, initialPrice, previousLimitPrice,
                                 self.maximumDeviationFromPrice,
                                 restricted) and orderQuantity != 0:
                orderQuantity = self.quantityLeftInOrder(
                    orderID, orderQuantity)
                if orderQuantity != 0:
                    res = self.sendLimitOrder(
                        type,
                        asset,
                        currency,
                        orderQuantity,
                        orderID,
                        note,
                        previousLimitPrice=previousLimitPrice)
                    if not hasattr(res, 'orderID'):
                        orderQuantity = self.quantityLeftInOrder(
                            orderID, orderQuantity)
                        orderID = None
                        previousLimitPrice = self.getCurrentPrice(
                            asset, currency)
                    else:
                        orderID = res.orderID
                        previousLimitPrice = res.limitPrice
                        sleep(self.delayBetweenLimitOrder)

            if self.orderOpen(orderID):
                self.closeLimitOrder(orderID)
            return True

        except:
            tb = traceback.format_exc()
            logger.logError(tb)
            if self.attemptsLeft == 0:
                self.attemptsLeft = self.attemptsTotal
                return None
            sleep(self.delayBetweenAttempts)
            self.connect()
            currentPrice = self.getCurrentPrice(asset, currency)
            self.attemptsLeft = self.attemptsLeft - 1
            self.followingLimitOrder(type, asset, currency, orderQuantity,
                                     restricted, initialPrice, orderID)