Latest Threat Research:SANDWORM_MODE: Shai-Hulud-Style npm Worm Hijacks CI Workflows and Poisons AI Toolchains.Details →
Socket
Book a DemoInstallSign in
Socket

checkdigit

Package Overview
Dependencies
Maintainers
1
Versions
16
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

checkdigit - npm Package Compare versions

Comparing version
0.3.0
to
0.3.1
+115
checkdigit/verhoeff.py
# /usr/bin/env python
# This file is part of checkdigit.
# checkdigit is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# checkdigit is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with checkdigit. If not, see <http://www.gnu.org/licenses/>.
"""The first check digit algorithm to detect all transposition and single digit errors.
Developed by Jacobus Verhoeff and published in 1969.
This particular implementation uses a table-based algorithm.
"""
from checkdigit._data import TupleType, cleanse, missing_template
DIHEDRAL_CAYLEY: TupleType[TupleType[int]] = (
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9),
(1, 2, 3, 4, 0, 6, 7, 8, 9, 5),
(2, 3, 4, 0, 1, 7, 8, 9, 5, 6),
(3, 4, 0, 1, 2, 8, 9, 5, 6, 7),
(4, 0, 1, 2, 3, 9, 5, 6, 7, 8),
(5, 9, 8, 7, 6, 0, 4, 3, 2, 1),
(6, 5, 9, 8, 7, 1, 0, 4, 3, 2),
(7, 6, 5, 9, 8, 2, 1, 0, 4, 3),
(8, 7, 6, 5, 9, 3, 2, 1, 0, 4),
(9, 8, 7, 6, 5, 4, 3, 2, 1, 0),
)
INVERSE: TupleType[int] = (0, 4, 3, 2, 1, 5, 6, 7, 8, 9)
PERMUTATION: TupleType[TupleType[int]] = (
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9),
(1, 5, 7, 6, 2, 8, 3, 0, 9, 4),
(5, 8, 0, 3, 7, 9, 6, 1, 4, 2),
(8, 9, 1, 6, 0, 4, 3, 5, 2, 7),
(9, 4, 5, 3, 1, 2, 6, 8, 7, 0),
(4, 2, 8, 6, 5, 7, 3, 9, 0, 1),
(2, 7, 9, 3, 8, 0, 6, 4, 1, 5),
(7, 0, 4, 6, 9, 1, 3, 2, 5, 8),
)
def calculate(data: str) -> str:
"""Calculates a Verhoeff check digit.
Args:
data: A block of data without the check digit
Returns:
str: A string representing the missing check digit
Examples:
>>> from checkdigit import verhoeff
>>> verhoeff.calculate('236')
'3'
>>> verhoeff.calculate('123456')
'8'
>>> verhoeff.calculate('1337')
'5'
"""
checksum = 0
data = cleanse(data)
# Start counting from 1 (hence enumerate(..., 1))
for count, value in enumerate(data[::-1], 1):
checksum = DIHEDRAL_CAYLEY[checksum][PERMUTATION[count % 8][int(value)]]
return str(INVERSE[checksum])
def validate(data: str) -> bool:
"""Validates a Verhoeff check digit.
Args:
data: A string of characters representing a full Verhoeff code.
Returns:
bool: A boolean representing whether the check digit validates the data or not.
Examples:
>>> from checkdigit import verhoeff
>>> verhoeff.validate('585649')
True
>>> verhoeff.validate('13735')
False
"""
return calculate(data[:-1]) == data[-1]
def missing(data: str) -> str:
"""Calculates a missing digit in a Verhoeff code.
Args:
data: A string of characters representing a full Verhoeff code
with a question mark for a missing character
Returns:
str: The missing value that should’ve been where the question mark was
Examples:
>>> from checkdigit import verhoeff
>>> verhoeff.missing("23?3")
'6'
>>> verhoeff.missing("999?")
'8'
>>> verhoeff.missing("123")
'Invalid'
"""
return missing_template(data, "verhoeff")
+119
-2

@@ -16,9 +16,17 @@ # /usr/bin/env python

