Beispiel #1
0
def check_census_case_fields(context):
    test_helper.assertTrue(context.case_details['caseRef'])
    test_helper.assertEquals(len(context.case_details['caseRef']), 10)
    test_helper.assertTrue(luhn.verify(context.case_details['caseRef']))

    test_helper.assertTrue(context.case_details['estabUprn'])
    test_helper.assertTrue(context.case_details['estabType'])
    test_helper.assertTrue(context.case_details['uprn'])
    test_helper.assertTrue(context.case_details['collectionExerciseId'])
    test_helper.assertTrue(context.case_details['createdDateTime'])
    test_helper.assertTrue(context.case_details['lastUpdated'])
    test_helper.assertTrue(context.case_details['addressLine1'])
    test_helper.assertTrue(context.case_details['addressLine2'])
    test_helper.assertTrue(context.case_details['addressLine3'])
    test_helper.assertTrue(context.case_details['townName'])
    test_helper.assertTrue(context.case_details['postcode'])
    test_helper.assertTrue(context.case_details['addressLevel'])
    test_helper.assertTrue(context.case_details['abpCode'])
    test_helper.assertTrue(context.case_details['region'])
    test_helper.assertTrue(context.case_details['latitude'])
    test_helper.assertTrue(context.case_details['longitude'])
    test_helper.assertTrue(context.case_details['oa'])
    test_helper.assertTrue(context.case_details['lsoa'])
    test_helper.assertTrue(context.case_details['msoa'])
    test_helper.assertTrue(context.case_details['lad'])
    test_helper.assertTrue(context.case_details['id'])
    test_helper.assertTrue(context.case_details['addressType'])
    test_helper.assertTrue(context.case_details['caseType'])
    test_helper.assertEqual(context.case_details['surveyType'], "CENSUS")
    test_helper.assertFalse(context.case_details['handDelivery'])
    def do_transfer(self):
        self.card_number_check = input("Enter your card number:")
        self.cur.execute(f'SELECT number FROM card')
        temp_info_transfer = self.cur.fetchall()
        if int(self.card_number_check) == int(self.card_number):
            print("You can't transfer money to the same account!")
            self.banking_menu()
        elif (self.card_number_check,) in temp_info_transfer:
            self.cur.execute(f'SELECT balance FROM card where number = {self.card_number}')
            temp_info_balance_transfer = self.cur.fetchone()
            self.temp_info_balance_transfer_check = temp_info_balance_transfer[0]
            self.amount_transfer = int(input("Enter how much money you want to transfer:"))
            if self.amount_transfer > self.temp_info_balance_transfer_check:
                print("Not enough money")
                self.banking_menu()
            elif self.amount_transfer <= self.temp_info_balance_transfer_check:
                self.cur.execute(f'UPDATE card SET balance = (balance + {self.amount_transfer}) WHERE number = ({self.card_number_check});')
                self.cur.execute(f'UPDATE card set balance = (balance - {self.amount_transfer}) WHERE number = ({self.card_number});')
                self.conn.commit()
                print("Success")
                self.banking_menu()

        elif luhn.verify(self.card_number_check) is False:
            print("Probably you made a mistake in the card number. Please try again!")
            self.banking_menu()
        elif (self.card_number_check,) not in temp_info_transfer:
            print("Such a card does not exist.")
            self.banking_menu()
Beispiel #3
0
 def on_input(self, **kwargs):
     """ 신용 카드 번호 체크 이벤트 """
     if (verify(kwargs['card_number']) == False):
         CreditError.register( \
             CreditError.CARD_NUMBER_ERROR_CODE, \
             CreditError.CARD_NUMBER_ERROR_MSG)
         kwargs['template'].input_error(**kwargs)
Beispiel #4
0
 def creditCardDetection(self, group, regex, lang, text, detec_state):
     res = re.compile(regex).findall(text)
     if res:
         for cb in res:
             sanatized = cb.replace(' ', '')
             if not sanatized.startswith("0") and luhn.verify(sanatized):
                 detec_state = self.updateState(group=group, word=cb, lang="", detec_state=detec_state)
     return detec_state
Beispiel #5
0
def _validate_case(parsed_body):
    test_helper.assertEqual('CENSUS',
                            parsed_body['payload']['collectionCase']['survey'])
    actual_case_ref = parsed_body['payload']['collectionCase']['caseRef']
    test_helper.assertEqual(10, len(actual_case_ref))
    parse_datetime(parsed_body['payload']['collectionCase']['createdDateTime'])
    parse_datetime(parsed_body['payload']['collectionCase']['lastUpdated'])

    test_helper.assertTrue(luhn.verify(actual_case_ref))
