<commit_before>from . import __Command
import Database
import Label
import collections
import serial
import select
import sys
import re
import copy


class Scan(__Command.Command):

    def __init__(self, partDB):
        super().__init__(partDB)

    @staticmethod
    def getParserHelp():
        return "Scan a part."

    @staticmethod
    def configureArgumentSubParser(subparser):
        super(__class__, Scan).configureArgumentSubParser(subparser)

        subparser.add_argument('-d', '--device',
                               dest='device',
                               metavar='device',
                               required=True,
                               help='Device to scan from.')

        subparser.add_argument('--confirm-quantity',
                               dest='confirmQuantity',
                               action='store_true',
                               help='Confirm quantity before adding item to database.')

        subparser.add_argument('--print-label',
                               dest='printLabel',
                               action='store_true',
                               help='Print label for item after adding it to database.')

        subparser.add_argument('--printer-name',
                               dest='printerName',
                               metavar='printer-name',
                               help="Name of printer to print on.",
                               default='zebra')

    def scan(self):
        ser = serial.Serial(self.partDB.args.device, timeout=0.05)
        ser.flushInput()

        while True:
            data = ser.read(1000)

            if len(data) > 0:
                break

        ser.close()

        return(data)

    def scanAndInput(self):
        ser = serial.Serial(self.partDB.args.device, timeout=0.05)
        ser.flushInput()

        while True:
            i, o, e = select.select([sys.stdin], [], [], 0.05)
            serialData = ser.read(1000)

            if (i):
                keyboardData = sys.stdin.readline()[:-1].encode('utf_8')
                return keyboardData

            if len(serialData) > 0:
                print(serialData.decode('utf_8'))
                ser.close()
                return serialData

    def handleScannedPartId(self, partId):
        result = self.partDB.db.query(
            filter=lambda k, v: (
                k == partId))

        if len(result) == 0:
            raise Exception('Part ID %s not found in database.' % (partId))

        data = result[partId]

        self.partDB.displayItem(data)

        print('Quantity is %u. Scan/Enter new quantity (+/- for relative) or press return:' %
              data['quantity'])
        quantityInput = self.scanAndInput()<commit_msg>Adds 'fix' option to scan command to fix database issues<commit_after>from . import __Command
import Database
import Label
import collections
import serial
import select
import sys
import re
import copy


class Scan(__Command.Command):

    def __init__(self, partDB):
        super().__init__(partDB)

    @staticmethod
    def getParserHelp():
        return "Scan a part."

    @staticmethod
    def configureArgumentSubParser(subparser):
        super(__class__, Scan).configureArgumentSubParser(subparser)

        subparser.add_argument('-d', '--device',
                               dest='device',
                               metavar='device',
                               required=True,
                               help='Device to scan from.')

        subparser.add_argument('--confirm-quantity',
                               dest='confirmQuantity',
                               action='store_true',
                               help='Confirm quantity before adding item to database.')

        subparser.add_argument('--print-label',
                               dest='printLabel',
                               action='store_true',
                               help='Print label for item after adding it to database.')

        subparser.add_argument('--printer-name',
                               dest='printerName',
                               metavar='printer-name',
                               help="Name of printer to print on.",
                               default='zebra')

        subparser.add_argument('--fix',
                               dest='fix',
                               action='store_true',
                               help='Try to fix database information.')

    def scan(self):
        ser = serial.Serial(self.partDB.args.device, timeout=0.05)
        ser.flushInput()

        while True:
            data = ser.read(1000)

            if len(data) > 0:
                break

        ser.close()

        return(data)

    def scanAndInput(self):
        ser = serial.Serial(self.partDB.args.device, timeout=0.05)
        ser.flushInput()

        while True:
            i, o, e = select.select([sys.stdin], [], [], 0.05)
            serialData = ser.read(1000)

            if (i):
                keyboardData = sys.stdin.readline()[:-1].encode('utf_8')
                return keyboardData

            if len(serialData) > 0:
                print(serialData.decode('utf_8'))
                ser.close()
                return serialData

    def handleScannedPartId(self, partId):
        result = self.partDB.db.query(
            filter=lambda k, v: (
                k == partId))

        if len(result) == 0:
            raise Exception('Part ID %s not found in database.' % (partId))

        if self.partDB.args.fix:
            result = self.partDB.db.query(
                filter=lambda k, v: (
                    k == partId))
            data = result[partId]

            distributorMatches = {}
            for distributorName in data['distributor']:
                minimumData = {
                    'distributor': {
                        distributorName: {
                            'distributorPartNumber': data['distributor'][distributorName]['distributorPartNumber']
                        }
                    }
                }

                newData = self.partDB.distributors[
                    distributorName].getData(minimumData)

                Database.mergeData(data, newData, override=True)

            self.partDB.db.update(data)

            if len(result) > 0:
                if (self.partDB.args.printLabel):
                    label = Label.Label()
                    label.createLabelFromData(data=data)
                    label.cupsPrint(printerName=self.partDB.args.printerName)
            else:
                raise Exception(
                    'ID %s not found in database.' %
                    (self.partDB.args.id))

            return

        data = result[partId]

        self.partDB.displayItem(data)

        print('Quantity is %u. Scan/Enter new quantity (+/- for relative) or press return:' %
              data['quantity'])
        quantityInput = self.scanAndInput()
{'fraction_non_alphanumeric': 0.1009016745384285, 'fraction_numerical': 0.006726778302561901, 'mean_word_length': 1.38173142467621, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 8, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1252777', 'n_tokens_mistral': 1823, 'n_tokens_neox': 1688, 'n_words': 386}