"""Data cleansing.
"""Generic helper methods.
This module contains functions that help to format data so that it can be interpreted easier.
It also helps deal with type hints in different versions, as well as with general refactoring.
"""
import importlib
import sys
from typing import Any
# ------------------------------------------------------------------------
# DATA CLEANSING FUNCTIONS
# ------------------------------------------------------------------------
def cleanse(data: str) -> str:

@@ -39,1 +47,110 @@ """Removes Hyphens and Spaces so that data can be parsed."""

return "0" if digit == 11 else str(digit)
# ------------------------------------------------------------------------
# PYTHON TYPING IMPORTS
# ------------------------------------------------------------------------
# Deals with typing module being depreciated
PYTHON_AT_LEAST_3_9 = sys.version_info >= (3, 9)
# Use typing module below python 3.9
# Initialised first with Any to make mypy happy
TupleType: Any = None
# Don't count code coverage since different python versions
# won't run different parts of code
if PYTHON_AT_LEAST_3_9: # pragma: no cover
TupleType = tuple
else: # pragma: no cover
from typing import Tuple
TupleType = Tuple
# ------------------------------------------------------------------------
# REFACTORED MISSING METHOD
# ------------------------------------------------------------------------
# Inspired by https://stackoverflow.com/a/48981829
# Pytest coverage not applicable since these are just types.
class ModuleInterface: # pragma: no cover
"""Sets the types of the various functions that are imported by missing_template."""
# The data parameter isn't used, although is required to set the type.
# pylint: disable=unused-argument
@staticmethod
def validate(data: str) -> bool:
"""Validates check digits in a full block of data.
Args:
data: A string of data representing a full code
Returns:
bool: A boolean representing whether the data is valid or not.
"""
...
@staticmethod
def calculate(data: str) -> str:
"""Calculates check digits for a block of data.
Args:
data: A block of data with a missing check digit
Returns:
str: The missing check digit
"""
...
def import_module_with_interface(module: str) -> ModuleInterface:
"""Imports the module,, and sets its type to ModuleInterface to play nice with mypy.
Args:
module: The checkdigit module to import
Returns:
ModuleInterface: The imported module with the custom validate and calculate types.
"""
# Type ignore since the type is being reassigned to ModuleInterface
return importlib.import_module(f"checkdigit.{module}") # type: ignore
def missing_template(data: str, module: str) -> str:
"""This acts as a general template for the "missing digit" methods.
Many of the "missing" methods have the same general format.
i.e. brute force all the digits from 0-9. This template puts
all the logic into one place.
This also has the advantage that the docstrings of the original
missing methods are maintained.
Args:
data: A string of characters representing a full code
with a question mark representing a missing character
module: The type of code (e.g. isbn, crc, etc). This is
imported from the checkdigit folder
Returns:
str: The missing value that should've been where the question mark was
"""
# Imports the relevant module for the data type
data_type = import_module_with_interface(module)
# data_type = __import__(f"checkdigit.{module}", fromlist=["validate, calculate"])
# We already have an efficient method for the check digit
if data[-1] == "?":
# Remove question mark check digit
return data_type.calculate(data[:-1])
# We've dealt with the check digit, so X can't be an option
# Brute force all the possible numbers (0-9 inclusive)
for option in (data.replace("?", str(i)) for i in range(10)):
# Validate the new option
if data_type.validate(option):
# Replace question mark with new value
return option[data.index("?")]
return "Invalid"
+3
-6

@@ -25,3 +25,2 @@ # /usr/bin/env python

"""

@@ -53,7 +52,5 @@ from checkdigit._data import cleanse

while len(bitarray) != len(polynomial) - 1:
for (bit, _) in enumerate(polynomial):
if polynomial[bit] == bitarray[bit]:
bitarray[bit] = "0" # XOR calculation
else:
bitarray[bit] = "1"
for position, bit in enumerate(polynomial):
# XOR calculation
bitarray[position] = "0" if bit == bitarray[position] else "1"
while bitarray[0] == "0" and len(bitarray) >= len(polynomial):

@@ -60,0 +57,0 @@ bitarray.pop(0)

@@ -16,6 +16,8 @@ # /usr/bin/env python

"""GS1 Standards.
"""Global Standards One.
This includes support for the following:
GS1 provides a variety of different standards
This implementation includes support for the following:
- GSIN

@@ -35,3 +37,3 @@ - GLN

from checkdigit._data import cleanse, convert
from checkdigit._data import cleanse, convert, missing_template

@@ -118,9 +120,2 @@