Beispiel #6
0
 def guarda(self):
     '''Guarda Icc a base de datos, se requiere de Id, Agencia, Caja\n
   Si no existe, se crea nuevo registro\n
   Exito: True'''
     if self.agencia != '' or self.caja != '' or verify(self.id) == False:
         self.modificado = hoy
         existeRegistro = db.find_one({'_id': self.id})
         #Si existe registro
         if existeRegistro:
             #Revisa portacione y revisiones
             if 'revisiones' in existeRegistro:
                 self.revisiones = existeRegistro['revisiones']
             if 'portaciones' in existeRegistro:
                 self.portaciones = existeRegistro['portaciones']
             db.update_one({'_id': self.id}, {
                 '$set': {
                     'agencia': self.agencia,
                     'modificado': self.modificado,
                     'estado': self.estado,
                     'caja': self.caja,
                 }
             })
             print(
                 Color('{autobgblack}{hiyellow}' + 'GUARDADO'.center(80) +
                       '{/yellow}{/bgblack}'))
             self.cantEnCaja = str(self.cantidadEnCaja(self.caja))
             self.muestraDatos()
         else:
             #Si no existe registro, pone datos por default
             if self.estado == '':
                 self.estado = 'DESCONOCIDO'
             if self.creado == '':
                 self.creado = hoy
             db.insert_one({
                 "_id": self.id,
                 "agencia": self.agencia,
                 "creado": self.creado,
                 "modificado": self.modificado,
                 "estado": self.estado,
                 "caja": self.caja
             })
             print(
                 Color('{hibgyellow}{hiblack}' +
                       'REGISTRO CREADO'.center(80) +
                       '{/black}{/bgyellow}'))
             self.cantEnCaja = str(self.cantidadEnCaja(self.caja))
             self.muestraDatos()
         return True
     else:
         print(
             Color('{bgred}{hiwhite}' + 'NO SE PUDO GUARDAR'.center(50) +
                   '{/white}{/bgred}'))
         print(
             Color('{bgred}{hiwhite}' + 'DATOS INCOMPLETOS'.center(50) +
                   '{/white}{/bgred}'))
         return False
Beispiel #7
0
 def creditCardDetection(self, group, regex, lang, text, detec_state):
     res = re.compile(regex).findall(text)
     if res:
         for cb in res:
             if luhn.verify(cb.replace(' ', '')):
                 detec_state = self.updateState(group=group,
                                                word=cb,
                                                lang="",
                                                detec_state=detec_state)
     return detec_state
Beispiel #8
0
def valid():
    tests = [
        ("0000000000000000", True),
        ("4111111111111111", True),
        ("5500000000000004", True),
        ("6250941006528599", True),
        ("5425233430109903", True),
        ("6034883265619896", True),
        ("4242424242424249", False),
    ]

    for t in tests:
        num, res = t
        assert luhn.verify(num)
Beispiel #9
0
def add_creditcard():
    '''
    Add a credit card number to the system.
    Returns a token associated with the credit card number.
    '''
    if not request.json or not 'credit-card' in request.json:
        abort(400)

    cc = request.json['credit-card']
    ccnum = ''.join(filter(str.isdigit, cc))
    if not verify(ccnum):
        abort(400)

    token = str(uuid.uuid4())
    result = redis_client.set(token, cc)
    return jsonify({ 'token': token }), 200
Beispiel #10
0
def cc_verify():
    from luhn import verify
    from luhn import append
    print('1.APPEND/CORRECT')
    print('2.VERIFY YOUR CREDIT CARD')
    a = input('Please Choose Your Option: ')
    if a == '1':
        result1 = append(input('Enter Your Card: '))
        print(result1)
        return cc_verify()
    elif a == '2':
        result2 = verify(input('Enter Your Card: '))
        print(result2)
        return cc_verify()
    else:
        print('Unknown Input Please try Again....')
        return cc_verify()