"""
data = cleanse(data)
for poss_digit in range(10): # Brute Force the 10 options
option = convert(poss_digit)
# tests it with the generated number
# If this fails, the next number is tried
if validate(data.replace("?", option)):
return option
return "Invalid"
return missing_template(data, "gs1")

@@ -23,3 +23,3 @@ # /usr/bin/env python

from checkdigit._data import cleanse, convert
from checkdigit._data import cleanse, convert, missing_template

@@ -111,14 +111,2 @@

"""
# We already have an efficient method for the check digit
if data[-1] == "?":
# Remove question mark check digit
return calculate(data[:-1])
# We've dealt with the check digit, so X can't be an option
# Brute force all the possible numbers (0-9 inclusive)
for option in (data.replace("?", str(i)) for i in range(10)):
# Validate the new option
if validate(option):
# Replace question mark with new value
return option[data.index("?")]
return "Invalid"
return missing_template(data, "isbn")

@@ -23,3 +23,3 @@ # /usr/bin/env python

from checkdigit._data import cleanse
from checkdigit._data import cleanse, missing_template

@@ -106,6 +106,2 @@

"""
data = cleanse(data)
for poss_digit in range(10): # Brute Force the 10 options
if validate(data.replace("?", str(poss_digit))):
return str(poss_digit)
return "Invalid"
return missing_template(data, "luhn")
Metadata-Version: 2.1
Name: checkdigit
Version: 0.3.0
Version: 0.3.1
Summary: A check digit library for data validation

@@ -106,2 +106,3 @@ Home-page: https://checkdigit.rtfd.io

* `Luhn <https://checkdigit.readthedocs.io/en/latest/_autosummary/checkdigit.luhn.html#module-checkdigit.luhn>`_
* `Verhoeff <https://checkdigit.readthedocs.io/en/latest/_autosummary/checkdigit.verhoeff.html#module-checkdigit.verhoeff>`_

@@ -108,0 +109,0 @@ For each of these formats, we provide functions to validate them and calculate missing digits.

@@ -80,2 +80,3 @@ .. image:: https://raw.githubusercontent.com/harens/checkdigit/master/art/logo.png

* `Luhn <https://checkdigit.readthedocs.io/en/latest/_autosummary/checkdigit.luhn.html#module-checkdigit.luhn>`_
* `Verhoeff <https://checkdigit.readthedocs.io/en/latest/_autosummary/checkdigit.verhoeff.html#module-checkdigit.verhoeff>`_

@@ -82,0 +83,0 @@ For each of these formats, we provide functions to validate them and calculate missing digits.

[tool.poetry]
name = "checkdigit"
version = "0.3.0"
version = "0.3.1"
description = "A check digit library for data validation"

@@ -30,11 +30,11 @@ authors = ["harens <harensdeveloper@gmail.com>"]

error404 = "^1.1.8a0"
pylint = "^2.8.3"
mypy = "^0.902"
pylint = "^2.9.5"
mypy = "^0.910"
black = "^20.8b1"
isort = "^5.8.0"
isort = "^5.9.2"
pydocstyle = "^6.1.1"
coverage = "^5.5"
pre-commit = "^2.13.0"
pyupgrade = "^2.19.4"
Sphinx = "^4.0.2"
pyupgrade = "^2.23.0"
Sphinx = "^4.1.1"
sphinx-autobuild = "^2021.3.14"

@@ -41,0 +41,0 @@ pytest = "^6.2.4"

@@ -12,5 +12,5 @@ # -*- coding: utf-8 -*-

'name': 'checkdigit',
'version': '0.3.0',
'version': '0.3.1',
'description': 'A check digit library for data validation',
'long_description': ".. image:: https://raw.githubusercontent.com/harens/checkdigit/master/art/logo.png\n :alt: checkdigit logo\n :target: https://github.com/harens/checkdigit\n :align: center\n\n|\n\n.. image:: https://img.shields.io/github/workflow/status/harens/checkdigit/Tests?logo=github&style=flat-square\n :alt: GitHub Tests status\n :target: https://github.com/harens/checkdigit/actions\n\n.. image:: https://img.shields.io/codecov/c/github/harens/checkdigit?logo=codecov&style=flat-square\n :alt: Codecov\n :target: https://app.codecov.io/gh/harens/checkdigit\n\n.. image:: https://img.shields.io/pypi/dm/checkdigit?logo=python&logoColor=white&style=flat-square\n :alt: PyPi - Downloads\n :target: https://pepy.tech/project/checkdigit\n\n.. image:: https://img.shields.io/codefactor/grade/github/harens/checkdigit?logo=codefactor&style=flat-square\n :alt: CodeFactor Grade\n :target: https://www.codefactor.io/repository/github/harens/checkdigit/\n\n.. image:: https://img.shields.io/lgtm/grade/python/github/harens/checkdigit?logo=lgtm&style=flat-square\n :alt: LGTM Grade\n :target: https://lgtm.com/projects/g/harens/checkdigit/\n\n=========\n\n.. image:: https://repology.org/badge/vertical-allrepos/python:checkdigit.svg\n :alt: checkdigit repology\n :target: https://repology.org/project/python:checkdigit/versions\n :align: right\n\n**checkdigit** is a pure Python library built for identification numbers.\nYou want to validate a credit card number, or maybe even calculate a missing digit on an ISBN code?\nWe've got you covered šŸ˜Ž.\n\nWant to know more? Check out the `API Reference and documentation <https://checkdigit.readthedocs.io/en/latest/reference.html>`_!\n\nInstallation\n------------\n\n`MacPorts <https://ports.macports.org/port/py-checkdigit/summary>`_ šŸŽ\n*************************************************************************\n\n.. code-block::\n\n sudo port install py-checkdigit\n\n`PyPi <https://pypi.org/project/checkdigit/>`_ šŸ\n**************************************************\n\n.. code-block::\n\n pip install checkdigit\n\n✨ Features\n------------\n\n* `PEP 561 compatible <https://www.python.org/dev/peps/pep-0561>`_, with built in support for type checking.\n* Capable of calculating missing digits or validating a block of data.\n* Extensive in-code comments and docstrings to explain how it works behind the scenes. \U0001fa84\n\nāœ… Supported Formats\n---------------------\n\n* `Even/Odd binary parity <https://checkdigit.readthedocs.io/en/latest/_autosummary/checkdigit.parity.html#module-checkdigit.parity>`_\n* `CRC <https://checkdigit.readthedocs.io/en/latest/_autosummary/checkdigit.crc.html#module-checkdigit.crc>`_\n (credit to `@sapieninja <https://github.com/sapieninja>`_)\n* `GS1 Standards <https://checkdigit.readthedocs.io/en/latest/_autosummary/checkdigit.gs1.html#module-checkdigit.gs1>`_ (credit to `@OtherBarry <https://github.com/OtherBarry>`_)\n * EAN-8/13\n * GDTI\n * GLN\n * SSCC\n * UPC-A/E\n * etc. *(all fixed length numeric GS1 data structures with a check digit)*\n* `ISBN-10/13 <https://checkdigit.readthedocs.io/en/latest/_autosummary/checkdigit.isbn.html#module-checkdigit.isbn>`_\n* `Luhn <https://checkdigit.readthedocs.io/en/latest/_autosummary/checkdigit.luhn.html#module-checkdigit.luhn>`_\n\nFor each of these formats, we provide functions to validate them and calculate missing digits.\n\nDo you have any formats that you'd like to see supported? šŸ¤” Feel free to raise an issue,\nor even to send a pull request!\n\nšŸ”Ø Contributing\n---------------\n\n- Contributing Page: `<https://checkdigit.rtfd.io/en/latest/contributing.html>`_\n- Issue Tracker: `<https://github.com/harens/checkdigit/issues>`_\n- Source Code: `<https://github.com/harens/checkdigit>`_\n\nAny change, big or small, that you think can help improve this project is more than welcome šŸŽ‰.\n\nAs well as this, feel free to open an issue with any new suggestions or bug reports. Every contribution is appreciated.\n\nTo find out more, please read our `contributing page <https://checkdigit.readthedocs.io/en/latest/contributing.html>`_. Thank you!\n\nšŸ“™ License\n-----------\n\nThis project is licensed under `GPL-3.0-or-later <https://github.com/harens/checkdigit/blob/master/LICENSE>`_.\n",
'long_description': ".. image:: https://raw.githubusercontent.com/harens/checkdigit/master/art/logo.png\n :alt: checkdigit logo\n :target: https://github.com/harens/checkdigit\n :align: center\n\n|\n\n.. image:: https://img.shields.io/github/workflow/status/harens/checkdigit/Tests?logo=github&style=flat-square\n :alt: GitHub Tests status\n :target: https://github.com/harens/checkdigit/actions\n\n.. image:: https://img.shields.io/codecov/c/github/harens/checkdigit?logo=codecov&style=flat-square\n :alt: Codecov\n :target: https://app.codecov.io/gh/harens/checkdigit\n\n.. image:: https://img.shields.io/pypi/dm/checkdigit?logo=python&logoColor=white&style=flat-square\n :alt: PyPi - Downloads\n :target: https://pepy.tech/project/checkdigit\n\n.. image:: https://img.shields.io/codefactor/grade/github/harens/checkdigit?logo=codefactor&style=flat-square\n :alt: CodeFactor Grade\n :target: https://www.codefactor.io/repository/github/harens/checkdigit/\n\n.. image:: https://img.shields.io/lgtm/grade/python/github/harens/checkdigit?logo=lgtm&style=flat-square\n :alt: LGTM Grade\n :target: https://lgtm.com/projects/g/harens/checkdigit/\n\n=========\n\n.. image:: https://repology.org/badge/vertical-allrepos/python:checkdigit.svg\n :alt: checkdigit repology\n :target: https://repology.org/project/python:checkdigit/versions\n :align: right\n\n**checkdigit** is a pure Python library built for identification numbers.\nYou want to validate a credit card number, or maybe even calculate a missing digit on an ISBN code?\nWe've got you covered šŸ˜Ž.\n\nWant to know more? Check out the `API Reference and documentation <https://checkdigit.readthedocs.io/en/latest/reference.html>`_!\n\nInstallation\n------------\n\n`MacPorts <https://ports.macports.org/port/py-checkdigit/summary>`_ šŸŽ\n*************************************************************************\n\n.. code-block::\n\n sudo port install py-checkdigit\n\n`PyPi <https://pypi.org/project/checkdigit/>`_ šŸ\n**************************************************\n\n.. code-block::\n\n pip install checkdigit\n\n✨ Features\n------------\n\n* `PEP 561 compatible <https://www.python.org/dev/peps/pep-0561>`_, with built in support for type checking.\n* Capable of calculating missing digits or validating a block of data.\n* Extensive in-code comments and docstrings to explain how it works behind the scenes. \U0001fa84\n\nāœ… Supported Formats\n---------------------\n\n* `Even/Odd binary parity <https://checkdigit.readthedocs.io/en/latest/_autosummary/checkdigit.parity.html#module-checkdigit.parity>`_\n* `CRC <https://checkdigit.readthedocs.io/en/latest/_autosummary/checkdigit.crc.html#module-checkdigit.crc>`_\n (credit to `@sapieninja <https://github.com/sapieninja>`_)\n* `GS1 Standards <https://checkdigit.readthedocs.io/en/latest/_autosummary/checkdigit.gs1.html#module-checkdigit.gs1>`_ (credit to `@OtherBarry <https://github.com/OtherBarry>`_)\n * EAN-8/13\n * GDTI\n * GLN\n * SSCC\n * UPC-A/E\n * etc. *(all fixed length numeric GS1 data structures with a check digit)*\n* `ISBN-10/13 <https://checkdigit.readthedocs.io/en/latest/_autosummary/checkdigit.isbn.html#module-checkdigit.isbn>`_\n* `Luhn <https://checkdigit.readthedocs.io/en/latest/_autosummary/checkdigit.luhn.html#module-checkdigit.luhn>`_\n* `Verhoeff <https://checkdigit.readthedocs.io/en/latest/_autosummary/checkdigit.verhoeff.html#module-checkdigit.verhoeff>`_\n\nFor each of these formats, we provide functions to validate them and calculate missing digits.\n\nDo you have any formats that you'd like to see supported? šŸ¤” Feel free to raise an issue,\nor even to send a pull request!\n\nšŸ”Ø Contributing\n---------------\n\n- Contributing Page: `<https://checkdigit.rtfd.io/en/latest/contributing.html>`_\n- Issue Tracker: `<https://github.com/harens/checkdigit/issues>`_\n- Source Code: `<https://github.com/harens/checkdigit>`_\n\nAny change, big or small, that you think can help improve this project is more than welcome šŸŽ‰.\n\nAs well as this, feel free to open an issue with any new suggestions or bug reports. Every contribution is appreciated.\n\nTo find out more, please read our `contributing page <https://checkdigit.readthedocs.io/en/latest/contributing.html>`_. Thank you!\n\nšŸ“™ License\n-----------\n\nThis project is licensed under `GPL-3.0-or-later <https://github.com/harens/checkdigit/blob/master/LICENSE>`_.\n",
'author': 'harens',

@@ -17,0 +17,0 @@ 'author_email': 'harensdeveloper@gmail.com',