Beispiel #11
0
    def test_checkin_code(self):
        attendee = Attendee.objects.create(user=self.user, event=self.event)
        self.assertEqual(str(attendee.user), USER_EMAIL)
        self.assertTrue(len(attendee.checkin_code) > 0, "has a checkin-code")
        self.assertTrue(luhn.verify(attendee.checkin_code),
                        "checkin-code is valid")
        self.assertIsNone(attendee.checked_in, "is not checked in")

        u2 = DevDayUser.objects.create_user("*****@*****.**", "foo")
        a2 = Attendee.objects.create(user=u2, event=self.event)
        self.assertNotEqual(attendee.checkin_code, a2.checkin_code)
        a3 = Attendee.objects.get_by_checkin_code_or_email(
            attendee.checkin_code, self.event)
        self.assertEqual(attendee, a3)

        attendee.check_in()
        self.assertIsNotNone(attendee.checked_in)
        with self.assertRaises(IntegrityError):
            attendee.check_in()
Beispiel #12
0
 def _add(self, name, card_number, limit):
     """
     This method is used to add a new credit for a given name
     All new cards start with $0 balance
     """
     if not verify(card_number) or not self._verify_unique_card_number(card_number):
         # Invalid/Existing card number
         self.summary[name] = "error"
         return
     if name in self.accounts:
         # Add new card to existing user
         self.accounts[name].append(
             {"card_number": card_number, "limit": int(limit[1:]), "balance": 0}
         )
     else:
         # Initiate new user and new card
         self.accounts[name] = [
             {"card_number": card_number, "limit": int(limit[1:]), "balance": 0}
         ]
Beispiel #13
0
def do_transfer():  # using login_cardnum
    user_input_transfer = input("1. Enter card number:\n")

    if luhn.verify(user_input_transfer):
        cur.execute("SELECT number FROM card")
        result = cur.fetchall()
        result_flat_list = []
        for sublist in result:
            for item in sublist:
                result_flat_list.append(item)
        if user_input_transfer not in result_flat_list:
            print("Such a card does not exist.\n")    # this is used twice - method?
            check_balance()
        else:
            user_input_transfer_amount = input("Enter how much money you want to transfer:\n")
    else:
        print("Probably you made a mistake in the card number. Please try again!\n")
        check_balance()

    cur.execute('SELECT balance FROM card WHERE number = ?', (login_cardnum,))
    balance_result = cur.fetchone()
    if int(user_input_transfer_amount) > balance_result[0]:
        print("Not enough money!")
        check_balance()
    else:
        cur.execute('SELECT balance FROM card WHERE number = ?', (user_input_transfer,))
        balance_result = cur.fetchone()
        new_transfer_balance = int(user_input_transfer_amount) + balance_result[0]
        cur.execute('UPDATE card SET balance = ? WHERE number = ?', (new_transfer_balance, user_input_transfer,))
        conn.commit()
        print("Success!\n")
        #  deduct amount and commit changes
        cur.execute('SELECT balance FROM card WHERE number = ?', (login_cardnum,))
        balance_result = cur.fetchone()
        post_transfer_balance = balance_result[0] - int(user_input_transfer_amount)
        cur.execute('UPDATE card SET balance = ? WHERE number = ?', (post_transfer_balance, login_cardnum,))
        conn.commit()
        check_balance()
Beispiel #14
0
 def validate_credit_card_number(self, value):
     if not luhn.verify(str(value)):
         raise ValidationError("CreditCard number is invalid")
Beispiel #15
0
 def validate_credit_card_number(self, value):
     if not luhn.verify(str(value)) or len(str(value)) != 16:
         logger.error("CreditCard number is invalid")
         raise ValidationError("CreditCard number is invalid")
def check_credit_card_number(credit_card_number):
    return verify(credit_card_number)
Beispiel #17
0
import luhn

for i in range(5432100000001234, 5432109999991234, 10000):
    if i % 123457 == 0 and luhn.verify(str(i)):
        print("CTFlearn{{{}}}".format(i))
""" 
from itertools import *
def convertTuple(tup):
    str = ''.join(tup)
    return str


for i in product('0123456789', repeat=6):
    str = convertTuple(i)
    number = '543210' + str + '1234'
    mulnum = int(number)
    if (verify(number)) and (mulnum % 123457 == 0):
        print("CTFlearn{{{}}}".format(number)) """
Beispiel #18
0
 def add(self, name, number, limit):
     self.accounts[name] = {'is_valid': luhn.verify(number),
                            'limit': money.unformat(limit),
                            'balance': 0}
Beispiel #19
0
 def valid(self):
     if (not self.number) or (not self.number.isdigit()):
         return False
     return luhn.verify(self.number)
    test_helper.assertEqual('CENSUS', action_instruction['surveyName'])
    test_helper.assertEqual(case['address']['estabType'],
                            action_instruction['estabType'])
    test_helper.assertEquals(case['ceExpectedCapacity'],
                             int(action_instruction['ceExpectedCapacity']))
    test_helper.assertEquals(case['ceActualResponses'],
                             int(action_instruction['ceActualResponses']))
    test_helper.assertEquals(case['handDelivery'],
                             action_instruction['handDeliver'])
    test_helper.assertEquals(case['caseRef'], action_instruction['caseRef'])
    test_helper.assertEquals(len(action_instruction['caseRef']), 10)
    test_helper.assertEquals(case['address']['uprn'],
                             action_instruction['uprn'])
    test_helper.assertEquals(case['address']['estabUprn'],
                             action_instruction['estabUprn'])
    test_helper.assertTrue(luhn.verify(action_instruction['caseRef']))


def field_work_cancel_callback(ch, method, _properties, body, context):
    action_cancel = json.loads(body)

    if not action_cancel['actionInstruction'] == 'CANCEL':
        ch.basic_nack(delivery_tag=method.delivery_tag)
        test_helper.fail(
            f'Unexpected message on {Config.RABBITMQ_OUTBOUND_FIELD_QUEUE} case queue. '
            f'Got "{action_cancel["actionInstruction"]}", wanted "CANCEL"')

    context.addressType = action_cancel['addressType']
    context.fwmt_emitted_case_id = action_cancel['caseId']
    context.field_action_cancel_message = action_cancel
    ch.basic_ack(delivery_tag=method.delivery_tag)
Beispiel #21
0
 def validate_card(cls, card_number) -> bool:
     return verify(card_number)
Beispiel #22
0
def test_valid():
    assert luhn.verify('356938035643809')
Beispiel #23
0
def verify_npi(number):
    prefixed_number = "%s%s" % (LUHN_PREFIX, number)
    return verify(prefixed_number)
Beispiel #24
0
 def check(self, pan: str) -> bool:
     try:
         return luhn.verify(pan)
     except ValueError:
         return False
Beispiel #25
0
def test_invalid():
    assert not luhn.verify('4222222222222222')
Beispiel #26
0
def test_invalid():
    assert not luhn.verify('4222222222222222')
Beispiel #27
0
def looks_like_a_code(string):
    return len(string) == 6 and string.isdigit() and luhn.verify(string)
Beispiel #28
0
def is_valid_sa_id(id):
    return luhn.verify(id) and len(id) == 13
Beispiel #29
0
def npi_is_valid(npi):
    LUHN_PREFIX = "80840"
    prefixed_number = "%s%s" % (LUHN_PREFIX, npi)
    return verify(prefixed_number)
Beispiel #30
0
def test_valid():
    assert luhn.verify('356938035643809')
Beispiel #31
0
    def validate(self) -> bool:

        return bool(verify(self.id_number))
text_file = open(wd+'\salt\\'+'salt'+salt[:5]+'.txt','w+')
text_file.write(salt)
text_file.close()

# STEP 3: add prefix
# define 2 digit prefix for id - should evaluate if len is 2
prefix = input('Define a 1 digit prefix number for id ')
idbase['hashedid11'] = str(prefix) + idbase['hashedid9']

# STEP 4
# generate the luhn check digit in new column for visability (will be dropped)
idbase['luhn1'] = idbase['hashedid11'].apply(lambda x: luhn.generate(x))
 # append the check digit
idbase['hashedid12'] = idbase['hashedid11'].apply(lambda x: luhn.append(x))
# test verify
idbase['luhnvalid'] = idbase['hashedid12'].apply(lambda x: luhn.verify(x))
# check if any invalid numbers
if idbase.luhnvalid.all() == True:
    print('no issue with check digits')
elif idbase.luhnvalid.all() == False:
    sys.exit('STOP - issue with luhn check digit')
    
# STEP 5: cleanup and strip down
# rename new id column
idcolname = input('specify column name for new ID... ')
idbase.rename(columns={'hashedid12':idcolname},inplace=True)
# strip down file
sailpreg = idbase[[idtohash, idcolname]]
# create input for file name
filename = input('please define a filename for output... ')
# export as csv
Beispiel #33
0
def luhn_check(field, value, error):
    if not verify(value):
        error(field, "does not pass Luhn check")