repository_name
stringlengths 7
55
| func_path_in_repository
stringlengths 4
223
| func_name
stringlengths 1
134
| whole_func_string
stringlengths 75
104k
| language
stringclasses 1
value | func_code_string
stringlengths 75
104k
| func_code_tokens
sequencelengths 19
28.4k
| func_documentation_string
stringlengths 1
46.9k
| func_documentation_tokens
sequencelengths 1
1.97k
| split_name
stringclasses 1
value | func_code_url
stringlengths 87
315
|
---|---|---|---|---|---|---|---|---|---|---|
davenquinn/Attitude | attitude/geom/__init__.py | fit_angle | def fit_angle(fit1, fit2, degrees=True):
"""
Finds the angle between the nominal vectors
"""
return N.degrees(angle(fit1.normal,fit2.normal)) | python | def fit_angle(fit1, fit2, degrees=True):
"""
Finds the angle between the nominal vectors
"""
return N.degrees(angle(fit1.normal,fit2.normal)) | [
"def",
"fit_angle",
"(",
"fit1",
",",
"fit2",
",",
"degrees",
"=",
"True",
")",
":",
"return",
"N",
".",
"degrees",
"(",
"angle",
"(",
"fit1",
".",
"normal",
",",
"fit2",
".",
"normal",
")",
")"
] | Finds the angle between the nominal vectors | [
"Finds",
"the",
"angle",
"between",
"the",
"nominal",
"vectors"
] | train | https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/geom/__init__.py#L17-L21 |
davenquinn/Attitude | attitude/geom/__init__.py | fit_similarity | def fit_similarity(fit1, fit2):
"""
Distance apart for vectors, given in
standard deviations
"""
cov1 = aligned_covariance(fit1)
cov2 = aligned_covariance(fit2)
if fit2.axes[2,2] < 0:
cov2 *= -1
v0 = fit1.normal-fit2.normal
cov0 = cov1+cov2 # Axes are aligned, so no covariances
# Find distance of point from center
# Decompose covariance matrix
U,s,V = N.linalg.svd(cov0)
rotated = dot(V,v0) # rotate vector into PCA space
val = rotated**2/N.sqrt(s)
return N.sqrt(val.sum()) | python | def fit_similarity(fit1, fit2):
"""
Distance apart for vectors, given in
standard deviations
"""
cov1 = aligned_covariance(fit1)
cov2 = aligned_covariance(fit2)
if fit2.axes[2,2] < 0:
cov2 *= -1
v0 = fit1.normal-fit2.normal
cov0 = cov1+cov2 # Axes are aligned, so no covariances
# Find distance of point from center
# Decompose covariance matrix
U,s,V = N.linalg.svd(cov0)
rotated = dot(V,v0) # rotate vector into PCA space
val = rotated**2/N.sqrt(s)
return N.sqrt(val.sum()) | [
"def",
"fit_similarity",
"(",
"fit1",
",",
"fit2",
")",
":",
"cov1",
"=",
"aligned_covariance",
"(",
"fit1",
")",
"cov2",
"=",
"aligned_covariance",
"(",
"fit2",
")",
"if",
"fit2",
".",
"axes",
"[",
"2",
",",
"2",
"]",
"<",
"0",
":",
"cov2",
"*=",
"-",
"1",
"v0",
"=",
"fit1",
".",
"normal",
"-",
"fit2",
".",
"normal",
"cov0",
"=",
"cov1",
"+",
"cov2",
"# Axes are aligned, so no covariances",
"# Find distance of point from center",
"# Decompose covariance matrix",
"U",
",",
"s",
",",
"V",
"=",
"N",
".",
"linalg",
".",
"svd",
"(",
"cov0",
")",
"rotated",
"=",
"dot",
"(",
"V",
",",
"v0",
")",
"# rotate vector into PCA space",
"val",
"=",
"rotated",
"**",
"2",
"/",
"N",
".",
"sqrt",
"(",
"s",
")",
"return",
"N",
".",
"sqrt",
"(",
"val",
".",
"sum",
"(",
")",
")"
] | Distance apart for vectors, given in
standard deviations | [
"Distance",
"apart",
"for",
"vectors",
"given",
"in",
"standard",
"deviations"
] | train | https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/geom/__init__.py#L23-L41 |
davenquinn/Attitude | attitude/geom/__init__.py | axis_aligned_transforms | def axis_aligned_transforms():
"""
Generates three transformation matrices
to map three-dimensional data down
to slices on the xy, xz and yz planes, respectively.
The typical use case for this is to iterate over the results
of this method to provide arguments to e.g. the `HyperbolicErrors`
function.
"""
I = N.eye(3)
xy = I[:2]
xz = N.vstack((I[0],I[2]))
yz = I[1:]
return xy,xz,yz | python | def axis_aligned_transforms():
"""
Generates three transformation matrices
to map three-dimensional data down
to slices on the xy, xz and yz planes, respectively.
The typical use case for this is to iterate over the results
of this method to provide arguments to e.g. the `HyperbolicErrors`
function.
"""
I = N.eye(3)
xy = I[:2]
xz = N.vstack((I[0],I[2]))
yz = I[1:]
return xy,xz,yz | [
"def",
"axis_aligned_transforms",
"(",
")",
":",
"I",
"=",
"N",
".",
"eye",
"(",
"3",
")",
"xy",
"=",
"I",
"[",
":",
"2",
"]",
"xz",
"=",
"N",
".",
"vstack",
"(",
"(",
"I",
"[",
"0",
"]",
",",
"I",
"[",
"2",
"]",
")",
")",
"yz",
"=",
"I",
"[",
"1",
":",
"]",
"return",
"xy",
",",
"xz",
",",
"yz"
] | Generates three transformation matrices
to map three-dimensional data down
to slices on the xy, xz and yz planes, respectively.
The typical use case for this is to iterate over the results
of this method to provide arguments to e.g. the `HyperbolicErrors`
function. | [
"Generates",
"three",
"transformation",
"matrices",
"to",
"map",
"three",
"-",
"dimensional",
"data",
"down",
"to",
"slices",
"on",
"the",
"xy",
"xz",
"and",
"yz",
"planes",
"respectively",
".",
"The",
"typical",
"use",
"case",
"for",
"this",
"is",
"to",
"iterate",
"over",
"the",
"results",
"of",
"this",
"method",
"to",
"provide",
"arguments",
"to",
"e",
".",
"g",
".",
"the",
"HyperbolicErrors",
"function",
"."
] | train | https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/geom/__init__.py#L43-L56 |
RudolfCardinal/pythonlib | cardinal_pythonlib/plot.py | png_img_html_from_pyplot_figure | def png_img_html_from_pyplot_figure(fig: "Figure",
dpi: int = 100,
extra_html_class: str = None) -> str:
"""
Converts a ``pyplot`` figure to an HTML IMG tag with encapsulated PNG.
"""
if fig is None:
return ""
# Make a file-like object
memfile = io.BytesIO()
# In general, can do
# fig.savefig(filename/file-like-object/backend, format=...)
# or
# backend.savefig(fig):
# see e.g. http://matplotlib.org/api/backend_pdf_api.html
fig.savefig(memfile, format="png", dpi=dpi)
memfile.seek(0)
pngblob = memoryview(memfile.read())
return rnc_web.get_png_img_html(pngblob, extra_html_class) | python | def png_img_html_from_pyplot_figure(fig: "Figure",
dpi: int = 100,
extra_html_class: str = None) -> str:
"""
Converts a ``pyplot`` figure to an HTML IMG tag with encapsulated PNG.
"""
if fig is None:
return ""
# Make a file-like object
memfile = io.BytesIO()
# In general, can do
# fig.savefig(filename/file-like-object/backend, format=...)
# or
# backend.savefig(fig):
# see e.g. http://matplotlib.org/api/backend_pdf_api.html
fig.savefig(memfile, format="png", dpi=dpi)
memfile.seek(0)
pngblob = memoryview(memfile.read())
return rnc_web.get_png_img_html(pngblob, extra_html_class) | [
"def",
"png_img_html_from_pyplot_figure",
"(",
"fig",
":",
"\"Figure\"",
",",
"dpi",
":",
"int",
"=",
"100",
",",
"extra_html_class",
":",
"str",
"=",
"None",
")",
"->",
"str",
":",
"if",
"fig",
"is",
"None",
":",
"return",
"\"\"",
"# Make a file-like object",
"memfile",
"=",
"io",
".",
"BytesIO",
"(",
")",
"# In general, can do",
"# fig.savefig(filename/file-like-object/backend, format=...)",
"# or",
"# backend.savefig(fig):",
"# see e.g. http://matplotlib.org/api/backend_pdf_api.html",
"fig",
".",
"savefig",
"(",
"memfile",
",",
"format",
"=",
"\"png\"",
",",
"dpi",
"=",
"dpi",
")",
"memfile",
".",
"seek",
"(",
"0",
")",
"pngblob",
"=",
"memoryview",
"(",
"memfile",
".",
"read",
"(",
")",
")",
"return",
"rnc_web",
".",
"get_png_img_html",
"(",
"pngblob",
",",
"extra_html_class",
")"
] | Converts a ``pyplot`` figure to an HTML IMG tag with encapsulated PNG. | [
"Converts",
"a",
"pyplot",
"figure",
"to",
"an",
"HTML",
"IMG",
"tag",
"with",
"encapsulated",
"PNG",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/plot.py#L52-L70 |
RudolfCardinal/pythonlib | cardinal_pythonlib/plot.py | svg_html_from_pyplot_figure | def svg_html_from_pyplot_figure(fig: "Figure") -> str:
"""
Converts a ``pyplot`` figure to an SVG tag.
"""
if fig is None:
return ""
memfile = io.BytesIO() # StringIO doesn't like mixing str/unicode
fig.savefig(memfile, format="svg")
return memfile.getvalue().decode("utf-8") | python | def svg_html_from_pyplot_figure(fig: "Figure") -> str:
"""
Converts a ``pyplot`` figure to an SVG tag.
"""
if fig is None:
return ""
memfile = io.BytesIO() # StringIO doesn't like mixing str/unicode
fig.savefig(memfile, format="svg")
return memfile.getvalue().decode("utf-8") | [
"def",
"svg_html_from_pyplot_figure",
"(",
"fig",
":",
"\"Figure\"",
")",
"->",
"str",
":",
"if",
"fig",
"is",
"None",
":",
"return",
"\"\"",
"memfile",
"=",
"io",
".",
"BytesIO",
"(",
")",
"# StringIO doesn't like mixing str/unicode",
"fig",
".",
"savefig",
"(",
"memfile",
",",
"format",
"=",
"\"svg\"",
")",
"return",
"memfile",
".",
"getvalue",
"(",
")",
".",
"decode",
"(",
"\"utf-8\"",
")"
] | Converts a ``pyplot`` figure to an SVG tag. | [
"Converts",
"a",
"pyplot",
"figure",
"to",
"an",
"SVG",
"tag",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/plot.py#L73-L81 |
RudolfCardinal/pythonlib | cardinal_pythonlib/plot.py | set_matplotlib_fontsize | def set_matplotlib_fontsize(matplotlib: ModuleType,
fontsize: Union[int, float] = 12) -> None:
"""
Sets the current font size within the ``matplotlib`` library.
**WARNING:** not an appropriate method for multithreaded environments, as
it writes (indirectly) to ``matplotlib`` global objects. See CamCOPS for
alternative methods.
"""
font = {
# http://stackoverflow.com/questions/3899980
# http://matplotlib.org/users/customizing.html
'family': 'sans-serif',
# ... serif, sans-serif, cursive, fantasy, monospace
'style': 'normal', # normal (roman), italic, oblique
'variant': 'normal', # normal, small-caps
'weight': 'normal',
# ... normal [=400], bold [=700], bolder [relative to current],
# lighter [relative], 100, 200, 300, ..., 900
'size': fontsize # in pt (default 12)
}
# noinspection PyUnresolvedReferences
matplotlib.rc('font', **font)
legend = {
# http://stackoverflow.com/questions/7125009
'fontsize': fontsize
}
# noinspection PyUnresolvedReferences
matplotlib.rc('legend', **legend) | python | def set_matplotlib_fontsize(matplotlib: ModuleType,
fontsize: Union[int, float] = 12) -> None:
"""
Sets the current font size within the ``matplotlib`` library.
**WARNING:** not an appropriate method for multithreaded environments, as
it writes (indirectly) to ``matplotlib`` global objects. See CamCOPS for
alternative methods.
"""
font = {
# http://stackoverflow.com/questions/3899980
# http://matplotlib.org/users/customizing.html
'family': 'sans-serif',
# ... serif, sans-serif, cursive, fantasy, monospace
'style': 'normal', # normal (roman), italic, oblique
'variant': 'normal', # normal, small-caps
'weight': 'normal',
# ... normal [=400], bold [=700], bolder [relative to current],
# lighter [relative], 100, 200, 300, ..., 900
'size': fontsize # in pt (default 12)
}
# noinspection PyUnresolvedReferences
matplotlib.rc('font', **font)
legend = {
# http://stackoverflow.com/questions/7125009
'fontsize': fontsize
}
# noinspection PyUnresolvedReferences
matplotlib.rc('legend', **legend) | [
"def",
"set_matplotlib_fontsize",
"(",
"matplotlib",
":",
"ModuleType",
",",
"fontsize",
":",
"Union",
"[",
"int",
",",
"float",
"]",
"=",
"12",
")",
"->",
"None",
":",
"font",
"=",
"{",
"# http://stackoverflow.com/questions/3899980",
"# http://matplotlib.org/users/customizing.html",
"'family'",
":",
"'sans-serif'",
",",
"# ... serif, sans-serif, cursive, fantasy, monospace",
"'style'",
":",
"'normal'",
",",
"# normal (roman), italic, oblique",
"'variant'",
":",
"'normal'",
",",
"# normal, small-caps",
"'weight'",
":",
"'normal'",
",",
"# ... normal [=400], bold [=700], bolder [relative to current],",
"# lighter [relative], 100, 200, 300, ..., 900",
"'size'",
":",
"fontsize",
"# in pt (default 12)",
"}",
"# noinspection PyUnresolvedReferences",
"matplotlib",
".",
"rc",
"(",
"'font'",
",",
"*",
"*",
"font",
")",
"legend",
"=",
"{",
"# http://stackoverflow.com/questions/7125009",
"'fontsize'",
":",
"fontsize",
"}",
"# noinspection PyUnresolvedReferences",
"matplotlib",
".",
"rc",
"(",
"'legend'",
",",
"*",
"*",
"legend",
")"
] | Sets the current font size within the ``matplotlib`` library.
**WARNING:** not an appropriate method for multithreaded environments, as
it writes (indirectly) to ``matplotlib`` global objects. See CamCOPS for
alternative methods. | [
"Sets",
"the",
"current",
"font",
"size",
"within",
"the",
"matplotlib",
"library",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/plot.py#L89-L117 |
Autodesk/cryptorito | cryptorito/cli.py | massage_keys | def massage_keys(keys):
"""Goes through list of GPG/Keybase keys. For the keybase keys
it will attempt to look up the GPG key"""
m_keys = []
for key in keys:
if key.startswith('keybase:'):
m_keys.append(cryptorito.key_from_keybase(key[8:])['fingerprint'])
else:
m_keys.append(key)
return m_keys | python | def massage_keys(keys):
"""Goes through list of GPG/Keybase keys. For the keybase keys
it will attempt to look up the GPG key"""
m_keys = []
for key in keys:
if key.startswith('keybase:'):
m_keys.append(cryptorito.key_from_keybase(key[8:])['fingerprint'])
else:
m_keys.append(key)
return m_keys | [
"def",
"massage_keys",
"(",
"keys",
")",
":",
"m_keys",
"=",
"[",
"]",
"for",
"key",
"in",
"keys",
":",
"if",
"key",
".",
"startswith",
"(",
"'keybase:'",
")",
":",
"m_keys",
".",
"append",
"(",
"cryptorito",
".",
"key_from_keybase",
"(",
"key",
"[",
"8",
":",
"]",
")",
"[",
"'fingerprint'",
"]",
")",
"else",
":",
"m_keys",
".",
"append",
"(",
"key",
")",
"return",
"m_keys"
] | Goes through list of GPG/Keybase keys. For the keybase keys
it will attempt to look up the GPG key | [
"Goes",
"through",
"list",
"of",
"GPG",
"/",
"Keybase",
"keys",
".",
"For",
"the",
"keybase",
"keys",
"it",
"will",
"attempt",
"to",
"look",
"up",
"the",
"GPG",
"key"
] | train | https://github.com/Autodesk/cryptorito/blob/277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85/cryptorito/cli.py#L8-L18 |
Autodesk/cryptorito | cryptorito/cli.py | encrypt_file | def encrypt_file(src, dest, csv_keys):
"""Encrypt a file with the specific GPG keys and write out
to the specified path"""
keys = massage_keys(csv_keys.split(','))
cryptorito.encrypt(src, dest, keys) | python | def encrypt_file(src, dest, csv_keys):
"""Encrypt a file with the specific GPG keys and write out
to the specified path"""
keys = massage_keys(csv_keys.split(','))
cryptorito.encrypt(src, dest, keys) | [
"def",
"encrypt_file",
"(",
"src",
",",
"dest",
",",
"csv_keys",
")",
":",
"keys",
"=",
"massage_keys",
"(",
"csv_keys",
".",
"split",
"(",
"','",
")",
")",
"cryptorito",
".",
"encrypt",
"(",
"src",
",",
"dest",
",",
"keys",
")"
] | Encrypt a file with the specific GPG keys and write out
to the specified path | [
"Encrypt",
"a",
"file",
"with",
"the",
"specific",
"GPG",
"keys",
"and",
"write",
"out",
"to",
"the",
"specified",
"path"
] | train | https://github.com/Autodesk/cryptorito/blob/277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85/cryptorito/cli.py#L21-L25 |
Autodesk/cryptorito | cryptorito/cli.py | encrypt_var | def encrypt_var(csv_keys):
"""Encrypt what comes in from stdin and return base64
encrypted against the specified keys, returning on stdout"""
keys = massage_keys(csv_keys.split(','))
data = sys.stdin.read()
encrypted = cryptorito.encrypt_var(data, keys)
print(cryptorito.portable_b64encode(encrypted)) | python | def encrypt_var(csv_keys):
"""Encrypt what comes in from stdin and return base64
encrypted against the specified keys, returning on stdout"""
keys = massage_keys(csv_keys.split(','))
data = sys.stdin.read()
encrypted = cryptorito.encrypt_var(data, keys)
print(cryptorito.portable_b64encode(encrypted)) | [
"def",
"encrypt_var",
"(",
"csv_keys",
")",
":",
"keys",
"=",
"massage_keys",
"(",
"csv_keys",
".",
"split",
"(",
"','",
")",
")",
"data",
"=",
"sys",
".",
"stdin",
".",
"read",
"(",
")",
"encrypted",
"=",
"cryptorito",
".",
"encrypt_var",
"(",
"data",
",",
"keys",
")",
"print",
"(",
"cryptorito",
".",
"portable_b64encode",
"(",
"encrypted",
")",
")"
] | Encrypt what comes in from stdin and return base64
encrypted against the specified keys, returning on stdout | [
"Encrypt",
"what",
"comes",
"in",
"from",
"stdin",
"and",
"return",
"base64",
"encrypted",
"against",
"the",
"specified",
"keys",
"returning",
"on",
"stdout"
] | train | https://github.com/Autodesk/cryptorito/blob/277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85/cryptorito/cli.py#L33-L39 |
Autodesk/cryptorito | cryptorito/cli.py | decrypt_var | def decrypt_var(passphrase=None):
"""Decrypt what comes in from stdin (base64'd) and
write it out to stdout"""
encrypted = cryptorito.portable_b64decode(sys.stdin.read())
print(cryptorito.decrypt_var(encrypted, passphrase)) | python | def decrypt_var(passphrase=None):
"""Decrypt what comes in from stdin (base64'd) and
write it out to stdout"""
encrypted = cryptorito.portable_b64decode(sys.stdin.read())
print(cryptorito.decrypt_var(encrypted, passphrase)) | [
"def",
"decrypt_var",
"(",
"passphrase",
"=",
"None",
")",
":",
"encrypted",
"=",
"cryptorito",
".",
"portable_b64decode",
"(",
"sys",
".",
"stdin",
".",
"read",
"(",
")",
")",
"print",
"(",
"cryptorito",
".",
"decrypt_var",
"(",
"encrypted",
",",
"passphrase",
")",
")"
] | Decrypt what comes in from stdin (base64'd) and
write it out to stdout | [
"Decrypt",
"what",
"comes",
"in",
"from",
"stdin",
"(",
"base64",
"d",
")",
"and",
"write",
"it",
"out",
"to",
"stdout"
] | train | https://github.com/Autodesk/cryptorito/blob/277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85/cryptorito/cli.py#L42-L46 |
Autodesk/cryptorito | cryptorito/cli.py | import_keybase | def import_keybase(useropt):
"""Imports a public GPG key from Keybase"""
public_key = None
u_bits = useropt.split(':')
username = u_bits[0]
if len(u_bits) == 1:
public_key = cryptorito.key_from_keybase(username)
else:
fingerprint = u_bits[1]
public_key = cryptorito.key_from_keybase(username, fingerprint)
if cryptorito.has_gpg_key(public_key['fingerprint']):
sys.exit(2)
cryptorito.import_gpg_key(public_key['bundle'].encode('ascii'))
sys.exit(0) | python | def import_keybase(useropt):
"""Imports a public GPG key from Keybase"""
public_key = None
u_bits = useropt.split(':')
username = u_bits[0]
if len(u_bits) == 1:
public_key = cryptorito.key_from_keybase(username)
else:
fingerprint = u_bits[1]
public_key = cryptorito.key_from_keybase(username, fingerprint)
if cryptorito.has_gpg_key(public_key['fingerprint']):
sys.exit(2)
cryptorito.import_gpg_key(public_key['bundle'].encode('ascii'))
sys.exit(0) | [
"def",
"import_keybase",
"(",
"useropt",
")",
":",
"public_key",
"=",
"None",
"u_bits",
"=",
"useropt",
".",
"split",
"(",
"':'",
")",
"username",
"=",
"u_bits",
"[",
"0",
"]",
"if",
"len",
"(",
"u_bits",
")",
"==",
"1",
":",
"public_key",
"=",
"cryptorito",
".",
"key_from_keybase",
"(",
"username",
")",
"else",
":",
"fingerprint",
"=",
"u_bits",
"[",
"1",
"]",
"public_key",
"=",
"cryptorito",
".",
"key_from_keybase",
"(",
"username",
",",
"fingerprint",
")",
"if",
"cryptorito",
".",
"has_gpg_key",
"(",
"public_key",
"[",
"'fingerprint'",
"]",
")",
":",
"sys",
".",
"exit",
"(",
"2",
")",
"cryptorito",
".",
"import_gpg_key",
"(",
"public_key",
"[",
"'bundle'",
"]",
".",
"encode",
"(",
"'ascii'",
")",
")",
"sys",
".",
"exit",
"(",
"0",
")"
] | Imports a public GPG key from Keybase | [
"Imports",
"a",
"public",
"GPG",
"key",
"from",
"Keybase"
] | train | https://github.com/Autodesk/cryptorito/blob/277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85/cryptorito/cli.py#L57-L72 |
Autodesk/cryptorito | cryptorito/cli.py | do_thing | def do_thing():
"""Execute command line cryptorito actions"""
if len(sys.argv) == 5 and sys.argv[1] == "encrypt_file":
encrypt_file(sys.argv[2], sys.argv[3], sys.argv[4])
elif len(sys.argv) == 4 and sys.argv[1] == "decrypt_file":
decrypt_file(sys.argv[2], sys.argv[3])
elif len(sys.argv) == 3 and sys.argv[1] == "encrypt":
encrypt_var(sys.argv[2])
elif len(sys.argv) == 2 and sys.argv[1] == "decrypt":
decrypt_var()
elif len(sys.argv) == 3 and sys.argv[1] == "decrypt":
decrypt_var(passphrase=sys.argv[2])
elif len(sys.argv) == 3 and sys.argv[1] == "has_key":
has_key(sys.argv[2])
elif len(sys.argv) == 3 and sys.argv[1] == "import_keybase":
import_keybase(sys.argv[2])
elif len(sys.argv) == 3 and sys.argv[1] == "export":
export_key(sys.argv[2])
else:
print("Cryptorito testing wrapper. Not suitable for routine use.",
file=sys.stderr)
sys.exit(1) | python | def do_thing():
"""Execute command line cryptorito actions"""
if len(sys.argv) == 5 and sys.argv[1] == "encrypt_file":
encrypt_file(sys.argv[2], sys.argv[3], sys.argv[4])
elif len(sys.argv) == 4 and sys.argv[1] == "decrypt_file":
decrypt_file(sys.argv[2], sys.argv[3])
elif len(sys.argv) == 3 and sys.argv[1] == "encrypt":
encrypt_var(sys.argv[2])
elif len(sys.argv) == 2 and sys.argv[1] == "decrypt":
decrypt_var()
elif len(sys.argv) == 3 and sys.argv[1] == "decrypt":
decrypt_var(passphrase=sys.argv[2])
elif len(sys.argv) == 3 and sys.argv[1] == "has_key":
has_key(sys.argv[2])
elif len(sys.argv) == 3 and sys.argv[1] == "import_keybase":
import_keybase(sys.argv[2])
elif len(sys.argv) == 3 and sys.argv[1] == "export":
export_key(sys.argv[2])
else:
print("Cryptorito testing wrapper. Not suitable for routine use.",
file=sys.stderr)
sys.exit(1) | [
"def",
"do_thing",
"(",
")",
":",
"if",
"len",
"(",
"sys",
".",
"argv",
")",
"==",
"5",
"and",
"sys",
".",
"argv",
"[",
"1",
"]",
"==",
"\"encrypt_file\"",
":",
"encrypt_file",
"(",
"sys",
".",
"argv",
"[",
"2",
"]",
",",
"sys",
".",
"argv",
"[",
"3",
"]",
",",
"sys",
".",
"argv",
"[",
"4",
"]",
")",
"elif",
"len",
"(",
"sys",
".",
"argv",
")",
"==",
"4",
"and",
"sys",
".",
"argv",
"[",
"1",
"]",
"==",
"\"decrypt_file\"",
":",
"decrypt_file",
"(",
"sys",
".",
"argv",
"[",
"2",
"]",
",",
"sys",
".",
"argv",
"[",
"3",
"]",
")",
"elif",
"len",
"(",
"sys",
".",
"argv",
")",
"==",
"3",
"and",
"sys",
".",
"argv",
"[",
"1",
"]",
"==",
"\"encrypt\"",
":",
"encrypt_var",
"(",
"sys",
".",
"argv",
"[",
"2",
"]",
")",
"elif",
"len",
"(",
"sys",
".",
"argv",
")",
"==",
"2",
"and",
"sys",
".",
"argv",
"[",
"1",
"]",
"==",
"\"decrypt\"",
":",
"decrypt_var",
"(",
")",
"elif",
"len",
"(",
"sys",
".",
"argv",
")",
"==",
"3",
"and",
"sys",
".",
"argv",
"[",
"1",
"]",
"==",
"\"decrypt\"",
":",
"decrypt_var",
"(",
"passphrase",
"=",
"sys",
".",
"argv",
"[",
"2",
"]",
")",
"elif",
"len",
"(",
"sys",
".",
"argv",
")",
"==",
"3",
"and",
"sys",
".",
"argv",
"[",
"1",
"]",
"==",
"\"has_key\"",
":",
"has_key",
"(",
"sys",
".",
"argv",
"[",
"2",
"]",
")",
"elif",
"len",
"(",
"sys",
".",
"argv",
")",
"==",
"3",
"and",
"sys",
".",
"argv",
"[",
"1",
"]",
"==",
"\"import_keybase\"",
":",
"import_keybase",
"(",
"sys",
".",
"argv",
"[",
"2",
"]",
")",
"elif",
"len",
"(",
"sys",
".",
"argv",
")",
"==",
"3",
"and",
"sys",
".",
"argv",
"[",
"1",
"]",
"==",
"\"export\"",
":",
"export_key",
"(",
"sys",
".",
"argv",
"[",
"2",
"]",
")",
"else",
":",
"print",
"(",
"\"Cryptorito testing wrapper. Not suitable for routine use.\"",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"sys",
".",
"exit",
"(",
"1",
")"
] | Execute command line cryptorito actions | [
"Execute",
"command",
"line",
"cryptorito",
"actions"
] | train | https://github.com/Autodesk/cryptorito/blob/277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85/cryptorito/cli.py#L81-L102 |
RudolfCardinal/pythonlib | cardinal_pythonlib/logs.py | get_monochrome_handler | def get_monochrome_handler(
extranames: List[str] = None,
with_process_id: bool = False,
with_thread_id: bool = False,
stream: TextIO = None) -> logging.StreamHandler:
"""
Gets a monochrome log handler using a standard format.
Args:
extranames: additional names to append to the logger's name
with_process_id: include the process ID in the logger's name?
with_thread_id: include the thread ID in the logger's name?
stream: ``TextIO`` stream to send log output to
Returns:
the :class:`logging.StreamHandler`
"""
fmt = "%(asctime)s.%(msecs)03d"
if with_process_id or with_thread_id:
procinfo = [] # type: List[str]
if with_process_id:
procinfo.append("p%(process)d")
if with_thread_id:
procinfo.append("t%(thread)d")
fmt += " [{}]".format(".".join(procinfo))
extras = ":" + ":".join(extranames) if extranames else ""
fmt += " %(name)s{extras}:%(levelname)s: ".format(extras=extras)
fmt += "%(message)s"
f = logging.Formatter(fmt, datefmt=LOG_DATEFMT, style='%')
h = logging.StreamHandler(stream)
h.setFormatter(f)
return h | python | def get_monochrome_handler(
extranames: List[str] = None,
with_process_id: bool = False,
with_thread_id: bool = False,
stream: TextIO = None) -> logging.StreamHandler:
"""
Gets a monochrome log handler using a standard format.
Args:
extranames: additional names to append to the logger's name
with_process_id: include the process ID in the logger's name?
with_thread_id: include the thread ID in the logger's name?
stream: ``TextIO`` stream to send log output to
Returns:
the :class:`logging.StreamHandler`
"""
fmt = "%(asctime)s.%(msecs)03d"
if with_process_id or with_thread_id:
procinfo = [] # type: List[str]
if with_process_id:
procinfo.append("p%(process)d")
if with_thread_id:
procinfo.append("t%(thread)d")
fmt += " [{}]".format(".".join(procinfo))
extras = ":" + ":".join(extranames) if extranames else ""
fmt += " %(name)s{extras}:%(levelname)s: ".format(extras=extras)
fmt += "%(message)s"
f = logging.Formatter(fmt, datefmt=LOG_DATEFMT, style='%')
h = logging.StreamHandler(stream)
h.setFormatter(f)
return h | [
"def",
"get_monochrome_handler",
"(",
"extranames",
":",
"List",
"[",
"str",
"]",
"=",
"None",
",",
"with_process_id",
":",
"bool",
"=",
"False",
",",
"with_thread_id",
":",
"bool",
"=",
"False",
",",
"stream",
":",
"TextIO",
"=",
"None",
")",
"->",
"logging",
".",
"StreamHandler",
":",
"fmt",
"=",
"\"%(asctime)s.%(msecs)03d\"",
"if",
"with_process_id",
"or",
"with_thread_id",
":",
"procinfo",
"=",
"[",
"]",
"# type: List[str]",
"if",
"with_process_id",
":",
"procinfo",
".",
"append",
"(",
"\"p%(process)d\"",
")",
"if",
"with_thread_id",
":",
"procinfo",
".",
"append",
"(",
"\"t%(thread)d\"",
")",
"fmt",
"+=",
"\" [{}]\"",
".",
"format",
"(",
"\".\"",
".",
"join",
"(",
"procinfo",
")",
")",
"extras",
"=",
"\":\"",
"+",
"\":\"",
".",
"join",
"(",
"extranames",
")",
"if",
"extranames",
"else",
"\"\"",
"fmt",
"+=",
"\" %(name)s{extras}:%(levelname)s: \"",
".",
"format",
"(",
"extras",
"=",
"extras",
")",
"fmt",
"+=",
"\"%(message)s\"",
"f",
"=",
"logging",
".",
"Formatter",
"(",
"fmt",
",",
"datefmt",
"=",
"LOG_DATEFMT",
",",
"style",
"=",
"'%'",
")",
"h",
"=",
"logging",
".",
"StreamHandler",
"(",
"stream",
")",
"h",
".",
"setFormatter",
"(",
"f",
")",
"return",
"h"
] | Gets a monochrome log handler using a standard format.
Args:
extranames: additional names to append to the logger's name
with_process_id: include the process ID in the logger's name?
with_thread_id: include the thread ID in the logger's name?
stream: ``TextIO`` stream to send log output to
Returns:
the :class:`logging.StreamHandler` | [
"Gets",
"a",
"monochrome",
"log",
"handler",
"using",
"a",
"standard",
"format",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/logs.py#L105-L137 |
RudolfCardinal/pythonlib | cardinal_pythonlib/logs.py | get_colour_handler | def get_colour_handler(extranames: List[str] = None,
with_process_id: bool = False,
with_thread_id: bool = False,
stream: TextIO = None) -> logging.StreamHandler:
"""
Gets a colour log handler using a standard format.
Args:
extranames: additional names to append to the logger's name
with_process_id: include the process ID in the logger's name?
with_thread_id: include the thread ID in the logger's name?
stream: ``TextIO`` stream to send log output to
Returns:
the :class:`logging.StreamHandler`
"""
fmt = "%(white)s%(asctime)s.%(msecs)03d" # this is dim white = grey
if with_process_id or with_thread_id:
procinfo = [] # type: List[str]
if with_process_id:
procinfo.append("p%(process)d")
if with_thread_id:
procinfo.append("t%(thread)d")
fmt += " [{}]".format(".".join(procinfo))
extras = ":" + ":".join(extranames) if extranames else ""
fmt += " %(name)s{extras}:%(levelname)s: ".format(extras=extras)
fmt += "%(reset)s%(log_color)s%(message)s"
cf = ColoredFormatter(fmt,
datefmt=LOG_DATEFMT,
reset=True,
log_colors=LOG_COLORS,
secondary_log_colors={},
style='%')
ch = logging.StreamHandler(stream)
ch.setFormatter(cf)
return ch | python | def get_colour_handler(extranames: List[str] = None,
with_process_id: bool = False,
with_thread_id: bool = False,
stream: TextIO = None) -> logging.StreamHandler:
"""
Gets a colour log handler using a standard format.
Args:
extranames: additional names to append to the logger's name
with_process_id: include the process ID in the logger's name?
with_thread_id: include the thread ID in the logger's name?
stream: ``TextIO`` stream to send log output to
Returns:
the :class:`logging.StreamHandler`
"""
fmt = "%(white)s%(asctime)s.%(msecs)03d" # this is dim white = grey
if with_process_id or with_thread_id:
procinfo = [] # type: List[str]
if with_process_id:
procinfo.append("p%(process)d")
if with_thread_id:
procinfo.append("t%(thread)d")
fmt += " [{}]".format(".".join(procinfo))
extras = ":" + ":".join(extranames) if extranames else ""
fmt += " %(name)s{extras}:%(levelname)s: ".format(extras=extras)
fmt += "%(reset)s%(log_color)s%(message)s"
cf = ColoredFormatter(fmt,
datefmt=LOG_DATEFMT,
reset=True,
log_colors=LOG_COLORS,
secondary_log_colors={},
style='%')
ch = logging.StreamHandler(stream)
ch.setFormatter(cf)
return ch | [
"def",
"get_colour_handler",
"(",
"extranames",
":",
"List",
"[",
"str",
"]",
"=",
"None",
",",
"with_process_id",
":",
"bool",
"=",
"False",
",",
"with_thread_id",
":",
"bool",
"=",
"False",
",",
"stream",
":",
"TextIO",
"=",
"None",
")",
"->",
"logging",
".",
"StreamHandler",
":",
"fmt",
"=",
"\"%(white)s%(asctime)s.%(msecs)03d\"",
"# this is dim white = grey",
"if",
"with_process_id",
"or",
"with_thread_id",
":",
"procinfo",
"=",
"[",
"]",
"# type: List[str]",
"if",
"with_process_id",
":",
"procinfo",
".",
"append",
"(",
"\"p%(process)d\"",
")",
"if",
"with_thread_id",
":",
"procinfo",
".",
"append",
"(",
"\"t%(thread)d\"",
")",
"fmt",
"+=",
"\" [{}]\"",
".",
"format",
"(",
"\".\"",
".",
"join",
"(",
"procinfo",
")",
")",
"extras",
"=",
"\":\"",
"+",
"\":\"",
".",
"join",
"(",
"extranames",
")",
"if",
"extranames",
"else",
"\"\"",
"fmt",
"+=",
"\" %(name)s{extras}:%(levelname)s: \"",
".",
"format",
"(",
"extras",
"=",
"extras",
")",
"fmt",
"+=",
"\"%(reset)s%(log_color)s%(message)s\"",
"cf",
"=",
"ColoredFormatter",
"(",
"fmt",
",",
"datefmt",
"=",
"LOG_DATEFMT",
",",
"reset",
"=",
"True",
",",
"log_colors",
"=",
"LOG_COLORS",
",",
"secondary_log_colors",
"=",
"{",
"}",
",",
"style",
"=",
"'%'",
")",
"ch",
"=",
"logging",
".",
"StreamHandler",
"(",
"stream",
")",
"ch",
".",
"setFormatter",
"(",
"cf",
")",
"return",
"ch"
] | Gets a colour log handler using a standard format.
Args:
extranames: additional names to append to the logger's name
with_process_id: include the process ID in the logger's name?
with_thread_id: include the thread ID in the logger's name?
stream: ``TextIO`` stream to send log output to
Returns:
the :class:`logging.StreamHandler` | [
"Gets",
"a",
"colour",
"log",
"handler",
"using",
"a",
"standard",
"format",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/logs.py#L140-L176 |
RudolfCardinal/pythonlib | cardinal_pythonlib/logs.py | configure_logger_for_colour | def configure_logger_for_colour(logger: logging.Logger,
level: int = logging.INFO,
remove_existing: bool = False,
extranames: List[str] = None,
with_process_id: bool = False,
with_thread_id: bool = False) -> None:
"""
Applies a preconfigured datetime/colour scheme to a logger.
Should ONLY be called from the ``if __name__ == 'main'`` script;
see https://docs.python.org/3.4/howto/logging.html#library-config.
Args:
logger: logger to modify
level: log level to set
remove_existing: remove existing handlers from logger first?
extranames: additional names to append to the logger's name
with_process_id: include the process ID in the logger's name?
with_thread_id: include the thread ID in the logger's name?
"""
if remove_existing:
logger.handlers = [] # http://stackoverflow.com/questions/7484454
handler = get_colour_handler(extranames,
with_process_id=with_process_id,
with_thread_id=with_thread_id)
handler.setLevel(level)
logger.addHandler(handler)
logger.setLevel(level) | python | def configure_logger_for_colour(logger: logging.Logger,
level: int = logging.INFO,
remove_existing: bool = False,
extranames: List[str] = None,
with_process_id: bool = False,
with_thread_id: bool = False) -> None:
"""
Applies a preconfigured datetime/colour scheme to a logger.
Should ONLY be called from the ``if __name__ == 'main'`` script;
see https://docs.python.org/3.4/howto/logging.html#library-config.
Args:
logger: logger to modify
level: log level to set
remove_existing: remove existing handlers from logger first?
extranames: additional names to append to the logger's name
with_process_id: include the process ID in the logger's name?
with_thread_id: include the thread ID in the logger's name?
"""
if remove_existing:
logger.handlers = [] # http://stackoverflow.com/questions/7484454
handler = get_colour_handler(extranames,
with_process_id=with_process_id,
with_thread_id=with_thread_id)
handler.setLevel(level)
logger.addHandler(handler)
logger.setLevel(level) | [
"def",
"configure_logger_for_colour",
"(",
"logger",
":",
"logging",
".",
"Logger",
",",
"level",
":",
"int",
"=",
"logging",
".",
"INFO",
",",
"remove_existing",
":",
"bool",
"=",
"False",
",",
"extranames",
":",
"List",
"[",
"str",
"]",
"=",
"None",
",",
"with_process_id",
":",
"bool",
"=",
"False",
",",
"with_thread_id",
":",
"bool",
"=",
"False",
")",
"->",
"None",
":",
"if",
"remove_existing",
":",
"logger",
".",
"handlers",
"=",
"[",
"]",
"# http://stackoverflow.com/questions/7484454",
"handler",
"=",
"get_colour_handler",
"(",
"extranames",
",",
"with_process_id",
"=",
"with_process_id",
",",
"with_thread_id",
"=",
"with_thread_id",
")",
"handler",
".",
"setLevel",
"(",
"level",
")",
"logger",
".",
"addHandler",
"(",
"handler",
")",
"logger",
".",
"setLevel",
"(",
"level",
")"
] | Applies a preconfigured datetime/colour scheme to a logger.
Should ONLY be called from the ``if __name__ == 'main'`` script;
see https://docs.python.org/3.4/howto/logging.html#library-config.
Args:
logger: logger to modify
level: log level to set
remove_existing: remove existing handlers from logger first?
extranames: additional names to append to the logger's name
with_process_id: include the process ID in the logger's name?
with_thread_id: include the thread ID in the logger's name? | [
"Applies",
"a",
"preconfigured",
"datetime",
"/",
"colour",
"scheme",
"to",
"a",
"logger",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/logs.py#L179-L206 |
RudolfCardinal/pythonlib | cardinal_pythonlib/logs.py | main_only_quicksetup_rootlogger | def main_only_quicksetup_rootlogger(level: int = logging.DEBUG,
with_process_id: bool = False,
with_thread_id: bool = False) -> None:
"""
Quick function to set up the root logger for colour.
Should ONLY be called from the ``if __name__ == 'main'`` script;
see https://docs.python.org/3.4/howto/logging.html#library-config.
Args:
level: log level to set
with_process_id: include the process ID in the logger's name?
with_thread_id: include the thread ID in the logger's name?
"""
# Nasty. Only call from "if __name__ == '__main__'" clauses!
rootlogger = logging.getLogger()
configure_logger_for_colour(rootlogger, level, remove_existing=True,
with_process_id=with_process_id,
with_thread_id=with_thread_id) | python | def main_only_quicksetup_rootlogger(level: int = logging.DEBUG,
with_process_id: bool = False,
with_thread_id: bool = False) -> None:
"""
Quick function to set up the root logger for colour.
Should ONLY be called from the ``if __name__ == 'main'`` script;
see https://docs.python.org/3.4/howto/logging.html#library-config.
Args:
level: log level to set
with_process_id: include the process ID in the logger's name?
with_thread_id: include the thread ID in the logger's name?
"""
# Nasty. Only call from "if __name__ == '__main__'" clauses!
rootlogger = logging.getLogger()
configure_logger_for_colour(rootlogger, level, remove_existing=True,
with_process_id=with_process_id,
with_thread_id=with_thread_id) | [
"def",
"main_only_quicksetup_rootlogger",
"(",
"level",
":",
"int",
"=",
"logging",
".",
"DEBUG",
",",
"with_process_id",
":",
"bool",
"=",
"False",
",",
"with_thread_id",
":",
"bool",
"=",
"False",
")",
"->",
"None",
":",
"# Nasty. Only call from \"if __name__ == '__main__'\" clauses!",
"rootlogger",
"=",
"logging",
".",
"getLogger",
"(",
")",
"configure_logger_for_colour",
"(",
"rootlogger",
",",
"level",
",",
"remove_existing",
"=",
"True",
",",
"with_process_id",
"=",
"with_process_id",
",",
"with_thread_id",
"=",
"with_thread_id",
")"
] | Quick function to set up the root logger for colour.
Should ONLY be called from the ``if __name__ == 'main'`` script;
see https://docs.python.org/3.4/howto/logging.html#library-config.
Args:
level: log level to set
with_process_id: include the process ID in the logger's name?
with_thread_id: include the thread ID in the logger's name? | [
"Quick",
"function",
"to",
"set",
"up",
"the",
"root",
"logger",
"for",
"colour",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/logs.py#L209-L227 |
RudolfCardinal/pythonlib | cardinal_pythonlib/logs.py | remove_all_logger_handlers | def remove_all_logger_handlers(logger: logging.Logger) -> None:
"""
Remove all handlers from a logger.
Args:
logger: logger to modify
"""
while logger.handlers:
h = logger.handlers[0]
logger.removeHandler(h) | python | def remove_all_logger_handlers(logger: logging.Logger) -> None:
"""
Remove all handlers from a logger.
Args:
logger: logger to modify
"""
while logger.handlers:
h = logger.handlers[0]
logger.removeHandler(h) | [
"def",
"remove_all_logger_handlers",
"(",
"logger",
":",
"logging",
".",
"Logger",
")",
"->",
"None",
":",
"while",
"logger",
".",
"handlers",
":",
"h",
"=",
"logger",
".",
"handlers",
"[",
"0",
"]",
"logger",
".",
"removeHandler",
"(",
"h",
")"
] | Remove all handlers from a logger.
Args:
logger: logger to modify | [
"Remove",
"all",
"handlers",
"from",
"a",
"logger",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/logs.py#L235-L244 |
RudolfCardinal/pythonlib | cardinal_pythonlib/logs.py | reset_logformat | def reset_logformat(logger: logging.Logger,
fmt: str,
datefmt: str = '%Y-%m-%d %H:%M:%S') -> None:
"""
Create a new formatter and apply it to the logger.
:func:`logging.basicConfig` won't reset the formatter if another module
has called it, so always set the formatter like this.
Args:
logger: logger to modify
fmt: passed to the ``fmt=`` argument of :class:`logging.Formatter`
datefmt: passed to the ``datefmt=`` argument of
:class:`logging.Formatter`
"""
handler = logging.StreamHandler()
formatter = logging.Formatter(fmt=fmt, datefmt=datefmt)
handler.setFormatter(formatter)
remove_all_logger_handlers(logger)
logger.addHandler(handler)
logger.propagate = False | python | def reset_logformat(logger: logging.Logger,
fmt: str,
datefmt: str = '%Y-%m-%d %H:%M:%S') -> None:
"""
Create a new formatter and apply it to the logger.
:func:`logging.basicConfig` won't reset the formatter if another module
has called it, so always set the formatter like this.
Args:
logger: logger to modify
fmt: passed to the ``fmt=`` argument of :class:`logging.Formatter`
datefmt: passed to the ``datefmt=`` argument of
:class:`logging.Formatter`
"""
handler = logging.StreamHandler()
formatter = logging.Formatter(fmt=fmt, datefmt=datefmt)
handler.setFormatter(formatter)
remove_all_logger_handlers(logger)
logger.addHandler(handler)
logger.propagate = False | [
"def",
"reset_logformat",
"(",
"logger",
":",
"logging",
".",
"Logger",
",",
"fmt",
":",
"str",
",",
"datefmt",
":",
"str",
"=",
"'%Y-%m-%d %H:%M:%S'",
")",
"->",
"None",
":",
"handler",
"=",
"logging",
".",
"StreamHandler",
"(",
")",
"formatter",
"=",
"logging",
".",
"Formatter",
"(",
"fmt",
"=",
"fmt",
",",
"datefmt",
"=",
"datefmt",
")",
"handler",
".",
"setFormatter",
"(",
"formatter",
")",
"remove_all_logger_handlers",
"(",
"logger",
")",
"logger",
".",
"addHandler",
"(",
"handler",
")",
"logger",
".",
"propagate",
"=",
"False"
] | Create a new formatter and apply it to the logger.
:func:`logging.basicConfig` won't reset the formatter if another module
has called it, so always set the formatter like this.
Args:
logger: logger to modify
fmt: passed to the ``fmt=`` argument of :class:`logging.Formatter`
datefmt: passed to the ``datefmt=`` argument of
:class:`logging.Formatter` | [
"Create",
"a",
"new",
"formatter",
"and",
"apply",
"it",
"to",
"the",
"logger",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/logs.py#L247-L267 |
RudolfCardinal/pythonlib | cardinal_pythonlib/logs.py | reset_logformat_timestamped | def reset_logformat_timestamped(logger: logging.Logger,
extraname: str = "",
level: int = logging.INFO) -> None:
"""
Apply a simple time-stamped log format to an existing logger, and set
its loglevel to either ``logging.DEBUG`` or ``logging.INFO``.
Args:
logger: logger to modify
extraname: additional name to append to the logger's name
level: log level to set
"""
namebit = extraname + ":" if extraname else ""
fmt = ("%(asctime)s.%(msecs)03d:%(levelname)s:%(name)s:" + namebit +
"%(message)s")
# logger.info(fmt)
reset_logformat(logger, fmt=fmt)
# logger.info(fmt)
logger.setLevel(level) | python | def reset_logformat_timestamped(logger: logging.Logger,
extraname: str = "",
level: int = logging.INFO) -> None:
"""
Apply a simple time-stamped log format to an existing logger, and set
its loglevel to either ``logging.DEBUG`` or ``logging.INFO``.
Args:
logger: logger to modify
extraname: additional name to append to the logger's name
level: log level to set
"""
namebit = extraname + ":" if extraname else ""
fmt = ("%(asctime)s.%(msecs)03d:%(levelname)s:%(name)s:" + namebit +
"%(message)s")
# logger.info(fmt)
reset_logformat(logger, fmt=fmt)
# logger.info(fmt)
logger.setLevel(level) | [
"def",
"reset_logformat_timestamped",
"(",
"logger",
":",
"logging",
".",
"Logger",
",",
"extraname",
":",
"str",
"=",
"\"\"",
",",
"level",
":",
"int",
"=",
"logging",
".",
"INFO",
")",
"->",
"None",
":",
"namebit",
"=",
"extraname",
"+",
"\":\"",
"if",
"extraname",
"else",
"\"\"",
"fmt",
"=",
"(",
"\"%(asctime)s.%(msecs)03d:%(levelname)s:%(name)s:\"",
"+",
"namebit",
"+",
"\"%(message)s\"",
")",
"# logger.info(fmt)",
"reset_logformat",
"(",
"logger",
",",
"fmt",
"=",
"fmt",
")",
"# logger.info(fmt)",
"logger",
".",
"setLevel",
"(",
"level",
")"
] | Apply a simple time-stamped log format to an existing logger, and set
its loglevel to either ``logging.DEBUG`` or ``logging.INFO``.
Args:
logger: logger to modify
extraname: additional name to append to the logger's name
level: log level to set | [
"Apply",
"a",
"simple",
"time",
"-",
"stamped",
"log",
"format",
"to",
"an",
"existing",
"logger",
"and",
"set",
"its",
"loglevel",
"to",
"either",
"logging",
".",
"DEBUG",
"or",
"logging",
".",
"INFO",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/logs.py#L270-L288 |
RudolfCardinal/pythonlib | cardinal_pythonlib/logs.py | configure_all_loggers_for_colour | def configure_all_loggers_for_colour(remove_existing: bool = True) -> None:
"""
Applies a preconfigured datetime/colour scheme to ALL logger.
Should ONLY be called from the ``if __name__ == 'main'`` script;
see https://docs.python.org/3.4/howto/logging.html#library-config.
Generally MORE SENSIBLE just to apply a handler to the root logger.
Args:
remove_existing: remove existing handlers from logger first?
"""
handler = get_colour_handler()
apply_handler_to_all_logs(handler, remove_existing=remove_existing) | python | def configure_all_loggers_for_colour(remove_existing: bool = True) -> None:
"""
Applies a preconfigured datetime/colour scheme to ALL logger.
Should ONLY be called from the ``if __name__ == 'main'`` script;
see https://docs.python.org/3.4/howto/logging.html#library-config.
Generally MORE SENSIBLE just to apply a handler to the root logger.
Args:
remove_existing: remove existing handlers from logger first?
"""
handler = get_colour_handler()
apply_handler_to_all_logs(handler, remove_existing=remove_existing) | [
"def",
"configure_all_loggers_for_colour",
"(",
"remove_existing",
":",
"bool",
"=",
"True",
")",
"->",
"None",
":",
"handler",
"=",
"get_colour_handler",
"(",
")",
"apply_handler_to_all_logs",
"(",
"handler",
",",
"remove_existing",
"=",
"remove_existing",
")"
] | Applies a preconfigured datetime/colour scheme to ALL logger.
Should ONLY be called from the ``if __name__ == 'main'`` script;
see https://docs.python.org/3.4/howto/logging.html#library-config.
Generally MORE SENSIBLE just to apply a handler to the root logger.
Args:
remove_existing: remove existing handlers from logger first? | [
"Applies",
"a",
"preconfigured",
"datetime",
"/",
"colour",
"scheme",
"to",
"ALL",
"logger",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/logs.py#L295-L309 |
RudolfCardinal/pythonlib | cardinal_pythonlib/logs.py | apply_handler_to_root_log | def apply_handler_to_root_log(handler: logging.Handler,
remove_existing: bool = False) -> None:
"""
Applies a handler to all logs, optionally removing existing handlers.
Should ONLY be called from the ``if __name__ == 'main'`` script;
see https://docs.python.org/3.4/howto/logging.html#library-config.
Generally MORE SENSIBLE just to apply a handler to the root logger.
Args:
handler: the handler to apply
remove_existing: remove existing handlers from logger first?
"""
rootlog = logging.getLogger()
if remove_existing:
rootlog.handlers = []
rootlog.addHandler(handler) | python | def apply_handler_to_root_log(handler: logging.Handler,
remove_existing: bool = False) -> None:
"""
Applies a handler to all logs, optionally removing existing handlers.
Should ONLY be called from the ``if __name__ == 'main'`` script;
see https://docs.python.org/3.4/howto/logging.html#library-config.
Generally MORE SENSIBLE just to apply a handler to the root logger.
Args:
handler: the handler to apply
remove_existing: remove existing handlers from logger first?
"""
rootlog = logging.getLogger()
if remove_existing:
rootlog.handlers = []
rootlog.addHandler(handler) | [
"def",
"apply_handler_to_root_log",
"(",
"handler",
":",
"logging",
".",
"Handler",
",",
"remove_existing",
":",
"bool",
"=",
"False",
")",
"->",
"None",
":",
"rootlog",
"=",
"logging",
".",
"getLogger",
"(",
")",
"if",
"remove_existing",
":",
"rootlog",
".",
"handlers",
"=",
"[",
"]",
"rootlog",
".",
"addHandler",
"(",
"handler",
")"
] | Applies a handler to all logs, optionally removing existing handlers.
Should ONLY be called from the ``if __name__ == 'main'`` script;
see https://docs.python.org/3.4/howto/logging.html#library-config.
Generally MORE SENSIBLE just to apply a handler to the root logger.
Args:
handler: the handler to apply
remove_existing: remove existing handlers from logger first? | [
"Applies",
"a",
"handler",
"to",
"all",
"logs",
"optionally",
"removing",
"existing",
"handlers",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/logs.py#L312-L329 |
RudolfCardinal/pythonlib | cardinal_pythonlib/logs.py | apply_handler_to_all_logs | def apply_handler_to_all_logs(handler: logging.Handler,
remove_existing: bool = False) -> None:
"""
Applies a handler to all logs, optionally removing existing handlers.
Should ONLY be called from the ``if __name__ == 'main'`` script;
see https://docs.python.org/3.4/howto/logging.html#library-config.
Generally MORE SENSIBLE just to apply a handler to the root logger.
Args:
handler: the handler to apply
remove_existing: remove existing handlers from logger first?
"""
# noinspection PyUnresolvedReferences
for name, obj in logging.Logger.manager.loggerDict.items():
if remove_existing:
obj.handlers = [] # http://stackoverflow.com/questions/7484454
obj.addHandler(handler) | python | def apply_handler_to_all_logs(handler: logging.Handler,
remove_existing: bool = False) -> None:
"""
Applies a handler to all logs, optionally removing existing handlers.
Should ONLY be called from the ``if __name__ == 'main'`` script;
see https://docs.python.org/3.4/howto/logging.html#library-config.
Generally MORE SENSIBLE just to apply a handler to the root logger.
Args:
handler: the handler to apply
remove_existing: remove existing handlers from logger first?
"""
# noinspection PyUnresolvedReferences
for name, obj in logging.Logger.manager.loggerDict.items():
if remove_existing:
obj.handlers = [] # http://stackoverflow.com/questions/7484454
obj.addHandler(handler) | [
"def",
"apply_handler_to_all_logs",
"(",
"handler",
":",
"logging",
".",
"Handler",
",",
"remove_existing",
":",
"bool",
"=",
"False",
")",
"->",
"None",
":",
"# noinspection PyUnresolvedReferences",
"for",
"name",
",",
"obj",
"in",
"logging",
".",
"Logger",
".",
"manager",
".",
"loggerDict",
".",
"items",
"(",
")",
":",
"if",
"remove_existing",
":",
"obj",
".",
"handlers",
"=",
"[",
"]",
"# http://stackoverflow.com/questions/7484454",
"obj",
".",
"addHandler",
"(",
"handler",
")"
] | Applies a handler to all logs, optionally removing existing handlers.
Should ONLY be called from the ``if __name__ == 'main'`` script;
see https://docs.python.org/3.4/howto/logging.html#library-config.
Generally MORE SENSIBLE just to apply a handler to the root logger.
Args:
handler: the handler to apply
remove_existing: remove existing handlers from logger first? | [
"Applies",
"a",
"handler",
"to",
"all",
"logs",
"optionally",
"removing",
"existing",
"handlers",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/logs.py#L332-L350 |
RudolfCardinal/pythonlib | cardinal_pythonlib/logs.py | copy_root_log_to_file | def copy_root_log_to_file(filename: str,
fmt: str = LOG_FORMAT,
datefmt: str = LOG_DATEFMT) -> None:
"""
Copy all currently configured logs to the specified file.
Should ONLY be called from the ``if __name__ == 'main'`` script;
see https://docs.python.org/3.4/howto/logging.html#library-config.
"""
fh = logging.FileHandler(filename)
# default file mode is 'a' for append
formatter = logging.Formatter(fmt=fmt, datefmt=datefmt)
fh.setFormatter(formatter)
apply_handler_to_root_log(fh) | python | def copy_root_log_to_file(filename: str,
fmt: str = LOG_FORMAT,
datefmt: str = LOG_DATEFMT) -> None:
"""
Copy all currently configured logs to the specified file.
Should ONLY be called from the ``if __name__ == 'main'`` script;
see https://docs.python.org/3.4/howto/logging.html#library-config.
"""
fh = logging.FileHandler(filename)
# default file mode is 'a' for append
formatter = logging.Formatter(fmt=fmt, datefmt=datefmt)
fh.setFormatter(formatter)
apply_handler_to_root_log(fh) | [
"def",
"copy_root_log_to_file",
"(",
"filename",
":",
"str",
",",
"fmt",
":",
"str",
"=",
"LOG_FORMAT",
",",
"datefmt",
":",
"str",
"=",
"LOG_DATEFMT",
")",
"->",
"None",
":",
"fh",
"=",
"logging",
".",
"FileHandler",
"(",
"filename",
")",
"# default file mode is 'a' for append",
"formatter",
"=",
"logging",
".",
"Formatter",
"(",
"fmt",
"=",
"fmt",
",",
"datefmt",
"=",
"datefmt",
")",
"fh",
".",
"setFormatter",
"(",
"formatter",
")",
"apply_handler_to_root_log",
"(",
"fh",
")"
] | Copy all currently configured logs to the specified file.
Should ONLY be called from the ``if __name__ == 'main'`` script;
see https://docs.python.org/3.4/howto/logging.html#library-config. | [
"Copy",
"all",
"currently",
"configured",
"logs",
"to",
"the",
"specified",
"file",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/logs.py#L353-L366 |
RudolfCardinal/pythonlib | cardinal_pythonlib/logs.py | copy_all_logs_to_file | def copy_all_logs_to_file(filename: str,
fmt: str = LOG_FORMAT,
datefmt: str = LOG_DATEFMT) -> None:
"""
Copy all currently configured logs to the specified file.
Should ONLY be called from the ``if __name__ == 'main'`` script;
see https://docs.python.org/3.4/howto/logging.html#library-config.
Args:
filename: file to send log output to
fmt: passed to the ``fmt=`` argument of :class:`logging.Formatter`
datefmt: passed to the ``datefmt=`` argument of
:class:`logging.Formatter`
"""
fh = logging.FileHandler(filename)
# default file mode is 'a' for append
formatter = logging.Formatter(fmt=fmt, datefmt=datefmt)
fh.setFormatter(formatter)
apply_handler_to_all_logs(fh) | python | def copy_all_logs_to_file(filename: str,
fmt: str = LOG_FORMAT,
datefmt: str = LOG_DATEFMT) -> None:
"""
Copy all currently configured logs to the specified file.
Should ONLY be called from the ``if __name__ == 'main'`` script;
see https://docs.python.org/3.4/howto/logging.html#library-config.
Args:
filename: file to send log output to
fmt: passed to the ``fmt=`` argument of :class:`logging.Formatter`
datefmt: passed to the ``datefmt=`` argument of
:class:`logging.Formatter`
"""
fh = logging.FileHandler(filename)
# default file mode is 'a' for append
formatter = logging.Formatter(fmt=fmt, datefmt=datefmt)
fh.setFormatter(formatter)
apply_handler_to_all_logs(fh) | [
"def",
"copy_all_logs_to_file",
"(",
"filename",
":",
"str",
",",
"fmt",
":",
"str",
"=",
"LOG_FORMAT",
",",
"datefmt",
":",
"str",
"=",
"LOG_DATEFMT",
")",
"->",
"None",
":",
"fh",
"=",
"logging",
".",
"FileHandler",
"(",
"filename",
")",
"# default file mode is 'a' for append",
"formatter",
"=",
"logging",
".",
"Formatter",
"(",
"fmt",
"=",
"fmt",
",",
"datefmt",
"=",
"datefmt",
")",
"fh",
".",
"setFormatter",
"(",
"formatter",
")",
"apply_handler_to_all_logs",
"(",
"fh",
")"
] | Copy all currently configured logs to the specified file.
Should ONLY be called from the ``if __name__ == 'main'`` script;
see https://docs.python.org/3.4/howto/logging.html#library-config.
Args:
filename: file to send log output to
fmt: passed to the ``fmt=`` argument of :class:`logging.Formatter`
datefmt: passed to the ``datefmt=`` argument of
:class:`logging.Formatter` | [
"Copy",
"all",
"currently",
"configured",
"logs",
"to",
"the",
"specified",
"file",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/logs.py#L369-L388 |
RudolfCardinal/pythonlib | cardinal_pythonlib/logs.py | get_formatter_report | def get_formatter_report(f: logging.Formatter) -> Optional[Dict[str, str]]:
"""
Returns information on a log formatter, as a dictionary.
For debugging.
"""
if f is None:
return None
return {
'_fmt': f._fmt,
'datefmt': f.datefmt,
'_style': str(f._style),
} | python | def get_formatter_report(f: logging.Formatter) -> Optional[Dict[str, str]]:
"""
Returns information on a log formatter, as a dictionary.
For debugging.
"""
if f is None:
return None
return {
'_fmt': f._fmt,
'datefmt': f.datefmt,
'_style': str(f._style),
} | [
"def",
"get_formatter_report",
"(",
"f",
":",
"logging",
".",
"Formatter",
")",
"->",
"Optional",
"[",
"Dict",
"[",
"str",
",",
"str",
"]",
"]",
":",
"if",
"f",
"is",
"None",
":",
"return",
"None",
"return",
"{",
"'_fmt'",
":",
"f",
".",
"_fmt",
",",
"'datefmt'",
":",
"f",
".",
"datefmt",
",",
"'_style'",
":",
"str",
"(",
"f",
".",
"_style",
")",
",",
"}"
] | Returns information on a log formatter, as a dictionary.
For debugging. | [
"Returns",
"information",
"on",
"a",
"log",
"formatter",
"as",
"a",
"dictionary",
".",
"For",
"debugging",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/logs.py#L392-L403 |
RudolfCardinal/pythonlib | cardinal_pythonlib/logs.py | get_handler_report | def get_handler_report(h: logging.Handler) -> Dict[str, Any]:
"""
Returns information on a log handler, as a dictionary.
For debugging.
"""
return {
'get_name()': h.get_name(),
'level': h.level,
'formatter': get_formatter_report(h.formatter),
'filters': h.filters,
} | python | def get_handler_report(h: logging.Handler) -> Dict[str, Any]:
"""
Returns information on a log handler, as a dictionary.
For debugging.
"""
return {
'get_name()': h.get_name(),
'level': h.level,
'formatter': get_formatter_report(h.formatter),
'filters': h.filters,
} | [
"def",
"get_handler_report",
"(",
"h",
":",
"logging",
".",
"Handler",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"return",
"{",
"'get_name()'",
":",
"h",
".",
"get_name",
"(",
")",
",",
"'level'",
":",
"h",
".",
"level",
",",
"'formatter'",
":",
"get_formatter_report",
"(",
"h",
".",
"formatter",
")",
",",
"'filters'",
":",
"h",
".",
"filters",
",",
"}"
] | Returns information on a log handler, as a dictionary.
For debugging. | [
"Returns",
"information",
"on",
"a",
"log",
"handler",
"as",
"a",
"dictionary",
".",
"For",
"debugging",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/logs.py#L406-L416 |
RudolfCardinal/pythonlib | cardinal_pythonlib/logs.py | get_log_report | def get_log_report(log: Union[logging.Logger,
logging.PlaceHolder]) -> Dict[str, Any]:
"""
Returns information on a log, as a dictionary. For debugging.
"""
if isinstance(log, logging.Logger):
# suppress invalid error for Logger.manager:
# noinspection PyUnresolvedReferences
return {
'(object)': str(log),
'level': log.level,
'disabled': log.disabled,
'propagate': log.propagate,
'parent': str(log.parent),
'manager': str(log.manager),
'handlers': [get_handler_report(h) for h in log.handlers],
}
elif isinstance(log, logging.PlaceHolder):
return {
"(object)": str(log),
}
else:
raise ValueError("Unknown object type: {!r}".format(log)) | python | def get_log_report(log: Union[logging.Logger,
logging.PlaceHolder]) -> Dict[str, Any]:
"""
Returns information on a log, as a dictionary. For debugging.
"""
if isinstance(log, logging.Logger):
# suppress invalid error for Logger.manager:
# noinspection PyUnresolvedReferences
return {
'(object)': str(log),
'level': log.level,
'disabled': log.disabled,
'propagate': log.propagate,
'parent': str(log.parent),
'manager': str(log.manager),
'handlers': [get_handler_report(h) for h in log.handlers],
}
elif isinstance(log, logging.PlaceHolder):
return {
"(object)": str(log),
}
else:
raise ValueError("Unknown object type: {!r}".format(log)) | [
"def",
"get_log_report",
"(",
"log",
":",
"Union",
"[",
"logging",
".",
"Logger",
",",
"logging",
".",
"PlaceHolder",
"]",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"if",
"isinstance",
"(",
"log",
",",
"logging",
".",
"Logger",
")",
":",
"# suppress invalid error for Logger.manager:",
"# noinspection PyUnresolvedReferences",
"return",
"{",
"'(object)'",
":",
"str",
"(",
"log",
")",
",",
"'level'",
":",
"log",
".",
"level",
",",
"'disabled'",
":",
"log",
".",
"disabled",
",",
"'propagate'",
":",
"log",
".",
"propagate",
",",
"'parent'",
":",
"str",
"(",
"log",
".",
"parent",
")",
",",
"'manager'",
":",
"str",
"(",
"log",
".",
"manager",
")",
",",
"'handlers'",
":",
"[",
"get_handler_report",
"(",
"h",
")",
"for",
"h",
"in",
"log",
".",
"handlers",
"]",
",",
"}",
"elif",
"isinstance",
"(",
"log",
",",
"logging",
".",
"PlaceHolder",
")",
":",
"return",
"{",
"\"(object)\"",
":",
"str",
"(",
"log",
")",
",",
"}",
"else",
":",
"raise",
"ValueError",
"(",
"\"Unknown object type: {!r}\"",
".",
"format",
"(",
"log",
")",
")"
] | Returns information on a log, as a dictionary. For debugging. | [
"Returns",
"information",
"on",
"a",
"log",
"as",
"a",
"dictionary",
".",
"For",
"debugging",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/logs.py#L419-L441 |
RudolfCardinal/pythonlib | cardinal_pythonlib/logs.py | print_report_on_all_logs | def print_report_on_all_logs() -> None:
"""
Use :func:`print` to report information on all logs.
"""
d = {}
# noinspection PyUnresolvedReferences
for name, obj in logging.Logger.manager.loggerDict.items():
d[name] = get_log_report(obj)
rootlogger = logging.getLogger()
d['(root logger)'] = get_log_report(rootlogger)
print(json.dumps(d, sort_keys=True, indent=4, separators=(',', ': '))) | python | def print_report_on_all_logs() -> None:
"""
Use :func:`print` to report information on all logs.
"""
d = {}
# noinspection PyUnresolvedReferences
for name, obj in logging.Logger.manager.loggerDict.items():
d[name] = get_log_report(obj)
rootlogger = logging.getLogger()
d['(root logger)'] = get_log_report(rootlogger)
print(json.dumps(d, sort_keys=True, indent=4, separators=(',', ': '))) | [
"def",
"print_report_on_all_logs",
"(",
")",
"->",
"None",
":",
"d",
"=",
"{",
"}",
"# noinspection PyUnresolvedReferences",
"for",
"name",
",",
"obj",
"in",
"logging",
".",
"Logger",
".",
"manager",
".",
"loggerDict",
".",
"items",
"(",
")",
":",
"d",
"[",
"name",
"]",
"=",
"get_log_report",
"(",
"obj",
")",
"rootlogger",
"=",
"logging",
".",
"getLogger",
"(",
")",
"d",
"[",
"'(root logger)'",
"]",
"=",
"get_log_report",
"(",
"rootlogger",
")",
"print",
"(",
"json",
".",
"dumps",
"(",
"d",
",",
"sort_keys",
"=",
"True",
",",
"indent",
"=",
"4",
",",
"separators",
"=",
"(",
"','",
",",
"': '",
")",
")",
")"
] | Use :func:`print` to report information on all logs. | [
"Use",
":",
"func",
":",
"print",
"to",
"report",
"information",
"on",
"all",
"logs",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/logs.py#L444-L454 |
RudolfCardinal/pythonlib | cardinal_pythonlib/logs.py | set_level_for_logger_and_its_handlers | def set_level_for_logger_and_its_handlers(log: logging.Logger,
level: int) -> None:
"""
Set a log level for a log and all its handlers.
Args:
log: log to modify
level: log level to set
"""
log.setLevel(level)
for h in log.handlers: # type: logging.Handler
h.setLevel(level) | python | def set_level_for_logger_and_its_handlers(log: logging.Logger,
level: int) -> None:
"""
Set a log level for a log and all its handlers.
Args:
log: log to modify
level: log level to set
"""
log.setLevel(level)
for h in log.handlers: # type: logging.Handler
h.setLevel(level) | [
"def",
"set_level_for_logger_and_its_handlers",
"(",
"log",
":",
"logging",
".",
"Logger",
",",
"level",
":",
"int",
")",
"->",
"None",
":",
"log",
".",
"setLevel",
"(",
"level",
")",
"for",
"h",
"in",
"log",
".",
"handlers",
":",
"# type: logging.Handler",
"h",
".",
"setLevel",
"(",
"level",
")"
] | Set a log level for a log and all its handlers.
Args:
log: log to modify
level: log level to set | [
"Set",
"a",
"log",
"level",
"for",
"a",
"log",
"and",
"all",
"its",
"handlers",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/logs.py#L457-L468 |
RudolfCardinal/pythonlib | cardinal_pythonlib/logs.py | get_brace_style_log_with_null_handler | def get_brace_style_log_with_null_handler(name: str) -> BraceStyleAdapter:
"""
For use by library functions. Returns a log with the specifed name that
has a null handler attached, and a :class:`BraceStyleAdapter`.
"""
log = logging.getLogger(name)
log.addHandler(logging.NullHandler())
return BraceStyleAdapter(log) | python | def get_brace_style_log_with_null_handler(name: str) -> BraceStyleAdapter:
"""
For use by library functions. Returns a log with the specifed name that
has a null handler attached, and a :class:`BraceStyleAdapter`.
"""
log = logging.getLogger(name)
log.addHandler(logging.NullHandler())
return BraceStyleAdapter(log) | [
"def",
"get_brace_style_log_with_null_handler",
"(",
"name",
":",
"str",
")",
"->",
"BraceStyleAdapter",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"name",
")",
"log",
".",
"addHandler",
"(",
"logging",
".",
"NullHandler",
"(",
")",
")",
"return",
"BraceStyleAdapter",
"(",
"log",
")"
] | For use by library functions. Returns a log with the specifed name that
has a null handler attached, and a :class:`BraceStyleAdapter`. | [
"For",
"use",
"by",
"library",
"functions",
".",
"Returns",
"a",
"log",
"with",
"the",
"specifed",
"name",
"that",
"has",
"a",
"null",
"handler",
"attached",
"and",
"a",
":",
"class",
":",
"BraceStyleAdapter",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/logs.py#L697-L704 |
RudolfCardinal/pythonlib | cardinal_pythonlib/logs.py | HtmlColorFormatter.format | def format(self, record: logging.LogRecord) -> str:
"""
Internal function to format the :class:`LogRecord` as HTML.
See https://docs.python.org/3.4/library/logging.html#logging.LogRecord
"""
# message = super().format(record)
super().format(record)
# Since fmt does not contain asctime, the Formatter.format()
# will not write asctime (since its usesTime()) function will be
# false. Therefore:
record.asctime = self.formatTime(record, self.datefmt)
bg_col = self.log_background_colors[record.levelno]
msg = escape(record.getMessage())
# escape() won't replace \n but will replace & etc.
if self.replace_nl_with_br:
msg = msg.replace("\n", "<br>")
html = (
'<span style="color:#008B8B">{time}.{ms:03d} {name}:{lvname}: '
'</span><span style="color:{color}{bg}">{msg}</font>{br}'.format(
time=record.asctime,
ms=int(record.msecs),
name=record.name,
lvname=record.levelname,
color=self.log_colors[record.levelno],
msg=msg,
bg=";background-color:{}".format(bg_col) if bg_col else "",
br="<br>" if self.append_br else "",
)
)
# print("record.__dict__: {}".format(record.__dict__))
# print("html: {}".format(html))
return html | python | def format(self, record: logging.LogRecord) -> str:
"""
Internal function to format the :class:`LogRecord` as HTML.
See https://docs.python.org/3.4/library/logging.html#logging.LogRecord
"""
# message = super().format(record)
super().format(record)
# Since fmt does not contain asctime, the Formatter.format()
# will not write asctime (since its usesTime()) function will be
# false. Therefore:
record.asctime = self.formatTime(record, self.datefmt)
bg_col = self.log_background_colors[record.levelno]
msg = escape(record.getMessage())
# escape() won't replace \n but will replace & etc.
if self.replace_nl_with_br:
msg = msg.replace("\n", "<br>")
html = (
'<span style="color:#008B8B">{time}.{ms:03d} {name}:{lvname}: '
'</span><span style="color:{color}{bg}">{msg}</font>{br}'.format(
time=record.asctime,
ms=int(record.msecs),
name=record.name,
lvname=record.levelname,
color=self.log_colors[record.levelno],
msg=msg,
bg=";background-color:{}".format(bg_col) if bg_col else "",
br="<br>" if self.append_br else "",
)
)
# print("record.__dict__: {}".format(record.__dict__))
# print("html: {}".format(html))
return html | [
"def",
"format",
"(",
"self",
",",
"record",
":",
"logging",
".",
"LogRecord",
")",
"->",
"str",
":",
"# message = super().format(record)",
"super",
"(",
")",
".",
"format",
"(",
"record",
")",
"# Since fmt does not contain asctime, the Formatter.format()",
"# will not write asctime (since its usesTime()) function will be",
"# false. Therefore:",
"record",
".",
"asctime",
"=",
"self",
".",
"formatTime",
"(",
"record",
",",
"self",
".",
"datefmt",
")",
"bg_col",
"=",
"self",
".",
"log_background_colors",
"[",
"record",
".",
"levelno",
"]",
"msg",
"=",
"escape",
"(",
"record",
".",
"getMessage",
"(",
")",
")",
"# escape() won't replace \\n but will replace & etc.",
"if",
"self",
".",
"replace_nl_with_br",
":",
"msg",
"=",
"msg",
".",
"replace",
"(",
"\"\\n\"",
",",
"\"<br>\"",
")",
"html",
"=",
"(",
"'<span style=\"color:#008B8B\">{time}.{ms:03d} {name}:{lvname}: '",
"'</span><span style=\"color:{color}{bg}\">{msg}</font>{br}'",
".",
"format",
"(",
"time",
"=",
"record",
".",
"asctime",
",",
"ms",
"=",
"int",
"(",
"record",
".",
"msecs",
")",
",",
"name",
"=",
"record",
".",
"name",
",",
"lvname",
"=",
"record",
".",
"levelname",
",",
"color",
"=",
"self",
".",
"log_colors",
"[",
"record",
".",
"levelno",
"]",
",",
"msg",
"=",
"msg",
",",
"bg",
"=",
"\";background-color:{}\"",
".",
"format",
"(",
"bg_col",
")",
"if",
"bg_col",
"else",
"\"\"",
",",
"br",
"=",
"\"<br>\"",
"if",
"self",
".",
"append_br",
"else",
"\"\"",
",",
")",
")",
"# print(\"record.__dict__: {}\".format(record.__dict__))",
"# print(\"html: {}\".format(html))",
"return",
"html"
] | Internal function to format the :class:`LogRecord` as HTML.
See https://docs.python.org/3.4/library/logging.html#logging.LogRecord | [
"Internal",
"function",
"to",
"format",
"the",
":",
"class",
":",
"LogRecord",
"as",
"HTML",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/logs.py#L511-L544 |
RudolfCardinal/pythonlib | cardinal_pythonlib/logs.py | HtmlColorHandler.emit | def emit(self, record: logging.LogRecord) -> None:
"""
Internal function to process a :class:`LogRecord`.
"""
# noinspection PyBroadException
try:
html = self.format(record)
self.logfunction(html)
except: # nopep8
self.handleError(record) | python | def emit(self, record: logging.LogRecord) -> None:
"""
Internal function to process a :class:`LogRecord`.
"""
# noinspection PyBroadException
try:
html = self.format(record)
self.logfunction(html)
except: # nopep8
self.handleError(record) | [
"def",
"emit",
"(",
"self",
",",
"record",
":",
"logging",
".",
"LogRecord",
")",
"->",
"None",
":",
"# noinspection PyBroadException",
"try",
":",
"html",
"=",
"self",
".",
"format",
"(",
"record",
")",
"self",
".",
"logfunction",
"(",
"html",
")",
"except",
":",
"# nopep8",
"self",
".",
"handleError",
"(",
"record",
")"
] | Internal function to process a :class:`LogRecord`. | [
"Internal",
"function",
"to",
"process",
"a",
":",
"class",
":",
"LogRecord",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/logs.py#L563-L572 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/schema.py | get_table_names | def get_table_names(engine: Engine) -> List[str]:
"""
Returns a list of database table names from the :class:`Engine`.
"""
insp = Inspector.from_engine(engine)
return insp.get_table_names() | python | def get_table_names(engine: Engine) -> List[str]:
"""
Returns a list of database table names from the :class:`Engine`.
"""
insp = Inspector.from_engine(engine)
return insp.get_table_names() | [
"def",
"get_table_names",
"(",
"engine",
":",
"Engine",
")",
"->",
"List",
"[",
"str",
"]",
":",
"insp",
"=",
"Inspector",
".",
"from_engine",
"(",
"engine",
")",
"return",
"insp",
".",
"get_table_names",
"(",
")"
] | Returns a list of database table names from the :class:`Engine`. | [
"Returns",
"a",
"list",
"of",
"database",
"table",
"names",
"from",
"the",
":",
"class",
":",
"Engine",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L71-L76 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/schema.py | get_view_names | def get_view_names(engine: Engine) -> List[str]:
"""
Returns a list of database view names from the :class:`Engine`.
"""
insp = Inspector.from_engine(engine)
return insp.get_view_names() | python | def get_view_names(engine: Engine) -> List[str]:
"""
Returns a list of database view names from the :class:`Engine`.
"""
insp = Inspector.from_engine(engine)
return insp.get_view_names() | [
"def",
"get_view_names",
"(",
"engine",
":",
"Engine",
")",
"->",
"List",
"[",
"str",
"]",
":",
"insp",
"=",
"Inspector",
".",
"from_engine",
"(",
"engine",
")",
"return",
"insp",
".",
"get_view_names",
"(",
")"
] | Returns a list of database view names from the :class:`Engine`. | [
"Returns",
"a",
"list",
"of",
"database",
"view",
"names",
"from",
"the",
":",
"class",
":",
"Engine",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L79-L84 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/schema.py | table_or_view_exists | def table_or_view_exists(engine: Engine, table_or_view_name: str) -> bool:
"""
Does the named table/view exist (either as a table or as a view) in the
database?
"""
tables_and_views = get_table_names(engine) + get_view_names(engine)
return table_or_view_name in tables_and_views | python | def table_or_view_exists(engine: Engine, table_or_view_name: str) -> bool:
"""
Does the named table/view exist (either as a table or as a view) in the
database?
"""
tables_and_views = get_table_names(engine) + get_view_names(engine)
return table_or_view_name in tables_and_views | [
"def",
"table_or_view_exists",
"(",
"engine",
":",
"Engine",
",",
"table_or_view_name",
":",
"str",
")",
"->",
"bool",
":",
"tables_and_views",
"=",
"get_table_names",
"(",
"engine",
")",
"+",
"get_view_names",
"(",
"engine",
")",
"return",
"table_or_view_name",
"in",
"tables_and_views"
] | Does the named table/view exist (either as a table or as a view) in the
database? | [
"Does",
"the",
"named",
"table",
"/",
"view",
"exist",
"(",
"either",
"as",
"a",
"table",
"or",
"as",
"a",
"view",
")",
"in",
"the",
"database?"
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L101-L107 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/schema.py | gen_columns_info | def gen_columns_info(engine: Engine,
tablename: str) -> Generator[SqlaColumnInspectionInfo,
None, None]:
"""
For the specified table, generate column information as
:class:`SqlaColumnInspectionInfo` objects.
"""
# Dictionary structure: see
# http://docs.sqlalchemy.org/en/latest/core/reflection.html#sqlalchemy.engine.reflection.Inspector.get_columns # noqa
insp = Inspector.from_engine(engine)
for d in insp.get_columns(tablename):
yield SqlaColumnInspectionInfo(d) | python | def gen_columns_info(engine: Engine,
tablename: str) -> Generator[SqlaColumnInspectionInfo,
None, None]:
"""
For the specified table, generate column information as
:class:`SqlaColumnInspectionInfo` objects.
"""
# Dictionary structure: see
# http://docs.sqlalchemy.org/en/latest/core/reflection.html#sqlalchemy.engine.reflection.Inspector.get_columns # noqa
insp = Inspector.from_engine(engine)
for d in insp.get_columns(tablename):
yield SqlaColumnInspectionInfo(d) | [
"def",
"gen_columns_info",
"(",
"engine",
":",
"Engine",
",",
"tablename",
":",
"str",
")",
"->",
"Generator",
"[",
"SqlaColumnInspectionInfo",
",",
"None",
",",
"None",
"]",
":",
"# Dictionary structure: see",
"# http://docs.sqlalchemy.org/en/latest/core/reflection.html#sqlalchemy.engine.reflection.Inspector.get_columns # noqa",
"insp",
"=",
"Inspector",
".",
"from_engine",
"(",
"engine",
")",
"for",
"d",
"in",
"insp",
".",
"get_columns",
"(",
"tablename",
")",
":",
"yield",
"SqlaColumnInspectionInfo",
"(",
"d",
")"
] | For the specified table, generate column information as
:class:`SqlaColumnInspectionInfo` objects. | [
"For",
"the",
"specified",
"table",
"generate",
"column",
"information",
"as",
":",
"class",
":",
"SqlaColumnInspectionInfo",
"objects",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L136-L147 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/schema.py | get_column_info | def get_column_info(engine: Engine, tablename: str,
columnname: str) -> Optional[SqlaColumnInspectionInfo]:
"""
For the specified column in the specified table, get column information
as a :class:`SqlaColumnInspectionInfo` object (or ``None`` if such a
column can't be found).
"""
for info in gen_columns_info(engine, tablename):
if info.name == columnname:
return info
return None | python | def get_column_info(engine: Engine, tablename: str,
columnname: str) -> Optional[SqlaColumnInspectionInfo]:
"""
For the specified column in the specified table, get column information
as a :class:`SqlaColumnInspectionInfo` object (or ``None`` if such a
column can't be found).
"""
for info in gen_columns_info(engine, tablename):
if info.name == columnname:
return info
return None | [
"def",
"get_column_info",
"(",
"engine",
":",
"Engine",
",",
"tablename",
":",
"str",
",",
"columnname",
":",
"str",
")",
"->",
"Optional",
"[",
"SqlaColumnInspectionInfo",
"]",
":",
"for",
"info",
"in",
"gen_columns_info",
"(",
"engine",
",",
"tablename",
")",
":",
"if",
"info",
".",
"name",
"==",
"columnname",
":",
"return",
"info",
"return",
"None"
] | For the specified column in the specified table, get column information
as a :class:`SqlaColumnInspectionInfo` object (or ``None`` if such a
column can't be found). | [
"For",
"the",
"specified",
"column",
"in",
"the",
"specified",
"table",
"get",
"column",
"information",
"as",
"a",
":",
"class",
":",
"SqlaColumnInspectionInfo",
"object",
"(",
"or",
"None",
"if",
"such",
"a",
"column",
"can",
"t",
"be",
"found",
")",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L150-L160 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/schema.py | get_column_type | def get_column_type(engine: Engine, tablename: str,
columnname: str) -> Optional[TypeEngine]:
"""
For the specified column in the specified table, get its type as an
instance of an SQLAlchemy column type class (or ``None`` if such a column
can't be found).
For more on :class:`TypeEngine`, see
:func:`cardinal_pythonlib.orm_inspect.coltype_as_typeengine`.
"""
for info in gen_columns_info(engine, tablename):
if info.name == columnname:
return info.type
return None | python | def get_column_type(engine: Engine, tablename: str,
columnname: str) -> Optional[TypeEngine]:
"""
For the specified column in the specified table, get its type as an
instance of an SQLAlchemy column type class (or ``None`` if such a column
can't be found).
For more on :class:`TypeEngine`, see
:func:`cardinal_pythonlib.orm_inspect.coltype_as_typeengine`.
"""
for info in gen_columns_info(engine, tablename):
if info.name == columnname:
return info.type
return None | [
"def",
"get_column_type",
"(",
"engine",
":",
"Engine",
",",
"tablename",
":",
"str",
",",
"columnname",
":",
"str",
")",
"->",
"Optional",
"[",
"TypeEngine",
"]",
":",
"for",
"info",
"in",
"gen_columns_info",
"(",
"engine",
",",
"tablename",
")",
":",
"if",
"info",
".",
"name",
"==",
"columnname",
":",
"return",
"info",
".",
"type",
"return",
"None"
] | For the specified column in the specified table, get its type as an
instance of an SQLAlchemy column type class (or ``None`` if such a column
can't be found).
For more on :class:`TypeEngine`, see
:func:`cardinal_pythonlib.orm_inspect.coltype_as_typeengine`. | [
"For",
"the",
"specified",
"column",
"in",
"the",
"specified",
"table",
"get",
"its",
"type",
"as",
"an",
"instance",
"of",
"an",
"SQLAlchemy",
"column",
"type",
"class",
"(",
"or",
"None",
"if",
"such",
"a",
"column",
"can",
"t",
"be",
"found",
")",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L163-L176 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/schema.py | get_column_names | def get_column_names(engine: Engine, tablename: str) -> List[str]:
"""
Get all the database column names for the specified table.
"""
return [info.name for info in gen_columns_info(engine, tablename)] | python | def get_column_names(engine: Engine, tablename: str) -> List[str]:
"""
Get all the database column names for the specified table.
"""
return [info.name for info in gen_columns_info(engine, tablename)] | [
"def",
"get_column_names",
"(",
"engine",
":",
"Engine",
",",
"tablename",
":",
"str",
")",
"->",
"List",
"[",
"str",
"]",
":",
"return",
"[",
"info",
".",
"name",
"for",
"info",
"in",
"gen_columns_info",
"(",
"engine",
",",
"tablename",
")",
"]"
] | Get all the database column names for the specified table. | [
"Get",
"all",
"the",
"database",
"column",
"names",
"for",
"the",
"specified",
"table",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L179-L183 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/schema.py | get_pk_colnames | def get_pk_colnames(table_: Table) -> List[str]:
"""
If a table has a PK, this will return its database column name(s);
otherwise, ``None``.
"""
pk_names = [] # type: List[str]
for col in table_.columns:
if col.primary_key:
pk_names.append(col.name)
return pk_names | python | def get_pk_colnames(table_: Table) -> List[str]:
"""
If a table has a PK, this will return its database column name(s);
otherwise, ``None``.
"""
pk_names = [] # type: List[str]
for col in table_.columns:
if col.primary_key:
pk_names.append(col.name)
return pk_names | [
"def",
"get_pk_colnames",
"(",
"table_",
":",
"Table",
")",
"->",
"List",
"[",
"str",
"]",
":",
"pk_names",
"=",
"[",
"]",
"# type: List[str]",
"for",
"col",
"in",
"table_",
".",
"columns",
":",
"if",
"col",
".",
"primary_key",
":",
"pk_names",
".",
"append",
"(",
"col",
".",
"name",
")",
"return",
"pk_names"
] | If a table has a PK, this will return its database column name(s);
otherwise, ``None``. | [
"If",
"a",
"table",
"has",
"a",
"PK",
"this",
"will",
"return",
"its",
"database",
"column",
"name",
"(",
"s",
")",
";",
"otherwise",
"None",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L190-L199 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/schema.py | get_single_int_pk_colname | def get_single_int_pk_colname(table_: Table) -> Optional[str]:
"""
If a table has a single-field (non-composite) integer PK, this will
return its database column name; otherwise, None.
Note that it is legitimate for a database table to have both a composite
primary key and a separate ``IDENTITY`` (``AUTOINCREMENT``) integer field.
This function won't find such columns.
"""
n_pks = 0
int_pk_names = []
for col in table_.columns:
if col.primary_key:
n_pks += 1
if is_sqlatype_integer(col.type):
int_pk_names.append(col.name)
if n_pks == 1 and len(int_pk_names) == 1:
return int_pk_names[0]
return None | python | def get_single_int_pk_colname(table_: Table) -> Optional[str]:
"""
If a table has a single-field (non-composite) integer PK, this will
return its database column name; otherwise, None.
Note that it is legitimate for a database table to have both a composite
primary key and a separate ``IDENTITY`` (``AUTOINCREMENT``) integer field.
This function won't find such columns.
"""
n_pks = 0
int_pk_names = []
for col in table_.columns:
if col.primary_key:
n_pks += 1
if is_sqlatype_integer(col.type):
int_pk_names.append(col.name)
if n_pks == 1 and len(int_pk_names) == 1:
return int_pk_names[0]
return None | [
"def",
"get_single_int_pk_colname",
"(",
"table_",
":",
"Table",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"n_pks",
"=",
"0",
"int_pk_names",
"=",
"[",
"]",
"for",
"col",
"in",
"table_",
".",
"columns",
":",
"if",
"col",
".",
"primary_key",
":",
"n_pks",
"+=",
"1",
"if",
"is_sqlatype_integer",
"(",
"col",
".",
"type",
")",
":",
"int_pk_names",
".",
"append",
"(",
"col",
".",
"name",
")",
"if",
"n_pks",
"==",
"1",
"and",
"len",
"(",
"int_pk_names",
")",
"==",
"1",
":",
"return",
"int_pk_names",
"[",
"0",
"]",
"return",
"None"
] | If a table has a single-field (non-composite) integer PK, this will
return its database column name; otherwise, None.
Note that it is legitimate for a database table to have both a composite
primary key and a separate ``IDENTITY`` (``AUTOINCREMENT``) integer field.
This function won't find such columns. | [
"If",
"a",
"table",
"has",
"a",
"single",
"-",
"field",
"(",
"non",
"-",
"composite",
")",
"integer",
"PK",
"this",
"will",
"return",
"its",
"database",
"column",
"name",
";",
"otherwise",
"None",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L202-L220 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/schema.py | get_single_int_autoincrement_colname | def get_single_int_autoincrement_colname(table_: Table) -> Optional[str]:
"""
If a table has a single integer ``AUTOINCREMENT`` column, this will
return its name; otherwise, ``None``.
- It's unlikely that a database has >1 ``AUTOINCREMENT`` field anyway, but
we should check.
- SQL Server's ``IDENTITY`` keyword is equivalent to MySQL's
``AUTOINCREMENT``.
- Verify against SQL Server:
.. code-block:: sql
SELECT table_name, column_name
FROM information_schema.columns
WHERE COLUMNPROPERTY(OBJECT_ID(table_schema + '.' + table_name),
column_name,
'IsIdentity') = 1
ORDER BY table_name;
... http://stackoverflow.com/questions/87747
- Also:
.. code-block:: sql
sp_columns 'tablename';
... which is what SQLAlchemy does (``dialects/mssql/base.py``, in
:func:`get_columns`).
"""
n_autoinc = 0
int_autoinc_names = []
for col in table_.columns:
if col.autoincrement:
n_autoinc += 1
if is_sqlatype_integer(col.type):
int_autoinc_names.append(col.name)
if n_autoinc > 1:
log.warning("Table {!r} has {} autoincrement columns",
table_.name, n_autoinc)
if n_autoinc == 1 and len(int_autoinc_names) == 1:
return int_autoinc_names[0]
return None | python | def get_single_int_autoincrement_colname(table_: Table) -> Optional[str]:
"""
If a table has a single integer ``AUTOINCREMENT`` column, this will
return its name; otherwise, ``None``.
- It's unlikely that a database has >1 ``AUTOINCREMENT`` field anyway, but
we should check.
- SQL Server's ``IDENTITY`` keyword is equivalent to MySQL's
``AUTOINCREMENT``.
- Verify against SQL Server:
.. code-block:: sql
SELECT table_name, column_name
FROM information_schema.columns
WHERE COLUMNPROPERTY(OBJECT_ID(table_schema + '.' + table_name),
column_name,
'IsIdentity') = 1
ORDER BY table_name;
... http://stackoverflow.com/questions/87747
- Also:
.. code-block:: sql
sp_columns 'tablename';
... which is what SQLAlchemy does (``dialects/mssql/base.py``, in
:func:`get_columns`).
"""
n_autoinc = 0
int_autoinc_names = []
for col in table_.columns:
if col.autoincrement:
n_autoinc += 1
if is_sqlatype_integer(col.type):
int_autoinc_names.append(col.name)
if n_autoinc > 1:
log.warning("Table {!r} has {} autoincrement columns",
table_.name, n_autoinc)
if n_autoinc == 1 and len(int_autoinc_names) == 1:
return int_autoinc_names[0]
return None | [
"def",
"get_single_int_autoincrement_colname",
"(",
"table_",
":",
"Table",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"n_autoinc",
"=",
"0",
"int_autoinc_names",
"=",
"[",
"]",
"for",
"col",
"in",
"table_",
".",
"columns",
":",
"if",
"col",
".",
"autoincrement",
":",
"n_autoinc",
"+=",
"1",
"if",
"is_sqlatype_integer",
"(",
"col",
".",
"type",
")",
":",
"int_autoinc_names",
".",
"append",
"(",
"col",
".",
"name",
")",
"if",
"n_autoinc",
">",
"1",
":",
"log",
".",
"warning",
"(",
"\"Table {!r} has {} autoincrement columns\"",
",",
"table_",
".",
"name",
",",
"n_autoinc",
")",
"if",
"n_autoinc",
"==",
"1",
"and",
"len",
"(",
"int_autoinc_names",
")",
"==",
"1",
":",
"return",
"int_autoinc_names",
"[",
"0",
"]",
"return",
"None"
] | If a table has a single integer ``AUTOINCREMENT`` column, this will
return its name; otherwise, ``None``.
- It's unlikely that a database has >1 ``AUTOINCREMENT`` field anyway, but
we should check.
- SQL Server's ``IDENTITY`` keyword is equivalent to MySQL's
``AUTOINCREMENT``.
- Verify against SQL Server:
.. code-block:: sql
SELECT table_name, column_name
FROM information_schema.columns
WHERE COLUMNPROPERTY(OBJECT_ID(table_schema + '.' + table_name),
column_name,
'IsIdentity') = 1
ORDER BY table_name;
... http://stackoverflow.com/questions/87747
- Also:
.. code-block:: sql
sp_columns 'tablename';
... which is what SQLAlchemy does (``dialects/mssql/base.py``, in
:func:`get_columns`). | [
"If",
"a",
"table",
"has",
"a",
"single",
"integer",
"AUTOINCREMENT",
"column",
"this",
"will",
"return",
"its",
"name",
";",
"otherwise",
"None",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L223-L266 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/schema.py | index_exists | def index_exists(engine: Engine, tablename: str, indexname: str) -> bool:
"""
Does the specified index exist for the specified table?
"""
insp = Inspector.from_engine(engine)
return any(i['name'] == indexname for i in insp.get_indexes(tablename)) | python | def index_exists(engine: Engine, tablename: str, indexname: str) -> bool:
"""
Does the specified index exist for the specified table?
"""
insp = Inspector.from_engine(engine)
return any(i['name'] == indexname for i in insp.get_indexes(tablename)) | [
"def",
"index_exists",
"(",
"engine",
":",
"Engine",
",",
"tablename",
":",
"str",
",",
"indexname",
":",
"str",
")",
"->",
"bool",
":",
"insp",
"=",
"Inspector",
".",
"from_engine",
"(",
"engine",
")",
"return",
"any",
"(",
"i",
"[",
"'name'",
"]",
"==",
"indexname",
"for",
"i",
"in",
"insp",
".",
"get_indexes",
"(",
"tablename",
")",
")"
] | Does the specified index exist for the specified table? | [
"Does",
"the",
"specified",
"index",
"exist",
"for",
"the",
"specified",
"table?"
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L285-L290 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/schema.py | mssql_get_pk_index_name | def mssql_get_pk_index_name(engine: Engine,
tablename: str,
schemaname: str = MSSQL_DEFAULT_SCHEMA) -> str:
"""
For Microsoft SQL Server specifically: fetch the name of the PK index
for the specified table (in the specified schema), or ``''`` if none is
found.
"""
# http://docs.sqlalchemy.org/en/latest/core/connections.html#sqlalchemy.engine.Connection.execute # noqa
# http://docs.sqlalchemy.org/en/latest/core/sqlelement.html#sqlalchemy.sql.expression.text # noqa
# http://docs.sqlalchemy.org/en/latest/core/sqlelement.html#sqlalchemy.sql.expression.TextClause.bindparams # noqa
# http://docs.sqlalchemy.org/en/latest/core/connections.html#sqlalchemy.engine.ResultProxy # noqa
query = text("""
SELECT
kc.name AS index_name
FROM
sys.key_constraints AS kc
INNER JOIN sys.tables AS ta ON ta.object_id = kc.parent_object_id
INNER JOIN sys.schemas AS s ON ta.schema_id = s.schema_id
WHERE
kc.[type] = 'PK'
AND ta.name = :tablename
AND s.name = :schemaname
""").bindparams(
tablename=tablename,
schemaname=schemaname,
)
with contextlib.closing(
engine.execute(query)) as result: # type: ResultProxy # noqa
row = result.fetchone()
return row[0] if row else '' | python | def mssql_get_pk_index_name(engine: Engine,
tablename: str,
schemaname: str = MSSQL_DEFAULT_SCHEMA) -> str:
"""
For Microsoft SQL Server specifically: fetch the name of the PK index
for the specified table (in the specified schema), or ``''`` if none is
found.
"""
# http://docs.sqlalchemy.org/en/latest/core/connections.html#sqlalchemy.engine.Connection.execute # noqa
# http://docs.sqlalchemy.org/en/latest/core/sqlelement.html#sqlalchemy.sql.expression.text # noqa
# http://docs.sqlalchemy.org/en/latest/core/sqlelement.html#sqlalchemy.sql.expression.TextClause.bindparams # noqa
# http://docs.sqlalchemy.org/en/latest/core/connections.html#sqlalchemy.engine.ResultProxy # noqa
query = text("""
SELECT
kc.name AS index_name
FROM
sys.key_constraints AS kc
INNER JOIN sys.tables AS ta ON ta.object_id = kc.parent_object_id
INNER JOIN sys.schemas AS s ON ta.schema_id = s.schema_id
WHERE
kc.[type] = 'PK'
AND ta.name = :tablename
AND s.name = :schemaname
""").bindparams(
tablename=tablename,
schemaname=schemaname,
)
with contextlib.closing(
engine.execute(query)) as result: # type: ResultProxy # noqa
row = result.fetchone()
return row[0] if row else '' | [
"def",
"mssql_get_pk_index_name",
"(",
"engine",
":",
"Engine",
",",
"tablename",
":",
"str",
",",
"schemaname",
":",
"str",
"=",
"MSSQL_DEFAULT_SCHEMA",
")",
"->",
"str",
":",
"# http://docs.sqlalchemy.org/en/latest/core/connections.html#sqlalchemy.engine.Connection.execute # noqa",
"# http://docs.sqlalchemy.org/en/latest/core/sqlelement.html#sqlalchemy.sql.expression.text # noqa",
"# http://docs.sqlalchemy.org/en/latest/core/sqlelement.html#sqlalchemy.sql.expression.TextClause.bindparams # noqa",
"# http://docs.sqlalchemy.org/en/latest/core/connections.html#sqlalchemy.engine.ResultProxy # noqa",
"query",
"=",
"text",
"(",
"\"\"\"\nSELECT\n kc.name AS index_name\nFROM\n sys.key_constraints AS kc\n INNER JOIN sys.tables AS ta ON ta.object_id = kc.parent_object_id\n INNER JOIN sys.schemas AS s ON ta.schema_id = s.schema_id\nWHERE\n kc.[type] = 'PK'\n AND ta.name = :tablename\n AND s.name = :schemaname\n \"\"\"",
")",
".",
"bindparams",
"(",
"tablename",
"=",
"tablename",
",",
"schemaname",
"=",
"schemaname",
",",
")",
"with",
"contextlib",
".",
"closing",
"(",
"engine",
".",
"execute",
"(",
"query",
")",
")",
"as",
"result",
":",
"# type: ResultProxy # noqa",
"row",
"=",
"result",
".",
"fetchone",
"(",
")",
"return",
"row",
"[",
"0",
"]",
"if",
"row",
"else",
"''"
] | For Microsoft SQL Server specifically: fetch the name of the PK index
for the specified table (in the specified schema), or ``''`` if none is
found. | [
"For",
"Microsoft",
"SQL",
"Server",
"specifically",
":",
"fetch",
"the",
"name",
"of",
"the",
"PK",
"index",
"for",
"the",
"specified",
"table",
"(",
"in",
"the",
"specified",
"schema",
")",
"or",
"if",
"none",
"is",
"found",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L293-L323 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/schema.py | mssql_transaction_count | def mssql_transaction_count(engine_or_conn: Union[Connection, Engine]) -> int:
"""
For Microsoft SQL Server specifically: fetch the value of the ``TRANCOUNT``
variable (see e.g.
https://docs.microsoft.com/en-us/sql/t-sql/functions/trancount-transact-sql?view=sql-server-2017).
Returns ``None`` if it can't be found (unlikely?).
"""
sql = "SELECT @@TRANCOUNT"
with contextlib.closing(
engine_or_conn.execute(sql)) as result: # type: ResultProxy # noqa
row = result.fetchone()
return row[0] if row else None | python | def mssql_transaction_count(engine_or_conn: Union[Connection, Engine]) -> int:
"""
For Microsoft SQL Server specifically: fetch the value of the ``TRANCOUNT``
variable (see e.g.
https://docs.microsoft.com/en-us/sql/t-sql/functions/trancount-transact-sql?view=sql-server-2017).
Returns ``None`` if it can't be found (unlikely?).
"""
sql = "SELECT @@TRANCOUNT"
with contextlib.closing(
engine_or_conn.execute(sql)) as result: # type: ResultProxy # noqa
row = result.fetchone()
return row[0] if row else None | [
"def",
"mssql_transaction_count",
"(",
"engine_or_conn",
":",
"Union",
"[",
"Connection",
",",
"Engine",
"]",
")",
"->",
"int",
":",
"sql",
"=",
"\"SELECT @@TRANCOUNT\"",
"with",
"contextlib",
".",
"closing",
"(",
"engine_or_conn",
".",
"execute",
"(",
"sql",
")",
")",
"as",
"result",
":",
"# type: ResultProxy # noqa",
"row",
"=",
"result",
".",
"fetchone",
"(",
")",
"return",
"row",
"[",
"0",
"]",
"if",
"row",
"else",
"None"
] | For Microsoft SQL Server specifically: fetch the value of the ``TRANCOUNT``
variable (see e.g.
https://docs.microsoft.com/en-us/sql/t-sql/functions/trancount-transact-sql?view=sql-server-2017).
Returns ``None`` if it can't be found (unlikely?). | [
"For",
"Microsoft",
"SQL",
"Server",
"specifically",
":",
"fetch",
"the",
"value",
"of",
"the",
"TRANCOUNT",
"variable",
"(",
"see",
"e",
".",
"g",
".",
"https",
":",
"//",
"docs",
".",
"microsoft",
".",
"com",
"/",
"en",
"-",
"us",
"/",
"sql",
"/",
"t",
"-",
"sql",
"/",
"functions",
"/",
"trancount",
"-",
"transact",
"-",
"sql?view",
"=",
"sql",
"-",
"server",
"-",
"2017",
")",
".",
"Returns",
"None",
"if",
"it",
"can",
"t",
"be",
"found",
"(",
"unlikely?",
")",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L354-L365 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/schema.py | add_index | def add_index(engine: Engine,
sqla_column: Column = None,
multiple_sqla_columns: List[Column] = None,
unique: bool = False,
fulltext: bool = False,
length: int = None) -> None:
"""
Adds an index to a database column (or, in restricted circumstances,
several columns).
The table name is worked out from the :class:`Column` object.
Args:
engine: SQLAlchemy :class:`Engine` object
sqla_column: single column to index
multiple_sqla_columns: multiple columns to index (see below)
unique: make a ``UNIQUE`` index?
fulltext: make a ``FULLTEXT`` index?
length: index length to use (default ``None``)
Restrictions:
- Specify either ``sqla_column`` or ``multiple_sqla_columns``, not both.
- The normal method is ``sqla_column``.
- ``multiple_sqla_columns`` is only used for Microsoft SQL Server full-text
indexing (as this database permits only one full-text index per table,
though that index can be on multiple columns).
"""
# We used to process a table as a unit; this makes index creation faster
# (using ALTER TABLE).
# http://dev.mysql.com/doc/innodb/1.1/en/innodb-create-index-examples.html # noqa
# ... ignored in transition to SQLAlchemy
def quote(identifier: str) -> str:
return quote_identifier(identifier, engine)
is_mssql = engine.dialect.name == SqlaDialectName.MSSQL
is_mysql = engine.dialect.name == SqlaDialectName.MYSQL
multiple_sqla_columns = multiple_sqla_columns or [] # type: List[Column]
if multiple_sqla_columns and not (fulltext and is_mssql):
raise ValueError("add_index: Use multiple_sqla_columns only for mssql "
"(Microsoft SQL Server) full-text indexing")
if bool(multiple_sqla_columns) == (sqla_column is not None):
raise ValueError(
"add_index: Use either sqla_column or multiple_sqla_columns, not "
"both (sqla_column = {}, multiple_sqla_columns = {}".format(
repr(sqla_column), repr(multiple_sqla_columns)))
if sqla_column is not None:
colnames = [sqla_column.name]
sqla_table = sqla_column.table
tablename = sqla_table.name
else:
colnames = [c.name for c in multiple_sqla_columns]
sqla_table = multiple_sqla_columns[0].table
tablename = sqla_table.name
if any(c.table.name != tablename for c in multiple_sqla_columns[1:]):
raise ValueError(
"add_index: tablenames are inconsistent in "
"multiple_sqla_columns = {}".format(
repr(multiple_sqla_columns)))
if fulltext:
if is_mssql:
idxname = '' # they are unnamed
else:
idxname = "_idxft_{}".format("_".join(colnames))
else:
idxname = "_idx_{}".format("_".join(colnames))
if idxname and index_exists(engine, tablename, idxname):
log.info("Skipping creation of index {} on table {}; already "
"exists".format(idxname, tablename))
return
# because it will crash if you add it again!
log.info(
"Creating{ft} index {i} on table {t}, column(s) {c}",
ft=" full-text" if fulltext else "",
i=idxname or "<unnamed>",
t=tablename,
c=", ".join(colnames),
)
if fulltext:
if is_mysql:
log.info('OK to ignore this warning, if it follows next: '
'"InnoDB rebuilding table to add column FTS_DOC_ID"')
# https://dev.mysql.com/doc/refman/5.6/en/innodb-fulltext-index.html
sql = (
"ALTER TABLE {tablename} "
"ADD FULLTEXT INDEX {idxname} ({colnames})".format(
tablename=quote(tablename),
idxname=quote(idxname),
colnames=", ".join(quote(c) for c in colnames),
)
)
# DDL(sql, bind=engine).execute_if(dialect=SqlaDialectName.MYSQL)
DDL(sql, bind=engine).execute()
elif is_mssql: # Microsoft SQL Server
# https://msdn.microsoft.com/library/ms187317(SQL.130).aspx
# Argh! Complex.
# Note that the database must also have had a
# CREATE FULLTEXT CATALOG somename AS DEFAULT;
# statement executed on it beforehand.
schemaname = engine.schema_for_object(
sqla_table) or MSSQL_DEFAULT_SCHEMA # noqa
if mssql_table_has_ft_index(engine=engine,
tablename=tablename,
schemaname=schemaname):
log.info(
"... skipping creation of full-text index on table {}; a "
"full-text index already exists for that table; you can "
"have only one full-text index per table, though it can "
"be on multiple columns".format(tablename))
return
pk_index_name = mssql_get_pk_index_name(
engine=engine, tablename=tablename, schemaname=schemaname)
if not pk_index_name:
raise ValueError(
"To make a FULLTEXT index under SQL Server, we need to "
"know the name of the PK index, but couldn't find one "
"from get_pk_index_name() for table {}".format(
repr(tablename)))
# We don't name the FULLTEXT index itself, but it has to relate
# to an existing unique index.
sql = (
"CREATE FULLTEXT INDEX ON {tablename} ({colnames}) "
"KEY INDEX {keyidxname} ".format(
tablename=quote(tablename),
keyidxname=quote(pk_index_name),
colnames=", ".join(quote(c) for c in colnames),
)
)
# SQL Server won't let you do this inside a transaction:
# "CREATE FULLTEXT INDEX statement cannot be used inside a user
# transaction."
# https://msdn.microsoft.com/nl-nl/library/ms191544(v=sql.105).aspx
# So let's ensure any preceding transactions are completed, and
# run the SQL in a raw way:
# engine.execute(sql).execution_options(autocommit=False)
# http://docs.sqlalchemy.org/en/latest/core/connections.html#understanding-autocommit
#
# ... lots of faff with this (see test code in no_transactions.py)
# ... ended up using explicit "autocommit=True" parameter (for
# pyodbc); see create_indexes()
transaction_count = mssql_transaction_count(engine)
if transaction_count != 0:
log.critical("SQL Server transaction count (should be 0): "
"{}".format(transaction_count))
# Executing serial COMMITs or a ROLLBACK won't help here if
# this transaction is due to Python DBAPI default behaviour.
DDL(sql, bind=engine).execute()
# The reversal procedure is DROP FULLTEXT INDEX ON tablename;
else:
log.error("Don't know how to make full text index on dialect "
"{}".format(engine.dialect.name))
else:
index = Index(idxname, sqla_column, unique=unique, mysql_length=length)
index.create(engine) | python | def add_index(engine: Engine,
sqla_column: Column = None,
multiple_sqla_columns: List[Column] = None,
unique: bool = False,
fulltext: bool = False,
length: int = None) -> None:
"""
Adds an index to a database column (or, in restricted circumstances,
several columns).
The table name is worked out from the :class:`Column` object.
Args:
engine: SQLAlchemy :class:`Engine` object
sqla_column: single column to index
multiple_sqla_columns: multiple columns to index (see below)
unique: make a ``UNIQUE`` index?
fulltext: make a ``FULLTEXT`` index?
length: index length to use (default ``None``)
Restrictions:
- Specify either ``sqla_column`` or ``multiple_sqla_columns``, not both.
- The normal method is ``sqla_column``.
- ``multiple_sqla_columns`` is only used for Microsoft SQL Server full-text
indexing (as this database permits only one full-text index per table,
though that index can be on multiple columns).
"""
# We used to process a table as a unit; this makes index creation faster
# (using ALTER TABLE).
# http://dev.mysql.com/doc/innodb/1.1/en/innodb-create-index-examples.html # noqa
# ... ignored in transition to SQLAlchemy
def quote(identifier: str) -> str:
return quote_identifier(identifier, engine)
is_mssql = engine.dialect.name == SqlaDialectName.MSSQL
is_mysql = engine.dialect.name == SqlaDialectName.MYSQL
multiple_sqla_columns = multiple_sqla_columns or [] # type: List[Column]
if multiple_sqla_columns and not (fulltext and is_mssql):
raise ValueError("add_index: Use multiple_sqla_columns only for mssql "
"(Microsoft SQL Server) full-text indexing")
if bool(multiple_sqla_columns) == (sqla_column is not None):
raise ValueError(
"add_index: Use either sqla_column or multiple_sqla_columns, not "
"both (sqla_column = {}, multiple_sqla_columns = {}".format(
repr(sqla_column), repr(multiple_sqla_columns)))
if sqla_column is not None:
colnames = [sqla_column.name]
sqla_table = sqla_column.table
tablename = sqla_table.name
else:
colnames = [c.name for c in multiple_sqla_columns]
sqla_table = multiple_sqla_columns[0].table
tablename = sqla_table.name
if any(c.table.name != tablename for c in multiple_sqla_columns[1:]):
raise ValueError(
"add_index: tablenames are inconsistent in "
"multiple_sqla_columns = {}".format(
repr(multiple_sqla_columns)))
if fulltext:
if is_mssql:
idxname = '' # they are unnamed
else:
idxname = "_idxft_{}".format("_".join(colnames))
else:
idxname = "_idx_{}".format("_".join(colnames))
if idxname and index_exists(engine, tablename, idxname):
log.info("Skipping creation of index {} on table {}; already "
"exists".format(idxname, tablename))
return
# because it will crash if you add it again!
log.info(
"Creating{ft} index {i} on table {t}, column(s) {c}",
ft=" full-text" if fulltext else "",
i=idxname or "<unnamed>",
t=tablename,
c=", ".join(colnames),
)
if fulltext:
if is_mysql:
log.info('OK to ignore this warning, if it follows next: '
'"InnoDB rebuilding table to add column FTS_DOC_ID"')
# https://dev.mysql.com/doc/refman/5.6/en/innodb-fulltext-index.html
sql = (
"ALTER TABLE {tablename} "
"ADD FULLTEXT INDEX {idxname} ({colnames})".format(
tablename=quote(tablename),
idxname=quote(idxname),
colnames=", ".join(quote(c) for c in colnames),
)
)
# DDL(sql, bind=engine).execute_if(dialect=SqlaDialectName.MYSQL)
DDL(sql, bind=engine).execute()
elif is_mssql: # Microsoft SQL Server
# https://msdn.microsoft.com/library/ms187317(SQL.130).aspx
# Argh! Complex.
# Note that the database must also have had a
# CREATE FULLTEXT CATALOG somename AS DEFAULT;
# statement executed on it beforehand.
schemaname = engine.schema_for_object(
sqla_table) or MSSQL_DEFAULT_SCHEMA # noqa
if mssql_table_has_ft_index(engine=engine,
tablename=tablename,
schemaname=schemaname):
log.info(
"... skipping creation of full-text index on table {}; a "
"full-text index already exists for that table; you can "
"have only one full-text index per table, though it can "
"be on multiple columns".format(tablename))
return
pk_index_name = mssql_get_pk_index_name(
engine=engine, tablename=tablename, schemaname=schemaname)
if not pk_index_name:
raise ValueError(
"To make a FULLTEXT index under SQL Server, we need to "
"know the name of the PK index, but couldn't find one "
"from get_pk_index_name() for table {}".format(
repr(tablename)))
# We don't name the FULLTEXT index itself, but it has to relate
# to an existing unique index.
sql = (
"CREATE FULLTEXT INDEX ON {tablename} ({colnames}) "
"KEY INDEX {keyidxname} ".format(
tablename=quote(tablename),
keyidxname=quote(pk_index_name),
colnames=", ".join(quote(c) for c in colnames),
)
)
# SQL Server won't let you do this inside a transaction:
# "CREATE FULLTEXT INDEX statement cannot be used inside a user
# transaction."
# https://msdn.microsoft.com/nl-nl/library/ms191544(v=sql.105).aspx
# So let's ensure any preceding transactions are completed, and
# run the SQL in a raw way:
# engine.execute(sql).execution_options(autocommit=False)
# http://docs.sqlalchemy.org/en/latest/core/connections.html#understanding-autocommit
#
# ... lots of faff with this (see test code in no_transactions.py)
# ... ended up using explicit "autocommit=True" parameter (for
# pyodbc); see create_indexes()
transaction_count = mssql_transaction_count(engine)
if transaction_count != 0:
log.critical("SQL Server transaction count (should be 0): "
"{}".format(transaction_count))
# Executing serial COMMITs or a ROLLBACK won't help here if
# this transaction is due to Python DBAPI default behaviour.
DDL(sql, bind=engine).execute()
# The reversal procedure is DROP FULLTEXT INDEX ON tablename;
else:
log.error("Don't know how to make full text index on dialect "
"{}".format(engine.dialect.name))
else:
index = Index(idxname, sqla_column, unique=unique, mysql_length=length)
index.create(engine) | [
"def",
"add_index",
"(",
"engine",
":",
"Engine",
",",
"sqla_column",
":",
"Column",
"=",
"None",
",",
"multiple_sqla_columns",
":",
"List",
"[",
"Column",
"]",
"=",
"None",
",",
"unique",
":",
"bool",
"=",
"False",
",",
"fulltext",
":",
"bool",
"=",
"False",
",",
"length",
":",
"int",
"=",
"None",
")",
"->",
"None",
":",
"# We used to process a table as a unit; this makes index creation faster",
"# (using ALTER TABLE).",
"# http://dev.mysql.com/doc/innodb/1.1/en/innodb-create-index-examples.html # noqa",
"# ... ignored in transition to SQLAlchemy",
"def",
"quote",
"(",
"identifier",
":",
"str",
")",
"->",
"str",
":",
"return",
"quote_identifier",
"(",
"identifier",
",",
"engine",
")",
"is_mssql",
"=",
"engine",
".",
"dialect",
".",
"name",
"==",
"SqlaDialectName",
".",
"MSSQL",
"is_mysql",
"=",
"engine",
".",
"dialect",
".",
"name",
"==",
"SqlaDialectName",
".",
"MYSQL",
"multiple_sqla_columns",
"=",
"multiple_sqla_columns",
"or",
"[",
"]",
"# type: List[Column]",
"if",
"multiple_sqla_columns",
"and",
"not",
"(",
"fulltext",
"and",
"is_mssql",
")",
":",
"raise",
"ValueError",
"(",
"\"add_index: Use multiple_sqla_columns only for mssql \"",
"\"(Microsoft SQL Server) full-text indexing\"",
")",
"if",
"bool",
"(",
"multiple_sqla_columns",
")",
"==",
"(",
"sqla_column",
"is",
"not",
"None",
")",
":",
"raise",
"ValueError",
"(",
"\"add_index: Use either sqla_column or multiple_sqla_columns, not \"",
"\"both (sqla_column = {}, multiple_sqla_columns = {}\"",
".",
"format",
"(",
"repr",
"(",
"sqla_column",
")",
",",
"repr",
"(",
"multiple_sqla_columns",
")",
")",
")",
"if",
"sqla_column",
"is",
"not",
"None",
":",
"colnames",
"=",
"[",
"sqla_column",
".",
"name",
"]",
"sqla_table",
"=",
"sqla_column",
".",
"table",
"tablename",
"=",
"sqla_table",
".",
"name",
"else",
":",
"colnames",
"=",
"[",
"c",
".",
"name",
"for",
"c",
"in",
"multiple_sqla_columns",
"]",
"sqla_table",
"=",
"multiple_sqla_columns",
"[",
"0",
"]",
".",
"table",
"tablename",
"=",
"sqla_table",
".",
"name",
"if",
"any",
"(",
"c",
".",
"table",
".",
"name",
"!=",
"tablename",
"for",
"c",
"in",
"multiple_sqla_columns",
"[",
"1",
":",
"]",
")",
":",
"raise",
"ValueError",
"(",
"\"add_index: tablenames are inconsistent in \"",
"\"multiple_sqla_columns = {}\"",
".",
"format",
"(",
"repr",
"(",
"multiple_sqla_columns",
")",
")",
")",
"if",
"fulltext",
":",
"if",
"is_mssql",
":",
"idxname",
"=",
"''",
"# they are unnamed",
"else",
":",
"idxname",
"=",
"\"_idxft_{}\"",
".",
"format",
"(",
"\"_\"",
".",
"join",
"(",
"colnames",
")",
")",
"else",
":",
"idxname",
"=",
"\"_idx_{}\"",
".",
"format",
"(",
"\"_\"",
".",
"join",
"(",
"colnames",
")",
")",
"if",
"idxname",
"and",
"index_exists",
"(",
"engine",
",",
"tablename",
",",
"idxname",
")",
":",
"log",
".",
"info",
"(",
"\"Skipping creation of index {} on table {}; already \"",
"\"exists\"",
".",
"format",
"(",
"idxname",
",",
"tablename",
")",
")",
"return",
"# because it will crash if you add it again!",
"log",
".",
"info",
"(",
"\"Creating{ft} index {i} on table {t}, column(s) {c}\"",
",",
"ft",
"=",
"\" full-text\"",
"if",
"fulltext",
"else",
"\"\"",
",",
"i",
"=",
"idxname",
"or",
"\"<unnamed>\"",
",",
"t",
"=",
"tablename",
",",
"c",
"=",
"\", \"",
".",
"join",
"(",
"colnames",
")",
",",
")",
"if",
"fulltext",
":",
"if",
"is_mysql",
":",
"log",
".",
"info",
"(",
"'OK to ignore this warning, if it follows next: '",
"'\"InnoDB rebuilding table to add column FTS_DOC_ID\"'",
")",
"# https://dev.mysql.com/doc/refman/5.6/en/innodb-fulltext-index.html",
"sql",
"=",
"(",
"\"ALTER TABLE {tablename} \"",
"\"ADD FULLTEXT INDEX {idxname} ({colnames})\"",
".",
"format",
"(",
"tablename",
"=",
"quote",
"(",
"tablename",
")",
",",
"idxname",
"=",
"quote",
"(",
"idxname",
")",
",",
"colnames",
"=",
"\", \"",
".",
"join",
"(",
"quote",
"(",
"c",
")",
"for",
"c",
"in",
"colnames",
")",
",",
")",
")",
"# DDL(sql, bind=engine).execute_if(dialect=SqlaDialectName.MYSQL)",
"DDL",
"(",
"sql",
",",
"bind",
"=",
"engine",
")",
".",
"execute",
"(",
")",
"elif",
"is_mssql",
":",
"# Microsoft SQL Server",
"# https://msdn.microsoft.com/library/ms187317(SQL.130).aspx",
"# Argh! Complex.",
"# Note that the database must also have had a",
"# CREATE FULLTEXT CATALOG somename AS DEFAULT;",
"# statement executed on it beforehand.",
"schemaname",
"=",
"engine",
".",
"schema_for_object",
"(",
"sqla_table",
")",
"or",
"MSSQL_DEFAULT_SCHEMA",
"# noqa",
"if",
"mssql_table_has_ft_index",
"(",
"engine",
"=",
"engine",
",",
"tablename",
"=",
"tablename",
",",
"schemaname",
"=",
"schemaname",
")",
":",
"log",
".",
"info",
"(",
"\"... skipping creation of full-text index on table {}; a \"",
"\"full-text index already exists for that table; you can \"",
"\"have only one full-text index per table, though it can \"",
"\"be on multiple columns\"",
".",
"format",
"(",
"tablename",
")",
")",
"return",
"pk_index_name",
"=",
"mssql_get_pk_index_name",
"(",
"engine",
"=",
"engine",
",",
"tablename",
"=",
"tablename",
",",
"schemaname",
"=",
"schemaname",
")",
"if",
"not",
"pk_index_name",
":",
"raise",
"ValueError",
"(",
"\"To make a FULLTEXT index under SQL Server, we need to \"",
"\"know the name of the PK index, but couldn't find one \"",
"\"from get_pk_index_name() for table {}\"",
".",
"format",
"(",
"repr",
"(",
"tablename",
")",
")",
")",
"# We don't name the FULLTEXT index itself, but it has to relate",
"# to an existing unique index.",
"sql",
"=",
"(",
"\"CREATE FULLTEXT INDEX ON {tablename} ({colnames}) \"",
"\"KEY INDEX {keyidxname} \"",
".",
"format",
"(",
"tablename",
"=",
"quote",
"(",
"tablename",
")",
",",
"keyidxname",
"=",
"quote",
"(",
"pk_index_name",
")",
",",
"colnames",
"=",
"\", \"",
".",
"join",
"(",
"quote",
"(",
"c",
")",
"for",
"c",
"in",
"colnames",
")",
",",
")",
")",
"# SQL Server won't let you do this inside a transaction:",
"# \"CREATE FULLTEXT INDEX statement cannot be used inside a user",
"# transaction.\"",
"# https://msdn.microsoft.com/nl-nl/library/ms191544(v=sql.105).aspx",
"# So let's ensure any preceding transactions are completed, and",
"# run the SQL in a raw way:",
"# engine.execute(sql).execution_options(autocommit=False)",
"# http://docs.sqlalchemy.org/en/latest/core/connections.html#understanding-autocommit",
"#",
"# ... lots of faff with this (see test code in no_transactions.py)",
"# ... ended up using explicit \"autocommit=True\" parameter (for",
"# pyodbc); see create_indexes()",
"transaction_count",
"=",
"mssql_transaction_count",
"(",
"engine",
")",
"if",
"transaction_count",
"!=",
"0",
":",
"log",
".",
"critical",
"(",
"\"SQL Server transaction count (should be 0): \"",
"\"{}\"",
".",
"format",
"(",
"transaction_count",
")",
")",
"# Executing serial COMMITs or a ROLLBACK won't help here if",
"# this transaction is due to Python DBAPI default behaviour.",
"DDL",
"(",
"sql",
",",
"bind",
"=",
"engine",
")",
".",
"execute",
"(",
")",
"# The reversal procedure is DROP FULLTEXT INDEX ON tablename;",
"else",
":",
"log",
".",
"error",
"(",
"\"Don't know how to make full text index on dialect \"",
"\"{}\"",
".",
"format",
"(",
"engine",
".",
"dialect",
".",
"name",
")",
")",
"else",
":",
"index",
"=",
"Index",
"(",
"idxname",
",",
"sqla_column",
",",
"unique",
"=",
"unique",
",",
"mysql_length",
"=",
"length",
")",
"index",
".",
"create",
"(",
"engine",
")"
] | Adds an index to a database column (or, in restricted circumstances,
several columns).
The table name is worked out from the :class:`Column` object.
Args:
engine: SQLAlchemy :class:`Engine` object
sqla_column: single column to index
multiple_sqla_columns: multiple columns to index (see below)
unique: make a ``UNIQUE`` index?
fulltext: make a ``FULLTEXT`` index?
length: index length to use (default ``None``)
Restrictions:
- Specify either ``sqla_column`` or ``multiple_sqla_columns``, not both.
- The normal method is ``sqla_column``.
- ``multiple_sqla_columns`` is only used for Microsoft SQL Server full-text
indexing (as this database permits only one full-text index per table,
though that index can be on multiple columns). | [
"Adds",
"an",
"index",
"to",
"a",
"database",
"column",
"(",
"or",
"in",
"restricted",
"circumstances",
"several",
"columns",
")",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L368-L530 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/schema.py | make_bigint_autoincrement_column | def make_bigint_autoincrement_column(column_name: str,
dialect: Dialect) -> Column:
"""
Returns an instance of :class:`Column` representing a :class:`BigInteger`
``AUTOINCREMENT`` column in the specified :class:`Dialect`.
"""
# noinspection PyUnresolvedReferences
if dialect.name == SqlaDialectName.MSSQL:
return Column(column_name, BigInteger,
Sequence('dummy_name', start=1, increment=1))
else:
# return Column(column_name, BigInteger, autoincrement=True)
# noinspection PyUnresolvedReferences
raise AssertionError(
"SQLAlchemy doesn't support non-PK autoincrement fields yet for "
"dialect {}".format(repr(dialect.name))) | python | def make_bigint_autoincrement_column(column_name: str,
dialect: Dialect) -> Column:
"""
Returns an instance of :class:`Column` representing a :class:`BigInteger`
``AUTOINCREMENT`` column in the specified :class:`Dialect`.
"""
# noinspection PyUnresolvedReferences
if dialect.name == SqlaDialectName.MSSQL:
return Column(column_name, BigInteger,
Sequence('dummy_name', start=1, increment=1))
else:
# return Column(column_name, BigInteger, autoincrement=True)
# noinspection PyUnresolvedReferences
raise AssertionError(
"SQLAlchemy doesn't support non-PK autoincrement fields yet for "
"dialect {}".format(repr(dialect.name))) | [
"def",
"make_bigint_autoincrement_column",
"(",
"column_name",
":",
"str",
",",
"dialect",
":",
"Dialect",
")",
"->",
"Column",
":",
"# noinspection PyUnresolvedReferences",
"if",
"dialect",
".",
"name",
"==",
"SqlaDialectName",
".",
"MSSQL",
":",
"return",
"Column",
"(",
"column_name",
",",
"BigInteger",
",",
"Sequence",
"(",
"'dummy_name'",
",",
"start",
"=",
"1",
",",
"increment",
"=",
"1",
")",
")",
"else",
":",
"# return Column(column_name, BigInteger, autoincrement=True)",
"# noinspection PyUnresolvedReferences",
"raise",
"AssertionError",
"(",
"\"SQLAlchemy doesn't support non-PK autoincrement fields yet for \"",
"\"dialect {}\"",
".",
"format",
"(",
"repr",
"(",
"dialect",
".",
"name",
")",
")",
")"
] | Returns an instance of :class:`Column` representing a :class:`BigInteger`
``AUTOINCREMENT`` column in the specified :class:`Dialect`. | [
"Returns",
"an",
"instance",
"of",
":",
"class",
":",
"Column",
"representing",
"a",
":",
"class",
":",
"BigInteger",
"AUTOINCREMENT",
"column",
"in",
"the",
"specified",
":",
"class",
":",
"Dialect",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L538-L553 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/schema.py | column_creation_ddl | def column_creation_ddl(sqla_column: Column, dialect: Dialect) -> str:
"""
Returns DDL to create a column, using the specified dialect.
The column should already be bound to a table (because e.g. the SQL Server
dialect requires this for DDL generation).
Manual testing:
.. code-block:: python
from sqlalchemy.schema import Column, CreateColumn, MetaData, Sequence, Table
from sqlalchemy.sql.sqltypes import BigInteger
from sqlalchemy.dialects.mssql.base import MSDialect
dialect = MSDialect()
col1 = Column('hello', BigInteger, nullable=True)
col2 = Column('world', BigInteger, autoincrement=True) # does NOT generate IDENTITY
col3 = Column('you', BigInteger, Sequence('dummy_name', start=1, increment=1))
metadata = MetaData()
t = Table('mytable', metadata)
t.append_column(col1)
t.append_column(col2)
t.append_column(col3)
print(str(CreateColumn(col1).compile(dialect=dialect))) # hello BIGINT NULL
print(str(CreateColumn(col2).compile(dialect=dialect))) # world BIGINT NULL
print(str(CreateColumn(col3).compile(dialect=dialect))) # you BIGINT NOT NULL IDENTITY(1,1)
If you don't append the column to a Table object, the DDL generation step
gives:
.. code-block:: none
sqlalchemy.exc.CompileError: mssql requires Table-bound columns in order to generate DDL
""" # noqa
return str(CreateColumn(sqla_column).compile(dialect=dialect)) | python | def column_creation_ddl(sqla_column: Column, dialect: Dialect) -> str:
"""
Returns DDL to create a column, using the specified dialect.
The column should already be bound to a table (because e.g. the SQL Server
dialect requires this for DDL generation).
Manual testing:
.. code-block:: python
from sqlalchemy.schema import Column, CreateColumn, MetaData, Sequence, Table
from sqlalchemy.sql.sqltypes import BigInteger
from sqlalchemy.dialects.mssql.base import MSDialect
dialect = MSDialect()
col1 = Column('hello', BigInteger, nullable=True)
col2 = Column('world', BigInteger, autoincrement=True) # does NOT generate IDENTITY
col3 = Column('you', BigInteger, Sequence('dummy_name', start=1, increment=1))
metadata = MetaData()
t = Table('mytable', metadata)
t.append_column(col1)
t.append_column(col2)
t.append_column(col3)
print(str(CreateColumn(col1).compile(dialect=dialect))) # hello BIGINT NULL
print(str(CreateColumn(col2).compile(dialect=dialect))) # world BIGINT NULL
print(str(CreateColumn(col3).compile(dialect=dialect))) # you BIGINT NOT NULL IDENTITY(1,1)
If you don't append the column to a Table object, the DDL generation step
gives:
.. code-block:: none
sqlalchemy.exc.CompileError: mssql requires Table-bound columns in order to generate DDL
""" # noqa
return str(CreateColumn(sqla_column).compile(dialect=dialect)) | [
"def",
"column_creation_ddl",
"(",
"sqla_column",
":",
"Column",
",",
"dialect",
":",
"Dialect",
")",
"->",
"str",
":",
"# noqa",
"return",
"str",
"(",
"CreateColumn",
"(",
"sqla_column",
")",
".",
"compile",
"(",
"dialect",
"=",
"dialect",
")",
")"
] | Returns DDL to create a column, using the specified dialect.
The column should already be bound to a table (because e.g. the SQL Server
dialect requires this for DDL generation).
Manual testing:
.. code-block:: python
from sqlalchemy.schema import Column, CreateColumn, MetaData, Sequence, Table
from sqlalchemy.sql.sqltypes import BigInteger
from sqlalchemy.dialects.mssql.base import MSDialect
dialect = MSDialect()
col1 = Column('hello', BigInteger, nullable=True)
col2 = Column('world', BigInteger, autoincrement=True) # does NOT generate IDENTITY
col3 = Column('you', BigInteger, Sequence('dummy_name', start=1, increment=1))
metadata = MetaData()
t = Table('mytable', metadata)
t.append_column(col1)
t.append_column(col2)
t.append_column(col3)
print(str(CreateColumn(col1).compile(dialect=dialect))) # hello BIGINT NULL
print(str(CreateColumn(col2).compile(dialect=dialect))) # world BIGINT NULL
print(str(CreateColumn(col3).compile(dialect=dialect))) # you BIGINT NOT NULL IDENTITY(1,1)
If you don't append the column to a Table object, the DDL generation step
gives:
.. code-block:: none
sqlalchemy.exc.CompileError: mssql requires Table-bound columns in order to generate DDL | [
"Returns",
"DDL",
"to",
"create",
"a",
"column",
"using",
"the",
"specified",
"dialect",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L557-L591 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/schema.py | giant_text_sqltype | def giant_text_sqltype(dialect: Dialect) -> str:
"""
Returns the SQL column type used to make very large text columns for a
given dialect.
Args:
dialect: a SQLAlchemy :class:`Dialect`
Returns:
the SQL data type of "giant text", typically 'LONGTEXT' for MySQL
and 'NVARCHAR(MAX)' for SQL Server.
"""
if dialect.name == SqlaDialectName.SQLSERVER:
return 'NVARCHAR(MAX)'
elif dialect.name == SqlaDialectName.MYSQL:
return 'LONGTEXT'
else:
raise ValueError("Unknown dialect: {}".format(dialect.name)) | python | def giant_text_sqltype(dialect: Dialect) -> str:
"""
Returns the SQL column type used to make very large text columns for a
given dialect.
Args:
dialect: a SQLAlchemy :class:`Dialect`
Returns:
the SQL data type of "giant text", typically 'LONGTEXT' for MySQL
and 'NVARCHAR(MAX)' for SQL Server.
"""
if dialect.name == SqlaDialectName.SQLSERVER:
return 'NVARCHAR(MAX)'
elif dialect.name == SqlaDialectName.MYSQL:
return 'LONGTEXT'
else:
raise ValueError("Unknown dialect: {}".format(dialect.name)) | [
"def",
"giant_text_sqltype",
"(",
"dialect",
":",
"Dialect",
")",
"->",
"str",
":",
"if",
"dialect",
".",
"name",
"==",
"SqlaDialectName",
".",
"SQLSERVER",
":",
"return",
"'NVARCHAR(MAX)'",
"elif",
"dialect",
".",
"name",
"==",
"SqlaDialectName",
".",
"MYSQL",
":",
"return",
"'LONGTEXT'",
"else",
":",
"raise",
"ValueError",
"(",
"\"Unknown dialect: {}\"",
".",
"format",
"(",
"dialect",
".",
"name",
")",
")"
] | Returns the SQL column type used to make very large text columns for a
given dialect.
Args:
dialect: a SQLAlchemy :class:`Dialect`
Returns:
the SQL data type of "giant text", typically 'LONGTEXT' for MySQL
and 'NVARCHAR(MAX)' for SQL Server. | [
"Returns",
"the",
"SQL",
"column",
"type",
"used",
"to",
"make",
"very",
"large",
"text",
"columns",
"for",
"a",
"given",
"dialect",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L595-L611 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/schema.py | _get_sqla_coltype_class_from_str | def _get_sqla_coltype_class_from_str(coltype: str,
dialect: Dialect) -> Type[TypeEngine]:
"""
Returns the SQLAlchemy class corresponding to a particular SQL column
type in a given dialect.
Performs an upper- and lower-case search.
For example, the SQLite dialect uses upper case, and the
MySQL dialect uses lower case.
"""
# noinspection PyUnresolvedReferences
ischema_names = dialect.ischema_names
try:
return ischema_names[coltype.upper()]
except KeyError:
return ischema_names[coltype.lower()] | python | def _get_sqla_coltype_class_from_str(coltype: str,
dialect: Dialect) -> Type[TypeEngine]:
"""
Returns the SQLAlchemy class corresponding to a particular SQL column
type in a given dialect.
Performs an upper- and lower-case search.
For example, the SQLite dialect uses upper case, and the
MySQL dialect uses lower case.
"""
# noinspection PyUnresolvedReferences
ischema_names = dialect.ischema_names
try:
return ischema_names[coltype.upper()]
except KeyError:
return ischema_names[coltype.lower()] | [
"def",
"_get_sqla_coltype_class_from_str",
"(",
"coltype",
":",
"str",
",",
"dialect",
":",
"Dialect",
")",
"->",
"Type",
"[",
"TypeEngine",
"]",
":",
"# noinspection PyUnresolvedReferences",
"ischema_names",
"=",
"dialect",
".",
"ischema_names",
"try",
":",
"return",
"ischema_names",
"[",
"coltype",
".",
"upper",
"(",
")",
"]",
"except",
"KeyError",
":",
"return",
"ischema_names",
"[",
"coltype",
".",
"lower",
"(",
")",
"]"
] | Returns the SQLAlchemy class corresponding to a particular SQL column
type in a given dialect.
Performs an upper- and lower-case search.
For example, the SQLite dialect uses upper case, and the
MySQL dialect uses lower case. | [
"Returns",
"the",
"SQLAlchemy",
"class",
"corresponding",
"to",
"a",
"particular",
"SQL",
"column",
"type",
"in",
"a",
"given",
"dialect",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L632-L647 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/schema.py | get_list_of_sql_string_literals_from_quoted_csv | def get_list_of_sql_string_literals_from_quoted_csv(x: str) -> List[str]:
"""
Used to extract SQL column type parameters. For example, MySQL has column
types that look like ``ENUM('a', 'b', 'c', 'd')``. This function takes the
``"'a', 'b', 'c', 'd'"`` and converts it to ``['a', 'b', 'c', 'd']``.
"""
f = io.StringIO(x)
reader = csv.reader(f, delimiter=',', quotechar="'", quoting=csv.QUOTE_ALL,
skipinitialspace=True)
for line in reader: # should only be one
return [x for x in line] | python | def get_list_of_sql_string_literals_from_quoted_csv(x: str) -> List[str]:
"""
Used to extract SQL column type parameters. For example, MySQL has column
types that look like ``ENUM('a', 'b', 'c', 'd')``. This function takes the
``"'a', 'b', 'c', 'd'"`` and converts it to ``['a', 'b', 'c', 'd']``.
"""
f = io.StringIO(x)
reader = csv.reader(f, delimiter=',', quotechar="'", quoting=csv.QUOTE_ALL,
skipinitialspace=True)
for line in reader: # should only be one
return [x for x in line] | [
"def",
"get_list_of_sql_string_literals_from_quoted_csv",
"(",
"x",
":",
"str",
")",
"->",
"List",
"[",
"str",
"]",
":",
"f",
"=",
"io",
".",
"StringIO",
"(",
"x",
")",
"reader",
"=",
"csv",
".",
"reader",
"(",
"f",
",",
"delimiter",
"=",
"','",
",",
"quotechar",
"=",
"\"'\"",
",",
"quoting",
"=",
"csv",
".",
"QUOTE_ALL",
",",
"skipinitialspace",
"=",
"True",
")",
"for",
"line",
"in",
"reader",
":",
"# should only be one",
"return",
"[",
"x",
"for",
"x",
"in",
"line",
"]"
] | Used to extract SQL column type parameters. For example, MySQL has column
types that look like ``ENUM('a', 'b', 'c', 'd')``. This function takes the
``"'a', 'b', 'c', 'd'"`` and converts it to ``['a', 'b', 'c', 'd']``. | [
"Used",
"to",
"extract",
"SQL",
"column",
"type",
"parameters",
".",
"For",
"example",
"MySQL",
"has",
"column",
"types",
"that",
"look",
"like",
"ENUM",
"(",
"a",
"b",
"c",
"d",
")",
".",
"This",
"function",
"takes",
"the",
"a",
"b",
"c",
"d",
"and",
"converts",
"it",
"to",
"[",
"a",
"b",
"c",
"d",
"]",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L650-L660 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/schema.py | get_sqla_coltype_from_dialect_str | def get_sqla_coltype_from_dialect_str(coltype: str,
dialect: Dialect) -> TypeEngine:
"""
Returns an SQLAlchemy column type, given a column type name (a string) and
an SQLAlchemy dialect. For example, this might convert the string
``INTEGER(11)`` to an SQLAlchemy ``Integer(length=11)``.
Args:
dialect: a SQLAlchemy :class:`Dialect` class
coltype: a ``str()`` representation, e.g. from ``str(c['type'])`` where
``c`` is an instance of :class:`sqlalchemy.sql.schema.Column`.
Returns:
a Python object that is a subclass of
:class:`sqlalchemy.types.TypeEngine`
Example:
.. code-block:: python
get_sqla_coltype_from_string('INTEGER(11)', engine.dialect)
# gives: Integer(length=11)
Notes:
- :class:`sqlalchemy.engine.default.DefaultDialect` is the dialect base
class
- a dialect contains these things of interest:
- ``ischema_names``: string-to-class dictionary
- ``type_compiler``: instance of e.g.
:class:`sqlalchemy.sql.compiler.GenericTypeCompiler`. This has a
``process()`` method, but that operates on :class:`TypeEngine` objects.
- ``get_columns``: takes a table name, inspects the database
- example of the dangers of ``eval``:
http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html
- An example of a function doing the reflection/inspection within
SQLAlchemy is
:func:`sqlalchemy.dialects.mssql.base.MSDialect.get_columns`,
which has this lookup: ``coltype = self.ischema_names.get(type, None)``
Caveats:
- the parameters, e.g. ``DATETIME(6)``, do NOT necessarily either work at
all or work correctly. For example, SQLAlchemy will happily spit out
``'INTEGER(11)'`` but its :class:`sqlalchemy.sql.sqltypes.INTEGER` class
takes no parameters, so you get the error ``TypeError: object() takes no
parameters``. Similarly, MySQL's ``DATETIME(6)`` uses the 6 to refer to
precision, but the ``DATETIME`` class in SQLAlchemy takes only a boolean
parameter (timezone).
- However, sometimes we have to have parameters, e.g. ``VARCHAR`` length.
- Thus, this is a bit useless.
- Fixed, with a few special cases.
"""
size = None # type: Optional[int]
dp = None # type: Optional[int]
args = [] # type: List[Any]
kwargs = {} # type: Dict[str, Any]
basetype = ''
# noinspection PyPep8,PyBroadException
try:
# Split e.g. "VARCHAR(32) COLLATE blah" into "VARCHAR(32)", "who cares"
m = RE_COLTYPE_WITH_COLLATE.match(coltype)
if m is not None:
coltype = m.group('maintype')
found = False
if not found:
# Deal with ENUM('a', 'b', 'c', ...)
m = RE_MYSQL_ENUM_COLTYPE.match(coltype)
if m is not None:
# Convert to VARCHAR with max size being that of largest enum
basetype = 'VARCHAR'
values = get_list_of_sql_string_literals_from_quoted_csv(
m.group('valuelist'))
length = max(len(x) for x in values)
kwargs = {'length': length}
found = True
if not found:
# Split e.g. "DECIMAL(10, 2)" into DECIMAL, 10, 2
m = RE_COLTYPE_WITH_TWO_PARAMS.match(coltype)
if m is not None:
basetype = m.group('type').upper()
size = ast.literal_eval(m.group('size'))
dp = ast.literal_eval(m.group('dp'))
found = True
if not found:
# Split e.g. "VARCHAR(32)" into VARCHAR, 32
m = RE_COLTYPE_WITH_ONE_PARAM.match(coltype)
if m is not None:
basetype = m.group('type').upper()
size_text = m.group('size').strip().upper()
if size_text != 'MAX':
size = ast.literal_eval(size_text)
found = True
if not found:
basetype = coltype.upper()
# Special cases: pre-processing
# noinspection PyUnresolvedReferences
if (dialect.name == SqlaDialectName.MSSQL and
basetype.lower() == 'integer'):
basetype = 'int'
cls = _get_sqla_coltype_class_from_str(basetype, dialect)
# Special cases: post-processing
if basetype == 'DATETIME' and size:
# First argument to DATETIME() is timezone, so...
# noinspection PyUnresolvedReferences
if dialect.name == SqlaDialectName.MYSQL:
kwargs = {'fsp': size}
else:
pass
else:
args = [x for x in (size, dp) if x is not None]
try:
return cls(*args, **kwargs)
except TypeError:
return cls()
except:
# noinspection PyUnresolvedReferences
raise ValueError("Failed to convert SQL type {} in dialect {} to an "
"SQLAlchemy type".format(repr(coltype),
repr(dialect.name))) | python | def get_sqla_coltype_from_dialect_str(coltype: str,
dialect: Dialect) -> TypeEngine:
"""
Returns an SQLAlchemy column type, given a column type name (a string) and
an SQLAlchemy dialect. For example, this might convert the string
``INTEGER(11)`` to an SQLAlchemy ``Integer(length=11)``.
Args:
dialect: a SQLAlchemy :class:`Dialect` class
coltype: a ``str()`` representation, e.g. from ``str(c['type'])`` where
``c`` is an instance of :class:`sqlalchemy.sql.schema.Column`.
Returns:
a Python object that is a subclass of
:class:`sqlalchemy.types.TypeEngine`
Example:
.. code-block:: python
get_sqla_coltype_from_string('INTEGER(11)', engine.dialect)
# gives: Integer(length=11)
Notes:
- :class:`sqlalchemy.engine.default.DefaultDialect` is the dialect base
class
- a dialect contains these things of interest:
- ``ischema_names``: string-to-class dictionary
- ``type_compiler``: instance of e.g.
:class:`sqlalchemy.sql.compiler.GenericTypeCompiler`. This has a
``process()`` method, but that operates on :class:`TypeEngine` objects.
- ``get_columns``: takes a table name, inspects the database
- example of the dangers of ``eval``:
http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html
- An example of a function doing the reflection/inspection within
SQLAlchemy is
:func:`sqlalchemy.dialects.mssql.base.MSDialect.get_columns`,
which has this lookup: ``coltype = self.ischema_names.get(type, None)``
Caveats:
- the parameters, e.g. ``DATETIME(6)``, do NOT necessarily either work at
all or work correctly. For example, SQLAlchemy will happily spit out
``'INTEGER(11)'`` but its :class:`sqlalchemy.sql.sqltypes.INTEGER` class
takes no parameters, so you get the error ``TypeError: object() takes no
parameters``. Similarly, MySQL's ``DATETIME(6)`` uses the 6 to refer to
precision, but the ``DATETIME`` class in SQLAlchemy takes only a boolean
parameter (timezone).
- However, sometimes we have to have parameters, e.g. ``VARCHAR`` length.
- Thus, this is a bit useless.
- Fixed, with a few special cases.
"""
size = None # type: Optional[int]
dp = None # type: Optional[int]
args = [] # type: List[Any]
kwargs = {} # type: Dict[str, Any]
basetype = ''
# noinspection PyPep8,PyBroadException
try:
# Split e.g. "VARCHAR(32) COLLATE blah" into "VARCHAR(32)", "who cares"
m = RE_COLTYPE_WITH_COLLATE.match(coltype)
if m is not None:
coltype = m.group('maintype')
found = False
if not found:
# Deal with ENUM('a', 'b', 'c', ...)
m = RE_MYSQL_ENUM_COLTYPE.match(coltype)
if m is not None:
# Convert to VARCHAR with max size being that of largest enum
basetype = 'VARCHAR'
values = get_list_of_sql_string_literals_from_quoted_csv(
m.group('valuelist'))
length = max(len(x) for x in values)
kwargs = {'length': length}
found = True
if not found:
# Split e.g. "DECIMAL(10, 2)" into DECIMAL, 10, 2
m = RE_COLTYPE_WITH_TWO_PARAMS.match(coltype)
if m is not None:
basetype = m.group('type').upper()
size = ast.literal_eval(m.group('size'))
dp = ast.literal_eval(m.group('dp'))
found = True
if not found:
# Split e.g. "VARCHAR(32)" into VARCHAR, 32
m = RE_COLTYPE_WITH_ONE_PARAM.match(coltype)
if m is not None:
basetype = m.group('type').upper()
size_text = m.group('size').strip().upper()
if size_text != 'MAX':
size = ast.literal_eval(size_text)
found = True
if not found:
basetype = coltype.upper()
# Special cases: pre-processing
# noinspection PyUnresolvedReferences
if (dialect.name == SqlaDialectName.MSSQL and
basetype.lower() == 'integer'):
basetype = 'int'
cls = _get_sqla_coltype_class_from_str(basetype, dialect)
# Special cases: post-processing
if basetype == 'DATETIME' and size:
# First argument to DATETIME() is timezone, so...
# noinspection PyUnresolvedReferences
if dialect.name == SqlaDialectName.MYSQL:
kwargs = {'fsp': size}
else:
pass
else:
args = [x for x in (size, dp) if x is not None]
try:
return cls(*args, **kwargs)
except TypeError:
return cls()
except:
# noinspection PyUnresolvedReferences
raise ValueError("Failed to convert SQL type {} in dialect {} to an "
"SQLAlchemy type".format(repr(coltype),
repr(dialect.name))) | [
"def",
"get_sqla_coltype_from_dialect_str",
"(",
"coltype",
":",
"str",
",",
"dialect",
":",
"Dialect",
")",
"->",
"TypeEngine",
":",
"size",
"=",
"None",
"# type: Optional[int]",
"dp",
"=",
"None",
"# type: Optional[int]",
"args",
"=",
"[",
"]",
"# type: List[Any]",
"kwargs",
"=",
"{",
"}",
"# type: Dict[str, Any]",
"basetype",
"=",
"''",
"# noinspection PyPep8,PyBroadException",
"try",
":",
"# Split e.g. \"VARCHAR(32) COLLATE blah\" into \"VARCHAR(32)\", \"who cares\"",
"m",
"=",
"RE_COLTYPE_WITH_COLLATE",
".",
"match",
"(",
"coltype",
")",
"if",
"m",
"is",
"not",
"None",
":",
"coltype",
"=",
"m",
".",
"group",
"(",
"'maintype'",
")",
"found",
"=",
"False",
"if",
"not",
"found",
":",
"# Deal with ENUM('a', 'b', 'c', ...)",
"m",
"=",
"RE_MYSQL_ENUM_COLTYPE",
".",
"match",
"(",
"coltype",
")",
"if",
"m",
"is",
"not",
"None",
":",
"# Convert to VARCHAR with max size being that of largest enum",
"basetype",
"=",
"'VARCHAR'",
"values",
"=",
"get_list_of_sql_string_literals_from_quoted_csv",
"(",
"m",
".",
"group",
"(",
"'valuelist'",
")",
")",
"length",
"=",
"max",
"(",
"len",
"(",
"x",
")",
"for",
"x",
"in",
"values",
")",
"kwargs",
"=",
"{",
"'length'",
":",
"length",
"}",
"found",
"=",
"True",
"if",
"not",
"found",
":",
"# Split e.g. \"DECIMAL(10, 2)\" into DECIMAL, 10, 2",
"m",
"=",
"RE_COLTYPE_WITH_TWO_PARAMS",
".",
"match",
"(",
"coltype",
")",
"if",
"m",
"is",
"not",
"None",
":",
"basetype",
"=",
"m",
".",
"group",
"(",
"'type'",
")",
".",
"upper",
"(",
")",
"size",
"=",
"ast",
".",
"literal_eval",
"(",
"m",
".",
"group",
"(",
"'size'",
")",
")",
"dp",
"=",
"ast",
".",
"literal_eval",
"(",
"m",
".",
"group",
"(",
"'dp'",
")",
")",
"found",
"=",
"True",
"if",
"not",
"found",
":",
"# Split e.g. \"VARCHAR(32)\" into VARCHAR, 32",
"m",
"=",
"RE_COLTYPE_WITH_ONE_PARAM",
".",
"match",
"(",
"coltype",
")",
"if",
"m",
"is",
"not",
"None",
":",
"basetype",
"=",
"m",
".",
"group",
"(",
"'type'",
")",
".",
"upper",
"(",
")",
"size_text",
"=",
"m",
".",
"group",
"(",
"'size'",
")",
".",
"strip",
"(",
")",
".",
"upper",
"(",
")",
"if",
"size_text",
"!=",
"'MAX'",
":",
"size",
"=",
"ast",
".",
"literal_eval",
"(",
"size_text",
")",
"found",
"=",
"True",
"if",
"not",
"found",
":",
"basetype",
"=",
"coltype",
".",
"upper",
"(",
")",
"# Special cases: pre-processing",
"# noinspection PyUnresolvedReferences",
"if",
"(",
"dialect",
".",
"name",
"==",
"SqlaDialectName",
".",
"MSSQL",
"and",
"basetype",
".",
"lower",
"(",
")",
"==",
"'integer'",
")",
":",
"basetype",
"=",
"'int'",
"cls",
"=",
"_get_sqla_coltype_class_from_str",
"(",
"basetype",
",",
"dialect",
")",
"# Special cases: post-processing",
"if",
"basetype",
"==",
"'DATETIME'",
"and",
"size",
":",
"# First argument to DATETIME() is timezone, so...",
"# noinspection PyUnresolvedReferences",
"if",
"dialect",
".",
"name",
"==",
"SqlaDialectName",
".",
"MYSQL",
":",
"kwargs",
"=",
"{",
"'fsp'",
":",
"size",
"}",
"else",
":",
"pass",
"else",
":",
"args",
"=",
"[",
"x",
"for",
"x",
"in",
"(",
"size",
",",
"dp",
")",
"if",
"x",
"is",
"not",
"None",
"]",
"try",
":",
"return",
"cls",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"TypeError",
":",
"return",
"cls",
"(",
")",
"except",
":",
"# noinspection PyUnresolvedReferences",
"raise",
"ValueError",
"(",
"\"Failed to convert SQL type {} in dialect {} to an \"",
"\"SQLAlchemy type\"",
".",
"format",
"(",
"repr",
"(",
"coltype",
")",
",",
"repr",
"(",
"dialect",
".",
"name",
")",
")",
")"
] | Returns an SQLAlchemy column type, given a column type name (a string) and
an SQLAlchemy dialect. For example, this might convert the string
``INTEGER(11)`` to an SQLAlchemy ``Integer(length=11)``.
Args:
dialect: a SQLAlchemy :class:`Dialect` class
coltype: a ``str()`` representation, e.g. from ``str(c['type'])`` where
``c`` is an instance of :class:`sqlalchemy.sql.schema.Column`.
Returns:
a Python object that is a subclass of
:class:`sqlalchemy.types.TypeEngine`
Example:
.. code-block:: python
get_sqla_coltype_from_string('INTEGER(11)', engine.dialect)
# gives: Integer(length=11)
Notes:
- :class:`sqlalchemy.engine.default.DefaultDialect` is the dialect base
class
- a dialect contains these things of interest:
- ``ischema_names``: string-to-class dictionary
- ``type_compiler``: instance of e.g.
:class:`sqlalchemy.sql.compiler.GenericTypeCompiler`. This has a
``process()`` method, but that operates on :class:`TypeEngine` objects.
- ``get_columns``: takes a table name, inspects the database
- example of the dangers of ``eval``:
http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html
- An example of a function doing the reflection/inspection within
SQLAlchemy is
:func:`sqlalchemy.dialects.mssql.base.MSDialect.get_columns`,
which has this lookup: ``coltype = self.ischema_names.get(type, None)``
Caveats:
- the parameters, e.g. ``DATETIME(6)``, do NOT necessarily either work at
all or work correctly. For example, SQLAlchemy will happily spit out
``'INTEGER(11)'`` but its :class:`sqlalchemy.sql.sqltypes.INTEGER` class
takes no parameters, so you get the error ``TypeError: object() takes no
parameters``. Similarly, MySQL's ``DATETIME(6)`` uses the 6 to refer to
precision, but the ``DATETIME`` class in SQLAlchemy takes only a boolean
parameter (timezone).
- However, sometimes we have to have parameters, e.g. ``VARCHAR`` length.
- Thus, this is a bit useless.
- Fixed, with a few special cases. | [
"Returns",
"an",
"SQLAlchemy",
"column",
"type",
"given",
"a",
"column",
"type",
"name",
"(",
"a",
"string",
")",
"and",
"an",
"SQLAlchemy",
"dialect",
".",
"For",
"example",
"this",
"might",
"convert",
"the",
"string",
"INTEGER",
"(",
"11",
")",
"to",
"an",
"SQLAlchemy",
"Integer",
"(",
"length",
"=",
"11",
")",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L664-L799 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/schema.py | remove_collation | def remove_collation(coltype: TypeEngine) -> TypeEngine:
"""
Returns a copy of the specific column type with any ``COLLATION`` removed.
"""
if not getattr(coltype, 'collation', None):
return coltype
newcoltype = copy.copy(coltype)
newcoltype.collation = None
return newcoltype | python | def remove_collation(coltype: TypeEngine) -> TypeEngine:
"""
Returns a copy of the specific column type with any ``COLLATION`` removed.
"""
if not getattr(coltype, 'collation', None):
return coltype
newcoltype = copy.copy(coltype)
newcoltype.collation = None
return newcoltype | [
"def",
"remove_collation",
"(",
"coltype",
":",
"TypeEngine",
")",
"->",
"TypeEngine",
":",
"if",
"not",
"getattr",
"(",
"coltype",
",",
"'collation'",
",",
"None",
")",
":",
"return",
"coltype",
"newcoltype",
"=",
"copy",
".",
"copy",
"(",
"coltype",
")",
"newcoltype",
".",
"collation",
"=",
"None",
"return",
"newcoltype"
] | Returns a copy of the specific column type with any ``COLLATION`` removed. | [
"Returns",
"a",
"copy",
"of",
"the",
"specific",
"column",
"type",
"with",
"any",
"COLLATION",
"removed",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L813-L821 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/schema.py | convert_sqla_type_for_dialect | def convert_sqla_type_for_dialect(
coltype: TypeEngine,
dialect: Dialect,
strip_collation: bool = True,
convert_mssql_timestamp: bool = True,
expand_for_scrubbing: bool = False) -> TypeEngine:
"""
Converts an SQLAlchemy column type from one SQL dialect to another.
Args:
coltype: SQLAlchemy column type in the source dialect
dialect: destination :class:`Dialect`
strip_collation: remove any ``COLLATION`` information?
convert_mssql_timestamp:
since you cannot write to a SQL Server ``TIMESTAMP`` field, setting
this option to ``True`` (the default) converts such types to
something equivalent but writable.
expand_for_scrubbing:
The purpose of expand_for_scrubbing is that, for example, a
``VARCHAR(200)`` field containing one or more instances of
``Jones``, where ``Jones`` is to be replaced with ``[XXXXXX]``,
will get longer (by an unpredictable amount). So, better to expand
to unlimited length.
Returns:
an SQLAlchemy column type instance, in the destination dialect
"""
assert coltype is not None
# noinspection PyUnresolvedReferences
to_mysql = dialect.name == SqlaDialectName.MYSQL
# noinspection PyUnresolvedReferences
to_mssql = dialect.name == SqlaDialectName.MSSQL
typeclass = type(coltype)
# -------------------------------------------------------------------------
# Text
# -------------------------------------------------------------------------
if isinstance(coltype, sqltypes.Enum):
return sqltypes.String(length=coltype.length)
if isinstance(coltype, sqltypes.UnicodeText):
# Unbounded Unicode text.
# Includes derived classes such as mssql.base.NTEXT.
return sqltypes.UnicodeText()
if isinstance(coltype, sqltypes.Text):
# Unbounded text, more generally. (UnicodeText inherits from Text.)
# Includes sqltypes.TEXT.
return sqltypes.Text()
# Everything inheriting from String has a length property, but can be None.
# There are types that can be unlimited in SQL Server, e.g. VARCHAR(MAX)
# and NVARCHAR(MAX), that MySQL needs a length for. (Failure to convert
# gives e.g.: 'NVARCHAR requires a length on dialect mysql'.)
if isinstance(coltype, sqltypes.Unicode):
# Includes NVARCHAR(MAX) in SQL -> NVARCHAR() in SQLAlchemy.
if (coltype.length is None and to_mysql) or expand_for_scrubbing:
return sqltypes.UnicodeText()
# The most general case; will pick up any other string types.
if isinstance(coltype, sqltypes.String):
# Includes VARCHAR(MAX) in SQL -> VARCHAR() in SQLAlchemy
if (coltype.length is None and to_mysql) or expand_for_scrubbing:
return sqltypes.Text()
if strip_collation:
return remove_collation(coltype)
return coltype
# -------------------------------------------------------------------------
# Binary
# -------------------------------------------------------------------------
# -------------------------------------------------------------------------
# BIT
# -------------------------------------------------------------------------
if typeclass == mssql.base.BIT and to_mysql:
# MySQL BIT objects have a length attribute.
return mysql.base.BIT()
# -------------------------------------------------------------------------
# TIMESTAMP
# -------------------------------------------------------------------------
is_mssql_timestamp = isinstance(coltype, MSSQL_TIMESTAMP)
if is_mssql_timestamp and to_mssql and convert_mssql_timestamp:
# You cannot write explicitly to a TIMESTAMP field in SQL Server; it's
# used for autogenerated values only.
# - http://stackoverflow.com/questions/10262426/sql-server-cannot-insert-an-explicit-value-into-a-timestamp-column # noqa
# - https://social.msdn.microsoft.com/Forums/sqlserver/en-US/5167204b-ef32-4662-8e01-00c9f0f362c2/how-to-tranfer-a-column-with-timestamp-datatype?forum=transactsql # noqa
# ... suggesting BINARY(8) to store the value.
# MySQL is more helpful:
# - http://stackoverflow.com/questions/409286/should-i-use-field-datetime-or-timestamp # noqa
return mssql.base.BINARY(8)
# -------------------------------------------------------------------------
# Some other type
# -------------------------------------------------------------------------
return coltype | python | def convert_sqla_type_for_dialect(
coltype: TypeEngine,
dialect: Dialect,
strip_collation: bool = True,
convert_mssql_timestamp: bool = True,
expand_for_scrubbing: bool = False) -> TypeEngine:
"""
Converts an SQLAlchemy column type from one SQL dialect to another.
Args:
coltype: SQLAlchemy column type in the source dialect
dialect: destination :class:`Dialect`
strip_collation: remove any ``COLLATION`` information?
convert_mssql_timestamp:
since you cannot write to a SQL Server ``TIMESTAMP`` field, setting
this option to ``True`` (the default) converts such types to
something equivalent but writable.
expand_for_scrubbing:
The purpose of expand_for_scrubbing is that, for example, a
``VARCHAR(200)`` field containing one or more instances of
``Jones``, where ``Jones`` is to be replaced with ``[XXXXXX]``,
will get longer (by an unpredictable amount). So, better to expand
to unlimited length.
Returns:
an SQLAlchemy column type instance, in the destination dialect
"""
assert coltype is not None
# noinspection PyUnresolvedReferences
to_mysql = dialect.name == SqlaDialectName.MYSQL
# noinspection PyUnresolvedReferences
to_mssql = dialect.name == SqlaDialectName.MSSQL
typeclass = type(coltype)
# -------------------------------------------------------------------------
# Text
# -------------------------------------------------------------------------
if isinstance(coltype, sqltypes.Enum):
return sqltypes.String(length=coltype.length)
if isinstance(coltype, sqltypes.UnicodeText):
# Unbounded Unicode text.
# Includes derived classes such as mssql.base.NTEXT.
return sqltypes.UnicodeText()
if isinstance(coltype, sqltypes.Text):
# Unbounded text, more generally. (UnicodeText inherits from Text.)
# Includes sqltypes.TEXT.
return sqltypes.Text()
# Everything inheriting from String has a length property, but can be None.
# There are types that can be unlimited in SQL Server, e.g. VARCHAR(MAX)
# and NVARCHAR(MAX), that MySQL needs a length for. (Failure to convert
# gives e.g.: 'NVARCHAR requires a length on dialect mysql'.)
if isinstance(coltype, sqltypes.Unicode):
# Includes NVARCHAR(MAX) in SQL -> NVARCHAR() in SQLAlchemy.
if (coltype.length is None and to_mysql) or expand_for_scrubbing:
return sqltypes.UnicodeText()
# The most general case; will pick up any other string types.
if isinstance(coltype, sqltypes.String):
# Includes VARCHAR(MAX) in SQL -> VARCHAR() in SQLAlchemy
if (coltype.length is None and to_mysql) or expand_for_scrubbing:
return sqltypes.Text()
if strip_collation:
return remove_collation(coltype)
return coltype
# -------------------------------------------------------------------------
# Binary
# -------------------------------------------------------------------------
# -------------------------------------------------------------------------
# BIT
# -------------------------------------------------------------------------
if typeclass == mssql.base.BIT and to_mysql:
# MySQL BIT objects have a length attribute.
return mysql.base.BIT()
# -------------------------------------------------------------------------
# TIMESTAMP
# -------------------------------------------------------------------------
is_mssql_timestamp = isinstance(coltype, MSSQL_TIMESTAMP)
if is_mssql_timestamp and to_mssql and convert_mssql_timestamp:
# You cannot write explicitly to a TIMESTAMP field in SQL Server; it's
# used for autogenerated values only.
# - http://stackoverflow.com/questions/10262426/sql-server-cannot-insert-an-explicit-value-into-a-timestamp-column # noqa
# - https://social.msdn.microsoft.com/Forums/sqlserver/en-US/5167204b-ef32-4662-8e01-00c9f0f362c2/how-to-tranfer-a-column-with-timestamp-datatype?forum=transactsql # noqa
# ... suggesting BINARY(8) to store the value.
# MySQL is more helpful:
# - http://stackoverflow.com/questions/409286/should-i-use-field-datetime-or-timestamp # noqa
return mssql.base.BINARY(8)
# -------------------------------------------------------------------------
# Some other type
# -------------------------------------------------------------------------
return coltype | [
"def",
"convert_sqla_type_for_dialect",
"(",
"coltype",
":",
"TypeEngine",
",",
"dialect",
":",
"Dialect",
",",
"strip_collation",
":",
"bool",
"=",
"True",
",",
"convert_mssql_timestamp",
":",
"bool",
"=",
"True",
",",
"expand_for_scrubbing",
":",
"bool",
"=",
"False",
")",
"->",
"TypeEngine",
":",
"assert",
"coltype",
"is",
"not",
"None",
"# noinspection PyUnresolvedReferences",
"to_mysql",
"=",
"dialect",
".",
"name",
"==",
"SqlaDialectName",
".",
"MYSQL",
"# noinspection PyUnresolvedReferences",
"to_mssql",
"=",
"dialect",
".",
"name",
"==",
"SqlaDialectName",
".",
"MSSQL",
"typeclass",
"=",
"type",
"(",
"coltype",
")",
"# -------------------------------------------------------------------------",
"# Text",
"# -------------------------------------------------------------------------",
"if",
"isinstance",
"(",
"coltype",
",",
"sqltypes",
".",
"Enum",
")",
":",
"return",
"sqltypes",
".",
"String",
"(",
"length",
"=",
"coltype",
".",
"length",
")",
"if",
"isinstance",
"(",
"coltype",
",",
"sqltypes",
".",
"UnicodeText",
")",
":",
"# Unbounded Unicode text.",
"# Includes derived classes such as mssql.base.NTEXT.",
"return",
"sqltypes",
".",
"UnicodeText",
"(",
")",
"if",
"isinstance",
"(",
"coltype",
",",
"sqltypes",
".",
"Text",
")",
":",
"# Unbounded text, more generally. (UnicodeText inherits from Text.)",
"# Includes sqltypes.TEXT.",
"return",
"sqltypes",
".",
"Text",
"(",
")",
"# Everything inheriting from String has a length property, but can be None.",
"# There are types that can be unlimited in SQL Server, e.g. VARCHAR(MAX)",
"# and NVARCHAR(MAX), that MySQL needs a length for. (Failure to convert",
"# gives e.g.: 'NVARCHAR requires a length on dialect mysql'.)",
"if",
"isinstance",
"(",
"coltype",
",",
"sqltypes",
".",
"Unicode",
")",
":",
"# Includes NVARCHAR(MAX) in SQL -> NVARCHAR() in SQLAlchemy.",
"if",
"(",
"coltype",
".",
"length",
"is",
"None",
"and",
"to_mysql",
")",
"or",
"expand_for_scrubbing",
":",
"return",
"sqltypes",
".",
"UnicodeText",
"(",
")",
"# The most general case; will pick up any other string types.",
"if",
"isinstance",
"(",
"coltype",
",",
"sqltypes",
".",
"String",
")",
":",
"# Includes VARCHAR(MAX) in SQL -> VARCHAR() in SQLAlchemy",
"if",
"(",
"coltype",
".",
"length",
"is",
"None",
"and",
"to_mysql",
")",
"or",
"expand_for_scrubbing",
":",
"return",
"sqltypes",
".",
"Text",
"(",
")",
"if",
"strip_collation",
":",
"return",
"remove_collation",
"(",
"coltype",
")",
"return",
"coltype",
"# -------------------------------------------------------------------------",
"# Binary",
"# -------------------------------------------------------------------------",
"# -------------------------------------------------------------------------",
"# BIT",
"# -------------------------------------------------------------------------",
"if",
"typeclass",
"==",
"mssql",
".",
"base",
".",
"BIT",
"and",
"to_mysql",
":",
"# MySQL BIT objects have a length attribute.",
"return",
"mysql",
".",
"base",
".",
"BIT",
"(",
")",
"# -------------------------------------------------------------------------",
"# TIMESTAMP",
"# -------------------------------------------------------------------------",
"is_mssql_timestamp",
"=",
"isinstance",
"(",
"coltype",
",",
"MSSQL_TIMESTAMP",
")",
"if",
"is_mssql_timestamp",
"and",
"to_mssql",
"and",
"convert_mssql_timestamp",
":",
"# You cannot write explicitly to a TIMESTAMP field in SQL Server; it's",
"# used for autogenerated values only.",
"# - http://stackoverflow.com/questions/10262426/sql-server-cannot-insert-an-explicit-value-into-a-timestamp-column # noqa",
"# - https://social.msdn.microsoft.com/Forums/sqlserver/en-US/5167204b-ef32-4662-8e01-00c9f0f362c2/how-to-tranfer-a-column-with-timestamp-datatype?forum=transactsql # noqa",
"# ... suggesting BINARY(8) to store the value.",
"# MySQL is more helpful:",
"# - http://stackoverflow.com/questions/409286/should-i-use-field-datetime-or-timestamp # noqa",
"return",
"mssql",
".",
"base",
".",
"BINARY",
"(",
"8",
")",
"# -------------------------------------------------------------------------",
"# Some other type",
"# -------------------------------------------------------------------------",
"return",
"coltype"
] | Converts an SQLAlchemy column type from one SQL dialect to another.
Args:
coltype: SQLAlchemy column type in the source dialect
dialect: destination :class:`Dialect`
strip_collation: remove any ``COLLATION`` information?
convert_mssql_timestamp:
since you cannot write to a SQL Server ``TIMESTAMP`` field, setting
this option to ``True`` (the default) converts such types to
something equivalent but writable.
expand_for_scrubbing:
The purpose of expand_for_scrubbing is that, for example, a
``VARCHAR(200)`` field containing one or more instances of
``Jones``, where ``Jones`` is to be replaced with ``[XXXXXX]``,
will get longer (by an unpredictable amount). So, better to expand
to unlimited length.
Returns:
an SQLAlchemy column type instance, in the destination dialect | [
"Converts",
"an",
"SQLAlchemy",
"column",
"type",
"from",
"one",
"SQL",
"dialect",
"to",
"another",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L825-L923 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/schema.py | _coltype_to_typeengine | def _coltype_to_typeengine(coltype: Union[TypeEngine,
VisitableType]) -> TypeEngine:
"""
An example is simplest: if you pass in ``Integer()`` (an instance of
:class:`TypeEngine`), you'll get ``Integer()`` back. If you pass in
``Integer`` (an instance of :class:`VisitableType`), you'll also get
``Integer()`` back. The function asserts that its return type is an
instance of :class:`TypeEngine`.
"""
if isinstance(coltype, VisitableType):
coltype = coltype()
assert isinstance(coltype, TypeEngine)
return coltype | python | def _coltype_to_typeengine(coltype: Union[TypeEngine,
VisitableType]) -> TypeEngine:
"""
An example is simplest: if you pass in ``Integer()`` (an instance of
:class:`TypeEngine`), you'll get ``Integer()`` back. If you pass in
``Integer`` (an instance of :class:`VisitableType`), you'll also get
``Integer()`` back. The function asserts that its return type is an
instance of :class:`TypeEngine`.
"""
if isinstance(coltype, VisitableType):
coltype = coltype()
assert isinstance(coltype, TypeEngine)
return coltype | [
"def",
"_coltype_to_typeengine",
"(",
"coltype",
":",
"Union",
"[",
"TypeEngine",
",",
"VisitableType",
"]",
")",
"->",
"TypeEngine",
":",
"if",
"isinstance",
"(",
"coltype",
",",
"VisitableType",
")",
":",
"coltype",
"=",
"coltype",
"(",
")",
"assert",
"isinstance",
"(",
"coltype",
",",
"TypeEngine",
")",
"return",
"coltype"
] | An example is simplest: if you pass in ``Integer()`` (an instance of
:class:`TypeEngine`), you'll get ``Integer()`` back. If you pass in
``Integer`` (an instance of :class:`VisitableType`), you'll also get
``Integer()`` back. The function asserts that its return type is an
instance of :class:`TypeEngine`. | [
"An",
"example",
"is",
"simplest",
":",
"if",
"you",
"pass",
"in",
"Integer",
"()",
"(",
"an",
"instance",
"of",
":",
"class",
":",
"TypeEngine",
")",
"you",
"ll",
"get",
"Integer",
"()",
"back",
".",
"If",
"you",
"pass",
"in",
"Integer",
"(",
"an",
"instance",
"of",
":",
"class",
":",
"VisitableType",
")",
"you",
"ll",
"also",
"get",
"Integer",
"()",
"back",
".",
"The",
"function",
"asserts",
"that",
"its",
"return",
"type",
"is",
"an",
"instance",
"of",
":",
"class",
":",
"TypeEngine",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L941-L953 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/schema.py | is_sqlatype_binary | def is_sqlatype_binary(coltype: Union[TypeEngine, VisitableType]) -> bool:
"""
Is the SQLAlchemy column type a binary type?
"""
# Several binary types inherit internally from _Binary, making that the
# easiest to check.
coltype = _coltype_to_typeengine(coltype)
# noinspection PyProtectedMember
return isinstance(coltype, sqltypes._Binary) | python | def is_sqlatype_binary(coltype: Union[TypeEngine, VisitableType]) -> bool:
"""
Is the SQLAlchemy column type a binary type?
"""
# Several binary types inherit internally from _Binary, making that the
# easiest to check.
coltype = _coltype_to_typeengine(coltype)
# noinspection PyProtectedMember
return isinstance(coltype, sqltypes._Binary) | [
"def",
"is_sqlatype_binary",
"(",
"coltype",
":",
"Union",
"[",
"TypeEngine",
",",
"VisitableType",
"]",
")",
"->",
"bool",
":",
"# Several binary types inherit internally from _Binary, making that the",
"# easiest to check.",
"coltype",
"=",
"_coltype_to_typeengine",
"(",
"coltype",
")",
"# noinspection PyProtectedMember",
"return",
"isinstance",
"(",
"coltype",
",",
"sqltypes",
".",
"_Binary",
")"
] | Is the SQLAlchemy column type a binary type? | [
"Is",
"the",
"SQLAlchemy",
"column",
"type",
"a",
"binary",
"type?"
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L956-L964 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/schema.py | is_sqlatype_date | def is_sqlatype_date(coltype: TypeEngine) -> bool:
"""
Is the SQLAlchemy column type a date type?
"""
coltype = _coltype_to_typeengine(coltype)
# No longer valid in SQLAlchemy 1.2.11:
# return isinstance(coltype, sqltypes._DateAffinity)
return (
isinstance(coltype, sqltypes.DateTime) or
isinstance(coltype, sqltypes.Date)
) | python | def is_sqlatype_date(coltype: TypeEngine) -> bool:
"""
Is the SQLAlchemy column type a date type?
"""
coltype = _coltype_to_typeengine(coltype)
# No longer valid in SQLAlchemy 1.2.11:
# return isinstance(coltype, sqltypes._DateAffinity)
return (
isinstance(coltype, sqltypes.DateTime) or
isinstance(coltype, sqltypes.Date)
) | [
"def",
"is_sqlatype_date",
"(",
"coltype",
":",
"TypeEngine",
")",
"->",
"bool",
":",
"coltype",
"=",
"_coltype_to_typeengine",
"(",
"coltype",
")",
"# No longer valid in SQLAlchemy 1.2.11:",
"# return isinstance(coltype, sqltypes._DateAffinity)",
"return",
"(",
"isinstance",
"(",
"coltype",
",",
"sqltypes",
".",
"DateTime",
")",
"or",
"isinstance",
"(",
"coltype",
",",
"sqltypes",
".",
"Date",
")",
")"
] | Is the SQLAlchemy column type a date type? | [
"Is",
"the",
"SQLAlchemy",
"column",
"type",
"a",
"date",
"type?"
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L967-L977 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/schema.py | is_sqlatype_integer | def is_sqlatype_integer(coltype: Union[TypeEngine, VisitableType]) -> bool:
"""
Is the SQLAlchemy column type an integer type?
"""
coltype = _coltype_to_typeengine(coltype)
return isinstance(coltype, sqltypes.Integer) | python | def is_sqlatype_integer(coltype: Union[TypeEngine, VisitableType]) -> bool:
"""
Is the SQLAlchemy column type an integer type?
"""
coltype = _coltype_to_typeengine(coltype)
return isinstance(coltype, sqltypes.Integer) | [
"def",
"is_sqlatype_integer",
"(",
"coltype",
":",
"Union",
"[",
"TypeEngine",
",",
"VisitableType",
"]",
")",
"->",
"bool",
":",
"coltype",
"=",
"_coltype_to_typeengine",
"(",
"coltype",
")",
"return",
"isinstance",
"(",
"coltype",
",",
"sqltypes",
".",
"Integer",
")"
] | Is the SQLAlchemy column type an integer type? | [
"Is",
"the",
"SQLAlchemy",
"column",
"type",
"an",
"integer",
"type?"
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L980-L985 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/schema.py | is_sqlatype_numeric | def is_sqlatype_numeric(coltype: Union[TypeEngine, VisitableType]) -> bool:
"""
Is the SQLAlchemy column type one that inherits from :class:`Numeric`,
such as :class:`Float`, :class:`Decimal`?
"""
coltype = _coltype_to_typeengine(coltype)
return isinstance(coltype, sqltypes.Numeric) | python | def is_sqlatype_numeric(coltype: Union[TypeEngine, VisitableType]) -> bool:
"""
Is the SQLAlchemy column type one that inherits from :class:`Numeric`,
such as :class:`Float`, :class:`Decimal`?
"""
coltype = _coltype_to_typeengine(coltype)
return isinstance(coltype, sqltypes.Numeric) | [
"def",
"is_sqlatype_numeric",
"(",
"coltype",
":",
"Union",
"[",
"TypeEngine",
",",
"VisitableType",
"]",
")",
"->",
"bool",
":",
"coltype",
"=",
"_coltype_to_typeengine",
"(",
"coltype",
")",
"return",
"isinstance",
"(",
"coltype",
",",
"sqltypes",
".",
"Numeric",
")"
] | Is the SQLAlchemy column type one that inherits from :class:`Numeric`,
such as :class:`Float`, :class:`Decimal`? | [
"Is",
"the",
"SQLAlchemy",
"column",
"type",
"one",
"that",
"inherits",
"from",
":",
"class",
":",
"Numeric",
"such",
"as",
":",
"class",
":",
"Float",
":",
"class",
":",
"Decimal",
"?"
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L988-L994 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/schema.py | is_sqlatype_string | def is_sqlatype_string(coltype: Union[TypeEngine, VisitableType]) -> bool:
"""
Is the SQLAlchemy column type a string type?
"""
coltype = _coltype_to_typeengine(coltype)
return isinstance(coltype, sqltypes.String) | python | def is_sqlatype_string(coltype: Union[TypeEngine, VisitableType]) -> bool:
"""
Is the SQLAlchemy column type a string type?
"""
coltype = _coltype_to_typeengine(coltype)
return isinstance(coltype, sqltypes.String) | [
"def",
"is_sqlatype_string",
"(",
"coltype",
":",
"Union",
"[",
"TypeEngine",
",",
"VisitableType",
"]",
")",
"->",
"bool",
":",
"coltype",
"=",
"_coltype_to_typeengine",
"(",
"coltype",
")",
"return",
"isinstance",
"(",
"coltype",
",",
"sqltypes",
".",
"String",
")"
] | Is the SQLAlchemy column type a string type? | [
"Is",
"the",
"SQLAlchemy",
"column",
"type",
"a",
"string",
"type?"
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L997-L1002 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/schema.py | is_sqlatype_text_of_length_at_least | def is_sqlatype_text_of_length_at_least(
coltype: Union[TypeEngine, VisitableType],
min_length: int = 1000) -> bool:
"""
Is the SQLAlchemy column type a string type that's at least the specified
length?
"""
coltype = _coltype_to_typeengine(coltype)
if not isinstance(coltype, sqltypes.String):
return False # not a string/text type at all
if coltype.length is None:
return True # string of unlimited length
return coltype.length >= min_length | python | def is_sqlatype_text_of_length_at_least(
coltype: Union[TypeEngine, VisitableType],
min_length: int = 1000) -> bool:
"""
Is the SQLAlchemy column type a string type that's at least the specified
length?
"""
coltype = _coltype_to_typeengine(coltype)
if not isinstance(coltype, sqltypes.String):
return False # not a string/text type at all
if coltype.length is None:
return True # string of unlimited length
return coltype.length >= min_length | [
"def",
"is_sqlatype_text_of_length_at_least",
"(",
"coltype",
":",
"Union",
"[",
"TypeEngine",
",",
"VisitableType",
"]",
",",
"min_length",
":",
"int",
"=",
"1000",
")",
"->",
"bool",
":",
"coltype",
"=",
"_coltype_to_typeengine",
"(",
"coltype",
")",
"if",
"not",
"isinstance",
"(",
"coltype",
",",
"sqltypes",
".",
"String",
")",
":",
"return",
"False",
"# not a string/text type at all",
"if",
"coltype",
".",
"length",
"is",
"None",
":",
"return",
"True",
"# string of unlimited length",
"return",
"coltype",
".",
"length",
">=",
"min_length"
] | Is the SQLAlchemy column type a string type that's at least the specified
length? | [
"Is",
"the",
"SQLAlchemy",
"column",
"type",
"a",
"string",
"type",
"that",
"s",
"at",
"least",
"the",
"specified",
"length?"
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L1005-L1017 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/schema.py | is_sqlatype_text_over_one_char | def is_sqlatype_text_over_one_char(
coltype: Union[TypeEngine, VisitableType]) -> bool:
"""
Is the SQLAlchemy column type a string type that's more than one character
long?
"""
coltype = _coltype_to_typeengine(coltype)
return is_sqlatype_text_of_length_at_least(coltype, 2) | python | def is_sqlatype_text_over_one_char(
coltype: Union[TypeEngine, VisitableType]) -> bool:
"""
Is the SQLAlchemy column type a string type that's more than one character
long?
"""
coltype = _coltype_to_typeengine(coltype)
return is_sqlatype_text_of_length_at_least(coltype, 2) | [
"def",
"is_sqlatype_text_over_one_char",
"(",
"coltype",
":",
"Union",
"[",
"TypeEngine",
",",
"VisitableType",
"]",
")",
"->",
"bool",
":",
"coltype",
"=",
"_coltype_to_typeengine",
"(",
"coltype",
")",
"return",
"is_sqlatype_text_of_length_at_least",
"(",
"coltype",
",",
"2",
")"
] | Is the SQLAlchemy column type a string type that's more than one character
long? | [
"Is",
"the",
"SQLAlchemy",
"column",
"type",
"a",
"string",
"type",
"that",
"s",
"more",
"than",
"one",
"character",
"long?"
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L1020-L1027 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/schema.py | does_sqlatype_merit_fulltext_index | def does_sqlatype_merit_fulltext_index(
coltype: Union[TypeEngine, VisitableType],
min_length: int = 1000) -> bool:
"""
Is the SQLAlchemy column type a type that might merit a ``FULLTEXT``
index (meaning a string type of at least ``min_length``)?
"""
coltype = _coltype_to_typeengine(coltype)
return is_sqlatype_text_of_length_at_least(coltype, min_length) | python | def does_sqlatype_merit_fulltext_index(
coltype: Union[TypeEngine, VisitableType],
min_length: int = 1000) -> bool:
"""
Is the SQLAlchemy column type a type that might merit a ``FULLTEXT``
index (meaning a string type of at least ``min_length``)?
"""
coltype = _coltype_to_typeengine(coltype)
return is_sqlatype_text_of_length_at_least(coltype, min_length) | [
"def",
"does_sqlatype_merit_fulltext_index",
"(",
"coltype",
":",
"Union",
"[",
"TypeEngine",
",",
"VisitableType",
"]",
",",
"min_length",
":",
"int",
"=",
"1000",
")",
"->",
"bool",
":",
"coltype",
"=",
"_coltype_to_typeengine",
"(",
"coltype",
")",
"return",
"is_sqlatype_text_of_length_at_least",
"(",
"coltype",
",",
"min_length",
")"
] | Is the SQLAlchemy column type a type that might merit a ``FULLTEXT``
index (meaning a string type of at least ``min_length``)? | [
"Is",
"the",
"SQLAlchemy",
"column",
"type",
"a",
"type",
"that",
"might",
"merit",
"a",
"FULLTEXT",
"index",
"(",
"meaning",
"a",
"string",
"type",
"of",
"at",
"least",
"min_length",
")",
"?"
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L1030-L1038 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/schema.py | does_sqlatype_require_index_len | def does_sqlatype_require_index_len(
coltype: Union[TypeEngine, VisitableType]) -> bool:
"""
Is the SQLAlchemy column type one that requires its indexes to have a
length specified?
(MySQL, at least, requires index length to be specified for ``BLOB`` and
``TEXT`` columns:
http://dev.mysql.com/doc/refman/5.7/en/create-index.html.)
"""
coltype = _coltype_to_typeengine(coltype)
if isinstance(coltype, sqltypes.Text):
return True
if isinstance(coltype, sqltypes.LargeBinary):
return True
return False | python | def does_sqlatype_require_index_len(
coltype: Union[TypeEngine, VisitableType]) -> bool:
"""
Is the SQLAlchemy column type one that requires its indexes to have a
length specified?
(MySQL, at least, requires index length to be specified for ``BLOB`` and
``TEXT`` columns:
http://dev.mysql.com/doc/refman/5.7/en/create-index.html.)
"""
coltype = _coltype_to_typeengine(coltype)
if isinstance(coltype, sqltypes.Text):
return True
if isinstance(coltype, sqltypes.LargeBinary):
return True
return False | [
"def",
"does_sqlatype_require_index_len",
"(",
"coltype",
":",
"Union",
"[",
"TypeEngine",
",",
"VisitableType",
"]",
")",
"->",
"bool",
":",
"coltype",
"=",
"_coltype_to_typeengine",
"(",
"coltype",
")",
"if",
"isinstance",
"(",
"coltype",
",",
"sqltypes",
".",
"Text",
")",
":",
"return",
"True",
"if",
"isinstance",
"(",
"coltype",
",",
"sqltypes",
".",
"LargeBinary",
")",
":",
"return",
"True",
"return",
"False"
] | Is the SQLAlchemy column type one that requires its indexes to have a
length specified?
(MySQL, at least, requires index length to be specified for ``BLOB`` and
``TEXT`` columns:
http://dev.mysql.com/doc/refman/5.7/en/create-index.html.) | [
"Is",
"the",
"SQLAlchemy",
"column",
"type",
"one",
"that",
"requires",
"its",
"indexes",
"to",
"have",
"a",
"length",
"specified?"
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L1041-L1056 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/schema.py | column_types_equal | def column_types_equal(a_coltype: TypeEngine, b_coltype: TypeEngine) -> bool:
"""
Checks that two SQLAlchemy column types are equal (by comparing ``str()``
versions of them).
See http://stackoverflow.com/questions/34787794/sqlalchemy-column-type-comparison.
IMPERFECT.
""" # noqa
return str(a_coltype) == str(b_coltype) | python | def column_types_equal(a_coltype: TypeEngine, b_coltype: TypeEngine) -> bool:
"""
Checks that two SQLAlchemy column types are equal (by comparing ``str()``
versions of them).
See http://stackoverflow.com/questions/34787794/sqlalchemy-column-type-comparison.
IMPERFECT.
""" # noqa
return str(a_coltype) == str(b_coltype) | [
"def",
"column_types_equal",
"(",
"a_coltype",
":",
"TypeEngine",
",",
"b_coltype",
":",
"TypeEngine",
")",
"->",
"bool",
":",
"# noqa",
"return",
"str",
"(",
"a_coltype",
")",
"==",
"str",
"(",
"b_coltype",
")"
] | Checks that two SQLAlchemy column types are equal (by comparing ``str()``
versions of them).
See http://stackoverflow.com/questions/34787794/sqlalchemy-column-type-comparison.
IMPERFECT. | [
"Checks",
"that",
"two",
"SQLAlchemy",
"column",
"types",
"are",
"equal",
"(",
"by",
"comparing",
"str",
"()",
"versions",
"of",
"them",
")",
".",
"See",
"http",
":",
"//",
"stackoverflow",
".",
"com",
"/",
"questions",
"/",
"34787794",
"/",
"sqlalchemy",
"-",
"column",
"-",
"type",
"-",
"comparison",
".",
"IMPERFECT",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L1089-L1098 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/schema.py | columns_equal | def columns_equal(a: Column, b: Column) -> bool:
"""
Are two SQLAlchemy columns are equal? Checks based on:
- column ``name``
- column ``type`` (see :func:`column_types_equal`)
- ``nullable``
"""
return (
a.name == b.name and
column_types_equal(a.type, b.type) and
a.nullable == b.nullable
) | python | def columns_equal(a: Column, b: Column) -> bool:
"""
Are two SQLAlchemy columns are equal? Checks based on:
- column ``name``
- column ``type`` (see :func:`column_types_equal`)
- ``nullable``
"""
return (
a.name == b.name and
column_types_equal(a.type, b.type) and
a.nullable == b.nullable
) | [
"def",
"columns_equal",
"(",
"a",
":",
"Column",
",",
"b",
":",
"Column",
")",
"->",
"bool",
":",
"return",
"(",
"a",
".",
"name",
"==",
"b",
".",
"name",
"and",
"column_types_equal",
"(",
"a",
".",
"type",
",",
"b",
".",
"type",
")",
"and",
"a",
".",
"nullable",
"==",
"b",
".",
"nullable",
")"
] | Are two SQLAlchemy columns are equal? Checks based on:
- column ``name``
- column ``type`` (see :func:`column_types_equal`)
- ``nullable`` | [
"Are",
"two",
"SQLAlchemy",
"columns",
"are",
"equal?",
"Checks",
"based",
"on",
":"
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L1101-L1113 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/schema.py | column_lists_equal | def column_lists_equal(a: List[Column], b: List[Column]) -> bool:
"""
Are all columns in list ``a`` equal to their counterparts in list ``b``,
as per :func:`columns_equal`?
"""
n = len(a)
if len(b) != n:
return False
for i in range(n):
if not columns_equal(a[i], b[i]):
log.debug("Mismatch: {!r} != {!r}", a[i], b[i])
return False
return True | python | def column_lists_equal(a: List[Column], b: List[Column]) -> bool:
"""
Are all columns in list ``a`` equal to their counterparts in list ``b``,
as per :func:`columns_equal`?
"""
n = len(a)
if len(b) != n:
return False
for i in range(n):
if not columns_equal(a[i], b[i]):
log.debug("Mismatch: {!r} != {!r}", a[i], b[i])
return False
return True | [
"def",
"column_lists_equal",
"(",
"a",
":",
"List",
"[",
"Column",
"]",
",",
"b",
":",
"List",
"[",
"Column",
"]",
")",
"->",
"bool",
":",
"n",
"=",
"len",
"(",
"a",
")",
"if",
"len",
"(",
"b",
")",
"!=",
"n",
":",
"return",
"False",
"for",
"i",
"in",
"range",
"(",
"n",
")",
":",
"if",
"not",
"columns_equal",
"(",
"a",
"[",
"i",
"]",
",",
"b",
"[",
"i",
"]",
")",
":",
"log",
".",
"debug",
"(",
"\"Mismatch: {!r} != {!r}\"",
",",
"a",
"[",
"i",
"]",
",",
"b",
"[",
"i",
"]",
")",
"return",
"False",
"return",
"True"
] | Are all columns in list ``a`` equal to their counterparts in list ``b``,
as per :func:`columns_equal`? | [
"Are",
"all",
"columns",
"in",
"list",
"a",
"equal",
"to",
"their",
"counterparts",
"in",
"list",
"b",
"as",
"per",
":",
"func",
":",
"columns_equal",
"?"
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L1116-L1128 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/schema.py | indexes_equal | def indexes_equal(a: Index, b: Index) -> bool:
"""
Are two indexes equal? Checks by comparing ``str()`` versions of them.
(AM UNSURE IF THIS IS ENOUGH.)
"""
return str(a) == str(b) | python | def indexes_equal(a: Index, b: Index) -> bool:
"""
Are two indexes equal? Checks by comparing ``str()`` versions of them.
(AM UNSURE IF THIS IS ENOUGH.)
"""
return str(a) == str(b) | [
"def",
"indexes_equal",
"(",
"a",
":",
"Index",
",",
"b",
":",
"Index",
")",
"->",
"bool",
":",
"return",
"str",
"(",
"a",
")",
"==",
"str",
"(",
"b",
")"
] | Are two indexes equal? Checks by comparing ``str()`` versions of them.
(AM UNSURE IF THIS IS ENOUGH.) | [
"Are",
"two",
"indexes",
"equal?",
"Checks",
"by",
"comparing",
"str",
"()",
"versions",
"of",
"them",
".",
"(",
"AM",
"UNSURE",
"IF",
"THIS",
"IS",
"ENOUGH",
".",
")"
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L1131-L1136 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/schema.py | index_lists_equal | def index_lists_equal(a: List[Index], b: List[Index]) -> bool:
"""
Are all indexes in list ``a`` equal to their counterparts in list ``b``,
as per :func:`indexes_equal`?
"""
n = len(a)
if len(b) != n:
return False
for i in range(n):
if not indexes_equal(a[i], b[i]):
log.debug("Mismatch: {!r} != {!r}", a[i], b[i])
return False
return True | python | def index_lists_equal(a: List[Index], b: List[Index]) -> bool:
"""
Are all indexes in list ``a`` equal to their counterparts in list ``b``,
as per :func:`indexes_equal`?
"""
n = len(a)
if len(b) != n:
return False
for i in range(n):
if not indexes_equal(a[i], b[i]):
log.debug("Mismatch: {!r} != {!r}", a[i], b[i])
return False
return True | [
"def",
"index_lists_equal",
"(",
"a",
":",
"List",
"[",
"Index",
"]",
",",
"b",
":",
"List",
"[",
"Index",
"]",
")",
"->",
"bool",
":",
"n",
"=",
"len",
"(",
"a",
")",
"if",
"len",
"(",
"b",
")",
"!=",
"n",
":",
"return",
"False",
"for",
"i",
"in",
"range",
"(",
"n",
")",
":",
"if",
"not",
"indexes_equal",
"(",
"a",
"[",
"i",
"]",
",",
"b",
"[",
"i",
"]",
")",
":",
"log",
".",
"debug",
"(",
"\"Mismatch: {!r} != {!r}\"",
",",
"a",
"[",
"i",
"]",
",",
"b",
"[",
"i",
"]",
")",
"return",
"False",
"return",
"True"
] | Are all indexes in list ``a`` equal to their counterparts in list ``b``,
as per :func:`indexes_equal`? | [
"Are",
"all",
"indexes",
"in",
"list",
"a",
"equal",
"to",
"their",
"counterparts",
"in",
"list",
"b",
"as",
"per",
":",
"func",
":",
"indexes_equal",
"?"
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L1139-L1151 |
RudolfCardinal/pythonlib | cardinal_pythonlib/hash.py | to_bytes | def to_bytes(data: Any) -> bytearray:
"""
Convert anything to a ``bytearray``.
See
- http://stackoverflow.com/questions/7585435/best-way-to-convert-string-to-bytes-in-python-3
- http://stackoverflow.com/questions/10459067/how-to-convert-my-bytearrayb-x9e-x18k-x9a-to-something-like-this-x9e-x1
""" # noqa
if isinstance(data, int):
return bytearray([data])
return bytearray(data, encoding='latin-1') | python | def to_bytes(data: Any) -> bytearray:
"""
Convert anything to a ``bytearray``.
See
- http://stackoverflow.com/questions/7585435/best-way-to-convert-string-to-bytes-in-python-3
- http://stackoverflow.com/questions/10459067/how-to-convert-my-bytearrayb-x9e-x18k-x9a-to-something-like-this-x9e-x1
""" # noqa
if isinstance(data, int):
return bytearray([data])
return bytearray(data, encoding='latin-1') | [
"def",
"to_bytes",
"(",
"data",
":",
"Any",
")",
"->",
"bytearray",
":",
"# noqa",
"if",
"isinstance",
"(",
"data",
",",
"int",
")",
":",
"return",
"bytearray",
"(",
"[",
"data",
"]",
")",
"return",
"bytearray",
"(",
"data",
",",
"encoding",
"=",
"'latin-1'",
")"
] | Convert anything to a ``bytearray``.
See
- http://stackoverflow.com/questions/7585435/best-way-to-convert-string-to-bytes-in-python-3
- http://stackoverflow.com/questions/10459067/how-to-convert-my-bytearrayb-x9e-x18k-x9a-to-something-like-this-x9e-x1 | [
"Convert",
"anything",
"to",
"a",
"bytearray",
".",
"See",
"-",
"http",
":",
"//",
"stackoverflow",
".",
"com",
"/",
"questions",
"/",
"7585435",
"/",
"best",
"-",
"way",
"-",
"to",
"-",
"convert",
"-",
"string",
"-",
"to",
"-",
"bytes",
"-",
"in",
"-",
"python",
"-",
"3",
"-",
"http",
":",
"//",
"stackoverflow",
".",
"com",
"/",
"questions",
"/",
"10459067",
"/",
"how",
"-",
"to",
"-",
"convert",
"-",
"my",
"-",
"bytearrayb",
"-",
"x9e",
"-",
"x18k",
"-",
"x9a",
"-",
"to",
"-",
"something",
"-",
"like",
"-",
"this",
"-",
"x9e",
"-",
"x1"
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/hash.py#L305-L316 |
RudolfCardinal/pythonlib | cardinal_pythonlib/hash.py | signed_to_twos_comp | def signed_to_twos_comp(val: int, n_bits: int) -> int:
"""
Convert a signed integer to its "two's complement" representation.
Args:
val: signed integer
n_bits: number of bits (which must reflect a whole number of bytes)
Returns:
unsigned integer: two's complement version
"""
assert n_bits % 8 == 0, "Must specify a whole number of bytes"
n_bytes = n_bits // 8
b = val.to_bytes(n_bytes, byteorder=sys.byteorder, signed=True)
return int.from_bytes(b, byteorder=sys.byteorder, signed=False) | python | def signed_to_twos_comp(val: int, n_bits: int) -> int:
"""
Convert a signed integer to its "two's complement" representation.
Args:
val: signed integer
n_bits: number of bits (which must reflect a whole number of bytes)
Returns:
unsigned integer: two's complement version
"""
assert n_bits % 8 == 0, "Must specify a whole number of bytes"
n_bytes = n_bits // 8
b = val.to_bytes(n_bytes, byteorder=sys.byteorder, signed=True)
return int.from_bytes(b, byteorder=sys.byteorder, signed=False) | [
"def",
"signed_to_twos_comp",
"(",
"val",
":",
"int",
",",
"n_bits",
":",
"int",
")",
"->",
"int",
":",
"assert",
"n_bits",
"%",
"8",
"==",
"0",
",",
"\"Must specify a whole number of bytes\"",
"n_bytes",
"=",
"n_bits",
"//",
"8",
"b",
"=",
"val",
".",
"to_bytes",
"(",
"n_bytes",
",",
"byteorder",
"=",
"sys",
".",
"byteorder",
",",
"signed",
"=",
"True",
")",
"return",
"int",
".",
"from_bytes",
"(",
"b",
",",
"byteorder",
"=",
"sys",
".",
"byteorder",
",",
"signed",
"=",
"False",
")"
] | Convert a signed integer to its "two's complement" representation.
Args:
val: signed integer
n_bits: number of bits (which must reflect a whole number of bytes)
Returns:
unsigned integer: two's complement version | [
"Convert",
"a",
"signed",
"integer",
"to",
"its",
"two",
"s",
"complement",
"representation",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/hash.py#L347-L362 |
RudolfCardinal/pythonlib | cardinal_pythonlib/hash.py | bytes_to_long | def bytes_to_long(bytesdata: bytes) -> int:
"""
Converts an 8-byte sequence to a long integer.
Args:
bytesdata: 8 consecutive bytes, as a ``bytes`` object, in
little-endian format (least significant byte [LSB] first)
Returns:
integer
"""
assert len(bytesdata) == 8
return sum((b << (k * 8) for k, b in enumerate(bytesdata))) | python | def bytes_to_long(bytesdata: bytes) -> int:
"""
Converts an 8-byte sequence to a long integer.
Args:
bytesdata: 8 consecutive bytes, as a ``bytes`` object, in
little-endian format (least significant byte [LSB] first)
Returns:
integer
"""
assert len(bytesdata) == 8
return sum((b << (k * 8) for k, b in enumerate(bytesdata))) | [
"def",
"bytes_to_long",
"(",
"bytesdata",
":",
"bytes",
")",
"->",
"int",
":",
"assert",
"len",
"(",
"bytesdata",
")",
"==",
"8",
"return",
"sum",
"(",
"(",
"b",
"<<",
"(",
"k",
"*",
"8",
")",
"for",
"k",
",",
"b",
"in",
"enumerate",
"(",
"bytesdata",
")",
")",
")"
] | Converts an 8-byte sequence to a long integer.
Args:
bytesdata: 8 consecutive bytes, as a ``bytes`` object, in
little-endian format (least significant byte [LSB] first)
Returns:
integer | [
"Converts",
"an",
"8",
"-",
"byte",
"sequence",
"to",
"a",
"long",
"integer",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/hash.py#L365-L378 |
RudolfCardinal/pythonlib | cardinal_pythonlib/hash.py | murmur3_x86_32 | def murmur3_x86_32(data: Union[bytes, bytearray], seed: int = 0) -> int:
"""
Pure 32-bit Python implementation of MurmurHash3; see
http://stackoverflow.com/questions/13305290/is-there-a-pure-python-implementation-of-murmurhash.
Args:
data: data to hash
seed: seed
Returns:
integer hash
""" # noqa
c1 = 0xcc9e2d51
c2 = 0x1b873593
length = len(data)
h1 = seed
rounded_end = (length & 0xfffffffc) # round down to 4 byte block
for i in range(0, rounded_end, 4):
# little endian load order
# RNC: removed ord() calls
k1 = (data[i] & 0xff) | ((data[i + 1] & 0xff) << 8) | \
((data[i + 2] & 0xff) << 16) | (data[i + 3] << 24)
k1 *= c1
k1 = (k1 << 15) | ((k1 & 0xffffffff) >> 17) # ROTL32(k1, 15)
k1 *= c2
h1 ^= k1
h1 = (h1 << 13) | ((h1 & 0xffffffff) >> 19) # ROTL32(h1, 13)
h1 = h1 * 5 + 0xe6546b64
# tail
k1 = 0
val = length & 0x03
if val == 3:
k1 = (data[rounded_end + 2] & 0xff) << 16
# fallthrough
if val in (2, 3):
k1 |= (data[rounded_end + 1] & 0xff) << 8
# fallthrough
if val in (1, 2, 3):
k1 |= data[rounded_end] & 0xff
k1 *= c1
k1 = (k1 << 15) | ((k1 & 0xffffffff) >> 17) # ROTL32(k1, 15)
k1 *= c2
h1 ^= k1
# finalization
h1 ^= length
# fmix(h1)
h1 ^= ((h1 & 0xffffffff) >> 16)
h1 *= 0x85ebca6b
h1 ^= ((h1 & 0xffffffff) >> 13)
h1 *= 0xc2b2ae35
h1 ^= ((h1 & 0xffffffff) >> 16)
return h1 & 0xffffffff | python | def murmur3_x86_32(data: Union[bytes, bytearray], seed: int = 0) -> int:
"""
Pure 32-bit Python implementation of MurmurHash3; see
http://stackoverflow.com/questions/13305290/is-there-a-pure-python-implementation-of-murmurhash.
Args:
data: data to hash
seed: seed
Returns:
integer hash
""" # noqa
c1 = 0xcc9e2d51
c2 = 0x1b873593
length = len(data)
h1 = seed
rounded_end = (length & 0xfffffffc) # round down to 4 byte block
for i in range(0, rounded_end, 4):
# little endian load order
# RNC: removed ord() calls
k1 = (data[i] & 0xff) | ((data[i + 1] & 0xff) << 8) | \
((data[i + 2] & 0xff) << 16) | (data[i + 3] << 24)
k1 *= c1
k1 = (k1 << 15) | ((k1 & 0xffffffff) >> 17) # ROTL32(k1, 15)
k1 *= c2
h1 ^= k1
h1 = (h1 << 13) | ((h1 & 0xffffffff) >> 19) # ROTL32(h1, 13)
h1 = h1 * 5 + 0xe6546b64
# tail
k1 = 0
val = length & 0x03
if val == 3:
k1 = (data[rounded_end + 2] & 0xff) << 16
# fallthrough
if val in (2, 3):
k1 |= (data[rounded_end + 1] & 0xff) << 8
# fallthrough
if val in (1, 2, 3):
k1 |= data[rounded_end] & 0xff
k1 *= c1
k1 = (k1 << 15) | ((k1 & 0xffffffff) >> 17) # ROTL32(k1, 15)
k1 *= c2
h1 ^= k1
# finalization
h1 ^= length
# fmix(h1)
h1 ^= ((h1 & 0xffffffff) >> 16)
h1 *= 0x85ebca6b
h1 ^= ((h1 & 0xffffffff) >> 13)
h1 *= 0xc2b2ae35
h1 ^= ((h1 & 0xffffffff) >> 16)
return h1 & 0xffffffff | [
"def",
"murmur3_x86_32",
"(",
"data",
":",
"Union",
"[",
"bytes",
",",
"bytearray",
"]",
",",
"seed",
":",
"int",
"=",
"0",
")",
"->",
"int",
":",
"# noqa",
"c1",
"=",
"0xcc9e2d51",
"c2",
"=",
"0x1b873593",
"length",
"=",
"len",
"(",
"data",
")",
"h1",
"=",
"seed",
"rounded_end",
"=",
"(",
"length",
"&",
"0xfffffffc",
")",
"# round down to 4 byte block",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"rounded_end",
",",
"4",
")",
":",
"# little endian load order",
"# RNC: removed ord() calls",
"k1",
"=",
"(",
"data",
"[",
"i",
"]",
"&",
"0xff",
")",
"|",
"(",
"(",
"data",
"[",
"i",
"+",
"1",
"]",
"&",
"0xff",
")",
"<<",
"8",
")",
"|",
"(",
"(",
"data",
"[",
"i",
"+",
"2",
"]",
"&",
"0xff",
")",
"<<",
"16",
")",
"|",
"(",
"data",
"[",
"i",
"+",
"3",
"]",
"<<",
"24",
")",
"k1",
"*=",
"c1",
"k1",
"=",
"(",
"k1",
"<<",
"15",
")",
"|",
"(",
"(",
"k1",
"&",
"0xffffffff",
")",
">>",
"17",
")",
"# ROTL32(k1, 15)",
"k1",
"*=",
"c2",
"h1",
"^=",
"k1",
"h1",
"=",
"(",
"h1",
"<<",
"13",
")",
"|",
"(",
"(",
"h1",
"&",
"0xffffffff",
")",
">>",
"19",
")",
"# ROTL32(h1, 13)",
"h1",
"=",
"h1",
"*",
"5",
"+",
"0xe6546b64",
"# tail",
"k1",
"=",
"0",
"val",
"=",
"length",
"&",
"0x03",
"if",
"val",
"==",
"3",
":",
"k1",
"=",
"(",
"data",
"[",
"rounded_end",
"+",
"2",
"]",
"&",
"0xff",
")",
"<<",
"16",
"# fallthrough",
"if",
"val",
"in",
"(",
"2",
",",
"3",
")",
":",
"k1",
"|=",
"(",
"data",
"[",
"rounded_end",
"+",
"1",
"]",
"&",
"0xff",
")",
"<<",
"8",
"# fallthrough",
"if",
"val",
"in",
"(",
"1",
",",
"2",
",",
"3",
")",
":",
"k1",
"|=",
"data",
"[",
"rounded_end",
"]",
"&",
"0xff",
"k1",
"*=",
"c1",
"k1",
"=",
"(",
"k1",
"<<",
"15",
")",
"|",
"(",
"(",
"k1",
"&",
"0xffffffff",
")",
">>",
"17",
")",
"# ROTL32(k1, 15)",
"k1",
"*=",
"c2",
"h1",
"^=",
"k1",
"# finalization",
"h1",
"^=",
"length",
"# fmix(h1)",
"h1",
"^=",
"(",
"(",
"h1",
"&",
"0xffffffff",
")",
">>",
"16",
")",
"h1",
"*=",
"0x85ebca6b",
"h1",
"^=",
"(",
"(",
"h1",
"&",
"0xffffffff",
")",
">>",
"13",
")",
"h1",
"*=",
"0xc2b2ae35",
"h1",
"^=",
"(",
"(",
"h1",
"&",
"0xffffffff",
")",
">>",
"16",
")",
"return",
"h1",
"&",
"0xffffffff"
] | Pure 32-bit Python implementation of MurmurHash3; see
http://stackoverflow.com/questions/13305290/is-there-a-pure-python-implementation-of-murmurhash.
Args:
data: data to hash
seed: seed
Returns:
integer hash | [
"Pure",
"32",
"-",
"bit",
"Python",
"implementation",
"of",
"MurmurHash3",
";",
"see",
"http",
":",
"//",
"stackoverflow",
".",
"com",
"/",
"questions",
"/",
"13305290",
"/",
"is",
"-",
"there",
"-",
"a",
"-",
"pure",
"-",
"python",
"-",
"implementation",
"-",
"of",
"-",
"murmurhash",
".",
"Args",
":",
"data",
":",
"data",
"to",
"hash",
"seed",
":",
"seed"
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/hash.py#L389-L448 |
RudolfCardinal/pythonlib | cardinal_pythonlib/hash.py | murmur3_64 | def murmur3_64(data: Union[bytes, bytearray], seed: int = 19820125) -> int:
"""
Pure 64-bit Python implementation of MurmurHash3; see
http://stackoverflow.com/questions/13305290/is-there-a-pure-python-implementation-of-murmurhash
(plus RNC bugfixes).
Args:
data: data to hash
seed: seed
Returns:
integer hash
""" # noqa
m = 0xc6a4a7935bd1e995
r = 47
mask = 2 ** 64 - 1
length = len(data)
h = seed ^ ((m * length) & mask)
offset = (length // 8) * 8
# RNC: was /, but for Python 3 that gives float; brackets added for clarity
for ll in range(0, offset, 8):
k = bytes_to_long(data[ll:ll + 8])
k = (k * m) & mask
k ^= (k >> r) & mask
k = (k * m) & mask
h = (h ^ k)
h = (h * m) & mask
l = length & 7
if l >= 7:
h = (h ^ (data[offset + 6] << 48))
if l >= 6:
h = (h ^ (data[offset + 5] << 40))
if l >= 5:
h = (h ^ (data[offset + 4] << 32))
if l >= 4:
h = (h ^ (data[offset + 3] << 24))
if l >= 3:
h = (h ^ (data[offset + 2] << 16))
if l >= 2:
h = (h ^ (data[offset + 1] << 8))
if l >= 1:
h = (h ^ data[offset])
h = (h * m) & mask
h ^= (h >> r) & mask
h = (h * m) & mask
h ^= (h >> r) & mask
return h | python | def murmur3_64(data: Union[bytes, bytearray], seed: int = 19820125) -> int:
"""
Pure 64-bit Python implementation of MurmurHash3; see
http://stackoverflow.com/questions/13305290/is-there-a-pure-python-implementation-of-murmurhash
(plus RNC bugfixes).
Args:
data: data to hash
seed: seed
Returns:
integer hash
""" # noqa
m = 0xc6a4a7935bd1e995
r = 47
mask = 2 ** 64 - 1
length = len(data)
h = seed ^ ((m * length) & mask)
offset = (length // 8) * 8
# RNC: was /, but for Python 3 that gives float; brackets added for clarity
for ll in range(0, offset, 8):
k = bytes_to_long(data[ll:ll + 8])
k = (k * m) & mask
k ^= (k >> r) & mask
k = (k * m) & mask
h = (h ^ k)
h = (h * m) & mask
l = length & 7
if l >= 7:
h = (h ^ (data[offset + 6] << 48))
if l >= 6:
h = (h ^ (data[offset + 5] << 40))
if l >= 5:
h = (h ^ (data[offset + 4] << 32))
if l >= 4:
h = (h ^ (data[offset + 3] << 24))
if l >= 3:
h = (h ^ (data[offset + 2] << 16))
if l >= 2:
h = (h ^ (data[offset + 1] << 8))
if l >= 1:
h = (h ^ data[offset])
h = (h * m) & mask
h ^= (h >> r) & mask
h = (h * m) & mask
h ^= (h >> r) & mask
return h | [
"def",
"murmur3_64",
"(",
"data",
":",
"Union",
"[",
"bytes",
",",
"bytearray",
"]",
",",
"seed",
":",
"int",
"=",
"19820125",
")",
"->",
"int",
":",
"# noqa",
"m",
"=",
"0xc6a4a7935bd1e995",
"r",
"=",
"47",
"mask",
"=",
"2",
"**",
"64",
"-",
"1",
"length",
"=",
"len",
"(",
"data",
")",
"h",
"=",
"seed",
"^",
"(",
"(",
"m",
"*",
"length",
")",
"&",
"mask",
")",
"offset",
"=",
"(",
"length",
"//",
"8",
")",
"*",
"8",
"# RNC: was /, but for Python 3 that gives float; brackets added for clarity",
"for",
"ll",
"in",
"range",
"(",
"0",
",",
"offset",
",",
"8",
")",
":",
"k",
"=",
"bytes_to_long",
"(",
"data",
"[",
"ll",
":",
"ll",
"+",
"8",
"]",
")",
"k",
"=",
"(",
"k",
"*",
"m",
")",
"&",
"mask",
"k",
"^=",
"(",
"k",
">>",
"r",
")",
"&",
"mask",
"k",
"=",
"(",
"k",
"*",
"m",
")",
"&",
"mask",
"h",
"=",
"(",
"h",
"^",
"k",
")",
"h",
"=",
"(",
"h",
"*",
"m",
")",
"&",
"mask",
"l",
"=",
"length",
"&",
"7",
"if",
"l",
">=",
"7",
":",
"h",
"=",
"(",
"h",
"^",
"(",
"data",
"[",
"offset",
"+",
"6",
"]",
"<<",
"48",
")",
")",
"if",
"l",
">=",
"6",
":",
"h",
"=",
"(",
"h",
"^",
"(",
"data",
"[",
"offset",
"+",
"5",
"]",
"<<",
"40",
")",
")",
"if",
"l",
">=",
"5",
":",
"h",
"=",
"(",
"h",
"^",
"(",
"data",
"[",
"offset",
"+",
"4",
"]",
"<<",
"32",
")",
")",
"if",
"l",
">=",
"4",
":",
"h",
"=",
"(",
"h",
"^",
"(",
"data",
"[",
"offset",
"+",
"3",
"]",
"<<",
"24",
")",
")",
"if",
"l",
">=",
"3",
":",
"h",
"=",
"(",
"h",
"^",
"(",
"data",
"[",
"offset",
"+",
"2",
"]",
"<<",
"16",
")",
")",
"if",
"l",
">=",
"2",
":",
"h",
"=",
"(",
"h",
"^",
"(",
"data",
"[",
"offset",
"+",
"1",
"]",
"<<",
"8",
")",
")",
"if",
"l",
">=",
"1",
":",
"h",
"=",
"(",
"h",
"^",
"data",
"[",
"offset",
"]",
")",
"h",
"=",
"(",
"h",
"*",
"m",
")",
"&",
"mask",
"h",
"^=",
"(",
"h",
">>",
"r",
")",
"&",
"mask",
"h",
"=",
"(",
"h",
"*",
"m",
")",
"&",
"mask",
"h",
"^=",
"(",
"h",
">>",
"r",
")",
"&",
"mask",
"return",
"h"
] | Pure 64-bit Python implementation of MurmurHash3; see
http://stackoverflow.com/questions/13305290/is-there-a-pure-python-implementation-of-murmurhash
(plus RNC bugfixes).
Args:
data: data to hash
seed: seed
Returns:
integer hash | [
"Pure",
"64",
"-",
"bit",
"Python",
"implementation",
"of",
"MurmurHash3",
";",
"see",
"http",
":",
"//",
"stackoverflow",
".",
"com",
"/",
"questions",
"/",
"13305290",
"/",
"is",
"-",
"there",
"-",
"a",
"-",
"pure",
"-",
"python",
"-",
"implementation",
"-",
"of",
"-",
"murmurhash",
"(",
"plus",
"RNC",
"bugfixes",
")",
".",
"Args",
":",
"data",
":",
"data",
"to",
"hash",
"seed",
":",
"seed"
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/hash.py#L452-L512 |
RudolfCardinal/pythonlib | cardinal_pythonlib/hash.py | pymmh3_hash128_x64 | def pymmh3_hash128_x64(key: Union[bytes, bytearray], seed: int) -> int:
"""
Implements 128-bit murmur3 hash for x64, as per ``pymmh3``, with some
bugfixes.
Args:
key: data to hash
seed: seed
Returns:
integer hash
"""
def fmix(k):
k ^= k >> 33
k = (k * 0xff51afd7ed558ccd) & 0xFFFFFFFFFFFFFFFF
k ^= k >> 33
k = (k * 0xc4ceb9fe1a85ec53) & 0xFFFFFFFFFFFFFFFF
k ^= k >> 33
return k
length = len(key)
nblocks = int(length / 16)
h1 = seed
h2 = seed
c1 = 0x87c37b91114253d5
c2 = 0x4cf5ad432745937f
# body
for block_start in range(0, nblocks * 8, 8):
# ??? big endian?
k1 = (
key[2 * block_start + 7] << 56 |
key[2 * block_start + 6] << 48 |
key[2 * block_start + 5] << 40 |
key[2 * block_start + 4] << 32 |
key[2 * block_start + 3] << 24 |
key[2 * block_start + 2] << 16 |
key[2 * block_start + 1] << 8 |
key[2 * block_start + 0]
)
k2 = (
key[2 * block_start + 15] << 56 |
key[2 * block_start + 14] << 48 |
key[2 * block_start + 13] << 40 |
key[2 * block_start + 12] << 32 |
key[2 * block_start + 11] << 24 |
key[2 * block_start + 10] << 16 |
key[2 * block_start + 9] << 8 |
key[2 * block_start + 8]
)
k1 = (c1 * k1) & 0xFFFFFFFFFFFFFFFF
k1 = (k1 << 31 | k1 >> 33) & 0xFFFFFFFFFFFFFFFF # inlined ROTL64
k1 = (c2 * k1) & 0xFFFFFFFFFFFFFFFF
h1 ^= k1
h1 = (h1 << 27 | h1 >> 37) & 0xFFFFFFFFFFFFFFFF # inlined ROTL64
h1 = (h1 + h2) & 0xFFFFFFFFFFFFFFFF
h1 = (h1 * 5 + 0x52dce729) & 0xFFFFFFFFFFFFFFFF
k2 = (c2 * k2) & 0xFFFFFFFFFFFFFFFF
k2 = (k2 << 33 | k2 >> 31) & 0xFFFFFFFFFFFFFFFF # inlined ROTL64
k2 = (c1 * k2) & 0xFFFFFFFFFFFFFFFF
h2 ^= k2
h2 = (h2 << 31 | h2 >> 33) & 0xFFFFFFFFFFFFFFFF # inlined ROTL64
h2 = (h1 + h2) & 0xFFFFFFFFFFFFFFFF
h2 = (h2 * 5 + 0x38495ab5) & 0xFFFFFFFFFFFFFFFF
# tail
tail_index = nblocks * 16
k1 = 0
k2 = 0
tail_size = length & 15
if tail_size >= 15:
k2 ^= key[tail_index + 14] << 48
if tail_size >= 14:
k2 ^= key[tail_index + 13] << 40
if tail_size >= 13:
k2 ^= key[tail_index + 12] << 32
if tail_size >= 12:
k2 ^= key[tail_index + 11] << 24
if tail_size >= 11:
k2 ^= key[tail_index + 10] << 16
if tail_size >= 10:
k2 ^= key[tail_index + 9] << 8
if tail_size >= 9:
k2 ^= key[tail_index + 8]
if tail_size > 8:
k2 = (k2 * c2) & 0xFFFFFFFFFFFFFFFF
k2 = (k2 << 33 | k2 >> 31) & 0xFFFFFFFFFFFFFFFF # inlined ROTL64
k2 = (k2 * c1) & 0xFFFFFFFFFFFFFFFF
h2 ^= k2
if tail_size >= 8:
k1 ^= key[tail_index + 7] << 56
if tail_size >= 7:
k1 ^= key[tail_index + 6] << 48
if tail_size >= 6:
k1 ^= key[tail_index + 5] << 40
if tail_size >= 5:
k1 ^= key[tail_index + 4] << 32
if tail_size >= 4:
k1 ^= key[tail_index + 3] << 24
if tail_size >= 3:
k1 ^= key[tail_index + 2] << 16
if tail_size >= 2:
k1 ^= key[tail_index + 1] << 8
if tail_size >= 1:
k1 ^= key[tail_index + 0]
if tail_size > 0:
k1 = (k1 * c1) & 0xFFFFFFFFFFFFFFFF
k1 = (k1 << 31 | k1 >> 33) & 0xFFFFFFFFFFFFFFFF # inlined ROTL64
k1 = (k1 * c2) & 0xFFFFFFFFFFFFFFFF
h1 ^= k1
# finalization
h1 ^= length
h2 ^= length
h1 = (h1 + h2) & 0xFFFFFFFFFFFFFFFF
h2 = (h1 + h2) & 0xFFFFFFFFFFFFFFFF
h1 = fmix(h1)
h2 = fmix(h2)
h1 = (h1 + h2) & 0xFFFFFFFFFFFFFFFF
h2 = (h1 + h2) & 0xFFFFFFFFFFFFFFFF
return h2 << 64 | h1 | python | def pymmh3_hash128_x64(key: Union[bytes, bytearray], seed: int) -> int:
"""
Implements 128-bit murmur3 hash for x64, as per ``pymmh3``, with some
bugfixes.
Args:
key: data to hash
seed: seed
Returns:
integer hash
"""
def fmix(k):
k ^= k >> 33
k = (k * 0xff51afd7ed558ccd) & 0xFFFFFFFFFFFFFFFF
k ^= k >> 33
k = (k * 0xc4ceb9fe1a85ec53) & 0xFFFFFFFFFFFFFFFF
k ^= k >> 33
return k
length = len(key)
nblocks = int(length / 16)
h1 = seed
h2 = seed
c1 = 0x87c37b91114253d5
c2 = 0x4cf5ad432745937f
# body
for block_start in range(0, nblocks * 8, 8):
# ??? big endian?
k1 = (
key[2 * block_start + 7] << 56 |
key[2 * block_start + 6] << 48 |
key[2 * block_start + 5] << 40 |
key[2 * block_start + 4] << 32 |
key[2 * block_start + 3] << 24 |
key[2 * block_start + 2] << 16 |
key[2 * block_start + 1] << 8 |
key[2 * block_start + 0]
)
k2 = (
key[2 * block_start + 15] << 56 |
key[2 * block_start + 14] << 48 |
key[2 * block_start + 13] << 40 |
key[2 * block_start + 12] << 32 |
key[2 * block_start + 11] << 24 |
key[2 * block_start + 10] << 16 |
key[2 * block_start + 9] << 8 |
key[2 * block_start + 8]
)
k1 = (c1 * k1) & 0xFFFFFFFFFFFFFFFF
k1 = (k1 << 31 | k1 >> 33) & 0xFFFFFFFFFFFFFFFF # inlined ROTL64
k1 = (c2 * k1) & 0xFFFFFFFFFFFFFFFF
h1 ^= k1
h1 = (h1 << 27 | h1 >> 37) & 0xFFFFFFFFFFFFFFFF # inlined ROTL64
h1 = (h1 + h2) & 0xFFFFFFFFFFFFFFFF
h1 = (h1 * 5 + 0x52dce729) & 0xFFFFFFFFFFFFFFFF
k2 = (c2 * k2) & 0xFFFFFFFFFFFFFFFF
k2 = (k2 << 33 | k2 >> 31) & 0xFFFFFFFFFFFFFFFF # inlined ROTL64
k2 = (c1 * k2) & 0xFFFFFFFFFFFFFFFF
h2 ^= k2
h2 = (h2 << 31 | h2 >> 33) & 0xFFFFFFFFFFFFFFFF # inlined ROTL64
h2 = (h1 + h2) & 0xFFFFFFFFFFFFFFFF
h2 = (h2 * 5 + 0x38495ab5) & 0xFFFFFFFFFFFFFFFF
# tail
tail_index = nblocks * 16
k1 = 0
k2 = 0
tail_size = length & 15
if tail_size >= 15:
k2 ^= key[tail_index + 14] << 48
if tail_size >= 14:
k2 ^= key[tail_index + 13] << 40
if tail_size >= 13:
k2 ^= key[tail_index + 12] << 32
if tail_size >= 12:
k2 ^= key[tail_index + 11] << 24
if tail_size >= 11:
k2 ^= key[tail_index + 10] << 16
if tail_size >= 10:
k2 ^= key[tail_index + 9] << 8
if tail_size >= 9:
k2 ^= key[tail_index + 8]
if tail_size > 8:
k2 = (k2 * c2) & 0xFFFFFFFFFFFFFFFF
k2 = (k2 << 33 | k2 >> 31) & 0xFFFFFFFFFFFFFFFF # inlined ROTL64
k2 = (k2 * c1) & 0xFFFFFFFFFFFFFFFF
h2 ^= k2
if tail_size >= 8:
k1 ^= key[tail_index + 7] << 56
if tail_size >= 7:
k1 ^= key[tail_index + 6] << 48
if tail_size >= 6:
k1 ^= key[tail_index + 5] << 40
if tail_size >= 5:
k1 ^= key[tail_index + 4] << 32
if tail_size >= 4:
k1 ^= key[tail_index + 3] << 24
if tail_size >= 3:
k1 ^= key[tail_index + 2] << 16
if tail_size >= 2:
k1 ^= key[tail_index + 1] << 8
if tail_size >= 1:
k1 ^= key[tail_index + 0]
if tail_size > 0:
k1 = (k1 * c1) & 0xFFFFFFFFFFFFFFFF
k1 = (k1 << 31 | k1 >> 33) & 0xFFFFFFFFFFFFFFFF # inlined ROTL64
k1 = (k1 * c2) & 0xFFFFFFFFFFFFFFFF
h1 ^= k1
# finalization
h1 ^= length
h2 ^= length
h1 = (h1 + h2) & 0xFFFFFFFFFFFFFFFF
h2 = (h1 + h2) & 0xFFFFFFFFFFFFFFFF
h1 = fmix(h1)
h2 = fmix(h2)
h1 = (h1 + h2) & 0xFFFFFFFFFFFFFFFF
h2 = (h1 + h2) & 0xFFFFFFFFFFFFFFFF
return h2 << 64 | h1 | [
"def",
"pymmh3_hash128_x64",
"(",
"key",
":",
"Union",
"[",
"bytes",
",",
"bytearray",
"]",
",",
"seed",
":",
"int",
")",
"->",
"int",
":",
"def",
"fmix",
"(",
"k",
")",
":",
"k",
"^=",
"k",
">>",
"33",
"k",
"=",
"(",
"k",
"*",
"0xff51afd7ed558ccd",
")",
"&",
"0xFFFFFFFFFFFFFFFF",
"k",
"^=",
"k",
">>",
"33",
"k",
"=",
"(",
"k",
"*",
"0xc4ceb9fe1a85ec53",
")",
"&",
"0xFFFFFFFFFFFFFFFF",
"k",
"^=",
"k",
">>",
"33",
"return",
"k",
"length",
"=",
"len",
"(",
"key",
")",
"nblocks",
"=",
"int",
"(",
"length",
"/",
"16",
")",
"h1",
"=",
"seed",
"h2",
"=",
"seed",
"c1",
"=",
"0x87c37b91114253d5",
"c2",
"=",
"0x4cf5ad432745937f",
"# body",
"for",
"block_start",
"in",
"range",
"(",
"0",
",",
"nblocks",
"*",
"8",
",",
"8",
")",
":",
"# ??? big endian?",
"k1",
"=",
"(",
"key",
"[",
"2",
"*",
"block_start",
"+",
"7",
"]",
"<<",
"56",
"|",
"key",
"[",
"2",
"*",
"block_start",
"+",
"6",
"]",
"<<",
"48",
"|",
"key",
"[",
"2",
"*",
"block_start",
"+",
"5",
"]",
"<<",
"40",
"|",
"key",
"[",
"2",
"*",
"block_start",
"+",
"4",
"]",
"<<",
"32",
"|",
"key",
"[",
"2",
"*",
"block_start",
"+",
"3",
"]",
"<<",
"24",
"|",
"key",
"[",
"2",
"*",
"block_start",
"+",
"2",
"]",
"<<",
"16",
"|",
"key",
"[",
"2",
"*",
"block_start",
"+",
"1",
"]",
"<<",
"8",
"|",
"key",
"[",
"2",
"*",
"block_start",
"+",
"0",
"]",
")",
"k2",
"=",
"(",
"key",
"[",
"2",
"*",
"block_start",
"+",
"15",
"]",
"<<",
"56",
"|",
"key",
"[",
"2",
"*",
"block_start",
"+",
"14",
"]",
"<<",
"48",
"|",
"key",
"[",
"2",
"*",
"block_start",
"+",
"13",
"]",
"<<",
"40",
"|",
"key",
"[",
"2",
"*",
"block_start",
"+",
"12",
"]",
"<<",
"32",
"|",
"key",
"[",
"2",
"*",
"block_start",
"+",
"11",
"]",
"<<",
"24",
"|",
"key",
"[",
"2",
"*",
"block_start",
"+",
"10",
"]",
"<<",
"16",
"|",
"key",
"[",
"2",
"*",
"block_start",
"+",
"9",
"]",
"<<",
"8",
"|",
"key",
"[",
"2",
"*",
"block_start",
"+",
"8",
"]",
")",
"k1",
"=",
"(",
"c1",
"*",
"k1",
")",
"&",
"0xFFFFFFFFFFFFFFFF",
"k1",
"=",
"(",
"k1",
"<<",
"31",
"|",
"k1",
">>",
"33",
")",
"&",
"0xFFFFFFFFFFFFFFFF",
"# inlined ROTL64",
"k1",
"=",
"(",
"c2",
"*",
"k1",
")",
"&",
"0xFFFFFFFFFFFFFFFF",
"h1",
"^=",
"k1",
"h1",
"=",
"(",
"h1",
"<<",
"27",
"|",
"h1",
">>",
"37",
")",
"&",
"0xFFFFFFFFFFFFFFFF",
"# inlined ROTL64",
"h1",
"=",
"(",
"h1",
"+",
"h2",
")",
"&",
"0xFFFFFFFFFFFFFFFF",
"h1",
"=",
"(",
"h1",
"*",
"5",
"+",
"0x52dce729",
")",
"&",
"0xFFFFFFFFFFFFFFFF",
"k2",
"=",
"(",
"c2",
"*",
"k2",
")",
"&",
"0xFFFFFFFFFFFFFFFF",
"k2",
"=",
"(",
"k2",
"<<",
"33",
"|",
"k2",
">>",
"31",
")",
"&",
"0xFFFFFFFFFFFFFFFF",
"# inlined ROTL64",
"k2",
"=",
"(",
"c1",
"*",
"k2",
")",
"&",
"0xFFFFFFFFFFFFFFFF",
"h2",
"^=",
"k2",
"h2",
"=",
"(",
"h2",
"<<",
"31",
"|",
"h2",
">>",
"33",
")",
"&",
"0xFFFFFFFFFFFFFFFF",
"# inlined ROTL64",
"h2",
"=",
"(",
"h1",
"+",
"h2",
")",
"&",
"0xFFFFFFFFFFFFFFFF",
"h2",
"=",
"(",
"h2",
"*",
"5",
"+",
"0x38495ab5",
")",
"&",
"0xFFFFFFFFFFFFFFFF",
"# tail",
"tail_index",
"=",
"nblocks",
"*",
"16",
"k1",
"=",
"0",
"k2",
"=",
"0",
"tail_size",
"=",
"length",
"&",
"15",
"if",
"tail_size",
">=",
"15",
":",
"k2",
"^=",
"key",
"[",
"tail_index",
"+",
"14",
"]",
"<<",
"48",
"if",
"tail_size",
">=",
"14",
":",
"k2",
"^=",
"key",
"[",
"tail_index",
"+",
"13",
"]",
"<<",
"40",
"if",
"tail_size",
">=",
"13",
":",
"k2",
"^=",
"key",
"[",
"tail_index",
"+",
"12",
"]",
"<<",
"32",
"if",
"tail_size",
">=",
"12",
":",
"k2",
"^=",
"key",
"[",
"tail_index",
"+",
"11",
"]",
"<<",
"24",
"if",
"tail_size",
">=",
"11",
":",
"k2",
"^=",
"key",
"[",
"tail_index",
"+",
"10",
"]",
"<<",
"16",
"if",
"tail_size",
">=",
"10",
":",
"k2",
"^=",
"key",
"[",
"tail_index",
"+",
"9",
"]",
"<<",
"8",
"if",
"tail_size",
">=",
"9",
":",
"k2",
"^=",
"key",
"[",
"tail_index",
"+",
"8",
"]",
"if",
"tail_size",
">",
"8",
":",
"k2",
"=",
"(",
"k2",
"*",
"c2",
")",
"&",
"0xFFFFFFFFFFFFFFFF",
"k2",
"=",
"(",
"k2",
"<<",
"33",
"|",
"k2",
">>",
"31",
")",
"&",
"0xFFFFFFFFFFFFFFFF",
"# inlined ROTL64",
"k2",
"=",
"(",
"k2",
"*",
"c1",
")",
"&",
"0xFFFFFFFFFFFFFFFF",
"h2",
"^=",
"k2",
"if",
"tail_size",
">=",
"8",
":",
"k1",
"^=",
"key",
"[",
"tail_index",
"+",
"7",
"]",
"<<",
"56",
"if",
"tail_size",
">=",
"7",
":",
"k1",
"^=",
"key",
"[",
"tail_index",
"+",
"6",
"]",
"<<",
"48",
"if",
"tail_size",
">=",
"6",
":",
"k1",
"^=",
"key",
"[",
"tail_index",
"+",
"5",
"]",
"<<",
"40",
"if",
"tail_size",
">=",
"5",
":",
"k1",
"^=",
"key",
"[",
"tail_index",
"+",
"4",
"]",
"<<",
"32",
"if",
"tail_size",
">=",
"4",
":",
"k1",
"^=",
"key",
"[",
"tail_index",
"+",
"3",
"]",
"<<",
"24",
"if",
"tail_size",
">=",
"3",
":",
"k1",
"^=",
"key",
"[",
"tail_index",
"+",
"2",
"]",
"<<",
"16",
"if",
"tail_size",
">=",
"2",
":",
"k1",
"^=",
"key",
"[",
"tail_index",
"+",
"1",
"]",
"<<",
"8",
"if",
"tail_size",
">=",
"1",
":",
"k1",
"^=",
"key",
"[",
"tail_index",
"+",
"0",
"]",
"if",
"tail_size",
">",
"0",
":",
"k1",
"=",
"(",
"k1",
"*",
"c1",
")",
"&",
"0xFFFFFFFFFFFFFFFF",
"k1",
"=",
"(",
"k1",
"<<",
"31",
"|",
"k1",
">>",
"33",
")",
"&",
"0xFFFFFFFFFFFFFFFF",
"# inlined ROTL64",
"k1",
"=",
"(",
"k1",
"*",
"c2",
")",
"&",
"0xFFFFFFFFFFFFFFFF",
"h1",
"^=",
"k1",
"# finalization",
"h1",
"^=",
"length",
"h2",
"^=",
"length",
"h1",
"=",
"(",
"h1",
"+",
"h2",
")",
"&",
"0xFFFFFFFFFFFFFFFF",
"h2",
"=",
"(",
"h1",
"+",
"h2",
")",
"&",
"0xFFFFFFFFFFFFFFFF",
"h1",
"=",
"fmix",
"(",
"h1",
")",
"h2",
"=",
"fmix",
"(",
"h2",
")",
"h1",
"=",
"(",
"h1",
"+",
"h2",
")",
"&",
"0xFFFFFFFFFFFFFFFF",
"h2",
"=",
"(",
"h1",
"+",
"h2",
")",
"&",
"0xFFFFFFFFFFFFFFFF",
"return",
"h2",
"<<",
"64",
"|",
"h1"
] | Implements 128-bit murmur3 hash for x64, as per ``pymmh3``, with some
bugfixes.
Args:
key: data to hash
seed: seed
Returns:
integer hash | [
"Implements",
"128",
"-",
"bit",
"murmur3",
"hash",
"for",
"x64",
"as",
"per",
"pymmh3",
"with",
"some",
"bugfixes",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/hash.py#L519-L655 |
RudolfCardinal/pythonlib | cardinal_pythonlib/hash.py | pymmh3_hash128_x86 | def pymmh3_hash128_x86(key: Union[bytes, bytearray], seed: int) -> int:
"""
Implements 128-bit murmur3 hash for x86, as per ``pymmh3``, with some
bugfixes.
Args:
key: data to hash
seed: seed
Returns:
integer hash
"""
def fmix(h):
h ^= h >> 16
h = (h * 0x85ebca6b) & 0xFFFFFFFF
h ^= h >> 13
h = (h * 0xc2b2ae35) & 0xFFFFFFFF
h ^= h >> 16
return h
length = len(key)
nblocks = int(length / 16)
h1 = seed
h2 = seed
h3 = seed
h4 = seed
c1 = 0x239b961b
c2 = 0xab0e9789
c3 = 0x38b34ae5
c4 = 0xa1e38b93
# body
for block_start in range(0, nblocks * 16, 16):
k1 = (
key[block_start + 3] << 24 |
key[block_start + 2] << 16 |
key[block_start + 1] << 8 |
key[block_start + 0]
)
k2 = (
key[block_start + 7] << 24 |
key[block_start + 6] << 16 |
key[block_start + 5] << 8 |
key[block_start + 4]
)
k3 = (
key[block_start + 11] << 24 |
key[block_start + 10] << 16 |
key[block_start + 9] << 8 |
key[block_start + 8]
)
k4 = (
key[block_start + 15] << 24 |
key[block_start + 14] << 16 |
key[block_start + 13] << 8 |
key[block_start + 12]
)
k1 = (c1 * k1) & 0xFFFFFFFF
k1 = (k1 << 15 | k1 >> 17) & 0xFFFFFFFF # inlined ROTL32
k1 = (c2 * k1) & 0xFFFFFFFF
h1 ^= k1
h1 = (h1 << 19 | h1 >> 13) & 0xFFFFFFFF # inlined ROTL32
h1 = (h1 + h2) & 0xFFFFFFFF
h1 = (h1 * 5 + 0x561ccd1b) & 0xFFFFFFFF
k2 = (c2 * k2) & 0xFFFFFFFF
k2 = (k2 << 16 | k2 >> 16) & 0xFFFFFFFF # inlined ROTL32
k2 = (c3 * k2) & 0xFFFFFFFF
h2 ^= k2
h2 = (h2 << 17 | h2 >> 15) & 0xFFFFFFFF # inlined ROTL32
h2 = (h2 + h3) & 0xFFFFFFFF
h2 = (h2 * 5 + 0x0bcaa747) & 0xFFFFFFFF
k3 = (c3 * k3) & 0xFFFFFFFF
k3 = (k3 << 17 | k3 >> 15) & 0xFFFFFFFF # inlined ROTL32
k3 = (c4 * k3) & 0xFFFFFFFF
h3 ^= k3
h3 = (h3 << 15 | h3 >> 17) & 0xFFFFFFFF # inlined ROTL32
h3 = (h3 + h4) & 0xFFFFFFFF
h3 = (h3 * 5 + 0x96cd1c35) & 0xFFFFFFFF
k4 = (c4 * k4) & 0xFFFFFFFF
k4 = (k4 << 18 | k4 >> 14) & 0xFFFFFFFF # inlined ROTL32
k4 = (c1 * k4) & 0xFFFFFFFF
h4 ^= k4
h4 = (h4 << 13 | h4 >> 19) & 0xFFFFFFFF # inlined ROTL32
h4 = (h1 + h4) & 0xFFFFFFFF
h4 = (h4 * 5 + 0x32ac3b17) & 0xFFFFFFFF
# tail
tail_index = nblocks * 16
k1 = 0
k2 = 0
k3 = 0
k4 = 0
tail_size = length & 15
if tail_size >= 15:
k4 ^= key[tail_index + 14] << 16
if tail_size >= 14:
k4 ^= key[tail_index + 13] << 8
if tail_size >= 13:
k4 ^= key[tail_index + 12]
if tail_size > 12:
k4 = (k4 * c4) & 0xFFFFFFFF
k4 = (k4 << 18 | k4 >> 14) & 0xFFFFFFFF # inlined ROTL32
k4 = (k4 * c1) & 0xFFFFFFFF
h4 ^= k4
if tail_size >= 12:
k3 ^= key[tail_index + 11] << 24
if tail_size >= 11:
k3 ^= key[tail_index + 10] << 16
if tail_size >= 10:
k3 ^= key[tail_index + 9] << 8
if tail_size >= 9:
k3 ^= key[tail_index + 8]
if tail_size > 8:
k3 = (k3 * c3) & 0xFFFFFFFF
k3 = (k3 << 17 | k3 >> 15) & 0xFFFFFFFF # inlined ROTL32
k3 = (k3 * c4) & 0xFFFFFFFF
h3 ^= k3
if tail_size >= 8:
k2 ^= key[tail_index + 7] << 24
if tail_size >= 7:
k2 ^= key[tail_index + 6] << 16
if tail_size >= 6:
k2 ^= key[tail_index + 5] << 8
if tail_size >= 5:
k2 ^= key[tail_index + 4]
if tail_size > 4:
k2 = (k2 * c2) & 0xFFFFFFFF
k2 = (k2 << 16 | k2 >> 16) & 0xFFFFFFFF # inlined ROTL32
k2 = (k2 * c3) & 0xFFFFFFFF
h2 ^= k2
if tail_size >= 4:
k1 ^= key[tail_index + 3] << 24
if tail_size >= 3:
k1 ^= key[tail_index + 2] << 16
if tail_size >= 2:
k1 ^= key[tail_index + 1] << 8
if tail_size >= 1:
k1 ^= key[tail_index + 0]
if tail_size > 0:
k1 = (k1 * c1) & 0xFFFFFFFF
k1 = (k1 << 15 | k1 >> 17) & 0xFFFFFFFF # inlined ROTL32
k1 = (k1 * c2) & 0xFFFFFFFF
h1 ^= k1
# finalization
h1 ^= length
h2 ^= length
h3 ^= length
h4 ^= length
h1 = (h1 + h2) & 0xFFFFFFFF
h1 = (h1 + h3) & 0xFFFFFFFF
h1 = (h1 + h4) & 0xFFFFFFFF
h2 = (h1 + h2) & 0xFFFFFFFF
h3 = (h1 + h3) & 0xFFFFFFFF
h4 = (h1 + h4) & 0xFFFFFFFF
h1 = fmix(h1)
h2 = fmix(h2)
h3 = fmix(h3)
h4 = fmix(h4)
h1 = (h1 + h2) & 0xFFFFFFFF
h1 = (h1 + h3) & 0xFFFFFFFF
h1 = (h1 + h4) & 0xFFFFFFFF
h2 = (h1 + h2) & 0xFFFFFFFF
h3 = (h1 + h3) & 0xFFFFFFFF
h4 = (h1 + h4) & 0xFFFFFFFF
return h4 << 96 | h3 << 64 | h2 << 32 | h1 | python | def pymmh3_hash128_x86(key: Union[bytes, bytearray], seed: int) -> int:
"""
Implements 128-bit murmur3 hash for x86, as per ``pymmh3``, with some
bugfixes.
Args:
key: data to hash
seed: seed
Returns:
integer hash
"""
def fmix(h):
h ^= h >> 16
h = (h * 0x85ebca6b) & 0xFFFFFFFF
h ^= h >> 13
h = (h * 0xc2b2ae35) & 0xFFFFFFFF
h ^= h >> 16
return h
length = len(key)
nblocks = int(length / 16)
h1 = seed
h2 = seed
h3 = seed
h4 = seed
c1 = 0x239b961b
c2 = 0xab0e9789
c3 = 0x38b34ae5
c4 = 0xa1e38b93
# body
for block_start in range(0, nblocks * 16, 16):
k1 = (
key[block_start + 3] << 24 |
key[block_start + 2] << 16 |
key[block_start + 1] << 8 |
key[block_start + 0]
)
k2 = (
key[block_start + 7] << 24 |
key[block_start + 6] << 16 |
key[block_start + 5] << 8 |
key[block_start + 4]
)
k3 = (
key[block_start + 11] << 24 |
key[block_start + 10] << 16 |
key[block_start + 9] << 8 |
key[block_start + 8]
)
k4 = (
key[block_start + 15] << 24 |
key[block_start + 14] << 16 |
key[block_start + 13] << 8 |
key[block_start + 12]
)
k1 = (c1 * k1) & 0xFFFFFFFF
k1 = (k1 << 15 | k1 >> 17) & 0xFFFFFFFF # inlined ROTL32
k1 = (c2 * k1) & 0xFFFFFFFF
h1 ^= k1
h1 = (h1 << 19 | h1 >> 13) & 0xFFFFFFFF # inlined ROTL32
h1 = (h1 + h2) & 0xFFFFFFFF
h1 = (h1 * 5 + 0x561ccd1b) & 0xFFFFFFFF
k2 = (c2 * k2) & 0xFFFFFFFF
k2 = (k2 << 16 | k2 >> 16) & 0xFFFFFFFF # inlined ROTL32
k2 = (c3 * k2) & 0xFFFFFFFF
h2 ^= k2
h2 = (h2 << 17 | h2 >> 15) & 0xFFFFFFFF # inlined ROTL32
h2 = (h2 + h3) & 0xFFFFFFFF
h2 = (h2 * 5 + 0x0bcaa747) & 0xFFFFFFFF
k3 = (c3 * k3) & 0xFFFFFFFF
k3 = (k3 << 17 | k3 >> 15) & 0xFFFFFFFF # inlined ROTL32
k3 = (c4 * k3) & 0xFFFFFFFF
h3 ^= k3
h3 = (h3 << 15 | h3 >> 17) & 0xFFFFFFFF # inlined ROTL32
h3 = (h3 + h4) & 0xFFFFFFFF
h3 = (h3 * 5 + 0x96cd1c35) & 0xFFFFFFFF
k4 = (c4 * k4) & 0xFFFFFFFF
k4 = (k4 << 18 | k4 >> 14) & 0xFFFFFFFF # inlined ROTL32
k4 = (c1 * k4) & 0xFFFFFFFF
h4 ^= k4
h4 = (h4 << 13 | h4 >> 19) & 0xFFFFFFFF # inlined ROTL32
h4 = (h1 + h4) & 0xFFFFFFFF
h4 = (h4 * 5 + 0x32ac3b17) & 0xFFFFFFFF
# tail
tail_index = nblocks * 16
k1 = 0
k2 = 0
k3 = 0
k4 = 0
tail_size = length & 15
if tail_size >= 15:
k4 ^= key[tail_index + 14] << 16
if tail_size >= 14:
k4 ^= key[tail_index + 13] << 8
if tail_size >= 13:
k4 ^= key[tail_index + 12]
if tail_size > 12:
k4 = (k4 * c4) & 0xFFFFFFFF
k4 = (k4 << 18 | k4 >> 14) & 0xFFFFFFFF # inlined ROTL32
k4 = (k4 * c1) & 0xFFFFFFFF
h4 ^= k4
if tail_size >= 12:
k3 ^= key[tail_index + 11] << 24
if tail_size >= 11:
k3 ^= key[tail_index + 10] << 16
if tail_size >= 10:
k3 ^= key[tail_index + 9] << 8
if tail_size >= 9:
k3 ^= key[tail_index + 8]
if tail_size > 8:
k3 = (k3 * c3) & 0xFFFFFFFF
k3 = (k3 << 17 | k3 >> 15) & 0xFFFFFFFF # inlined ROTL32
k3 = (k3 * c4) & 0xFFFFFFFF
h3 ^= k3
if tail_size >= 8:
k2 ^= key[tail_index + 7] << 24
if tail_size >= 7:
k2 ^= key[tail_index + 6] << 16
if tail_size >= 6:
k2 ^= key[tail_index + 5] << 8
if tail_size >= 5:
k2 ^= key[tail_index + 4]
if tail_size > 4:
k2 = (k2 * c2) & 0xFFFFFFFF
k2 = (k2 << 16 | k2 >> 16) & 0xFFFFFFFF # inlined ROTL32
k2 = (k2 * c3) & 0xFFFFFFFF
h2 ^= k2
if tail_size >= 4:
k1 ^= key[tail_index + 3] << 24
if tail_size >= 3:
k1 ^= key[tail_index + 2] << 16
if tail_size >= 2:
k1 ^= key[tail_index + 1] << 8
if tail_size >= 1:
k1 ^= key[tail_index + 0]
if tail_size > 0:
k1 = (k1 * c1) & 0xFFFFFFFF
k1 = (k1 << 15 | k1 >> 17) & 0xFFFFFFFF # inlined ROTL32
k1 = (k1 * c2) & 0xFFFFFFFF
h1 ^= k1
# finalization
h1 ^= length
h2 ^= length
h3 ^= length
h4 ^= length
h1 = (h1 + h2) & 0xFFFFFFFF
h1 = (h1 + h3) & 0xFFFFFFFF
h1 = (h1 + h4) & 0xFFFFFFFF
h2 = (h1 + h2) & 0xFFFFFFFF
h3 = (h1 + h3) & 0xFFFFFFFF
h4 = (h1 + h4) & 0xFFFFFFFF
h1 = fmix(h1)
h2 = fmix(h2)
h3 = fmix(h3)
h4 = fmix(h4)
h1 = (h1 + h2) & 0xFFFFFFFF
h1 = (h1 + h3) & 0xFFFFFFFF
h1 = (h1 + h4) & 0xFFFFFFFF
h2 = (h1 + h2) & 0xFFFFFFFF
h3 = (h1 + h3) & 0xFFFFFFFF
h4 = (h1 + h4) & 0xFFFFFFFF
return h4 << 96 | h3 << 64 | h2 << 32 | h1 | [
"def",
"pymmh3_hash128_x86",
"(",
"key",
":",
"Union",
"[",
"bytes",
",",
"bytearray",
"]",
",",
"seed",
":",
"int",
")",
"->",
"int",
":",
"def",
"fmix",
"(",
"h",
")",
":",
"h",
"^=",
"h",
">>",
"16",
"h",
"=",
"(",
"h",
"*",
"0x85ebca6b",
")",
"&",
"0xFFFFFFFF",
"h",
"^=",
"h",
">>",
"13",
"h",
"=",
"(",
"h",
"*",
"0xc2b2ae35",
")",
"&",
"0xFFFFFFFF",
"h",
"^=",
"h",
">>",
"16",
"return",
"h",
"length",
"=",
"len",
"(",
"key",
")",
"nblocks",
"=",
"int",
"(",
"length",
"/",
"16",
")",
"h1",
"=",
"seed",
"h2",
"=",
"seed",
"h3",
"=",
"seed",
"h4",
"=",
"seed",
"c1",
"=",
"0x239b961b",
"c2",
"=",
"0xab0e9789",
"c3",
"=",
"0x38b34ae5",
"c4",
"=",
"0xa1e38b93",
"# body",
"for",
"block_start",
"in",
"range",
"(",
"0",
",",
"nblocks",
"*",
"16",
",",
"16",
")",
":",
"k1",
"=",
"(",
"key",
"[",
"block_start",
"+",
"3",
"]",
"<<",
"24",
"|",
"key",
"[",
"block_start",
"+",
"2",
"]",
"<<",
"16",
"|",
"key",
"[",
"block_start",
"+",
"1",
"]",
"<<",
"8",
"|",
"key",
"[",
"block_start",
"+",
"0",
"]",
")",
"k2",
"=",
"(",
"key",
"[",
"block_start",
"+",
"7",
"]",
"<<",
"24",
"|",
"key",
"[",
"block_start",
"+",
"6",
"]",
"<<",
"16",
"|",
"key",
"[",
"block_start",
"+",
"5",
"]",
"<<",
"8",
"|",
"key",
"[",
"block_start",
"+",
"4",
"]",
")",
"k3",
"=",
"(",
"key",
"[",
"block_start",
"+",
"11",
"]",
"<<",
"24",
"|",
"key",
"[",
"block_start",
"+",
"10",
"]",
"<<",
"16",
"|",
"key",
"[",
"block_start",
"+",
"9",
"]",
"<<",
"8",
"|",
"key",
"[",
"block_start",
"+",
"8",
"]",
")",
"k4",
"=",
"(",
"key",
"[",
"block_start",
"+",
"15",
"]",
"<<",
"24",
"|",
"key",
"[",
"block_start",
"+",
"14",
"]",
"<<",
"16",
"|",
"key",
"[",
"block_start",
"+",
"13",
"]",
"<<",
"8",
"|",
"key",
"[",
"block_start",
"+",
"12",
"]",
")",
"k1",
"=",
"(",
"c1",
"*",
"k1",
")",
"&",
"0xFFFFFFFF",
"k1",
"=",
"(",
"k1",
"<<",
"15",
"|",
"k1",
">>",
"17",
")",
"&",
"0xFFFFFFFF",
"# inlined ROTL32",
"k1",
"=",
"(",
"c2",
"*",
"k1",
")",
"&",
"0xFFFFFFFF",
"h1",
"^=",
"k1",
"h1",
"=",
"(",
"h1",
"<<",
"19",
"|",
"h1",
">>",
"13",
")",
"&",
"0xFFFFFFFF",
"# inlined ROTL32",
"h1",
"=",
"(",
"h1",
"+",
"h2",
")",
"&",
"0xFFFFFFFF",
"h1",
"=",
"(",
"h1",
"*",
"5",
"+",
"0x561ccd1b",
")",
"&",
"0xFFFFFFFF",
"k2",
"=",
"(",
"c2",
"*",
"k2",
")",
"&",
"0xFFFFFFFF",
"k2",
"=",
"(",
"k2",
"<<",
"16",
"|",
"k2",
">>",
"16",
")",
"&",
"0xFFFFFFFF",
"# inlined ROTL32",
"k2",
"=",
"(",
"c3",
"*",
"k2",
")",
"&",
"0xFFFFFFFF",
"h2",
"^=",
"k2",
"h2",
"=",
"(",
"h2",
"<<",
"17",
"|",
"h2",
">>",
"15",
")",
"&",
"0xFFFFFFFF",
"# inlined ROTL32",
"h2",
"=",
"(",
"h2",
"+",
"h3",
")",
"&",
"0xFFFFFFFF",
"h2",
"=",
"(",
"h2",
"*",
"5",
"+",
"0x0bcaa747",
")",
"&",
"0xFFFFFFFF",
"k3",
"=",
"(",
"c3",
"*",
"k3",
")",
"&",
"0xFFFFFFFF",
"k3",
"=",
"(",
"k3",
"<<",
"17",
"|",
"k3",
">>",
"15",
")",
"&",
"0xFFFFFFFF",
"# inlined ROTL32",
"k3",
"=",
"(",
"c4",
"*",
"k3",
")",
"&",
"0xFFFFFFFF",
"h3",
"^=",
"k3",
"h3",
"=",
"(",
"h3",
"<<",
"15",
"|",
"h3",
">>",
"17",
")",
"&",
"0xFFFFFFFF",
"# inlined ROTL32",
"h3",
"=",
"(",
"h3",
"+",
"h4",
")",
"&",
"0xFFFFFFFF",
"h3",
"=",
"(",
"h3",
"*",
"5",
"+",
"0x96cd1c35",
")",
"&",
"0xFFFFFFFF",
"k4",
"=",
"(",
"c4",
"*",
"k4",
")",
"&",
"0xFFFFFFFF",
"k4",
"=",
"(",
"k4",
"<<",
"18",
"|",
"k4",
">>",
"14",
")",
"&",
"0xFFFFFFFF",
"# inlined ROTL32",
"k4",
"=",
"(",
"c1",
"*",
"k4",
")",
"&",
"0xFFFFFFFF",
"h4",
"^=",
"k4",
"h4",
"=",
"(",
"h4",
"<<",
"13",
"|",
"h4",
">>",
"19",
")",
"&",
"0xFFFFFFFF",
"# inlined ROTL32",
"h4",
"=",
"(",
"h1",
"+",
"h4",
")",
"&",
"0xFFFFFFFF",
"h4",
"=",
"(",
"h4",
"*",
"5",
"+",
"0x32ac3b17",
")",
"&",
"0xFFFFFFFF",
"# tail",
"tail_index",
"=",
"nblocks",
"*",
"16",
"k1",
"=",
"0",
"k2",
"=",
"0",
"k3",
"=",
"0",
"k4",
"=",
"0",
"tail_size",
"=",
"length",
"&",
"15",
"if",
"tail_size",
">=",
"15",
":",
"k4",
"^=",
"key",
"[",
"tail_index",
"+",
"14",
"]",
"<<",
"16",
"if",
"tail_size",
">=",
"14",
":",
"k4",
"^=",
"key",
"[",
"tail_index",
"+",
"13",
"]",
"<<",
"8",
"if",
"tail_size",
">=",
"13",
":",
"k4",
"^=",
"key",
"[",
"tail_index",
"+",
"12",
"]",
"if",
"tail_size",
">",
"12",
":",
"k4",
"=",
"(",
"k4",
"*",
"c4",
")",
"&",
"0xFFFFFFFF",
"k4",
"=",
"(",
"k4",
"<<",
"18",
"|",
"k4",
">>",
"14",
")",
"&",
"0xFFFFFFFF",
"# inlined ROTL32",
"k4",
"=",
"(",
"k4",
"*",
"c1",
")",
"&",
"0xFFFFFFFF",
"h4",
"^=",
"k4",
"if",
"tail_size",
">=",
"12",
":",
"k3",
"^=",
"key",
"[",
"tail_index",
"+",
"11",
"]",
"<<",
"24",
"if",
"tail_size",
">=",
"11",
":",
"k3",
"^=",
"key",
"[",
"tail_index",
"+",
"10",
"]",
"<<",
"16",
"if",
"tail_size",
">=",
"10",
":",
"k3",
"^=",
"key",
"[",
"tail_index",
"+",
"9",
"]",
"<<",
"8",
"if",
"tail_size",
">=",
"9",
":",
"k3",
"^=",
"key",
"[",
"tail_index",
"+",
"8",
"]",
"if",
"tail_size",
">",
"8",
":",
"k3",
"=",
"(",
"k3",
"*",
"c3",
")",
"&",
"0xFFFFFFFF",
"k3",
"=",
"(",
"k3",
"<<",
"17",
"|",
"k3",
">>",
"15",
")",
"&",
"0xFFFFFFFF",
"# inlined ROTL32",
"k3",
"=",
"(",
"k3",
"*",
"c4",
")",
"&",
"0xFFFFFFFF",
"h3",
"^=",
"k3",
"if",
"tail_size",
">=",
"8",
":",
"k2",
"^=",
"key",
"[",
"tail_index",
"+",
"7",
"]",
"<<",
"24",
"if",
"tail_size",
">=",
"7",
":",
"k2",
"^=",
"key",
"[",
"tail_index",
"+",
"6",
"]",
"<<",
"16",
"if",
"tail_size",
">=",
"6",
":",
"k2",
"^=",
"key",
"[",
"tail_index",
"+",
"5",
"]",
"<<",
"8",
"if",
"tail_size",
">=",
"5",
":",
"k2",
"^=",
"key",
"[",
"tail_index",
"+",
"4",
"]",
"if",
"tail_size",
">",
"4",
":",
"k2",
"=",
"(",
"k2",
"*",
"c2",
")",
"&",
"0xFFFFFFFF",
"k2",
"=",
"(",
"k2",
"<<",
"16",
"|",
"k2",
">>",
"16",
")",
"&",
"0xFFFFFFFF",
"# inlined ROTL32",
"k2",
"=",
"(",
"k2",
"*",
"c3",
")",
"&",
"0xFFFFFFFF",
"h2",
"^=",
"k2",
"if",
"tail_size",
">=",
"4",
":",
"k1",
"^=",
"key",
"[",
"tail_index",
"+",
"3",
"]",
"<<",
"24",
"if",
"tail_size",
">=",
"3",
":",
"k1",
"^=",
"key",
"[",
"tail_index",
"+",
"2",
"]",
"<<",
"16",
"if",
"tail_size",
">=",
"2",
":",
"k1",
"^=",
"key",
"[",
"tail_index",
"+",
"1",
"]",
"<<",
"8",
"if",
"tail_size",
">=",
"1",
":",
"k1",
"^=",
"key",
"[",
"tail_index",
"+",
"0",
"]",
"if",
"tail_size",
">",
"0",
":",
"k1",
"=",
"(",
"k1",
"*",
"c1",
")",
"&",
"0xFFFFFFFF",
"k1",
"=",
"(",
"k1",
"<<",
"15",
"|",
"k1",
">>",
"17",
")",
"&",
"0xFFFFFFFF",
"# inlined ROTL32",
"k1",
"=",
"(",
"k1",
"*",
"c2",
")",
"&",
"0xFFFFFFFF",
"h1",
"^=",
"k1",
"# finalization",
"h1",
"^=",
"length",
"h2",
"^=",
"length",
"h3",
"^=",
"length",
"h4",
"^=",
"length",
"h1",
"=",
"(",
"h1",
"+",
"h2",
")",
"&",
"0xFFFFFFFF",
"h1",
"=",
"(",
"h1",
"+",
"h3",
")",
"&",
"0xFFFFFFFF",
"h1",
"=",
"(",
"h1",
"+",
"h4",
")",
"&",
"0xFFFFFFFF",
"h2",
"=",
"(",
"h1",
"+",
"h2",
")",
"&",
"0xFFFFFFFF",
"h3",
"=",
"(",
"h1",
"+",
"h3",
")",
"&",
"0xFFFFFFFF",
"h4",
"=",
"(",
"h1",
"+",
"h4",
")",
"&",
"0xFFFFFFFF",
"h1",
"=",
"fmix",
"(",
"h1",
")",
"h2",
"=",
"fmix",
"(",
"h2",
")",
"h3",
"=",
"fmix",
"(",
"h3",
")",
"h4",
"=",
"fmix",
"(",
"h4",
")",
"h1",
"=",
"(",
"h1",
"+",
"h2",
")",
"&",
"0xFFFFFFFF",
"h1",
"=",
"(",
"h1",
"+",
"h3",
")",
"&",
"0xFFFFFFFF",
"h1",
"=",
"(",
"h1",
"+",
"h4",
")",
"&",
"0xFFFFFFFF",
"h2",
"=",
"(",
"h1",
"+",
"h2",
")",
"&",
"0xFFFFFFFF",
"h3",
"=",
"(",
"h1",
"+",
"h3",
")",
"&",
"0xFFFFFFFF",
"h4",
"=",
"(",
"h1",
"+",
"h4",
")",
"&",
"0xFFFFFFFF",
"return",
"h4",
"<<",
"96",
"|",
"h3",
"<<",
"64",
"|",
"h2",
"<<",
"32",
"|",
"h1"
] | Implements 128-bit murmur3 hash for x86, as per ``pymmh3``, with some
bugfixes.
Args:
key: data to hash
seed: seed
Returns:
integer hash | [
"Implements",
"128",
"-",
"bit",
"murmur3",
"hash",
"for",
"x86",
"as",
"per",
"pymmh3",
"with",
"some",
"bugfixes",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/hash.py#L658-L846 |
RudolfCardinal/pythonlib | cardinal_pythonlib/hash.py | pymmh3_hash128 | def pymmh3_hash128(key: Union[bytes, bytearray],
seed: int = 0,
x64arch: bool = True) -> int:
"""
Implements 128bit murmur3 hash, as per ``pymmh3``.
Args:
key: data to hash
seed: seed
x64arch: is a 64-bit architecture available?
Returns:
integer hash
"""
if x64arch:
return pymmh3_hash128_x64(key, seed)
else:
return pymmh3_hash128_x86(key, seed) | python | def pymmh3_hash128(key: Union[bytes, bytearray],
seed: int = 0,
x64arch: bool = True) -> int:
"""
Implements 128bit murmur3 hash, as per ``pymmh3``.
Args:
key: data to hash
seed: seed
x64arch: is a 64-bit architecture available?
Returns:
integer hash
"""
if x64arch:
return pymmh3_hash128_x64(key, seed)
else:
return pymmh3_hash128_x86(key, seed) | [
"def",
"pymmh3_hash128",
"(",
"key",
":",
"Union",
"[",
"bytes",
",",
"bytearray",
"]",
",",
"seed",
":",
"int",
"=",
"0",
",",
"x64arch",
":",
"bool",
"=",
"True",
")",
"->",
"int",
":",
"if",
"x64arch",
":",
"return",
"pymmh3_hash128_x64",
"(",
"key",
",",
"seed",
")",
"else",
":",
"return",
"pymmh3_hash128_x86",
"(",
"key",
",",
"seed",
")"
] | Implements 128bit murmur3 hash, as per ``pymmh3``.
Args:
key: data to hash
seed: seed
x64arch: is a 64-bit architecture available?
Returns:
integer hash | [
"Implements",
"128bit",
"murmur3",
"hash",
"as",
"per",
"pymmh3",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/hash.py#L849-L867 |
RudolfCardinal/pythonlib | cardinal_pythonlib/hash.py | pymmh3_hash64 | def pymmh3_hash64(key: Union[bytes, bytearray],
seed: int = 0,
x64arch: bool = True) -> Tuple[int, int]:
"""
Implements 64bit murmur3 hash, as per ``pymmh3``. Returns a tuple.
Args:
key: data to hash
seed: seed
x64arch: is a 64-bit architecture available?
Returns:
tuple: tuple of integers, ``(signed_val1, signed_val2)``
"""
hash_128 = pymmh3_hash128(key, seed, x64arch)
unsigned_val1 = hash_128 & 0xFFFFFFFFFFFFFFFF # low half
if unsigned_val1 & 0x8000000000000000 == 0:
signed_val1 = unsigned_val1
else:
signed_val1 = -((unsigned_val1 ^ 0xFFFFFFFFFFFFFFFF) + 1)
unsigned_val2 = (hash_128 >> 64) & 0xFFFFFFFFFFFFFFFF # high half
if unsigned_val2 & 0x8000000000000000 == 0:
signed_val2 = unsigned_val2
else:
signed_val2 = -((unsigned_val2 ^ 0xFFFFFFFFFFFFFFFF) + 1)
return signed_val1, signed_val2 | python | def pymmh3_hash64(key: Union[bytes, bytearray],
seed: int = 0,
x64arch: bool = True) -> Tuple[int, int]:
"""
Implements 64bit murmur3 hash, as per ``pymmh3``. Returns a tuple.
Args:
key: data to hash
seed: seed
x64arch: is a 64-bit architecture available?
Returns:
tuple: tuple of integers, ``(signed_val1, signed_val2)``
"""
hash_128 = pymmh3_hash128(key, seed, x64arch)
unsigned_val1 = hash_128 & 0xFFFFFFFFFFFFFFFF # low half
if unsigned_val1 & 0x8000000000000000 == 0:
signed_val1 = unsigned_val1
else:
signed_val1 = -((unsigned_val1 ^ 0xFFFFFFFFFFFFFFFF) + 1)
unsigned_val2 = (hash_128 >> 64) & 0xFFFFFFFFFFFFFFFF # high half
if unsigned_val2 & 0x8000000000000000 == 0:
signed_val2 = unsigned_val2
else:
signed_val2 = -((unsigned_val2 ^ 0xFFFFFFFFFFFFFFFF) + 1)
return signed_val1, signed_val2 | [
"def",
"pymmh3_hash64",
"(",
"key",
":",
"Union",
"[",
"bytes",
",",
"bytearray",
"]",
",",
"seed",
":",
"int",
"=",
"0",
",",
"x64arch",
":",
"bool",
"=",
"True",
")",
"->",
"Tuple",
"[",
"int",
",",
"int",
"]",
":",
"hash_128",
"=",
"pymmh3_hash128",
"(",
"key",
",",
"seed",
",",
"x64arch",
")",
"unsigned_val1",
"=",
"hash_128",
"&",
"0xFFFFFFFFFFFFFFFF",
"# low half",
"if",
"unsigned_val1",
"&",
"0x8000000000000000",
"==",
"0",
":",
"signed_val1",
"=",
"unsigned_val1",
"else",
":",
"signed_val1",
"=",
"-",
"(",
"(",
"unsigned_val1",
"^",
"0xFFFFFFFFFFFFFFFF",
")",
"+",
"1",
")",
"unsigned_val2",
"=",
"(",
"hash_128",
">>",
"64",
")",
"&",
"0xFFFFFFFFFFFFFFFF",
"# high half",
"if",
"unsigned_val2",
"&",
"0x8000000000000000",
"==",
"0",
":",
"signed_val2",
"=",
"unsigned_val2",
"else",
":",
"signed_val2",
"=",
"-",
"(",
"(",
"unsigned_val2",
"^",
"0xFFFFFFFFFFFFFFFF",
")",
"+",
"1",
")",
"return",
"signed_val1",
",",
"signed_val2"
] | Implements 64bit murmur3 hash, as per ``pymmh3``. Returns a tuple.
Args:
key: data to hash
seed: seed
x64arch: is a 64-bit architecture available?
Returns:
tuple: tuple of integers, ``(signed_val1, signed_val2)`` | [
"Implements",
"64bit",
"murmur3",
"hash",
"as",
"per",
"pymmh3",
".",
"Returns",
"a",
"tuple",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/hash.py#L870-L900 |
RudolfCardinal/pythonlib | cardinal_pythonlib/hash.py | compare_python_to_reference_murmur3_32 | def compare_python_to_reference_murmur3_32(data: Any, seed: int = 0) -> None:
"""
Checks the pure Python implementation of 32-bit murmur3 against the
``mmh3`` C-based module.
Args:
data: data to hash
seed: seed
Raises:
AssertionError: if the two calculations don't match
"""
assert mmh3, "Need mmh3 module"
c_data = to_str(data)
c_signed = mmh3.hash(c_data, seed=seed) # 32 bit
py_data = to_bytes(c_data)
py_unsigned = murmur3_x86_32(py_data, seed=seed)
py_signed = twos_comp_to_signed(py_unsigned, n_bits=32)
preamble = "Hashing {data} with MurmurHash3/32-bit/seed={seed}".format(
data=repr(data), seed=seed)
if c_signed == py_signed:
print(preamble + " -> {result}: OK".format(result=c_signed))
else:
raise AssertionError(
preamble + "; mmh3 says "
"{c_data} -> {c_signed}, Python version says {py_data} -> "
"{py_unsigned} = {py_signed}".format(
c_data=repr(c_data),
c_signed=c_signed,
py_data=repr(py_data),
py_unsigned=py_unsigned,
py_signed=py_signed)) | python | def compare_python_to_reference_murmur3_32(data: Any, seed: int = 0) -> None:
"""
Checks the pure Python implementation of 32-bit murmur3 against the
``mmh3`` C-based module.
Args:
data: data to hash
seed: seed
Raises:
AssertionError: if the two calculations don't match
"""
assert mmh3, "Need mmh3 module"
c_data = to_str(data)
c_signed = mmh3.hash(c_data, seed=seed) # 32 bit
py_data = to_bytes(c_data)
py_unsigned = murmur3_x86_32(py_data, seed=seed)
py_signed = twos_comp_to_signed(py_unsigned, n_bits=32)
preamble = "Hashing {data} with MurmurHash3/32-bit/seed={seed}".format(
data=repr(data), seed=seed)
if c_signed == py_signed:
print(preamble + " -> {result}: OK".format(result=c_signed))
else:
raise AssertionError(
preamble + "; mmh3 says "
"{c_data} -> {c_signed}, Python version says {py_data} -> "
"{py_unsigned} = {py_signed}".format(
c_data=repr(c_data),
c_signed=c_signed,
py_data=repr(py_data),
py_unsigned=py_unsigned,
py_signed=py_signed)) | [
"def",
"compare_python_to_reference_murmur3_32",
"(",
"data",
":",
"Any",
",",
"seed",
":",
"int",
"=",
"0",
")",
"->",
"None",
":",
"assert",
"mmh3",
",",
"\"Need mmh3 module\"",
"c_data",
"=",
"to_str",
"(",
"data",
")",
"c_signed",
"=",
"mmh3",
".",
"hash",
"(",
"c_data",
",",
"seed",
"=",
"seed",
")",
"# 32 bit",
"py_data",
"=",
"to_bytes",
"(",
"c_data",
")",
"py_unsigned",
"=",
"murmur3_x86_32",
"(",
"py_data",
",",
"seed",
"=",
"seed",
")",
"py_signed",
"=",
"twos_comp_to_signed",
"(",
"py_unsigned",
",",
"n_bits",
"=",
"32",
")",
"preamble",
"=",
"\"Hashing {data} with MurmurHash3/32-bit/seed={seed}\"",
".",
"format",
"(",
"data",
"=",
"repr",
"(",
"data",
")",
",",
"seed",
"=",
"seed",
")",
"if",
"c_signed",
"==",
"py_signed",
":",
"print",
"(",
"preamble",
"+",
"\" -> {result}: OK\"",
".",
"format",
"(",
"result",
"=",
"c_signed",
")",
")",
"else",
":",
"raise",
"AssertionError",
"(",
"preamble",
"+",
"\"; mmh3 says \"",
"\"{c_data} -> {c_signed}, Python version says {py_data} -> \"",
"\"{py_unsigned} = {py_signed}\"",
".",
"format",
"(",
"c_data",
"=",
"repr",
"(",
"c_data",
")",
",",
"c_signed",
"=",
"c_signed",
",",
"py_data",
"=",
"repr",
"(",
"py_data",
")",
",",
"py_unsigned",
"=",
"py_unsigned",
",",
"py_signed",
"=",
"py_signed",
")",
")"
] | Checks the pure Python implementation of 32-bit murmur3 against the
``mmh3`` C-based module.
Args:
data: data to hash
seed: seed
Raises:
AssertionError: if the two calculations don't match | [
"Checks",
"the",
"pure",
"Python",
"implementation",
"of",
"32",
"-",
"bit",
"murmur3",
"against",
"the",
"mmh3",
"C",
"-",
"based",
"module",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/hash.py#L907-L939 |
RudolfCardinal/pythonlib | cardinal_pythonlib/hash.py | compare_python_to_reference_murmur3_64 | def compare_python_to_reference_murmur3_64(data: Any, seed: int = 0) -> None:
"""
Checks the pure Python implementation of 64-bit murmur3 against the
``mmh3`` C-based module.
Args:
data: data to hash
seed: seed
Raises:
AssertionError: if the two calculations don't match
"""
assert mmh3, "Need mmh3 module"
c_data = to_str(data)
c_signed_low, c_signed_high = mmh3.hash64(c_data, seed=seed,
x64arch=IS_64_BIT)
py_data = to_bytes(c_data)
py_signed_low, py_signed_high = pymmh3_hash64(py_data, seed=seed)
preamble = "Hashing {data} with MurmurHash3/64-bit values from 128-bit " \
"hash/seed={seed}".format(data=repr(data), seed=seed)
if c_signed_low == py_signed_low and c_signed_high == py_signed_high:
print(preamble + " -> (low={low}, high={high}): OK".format(
low=c_signed_low, high=c_signed_high))
else:
raise AssertionError(
preamble +
"; mmh3 says {c_data} -> (low={c_low}, high={c_high}), Python "
"version says {py_data} -> (low={py_low}, high={py_high})".format(
c_data=repr(c_data),
c_low=c_signed_low,
c_high=c_signed_high,
py_data=repr(py_data),
py_low=py_signed_low,
py_high=py_signed_high)) | python | def compare_python_to_reference_murmur3_64(data: Any, seed: int = 0) -> None:
"""
Checks the pure Python implementation of 64-bit murmur3 against the
``mmh3`` C-based module.
Args:
data: data to hash
seed: seed
Raises:
AssertionError: if the two calculations don't match
"""
assert mmh3, "Need mmh3 module"
c_data = to_str(data)
c_signed_low, c_signed_high = mmh3.hash64(c_data, seed=seed,
x64arch=IS_64_BIT)
py_data = to_bytes(c_data)
py_signed_low, py_signed_high = pymmh3_hash64(py_data, seed=seed)
preamble = "Hashing {data} with MurmurHash3/64-bit values from 128-bit " \
"hash/seed={seed}".format(data=repr(data), seed=seed)
if c_signed_low == py_signed_low and c_signed_high == py_signed_high:
print(preamble + " -> (low={low}, high={high}): OK".format(
low=c_signed_low, high=c_signed_high))
else:
raise AssertionError(
preamble +
"; mmh3 says {c_data} -> (low={c_low}, high={c_high}), Python "
"version says {py_data} -> (low={py_low}, high={py_high})".format(
c_data=repr(c_data),
c_low=c_signed_low,
c_high=c_signed_high,
py_data=repr(py_data),
py_low=py_signed_low,
py_high=py_signed_high)) | [
"def",
"compare_python_to_reference_murmur3_64",
"(",
"data",
":",
"Any",
",",
"seed",
":",
"int",
"=",
"0",
")",
"->",
"None",
":",
"assert",
"mmh3",
",",
"\"Need mmh3 module\"",
"c_data",
"=",
"to_str",
"(",
"data",
")",
"c_signed_low",
",",
"c_signed_high",
"=",
"mmh3",
".",
"hash64",
"(",
"c_data",
",",
"seed",
"=",
"seed",
",",
"x64arch",
"=",
"IS_64_BIT",
")",
"py_data",
"=",
"to_bytes",
"(",
"c_data",
")",
"py_signed_low",
",",
"py_signed_high",
"=",
"pymmh3_hash64",
"(",
"py_data",
",",
"seed",
"=",
"seed",
")",
"preamble",
"=",
"\"Hashing {data} with MurmurHash3/64-bit values from 128-bit \"",
"\"hash/seed={seed}\"",
".",
"format",
"(",
"data",
"=",
"repr",
"(",
"data",
")",
",",
"seed",
"=",
"seed",
")",
"if",
"c_signed_low",
"==",
"py_signed_low",
"and",
"c_signed_high",
"==",
"py_signed_high",
":",
"print",
"(",
"preamble",
"+",
"\" -> (low={low}, high={high}): OK\"",
".",
"format",
"(",
"low",
"=",
"c_signed_low",
",",
"high",
"=",
"c_signed_high",
")",
")",
"else",
":",
"raise",
"AssertionError",
"(",
"preamble",
"+",
"\"; mmh3 says {c_data} -> (low={c_low}, high={c_high}), Python \"",
"\"version says {py_data} -> (low={py_low}, high={py_high})\"",
".",
"format",
"(",
"c_data",
"=",
"repr",
"(",
"c_data",
")",
",",
"c_low",
"=",
"c_signed_low",
",",
"c_high",
"=",
"c_signed_high",
",",
"py_data",
"=",
"repr",
"(",
"py_data",
")",
",",
"py_low",
"=",
"py_signed_low",
",",
"py_high",
"=",
"py_signed_high",
")",
")"
] | Checks the pure Python implementation of 64-bit murmur3 against the
``mmh3`` C-based module.
Args:
data: data to hash
seed: seed
Raises:
AssertionError: if the two calculations don't match | [
"Checks",
"the",
"pure",
"Python",
"implementation",
"of",
"64",
"-",
"bit",
"murmur3",
"against",
"the",
"mmh3",
"C",
"-",
"based",
"module",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/hash.py#L942-L976 |
RudolfCardinal/pythonlib | cardinal_pythonlib/hash.py | hash32 | def hash32(data: Any, seed=0) -> int:
"""
Non-cryptographic, deterministic, fast hash.
Args:
data: data to hash
seed: seed
Returns:
signed 32-bit integer
"""
with MultiTimerContext(timer, TIMING_HASH):
c_data = to_str(data)
if mmh3:
return mmh3.hash(c_data, seed=seed)
py_data = to_bytes(c_data)
py_unsigned = murmur3_x86_32(py_data, seed=seed)
return twos_comp_to_signed(py_unsigned, n_bits=32) | python | def hash32(data: Any, seed=0) -> int:
"""
Non-cryptographic, deterministic, fast hash.
Args:
data: data to hash
seed: seed
Returns:
signed 32-bit integer
"""
with MultiTimerContext(timer, TIMING_HASH):
c_data = to_str(data)
if mmh3:
return mmh3.hash(c_data, seed=seed)
py_data = to_bytes(c_data)
py_unsigned = murmur3_x86_32(py_data, seed=seed)
return twos_comp_to_signed(py_unsigned, n_bits=32) | [
"def",
"hash32",
"(",
"data",
":",
"Any",
",",
"seed",
"=",
"0",
")",
"->",
"int",
":",
"with",
"MultiTimerContext",
"(",
"timer",
",",
"TIMING_HASH",
")",
":",
"c_data",
"=",
"to_str",
"(",
"data",
")",
"if",
"mmh3",
":",
"return",
"mmh3",
".",
"hash",
"(",
"c_data",
",",
"seed",
"=",
"seed",
")",
"py_data",
"=",
"to_bytes",
"(",
"c_data",
")",
"py_unsigned",
"=",
"murmur3_x86_32",
"(",
"py_data",
",",
"seed",
"=",
"seed",
")",
"return",
"twos_comp_to_signed",
"(",
"py_unsigned",
",",
"n_bits",
"=",
"32",
")"
] | Non-cryptographic, deterministic, fast hash.
Args:
data: data to hash
seed: seed
Returns:
signed 32-bit integer | [
"Non",
"-",
"cryptographic",
"deterministic",
"fast",
"hash",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/hash.py#L983-L1000 |
RudolfCardinal/pythonlib | cardinal_pythonlib/hash.py | hash64 | def hash64(data: Any, seed: int = 0) -> int:
"""
Non-cryptographic, deterministic, fast hash.
Args:
data: data to hash
seed: seed
Returns:
signed 64-bit integer
"""
# -------------------------------------------------------------------------
# MurmurHash3
# -------------------------------------------------------------------------
c_data = to_str(data)
if mmh3:
c_signed_low, _ = mmh3.hash64(data, seed=seed, x64arch=IS_64_BIT)
return c_signed_low
py_data = to_bytes(c_data)
py_signed_low, _ = pymmh3_hash64(py_data, seed=seed)
return py_signed_low | python | def hash64(data: Any, seed: int = 0) -> int:
"""
Non-cryptographic, deterministic, fast hash.
Args:
data: data to hash
seed: seed
Returns:
signed 64-bit integer
"""
# -------------------------------------------------------------------------
# MurmurHash3
# -------------------------------------------------------------------------
c_data = to_str(data)
if mmh3:
c_signed_low, _ = mmh3.hash64(data, seed=seed, x64arch=IS_64_BIT)
return c_signed_low
py_data = to_bytes(c_data)
py_signed_low, _ = pymmh3_hash64(py_data, seed=seed)
return py_signed_low | [
"def",
"hash64",
"(",
"data",
":",
"Any",
",",
"seed",
":",
"int",
"=",
"0",
")",
"->",
"int",
":",
"# -------------------------------------------------------------------------",
"# MurmurHash3",
"# -------------------------------------------------------------------------",
"c_data",
"=",
"to_str",
"(",
"data",
")",
"if",
"mmh3",
":",
"c_signed_low",
",",
"_",
"=",
"mmh3",
".",
"hash64",
"(",
"data",
",",
"seed",
"=",
"seed",
",",
"x64arch",
"=",
"IS_64_BIT",
")",
"return",
"c_signed_low",
"py_data",
"=",
"to_bytes",
"(",
"c_data",
")",
"py_signed_low",
",",
"_",
"=",
"pymmh3_hash64",
"(",
"py_data",
",",
"seed",
"=",
"seed",
")",
"return",
"py_signed_low"
] | Non-cryptographic, deterministic, fast hash.
Args:
data: data to hash
seed: seed
Returns:
signed 64-bit integer | [
"Non",
"-",
"cryptographic",
"deterministic",
"fast",
"hash",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/hash.py#L1003-L1023 |
RudolfCardinal/pythonlib | cardinal_pythonlib/hash.py | main | def main() -> None:
"""
Command-line validation checks.
"""
_ = """
print(twos_comp_to_signed(0, n_bits=32)) # 0
print(twos_comp_to_signed(2 ** 31 - 1, n_bits=32)) # 2147483647
print(twos_comp_to_signed(2 ** 31, n_bits=32)) # -2147483648 == -(2 ** 31)
print(twos_comp_to_signed(2 ** 32 - 1, n_bits=32)) # -1
print(signed_to_twos_comp(-1, n_bits=32)) # 4294967295 = 2 ** 32 - 1
print(signed_to_twos_comp(-(2 ** 31), n_bits=32)) # 2147483648 = 2 ** 31 - 1
""" # noqa
testdata = [
"hello",
1,
["bongos", "today"],
]
for data in testdata:
compare_python_to_reference_murmur3_32(data, seed=0)
compare_python_to_reference_murmur3_64(data, seed=0)
print("All OK") | python | def main() -> None:
"""
Command-line validation checks.
"""
_ = """
print(twos_comp_to_signed(0, n_bits=32)) # 0
print(twos_comp_to_signed(2 ** 31 - 1, n_bits=32)) # 2147483647
print(twos_comp_to_signed(2 ** 31, n_bits=32)) # -2147483648 == -(2 ** 31)
print(twos_comp_to_signed(2 ** 32 - 1, n_bits=32)) # -1
print(signed_to_twos_comp(-1, n_bits=32)) # 4294967295 = 2 ** 32 - 1
print(signed_to_twos_comp(-(2 ** 31), n_bits=32)) # 2147483648 = 2 ** 31 - 1
""" # noqa
testdata = [
"hello",
1,
["bongos", "today"],
]
for data in testdata:
compare_python_to_reference_murmur3_32(data, seed=0)
compare_python_to_reference_murmur3_64(data, seed=0)
print("All OK") | [
"def",
"main",
"(",
")",
"->",
"None",
":",
"_",
"=",
"\"\"\"\n print(twos_comp_to_signed(0, n_bits=32)) # 0\n print(twos_comp_to_signed(2 ** 31 - 1, n_bits=32)) # 2147483647\n print(twos_comp_to_signed(2 ** 31, n_bits=32)) # -2147483648 == -(2 ** 31)\n print(twos_comp_to_signed(2 ** 32 - 1, n_bits=32)) # -1\n print(signed_to_twos_comp(-1, n_bits=32)) # 4294967295 = 2 ** 32 - 1\n print(signed_to_twos_comp(-(2 ** 31), n_bits=32)) # 2147483648 = 2 ** 31 - 1\n \"\"\"",
"# noqa",
"testdata",
"=",
"[",
"\"hello\"",
",",
"1",
",",
"[",
"\"bongos\"",
",",
"\"today\"",
"]",
",",
"]",
"for",
"data",
"in",
"testdata",
":",
"compare_python_to_reference_murmur3_32",
"(",
"data",
",",
"seed",
"=",
"0",
")",
"compare_python_to_reference_murmur3_64",
"(",
"data",
",",
"seed",
"=",
"0",
")",
"print",
"(",
"\"All OK\"",
")"
] | Command-line validation checks. | [
"Command",
"-",
"line",
"validation",
"checks",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/hash.py#L1042-L1062 |
RudolfCardinal/pythonlib | cardinal_pythonlib/hash.py | GenericHmacHasher.hash | def hash(self, raw: Any) -> str:
"""
Returns the hex digest of a HMAC-encoded version of the input.
"""
with MultiTimerContext(timer, TIMING_HASH):
raw_bytes = str(raw).encode('utf-8')
hmac_obj = hmac.new(key=self.key_bytes, msg=raw_bytes,
digestmod=self.digestmod)
return hmac_obj.hexdigest() | python | def hash(self, raw: Any) -> str:
"""
Returns the hex digest of a HMAC-encoded version of the input.
"""
with MultiTimerContext(timer, TIMING_HASH):
raw_bytes = str(raw).encode('utf-8')
hmac_obj = hmac.new(key=self.key_bytes, msg=raw_bytes,
digestmod=self.digestmod)
return hmac_obj.hexdigest() | [
"def",
"hash",
"(",
"self",
",",
"raw",
":",
"Any",
")",
"->",
"str",
":",
"with",
"MultiTimerContext",
"(",
"timer",
",",
"TIMING_HASH",
")",
":",
"raw_bytes",
"=",
"str",
"(",
"raw",
")",
".",
"encode",
"(",
"'utf-8'",
")",
"hmac_obj",
"=",
"hmac",
".",
"new",
"(",
"key",
"=",
"self",
".",
"key_bytes",
",",
"msg",
"=",
"raw_bytes",
",",
"digestmod",
"=",
"self",
".",
"digestmod",
")",
"return",
"hmac_obj",
".",
"hexdigest",
"(",
")"
] | Returns the hex digest of a HMAC-encoded version of the input. | [
"Returns",
"the",
"hex",
"digest",
"of",
"a",
"HMAC",
"-",
"encoded",
"version",
"of",
"the",
"input",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/hash.py#L188-L196 |
RudolfCardinal/pythonlib | cardinal_pythonlib/maths_py.py | mean | def mean(values: Sequence[Union[int, float, None]]) -> Optional[float]:
"""
Returns the mean of a list of numbers.
Args:
values: values to mean, ignoring any values that are ``None``
Returns:
the mean, or ``None`` if :math:`n = 0`
"""
total = 0.0 # starting with "0.0" causes automatic conversion to float
n = 0
for x in values:
if x is not None:
total += x
n += 1
return total / n if n > 0 else None | python | def mean(values: Sequence[Union[int, float, None]]) -> Optional[float]:
"""
Returns the mean of a list of numbers.
Args:
values: values to mean, ignoring any values that are ``None``
Returns:
the mean, or ``None`` if :math:`n = 0`
"""
total = 0.0 # starting with "0.0" causes automatic conversion to float
n = 0
for x in values:
if x is not None:
total += x
n += 1
return total / n if n > 0 else None | [
"def",
"mean",
"(",
"values",
":",
"Sequence",
"[",
"Union",
"[",
"int",
",",
"float",
",",
"None",
"]",
"]",
")",
"->",
"Optional",
"[",
"float",
"]",
":",
"total",
"=",
"0.0",
"# starting with \"0.0\" causes automatic conversion to float",
"n",
"=",
"0",
"for",
"x",
"in",
"values",
":",
"if",
"x",
"is",
"not",
"None",
":",
"total",
"+=",
"x",
"n",
"+=",
"1",
"return",
"total",
"/",
"n",
"if",
"n",
">",
"0",
"else",
"None"
] | Returns the mean of a list of numbers.
Args:
values: values to mean, ignoring any values that are ``None``
Returns:
the mean, or ``None`` if :math:`n = 0` | [
"Returns",
"the",
"mean",
"of",
"a",
"list",
"of",
"numbers",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/maths_py.py#L41-L58 |
RudolfCardinal/pythonlib | cardinal_pythonlib/maths_py.py | safe_logit | def safe_logit(p: Union[float, int]) -> Optional[float]:
r"""
Returns the logit (log odds) of its input probability
.. math::
\alpha = logit(p) = log(x / (1 - x))
Args:
p: :math:`p`
Returns:
:math:`\alpha`, or ``None`` if ``x`` is not in the range [0, 1].
"""
if p > 1 or p < 0:
return None # can't take log of negative number
if p == 1:
return float("inf")
if p == 0:
return float("-inf")
return math.log(p / (1 - p)) | python | def safe_logit(p: Union[float, int]) -> Optional[float]:
r"""
Returns the logit (log odds) of its input probability
.. math::
\alpha = logit(p) = log(x / (1 - x))
Args:
p: :math:`p`
Returns:
:math:`\alpha`, or ``None`` if ``x`` is not in the range [0, 1].
"""
if p > 1 or p < 0:
return None # can't take log of negative number
if p == 1:
return float("inf")
if p == 0:
return float("-inf")
return math.log(p / (1 - p)) | [
"def",
"safe_logit",
"(",
"p",
":",
"Union",
"[",
"float",
",",
"int",
"]",
")",
"->",
"Optional",
"[",
"float",
"]",
":",
"if",
"p",
">",
"1",
"or",
"p",
"<",
"0",
":",
"return",
"None",
"# can't take log of negative number",
"if",
"p",
"==",
"1",
":",
"return",
"float",
"(",
"\"inf\"",
")",
"if",
"p",
"==",
"0",
":",
"return",
"float",
"(",
"\"-inf\"",
")",
"return",
"math",
".",
"log",
"(",
"p",
"/",
"(",
"1",
"-",
"p",
")",
")"
] | r"""
Returns the logit (log odds) of its input probability
.. math::
\alpha = logit(p) = log(x / (1 - x))
Args:
p: :math:`p`
Returns:
:math:`\alpha`, or ``None`` if ``x`` is not in the range [0, 1]. | [
"r",
"Returns",
"the",
"logit",
"(",
"log",
"odds",
")",
"of",
"its",
"input",
"probability"
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/maths_py.py#L65-L86 |
RudolfCardinal/pythonlib | cardinal_pythonlib/maths_py.py | normal_round_float | def normal_round_float(x: float, dp: int = 0) -> float:
"""
Hmpf. Shouldn't need to have to implement this, but...
Conventional rounding to integer via the "round half away from zero"
method, e.g.
.. code-block:: none
1.1 -> 1
1.5 -> 2
1.6 -> 2
2.0 -> 2
-1.6 -> -2
etc.
... or the equivalent for a certain number of decimal places.
Note that round() implements "banker's rounding", which is never what
we want:
- https://stackoverflow.com/questions/33019698/how-to-properly-round-up-half-float-numbers-in-python # noqa
"""
if not math.isfinite(x):
return x
factor = pow(10, dp)
x = x * factor
if x >= 0:
x = math.floor(x + 0.5)
else:
x = math.ceil(x - 0.5)
x = x / factor
return x | python | def normal_round_float(x: float, dp: int = 0) -> float:
"""
Hmpf. Shouldn't need to have to implement this, but...
Conventional rounding to integer via the "round half away from zero"
method, e.g.
.. code-block:: none
1.1 -> 1
1.5 -> 2
1.6 -> 2
2.0 -> 2
-1.6 -> -2
etc.
... or the equivalent for a certain number of decimal places.
Note that round() implements "banker's rounding", which is never what
we want:
- https://stackoverflow.com/questions/33019698/how-to-properly-round-up-half-float-numbers-in-python # noqa
"""
if not math.isfinite(x):
return x
factor = pow(10, dp)
x = x * factor
if x >= 0:
x = math.floor(x + 0.5)
else:
x = math.ceil(x - 0.5)
x = x / factor
return x | [
"def",
"normal_round_float",
"(",
"x",
":",
"float",
",",
"dp",
":",
"int",
"=",
"0",
")",
"->",
"float",
":",
"if",
"not",
"math",
".",
"isfinite",
"(",
"x",
")",
":",
"return",
"x",
"factor",
"=",
"pow",
"(",
"10",
",",
"dp",
")",
"x",
"=",
"x",
"*",
"factor",
"if",
"x",
">=",
"0",
":",
"x",
"=",
"math",
".",
"floor",
"(",
"x",
"+",
"0.5",
")",
"else",
":",
"x",
"=",
"math",
".",
"ceil",
"(",
"x",
"-",
"0.5",
")",
"x",
"=",
"x",
"/",
"factor",
"return",
"x"
] | Hmpf. Shouldn't need to have to implement this, but...
Conventional rounding to integer via the "round half away from zero"
method, e.g.
.. code-block:: none
1.1 -> 1
1.5 -> 2
1.6 -> 2
2.0 -> 2
-1.6 -> -2
etc.
... or the equivalent for a certain number of decimal places.
Note that round() implements "banker's rounding", which is never what
we want:
- https://stackoverflow.com/questions/33019698/how-to-properly-round-up-half-float-numbers-in-python # noqa | [
"Hmpf",
".",
"Shouldn",
"t",
"need",
"to",
"have",
"to",
"implement",
"this",
"but",
"..."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/maths_py.py#L93-L125 |
RudolfCardinal/pythonlib | cardinal_pythonlib/maths_py.py | normal_round_int | def normal_round_int(x: float) -> int:
"""
Version of :func:`normal_round_float` but guaranteed to return an `int`.
"""
if not math.isfinite(x):
raise ValueError("Input to normal_round_int() is not finite")
if x >= 0:
# noinspection PyTypeChecker
return math.floor(x + 0.5)
else:
# noinspection PyTypeChecker
return math.ceil(x - 0.5) | python | def normal_round_int(x: float) -> int:
"""
Version of :func:`normal_round_float` but guaranteed to return an `int`.
"""
if not math.isfinite(x):
raise ValueError("Input to normal_round_int() is not finite")
if x >= 0:
# noinspection PyTypeChecker
return math.floor(x + 0.5)
else:
# noinspection PyTypeChecker
return math.ceil(x - 0.5) | [
"def",
"normal_round_int",
"(",
"x",
":",
"float",
")",
"->",
"int",
":",
"if",
"not",
"math",
".",
"isfinite",
"(",
"x",
")",
":",
"raise",
"ValueError",
"(",
"\"Input to normal_round_int() is not finite\"",
")",
"if",
"x",
">=",
"0",
":",
"# noinspection PyTypeChecker",
"return",
"math",
".",
"floor",
"(",
"x",
"+",
"0.5",
")",
"else",
":",
"# noinspection PyTypeChecker",
"return",
"math",
".",
"ceil",
"(",
"x",
"-",
"0.5",
")"
] | Version of :func:`normal_round_float` but guaranteed to return an `int`. | [
"Version",
"of",
":",
"func",
":",
"normal_round_float",
"but",
"guaranteed",
"to",
"return",
"an",
"int",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/maths_py.py#L128-L139 |
RudolfCardinal/pythonlib | cardinal_pythonlib/tools/backup_mysql_database.py | cmdargs | def cmdargs(mysqldump: str,
username: str,
password: str,
database: str,
verbose: bool,
with_drop_create_database: bool,
max_allowed_packet: str,
hide_password: bool = False) -> List[str]:
"""
Returns command arguments for a ``mysqldump`` call.
Args:
mysqldump: ``mysqldump`` executable filename
username: user name
password: password
database: database name
verbose: verbose output?
with_drop_create_database: produce commands to ``DROP`` the database
and recreate it?
max_allowed_packet: passed to ``mysqldump``
hide_password: obscure the password (will break the arguments but
provide a safe version to show the user)?
Returns:
list of command-line arguments
"""
ca = [
mysqldump,
"-u", username,
"-p{}".format("*****" if hide_password else password),
"--max_allowed_packet={}".format(max_allowed_packet),
"--hex-blob", # preferable to raw binary in our .sql file
]
if verbose:
ca.append("--verbose")
if with_drop_create_database:
ca.extend([
"--add-drop-database",
"--databases",
database
])
else:
ca.append(database)
pass
return ca | python | def cmdargs(mysqldump: str,
username: str,
password: str,
database: str,
verbose: bool,
with_drop_create_database: bool,
max_allowed_packet: str,
hide_password: bool = False) -> List[str]:
"""
Returns command arguments for a ``mysqldump`` call.
Args:
mysqldump: ``mysqldump`` executable filename
username: user name
password: password
database: database name
verbose: verbose output?
with_drop_create_database: produce commands to ``DROP`` the database
and recreate it?
max_allowed_packet: passed to ``mysqldump``
hide_password: obscure the password (will break the arguments but
provide a safe version to show the user)?
Returns:
list of command-line arguments
"""
ca = [
mysqldump,
"-u", username,
"-p{}".format("*****" if hide_password else password),
"--max_allowed_packet={}".format(max_allowed_packet),
"--hex-blob", # preferable to raw binary in our .sql file
]
if verbose:
ca.append("--verbose")
if with_drop_create_database:
ca.extend([
"--add-drop-database",
"--databases",
database
])
else:
ca.append(database)
pass
return ca | [
"def",
"cmdargs",
"(",
"mysqldump",
":",
"str",
",",
"username",
":",
"str",
",",
"password",
":",
"str",
",",
"database",
":",
"str",
",",
"verbose",
":",
"bool",
",",
"with_drop_create_database",
":",
"bool",
",",
"max_allowed_packet",
":",
"str",
",",
"hide_password",
":",
"bool",
"=",
"False",
")",
"->",
"List",
"[",
"str",
"]",
":",
"ca",
"=",
"[",
"mysqldump",
",",
"\"-u\"",
",",
"username",
",",
"\"-p{}\"",
".",
"format",
"(",
"\"*****\"",
"if",
"hide_password",
"else",
"password",
")",
",",
"\"--max_allowed_packet={}\"",
".",
"format",
"(",
"max_allowed_packet",
")",
",",
"\"--hex-blob\"",
",",
"# preferable to raw binary in our .sql file",
"]",
"if",
"verbose",
":",
"ca",
".",
"append",
"(",
"\"--verbose\"",
")",
"if",
"with_drop_create_database",
":",
"ca",
".",
"extend",
"(",
"[",
"\"--add-drop-database\"",
",",
"\"--databases\"",
",",
"database",
"]",
")",
"else",
":",
"ca",
".",
"append",
"(",
"database",
")",
"pass",
"return",
"ca"
] | Returns command arguments for a ``mysqldump`` call.
Args:
mysqldump: ``mysqldump`` executable filename
username: user name
password: password
database: database name
verbose: verbose output?
with_drop_create_database: produce commands to ``DROP`` the database
and recreate it?
max_allowed_packet: passed to ``mysqldump``
hide_password: obscure the password (will break the arguments but
provide a safe version to show the user)?
Returns:
list of command-line arguments | [
"Returns",
"command",
"arguments",
"for",
"a",
"mysqldump",
"call",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/tools/backup_mysql_database.py#L46-L90 |
RudolfCardinal/pythonlib | cardinal_pythonlib/tools/backup_mysql_database.py | main | def main() -> None:
"""
Command-line processor. See ``--help`` for details.
"""
main_only_quicksetup_rootlogger()
wdcd_suffix = "_with_drop_create_database"
timeformat = "%Y%m%dT%H%M%S"
parser = argparse.ArgumentParser(
description="""
Back up a specific MySQL database. The resulting filename has the
format '<DATABASENAME>_<DATETIME><SUFFIX>.sql', where <DATETIME> is of
the ISO-8601 format {timeformat!r} and <SUFFIX> is either blank or
{suffix!r}. A typical filename is therefore 'mydb_20190415T205524.sql'.
""".format(timeformat=timeformat, suffix=wdcd_suffix),
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument(
"databases", nargs="+",
help="Database(s) to back up")
parser.add_argument(
"--max_allowed_packet", default="1GB",
help="Maximum size of buffer")
parser.add_argument(
"--mysqldump", default="mysqldump",
help="mysqldump executable")
parser.add_argument(
"--username", default="root",
help="MySQL user")
parser.add_argument(
"--password",
help="MySQL password (AVOID THIS OPTION IF POSSIBLE; VERY INSECURE; "
"VISIBLE TO OTHER PROCESSES; if you don't use it, you'll be "
"prompted for the password)")
parser.add_argument(
"--with_drop_create_database", action="store_true",
help="Include DROP DATABASE and CREATE DATABASE commands, and append "
"a suffix to the output filename as above")
parser.add_argument(
"--output_dir", type=str,
help="Output directory (if not specified, current directory will be "
"used)")
parser.add_argument(
"--verbose", action="store_true",
help="Verbose output")
args = parser.parse_args()
output_dir = args.output_dir or os.getcwd()
os.chdir(output_dir)
password = args.password or getpass.getpass(
prompt="MySQL password for user {}: ".format(args.username))
output_files = [] # type: List[str]
if args.with_drop_create_database:
log.info("Note that the DROP DATABASE commands will look like they're "
"commented out, but they're not: "
"https://dba.stackexchange.com/questions/59294/")
suffix = wdcd_suffix
else:
suffix = ""
for db in args.databases:
now = datetime.datetime.now().strftime(timeformat)
outfilename = "{db}_{now}{suffix}.sql".format(db=db, now=now,
suffix=suffix)
display_args = cmdargs(
mysqldump=args.mysqldump,
username=args.username,
password=password,
database=db,
verbose=args.verbose,
with_drop_create_database=args.with_drop_create_database,
max_allowed_packet=args.max_allowed_packet,
hide_password=True
)
actual_args = cmdargs(
mysqldump=args.mysqldump,
username=args.username,
password=password,
database=db,
verbose=args.verbose,
with_drop_create_database=args.with_drop_create_database,
max_allowed_packet=args.max_allowed_packet,
hide_password=False
)
log.info("Executing: " + repr(display_args))
log.info("Output file: " + repr(outfilename))
try:
with open(outfilename, "w") as f:
subprocess.check_call(actual_args, stdout=f)
except subprocess.CalledProcessError:
os.remove(outfilename)
log.critical("Failed!")
sys.exit(1)
output_files.append(outfilename)
log.info("Done. See:\n" + "\n".join(" " + x for x in output_files))
if args.with_drop_create_database:
log.info("To restore: mysql -u USER -p < BACKUP.sql")
else:
log.info("To restore: mysql -u USER -p DATABASE < BACKUP.sql") | python | def main() -> None:
"""
Command-line processor. See ``--help`` for details.
"""
main_only_quicksetup_rootlogger()
wdcd_suffix = "_with_drop_create_database"
timeformat = "%Y%m%dT%H%M%S"
parser = argparse.ArgumentParser(
description="""
Back up a specific MySQL database. The resulting filename has the
format '<DATABASENAME>_<DATETIME><SUFFIX>.sql', where <DATETIME> is of
the ISO-8601 format {timeformat!r} and <SUFFIX> is either blank or
{suffix!r}. A typical filename is therefore 'mydb_20190415T205524.sql'.
""".format(timeformat=timeformat, suffix=wdcd_suffix),
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument(
"databases", nargs="+",
help="Database(s) to back up")
parser.add_argument(
"--max_allowed_packet", default="1GB",
help="Maximum size of buffer")
parser.add_argument(
"--mysqldump", default="mysqldump",
help="mysqldump executable")
parser.add_argument(
"--username", default="root",
help="MySQL user")
parser.add_argument(
"--password",
help="MySQL password (AVOID THIS OPTION IF POSSIBLE; VERY INSECURE; "
"VISIBLE TO OTHER PROCESSES; if you don't use it, you'll be "
"prompted for the password)")
parser.add_argument(
"--with_drop_create_database", action="store_true",
help="Include DROP DATABASE and CREATE DATABASE commands, and append "
"a suffix to the output filename as above")
parser.add_argument(
"--output_dir", type=str,
help="Output directory (if not specified, current directory will be "
"used)")
parser.add_argument(
"--verbose", action="store_true",
help="Verbose output")
args = parser.parse_args()
output_dir = args.output_dir or os.getcwd()
os.chdir(output_dir)
password = args.password or getpass.getpass(
prompt="MySQL password for user {}: ".format(args.username))
output_files = [] # type: List[str]
if args.with_drop_create_database:
log.info("Note that the DROP DATABASE commands will look like they're "
"commented out, but they're not: "
"https://dba.stackexchange.com/questions/59294/")
suffix = wdcd_suffix
else:
suffix = ""
for db in args.databases:
now = datetime.datetime.now().strftime(timeformat)
outfilename = "{db}_{now}{suffix}.sql".format(db=db, now=now,
suffix=suffix)
display_args = cmdargs(
mysqldump=args.mysqldump,
username=args.username,
password=password,
database=db,
verbose=args.verbose,
with_drop_create_database=args.with_drop_create_database,
max_allowed_packet=args.max_allowed_packet,
hide_password=True
)
actual_args = cmdargs(
mysqldump=args.mysqldump,
username=args.username,
password=password,
database=db,
verbose=args.verbose,
with_drop_create_database=args.with_drop_create_database,
max_allowed_packet=args.max_allowed_packet,
hide_password=False
)
log.info("Executing: " + repr(display_args))
log.info("Output file: " + repr(outfilename))
try:
with open(outfilename, "w") as f:
subprocess.check_call(actual_args, stdout=f)
except subprocess.CalledProcessError:
os.remove(outfilename)
log.critical("Failed!")
sys.exit(1)
output_files.append(outfilename)
log.info("Done. See:\n" + "\n".join(" " + x for x in output_files))
if args.with_drop_create_database:
log.info("To restore: mysql -u USER -p < BACKUP.sql")
else:
log.info("To restore: mysql -u USER -p DATABASE < BACKUP.sql") | [
"def",
"main",
"(",
")",
"->",
"None",
":",
"main_only_quicksetup_rootlogger",
"(",
")",
"wdcd_suffix",
"=",
"\"_with_drop_create_database\"",
"timeformat",
"=",
"\"%Y%m%dT%H%M%S\"",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"\"\"\"\n Back up a specific MySQL database. The resulting filename has the\n format '<DATABASENAME>_<DATETIME><SUFFIX>.sql', where <DATETIME> is of\n the ISO-8601 format {timeformat!r} and <SUFFIX> is either blank or\n {suffix!r}. A typical filename is therefore 'mydb_20190415T205524.sql'.\n \"\"\"",
".",
"format",
"(",
"timeformat",
"=",
"timeformat",
",",
"suffix",
"=",
"wdcd_suffix",
")",
",",
"formatter_class",
"=",
"argparse",
".",
"ArgumentDefaultsHelpFormatter",
")",
"parser",
".",
"add_argument",
"(",
"\"databases\"",
",",
"nargs",
"=",
"\"+\"",
",",
"help",
"=",
"\"Database(s) to back up\"",
")",
"parser",
".",
"add_argument",
"(",
"\"--max_allowed_packet\"",
",",
"default",
"=",
"\"1GB\"",
",",
"help",
"=",
"\"Maximum size of buffer\"",
")",
"parser",
".",
"add_argument",
"(",
"\"--mysqldump\"",
",",
"default",
"=",
"\"mysqldump\"",
",",
"help",
"=",
"\"mysqldump executable\"",
")",
"parser",
".",
"add_argument",
"(",
"\"--username\"",
",",
"default",
"=",
"\"root\"",
",",
"help",
"=",
"\"MySQL user\"",
")",
"parser",
".",
"add_argument",
"(",
"\"--password\"",
",",
"help",
"=",
"\"MySQL password (AVOID THIS OPTION IF POSSIBLE; VERY INSECURE; \"",
"\"VISIBLE TO OTHER PROCESSES; if you don't use it, you'll be \"",
"\"prompted for the password)\"",
")",
"parser",
".",
"add_argument",
"(",
"\"--with_drop_create_database\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Include DROP DATABASE and CREATE DATABASE commands, and append \"",
"\"a suffix to the output filename as above\"",
")",
"parser",
".",
"add_argument",
"(",
"\"--output_dir\"",
",",
"type",
"=",
"str",
",",
"help",
"=",
"\"Output directory (if not specified, current directory will be \"",
"\"used)\"",
")",
"parser",
".",
"add_argument",
"(",
"\"--verbose\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Verbose output\"",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"output_dir",
"=",
"args",
".",
"output_dir",
"or",
"os",
".",
"getcwd",
"(",
")",
"os",
".",
"chdir",
"(",
"output_dir",
")",
"password",
"=",
"args",
".",
"password",
"or",
"getpass",
".",
"getpass",
"(",
"prompt",
"=",
"\"MySQL password for user {}: \"",
".",
"format",
"(",
"args",
".",
"username",
")",
")",
"output_files",
"=",
"[",
"]",
"# type: List[str]",
"if",
"args",
".",
"with_drop_create_database",
":",
"log",
".",
"info",
"(",
"\"Note that the DROP DATABASE commands will look like they're \"",
"\"commented out, but they're not: \"",
"\"https://dba.stackexchange.com/questions/59294/\"",
")",
"suffix",
"=",
"wdcd_suffix",
"else",
":",
"suffix",
"=",
"\"\"",
"for",
"db",
"in",
"args",
".",
"databases",
":",
"now",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
".",
"strftime",
"(",
"timeformat",
")",
"outfilename",
"=",
"\"{db}_{now}{suffix}.sql\"",
".",
"format",
"(",
"db",
"=",
"db",
",",
"now",
"=",
"now",
",",
"suffix",
"=",
"suffix",
")",
"display_args",
"=",
"cmdargs",
"(",
"mysqldump",
"=",
"args",
".",
"mysqldump",
",",
"username",
"=",
"args",
".",
"username",
",",
"password",
"=",
"password",
",",
"database",
"=",
"db",
",",
"verbose",
"=",
"args",
".",
"verbose",
",",
"with_drop_create_database",
"=",
"args",
".",
"with_drop_create_database",
",",
"max_allowed_packet",
"=",
"args",
".",
"max_allowed_packet",
",",
"hide_password",
"=",
"True",
")",
"actual_args",
"=",
"cmdargs",
"(",
"mysqldump",
"=",
"args",
".",
"mysqldump",
",",
"username",
"=",
"args",
".",
"username",
",",
"password",
"=",
"password",
",",
"database",
"=",
"db",
",",
"verbose",
"=",
"args",
".",
"verbose",
",",
"with_drop_create_database",
"=",
"args",
".",
"with_drop_create_database",
",",
"max_allowed_packet",
"=",
"args",
".",
"max_allowed_packet",
",",
"hide_password",
"=",
"False",
")",
"log",
".",
"info",
"(",
"\"Executing: \"",
"+",
"repr",
"(",
"display_args",
")",
")",
"log",
".",
"info",
"(",
"\"Output file: \"",
"+",
"repr",
"(",
"outfilename",
")",
")",
"try",
":",
"with",
"open",
"(",
"outfilename",
",",
"\"w\"",
")",
"as",
"f",
":",
"subprocess",
".",
"check_call",
"(",
"actual_args",
",",
"stdout",
"=",
"f",
")",
"except",
"subprocess",
".",
"CalledProcessError",
":",
"os",
".",
"remove",
"(",
"outfilename",
")",
"log",
".",
"critical",
"(",
"\"Failed!\"",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"output_files",
".",
"append",
"(",
"outfilename",
")",
"log",
".",
"info",
"(",
"\"Done. See:\\n\"",
"+",
"\"\\n\"",
".",
"join",
"(",
"\" \"",
"+",
"x",
"for",
"x",
"in",
"output_files",
")",
")",
"if",
"args",
".",
"with_drop_create_database",
":",
"log",
".",
"info",
"(",
"\"To restore: mysql -u USER -p < BACKUP.sql\"",
")",
"else",
":",
"log",
".",
"info",
"(",
"\"To restore: mysql -u USER -p DATABASE < BACKUP.sql\"",
")"
] | Command-line processor. See ``--help`` for details. | [
"Command",
"-",
"line",
"processor",
".",
"See",
"--",
"help",
"for",
"details",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/tools/backup_mysql_database.py#L93-L190 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/dialect.py | get_dialect | def get_dialect(mixed: Union[SQLCompiler, Engine, Dialect]) -> Dialect:
"""
Finds the SQLAlchemy dialect in use.
Args:
mixed: an SQLAlchemy :class:`SQLCompiler`, :class:`Engine`, or
:class:`Dialect` object
Returns: the SQLAlchemy :class:`Dialect` being used
"""
if isinstance(mixed, Dialect):
return mixed
elif isinstance(mixed, Engine):
return mixed.dialect
elif isinstance(mixed, SQLCompiler):
return mixed.dialect
else:
raise ValueError("get_dialect: 'mixed' parameter of wrong type") | python | def get_dialect(mixed: Union[SQLCompiler, Engine, Dialect]) -> Dialect:
"""
Finds the SQLAlchemy dialect in use.
Args:
mixed: an SQLAlchemy :class:`SQLCompiler`, :class:`Engine`, or
:class:`Dialect` object
Returns: the SQLAlchemy :class:`Dialect` being used
"""
if isinstance(mixed, Dialect):
return mixed
elif isinstance(mixed, Engine):
return mixed.dialect
elif isinstance(mixed, SQLCompiler):
return mixed.dialect
else:
raise ValueError("get_dialect: 'mixed' parameter of wrong type") | [
"def",
"get_dialect",
"(",
"mixed",
":",
"Union",
"[",
"SQLCompiler",
",",
"Engine",
",",
"Dialect",
"]",
")",
"->",
"Dialect",
":",
"if",
"isinstance",
"(",
"mixed",
",",
"Dialect",
")",
":",
"return",
"mixed",
"elif",
"isinstance",
"(",
"mixed",
",",
"Engine",
")",
":",
"return",
"mixed",
".",
"dialect",
"elif",
"isinstance",
"(",
"mixed",
",",
"SQLCompiler",
")",
":",
"return",
"mixed",
".",
"dialect",
"else",
":",
"raise",
"ValueError",
"(",
"\"get_dialect: 'mixed' parameter of wrong type\"",
")"
] | Finds the SQLAlchemy dialect in use.
Args:
mixed: an SQLAlchemy :class:`SQLCompiler`, :class:`Engine`, or
:class:`Dialect` object
Returns: the SQLAlchemy :class:`Dialect` being used | [
"Finds",
"the",
"SQLAlchemy",
"dialect",
"in",
"use",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/dialect.py#L65-L83 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/dialect.py | get_dialect_name | def get_dialect_name(mixed: Union[SQLCompiler, Engine, Dialect]) -> str:
"""
Finds the name of the SQLAlchemy dialect in use.
Args:
mixed: an SQLAlchemy :class:`SQLCompiler`, :class:`Engine`, or
:class:`Dialect` object
Returns: the SQLAlchemy dialect name being used
"""
dialect = get_dialect(mixed)
# noinspection PyUnresolvedReferences
return dialect.name | python | def get_dialect_name(mixed: Union[SQLCompiler, Engine, Dialect]) -> str:
"""
Finds the name of the SQLAlchemy dialect in use.
Args:
mixed: an SQLAlchemy :class:`SQLCompiler`, :class:`Engine`, or
:class:`Dialect` object
Returns: the SQLAlchemy dialect name being used
"""
dialect = get_dialect(mixed)
# noinspection PyUnresolvedReferences
return dialect.name | [
"def",
"get_dialect_name",
"(",
"mixed",
":",
"Union",
"[",
"SQLCompiler",
",",
"Engine",
",",
"Dialect",
"]",
")",
"->",
"str",
":",
"dialect",
"=",
"get_dialect",
"(",
"mixed",
")",
"# noinspection PyUnresolvedReferences",
"return",
"dialect",
".",
"name"
] | Finds the name of the SQLAlchemy dialect in use.
Args:
mixed: an SQLAlchemy :class:`SQLCompiler`, :class:`Engine`, or
:class:`Dialect` object
Returns: the SQLAlchemy dialect name being used | [
"Finds",
"the",
"name",
"of",
"the",
"SQLAlchemy",
"dialect",
"in",
"use",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/dialect.py#L86-L98 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/dialect.py | get_preparer | def get_preparer(mixed: Union[SQLCompiler, Engine,
Dialect]) -> IdentifierPreparer:
"""
Returns the SQLAlchemy :class:`IdentifierPreparer` in use for the dialect
being used.
Args:
mixed: an SQLAlchemy :class:`SQLCompiler`, :class:`Engine`, or
:class:`Dialect` object
Returns: an :class:`IdentifierPreparer`
"""
dialect = get_dialect(mixed)
# noinspection PyUnresolvedReferences
return dialect.preparer(dialect) | python | def get_preparer(mixed: Union[SQLCompiler, Engine,
Dialect]) -> IdentifierPreparer:
"""
Returns the SQLAlchemy :class:`IdentifierPreparer` in use for the dialect
being used.
Args:
mixed: an SQLAlchemy :class:`SQLCompiler`, :class:`Engine`, or
:class:`Dialect` object
Returns: an :class:`IdentifierPreparer`
"""
dialect = get_dialect(mixed)
# noinspection PyUnresolvedReferences
return dialect.preparer(dialect) | [
"def",
"get_preparer",
"(",
"mixed",
":",
"Union",
"[",
"SQLCompiler",
",",
"Engine",
",",
"Dialect",
"]",
")",
"->",
"IdentifierPreparer",
":",
"dialect",
"=",
"get_dialect",
"(",
"mixed",
")",
"# noinspection PyUnresolvedReferences",
"return",
"dialect",
".",
"preparer",
"(",
"dialect",
")"
] | Returns the SQLAlchemy :class:`IdentifierPreparer` in use for the dialect
being used.
Args:
mixed: an SQLAlchemy :class:`SQLCompiler`, :class:`Engine`, or
:class:`Dialect` object
Returns: an :class:`IdentifierPreparer` | [
"Returns",
"the",
"SQLAlchemy",
":",
"class",
":",
"IdentifierPreparer",
"in",
"use",
"for",
"the",
"dialect",
"being",
"used",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/dialect.py#L101-L116 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/dialect.py | quote_identifier | def quote_identifier(identifier: str,
mixed: Union[SQLCompiler, Engine, Dialect]) -> str:
"""
Converts an SQL identifier to a quoted version, via the SQL dialect in
use.
Args:
identifier: the identifier to be quoted
mixed: an SQLAlchemy :class:`SQLCompiler`, :class:`Engine`, or
:class:`Dialect` object
Returns:
the quoted identifier
"""
# See also http://sqlalchemy-utils.readthedocs.io/en/latest/_modules/sqlalchemy_utils/functions/orm.html # noqa
return get_preparer(mixed).quote(identifier) | python | def quote_identifier(identifier: str,
mixed: Union[SQLCompiler, Engine, Dialect]) -> str:
"""
Converts an SQL identifier to a quoted version, via the SQL dialect in
use.
Args:
identifier: the identifier to be quoted
mixed: an SQLAlchemy :class:`SQLCompiler`, :class:`Engine`, or
:class:`Dialect` object
Returns:
the quoted identifier
"""
# See also http://sqlalchemy-utils.readthedocs.io/en/latest/_modules/sqlalchemy_utils/functions/orm.html # noqa
return get_preparer(mixed).quote(identifier) | [
"def",
"quote_identifier",
"(",
"identifier",
":",
"str",
",",
"mixed",
":",
"Union",
"[",
"SQLCompiler",
",",
"Engine",
",",
"Dialect",
"]",
")",
"->",
"str",
":",
"# See also http://sqlalchemy-utils.readthedocs.io/en/latest/_modules/sqlalchemy_utils/functions/orm.html # noqa",
"return",
"get_preparer",
"(",
"mixed",
")",
".",
"quote",
"(",
"identifier",
")"
] | Converts an SQL identifier to a quoted version, via the SQL dialect in
use.
Args:
identifier: the identifier to be quoted
mixed: an SQLAlchemy :class:`SQLCompiler`, :class:`Engine`, or
:class:`Dialect` object
Returns:
the quoted identifier | [
"Converts",
"an",
"SQL",
"identifier",
"to",
"a",
"quoted",
"version",
"via",
"the",
"SQL",
"dialect",
"in",
"use",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/dialect.py#L119-L135 |
renatahodovan/antlerinator | antlerinator/install.py | install | def install(force=False, lazy=False):
"""
Download the ANTLR v4 tool jar. (Raises :exception:`OSError` if jar
is already available, unless ``lazy`` is ``True``.)
:param bool force: Force download even if local jar already exists.
:param bool lazy: Don't report an error if local jar already exists and
don't try to download it either.
"""
if exists(antlr_jar_path):
if lazy:
return
if not force:
raise OSError(errno.EEXIST, 'file already exists', antlr_jar_path)
tool_url = config['tool_url']
ssl_context = ssl.create_default_context(purpose=ssl.Purpose.CLIENT_AUTH)
with contextlib.closing(urlopen(tool_url, context=ssl_context)) as response:
tool_jar = response.read()
if not isdir(dirname(antlr_jar_path)):
makedirs(dirname(antlr_jar_path))
with open(antlr_jar_path, mode='wb') as tool_file:
tool_file.write(tool_jar) | python | def install(force=False, lazy=False):
"""
Download the ANTLR v4 tool jar. (Raises :exception:`OSError` if jar
is already available, unless ``lazy`` is ``True``.)
:param bool force: Force download even if local jar already exists.
:param bool lazy: Don't report an error if local jar already exists and
don't try to download it either.
"""
if exists(antlr_jar_path):
if lazy:
return
if not force:
raise OSError(errno.EEXIST, 'file already exists', antlr_jar_path)
tool_url = config['tool_url']
ssl_context = ssl.create_default_context(purpose=ssl.Purpose.CLIENT_AUTH)
with contextlib.closing(urlopen(tool_url, context=ssl_context)) as response:
tool_jar = response.read()
if not isdir(dirname(antlr_jar_path)):
makedirs(dirname(antlr_jar_path))
with open(antlr_jar_path, mode='wb') as tool_file:
tool_file.write(tool_jar) | [
"def",
"install",
"(",
"force",
"=",
"False",
",",
"lazy",
"=",
"False",
")",
":",
"if",
"exists",
"(",
"antlr_jar_path",
")",
":",
"if",
"lazy",
":",
"return",
"if",
"not",
"force",
":",
"raise",
"OSError",
"(",
"errno",
".",
"EEXIST",
",",
"'file already exists'",
",",
"antlr_jar_path",
")",
"tool_url",
"=",
"config",
"[",
"'tool_url'",
"]",
"ssl_context",
"=",
"ssl",
".",
"create_default_context",
"(",
"purpose",
"=",
"ssl",
".",
"Purpose",
".",
"CLIENT_AUTH",
")",
"with",
"contextlib",
".",
"closing",
"(",
"urlopen",
"(",
"tool_url",
",",
"context",
"=",
"ssl_context",
")",
")",
"as",
"response",
":",
"tool_jar",
"=",
"response",
".",
"read",
"(",
")",
"if",
"not",
"isdir",
"(",
"dirname",
"(",
"antlr_jar_path",
")",
")",
":",
"makedirs",
"(",
"dirname",
"(",
"antlr_jar_path",
")",
")",
"with",
"open",
"(",
"antlr_jar_path",
",",
"mode",
"=",
"'wb'",
")",
"as",
"tool_file",
":",
"tool_file",
".",
"write",
"(",
"tool_jar",
")"
] | Download the ANTLR v4 tool jar. (Raises :exception:`OSError` if jar
is already available, unless ``lazy`` is ``True``.)
:param bool force: Force download even if local jar already exists.
:param bool lazy: Don't report an error if local jar already exists and
don't try to download it either. | [
"Download",
"the",
"ANTLR",
"v4",
"tool",
"jar",
".",
"(",
"Raises",
":",
"exception",
":",
"OSError",
"if",
"jar",
"is",
"already",
"available",
"unless",
"lazy",
"is",
"True",
".",
")"
] | train | https://github.com/renatahodovan/antlerinator/blob/02b165d758014bc064991e5dbc05f4b39f2bb5c9/antlerinator/install.py#L29-L54 |
renatahodovan/antlerinator | antlerinator/install.py | execute | def execute():
"""
Entry point of the install helper tool to ease the download of the right
version of the ANTLR v4 tool jar.
"""
arg_parser = ArgumentParser(description='Install helper tool to download the right version of the ANTLR v4 tool jar.')
arg_parser.add_argument('--version', action='version', version='%(prog)s {version}'.format(version=__version__))
mode_group = arg_parser.add_mutually_exclusive_group()
mode_group.add_argument('-f', '--force', action='store_true', default=False,
help='force download even if local antlr4.jar already exists')
mode_group.add_argument('-l', '--lazy', action='store_true', default=False,
help='don\'t report an error if local antlr4.jar already exists and don\'t try to download it either')
args = arg_parser.parse_args()
install(force=args.force, lazy=args.lazy) | python | def execute():
"""
Entry point of the install helper tool to ease the download of the right
version of the ANTLR v4 tool jar.
"""
arg_parser = ArgumentParser(description='Install helper tool to download the right version of the ANTLR v4 tool jar.')
arg_parser.add_argument('--version', action='version', version='%(prog)s {version}'.format(version=__version__))
mode_group = arg_parser.add_mutually_exclusive_group()
mode_group.add_argument('-f', '--force', action='store_true', default=False,
help='force download even if local antlr4.jar already exists')
mode_group.add_argument('-l', '--lazy', action='store_true', default=False,
help='don\'t report an error if local antlr4.jar already exists and don\'t try to download it either')
args = arg_parser.parse_args()
install(force=args.force, lazy=args.lazy) | [
"def",
"execute",
"(",
")",
":",
"arg_parser",
"=",
"ArgumentParser",
"(",
"description",
"=",
"'Install helper tool to download the right version of the ANTLR v4 tool jar.'",
")",
"arg_parser",
".",
"add_argument",
"(",
"'--version'",
",",
"action",
"=",
"'version'",
",",
"version",
"=",
"'%(prog)s {version}'",
".",
"format",
"(",
"version",
"=",
"__version__",
")",
")",
"mode_group",
"=",
"arg_parser",
".",
"add_mutually_exclusive_group",
"(",
")",
"mode_group",
".",
"add_argument",
"(",
"'-f'",
",",
"'--force'",
",",
"action",
"=",
"'store_true'",
",",
"default",
"=",
"False",
",",
"help",
"=",
"'force download even if local antlr4.jar already exists'",
")",
"mode_group",
".",
"add_argument",
"(",
"'-l'",
",",
"'--lazy'",
",",
"action",
"=",
"'store_true'",
",",
"default",
"=",
"False",
",",
"help",
"=",
"'don\\'t report an error if local antlr4.jar already exists and don\\'t try to download it either'",
")",
"args",
"=",
"arg_parser",
".",
"parse_args",
"(",
")",
"install",
"(",
"force",
"=",
"args",
".",
"force",
",",
"lazy",
"=",
"args",
".",
"lazy",
")"
] | Entry point of the install helper tool to ease the download of the right
version of the ANTLR v4 tool jar. | [
"Entry",
"point",
"of",
"the",
"install",
"helper",
"tool",
"to",
"ease",
"the",
"download",
"of",
"the",
"right",
"version",
"of",
"the",
"ANTLR",
"v4",
"tool",
"jar",
"."
] | train | https://github.com/renatahodovan/antlerinator/blob/02b165d758014bc064991e5dbc05f4b39f2bb5c9/antlerinator/install.py#L57-L75 |
RudolfCardinal/pythonlib | cardinal_pythonlib/tsv.py | tsv_escape | def tsv_escape(x: Any) -> str:
"""
Escape data for tab-separated value (TSV) format.
"""
if x is None:
return ""
x = str(x)
return x.replace("\t", "\\t").replace("\n", "\\n") | python | def tsv_escape(x: Any) -> str:
"""
Escape data for tab-separated value (TSV) format.
"""
if x is None:
return ""
x = str(x)
return x.replace("\t", "\\t").replace("\n", "\\n") | [
"def",
"tsv_escape",
"(",
"x",
":",
"Any",
")",
"->",
"str",
":",
"if",
"x",
"is",
"None",
":",
"return",
"\"\"",
"x",
"=",
"str",
"(",
"x",
")",
"return",
"x",
".",
"replace",
"(",
"\"\\t\"",
",",
"\"\\\\t\"",
")",
".",
"replace",
"(",
"\"\\n\"",
",",
"\"\\\\n\"",
")"
] | Escape data for tab-separated value (TSV) format. | [
"Escape",
"data",
"for",
"tab",
"-",
"separated",
"value",
"(",
"TSV",
")",
"format",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/tsv.py#L38-L45 |
RudolfCardinal/pythonlib | cardinal_pythonlib/tsv.py | make_tsv_row | def make_tsv_row(values: List[Any]) -> str:
"""
From a list of values, make a TSV line.
"""
return "\t".join([tsv_escape(x) for x in values]) + "\n" | python | def make_tsv_row(values: List[Any]) -> str:
"""
From a list of values, make a TSV line.
"""
return "\t".join([tsv_escape(x) for x in values]) + "\n" | [
"def",
"make_tsv_row",
"(",
"values",
":",
"List",
"[",
"Any",
"]",
")",
"->",
"str",
":",
"return",
"\"\\t\"",
".",
"join",
"(",
"[",
"tsv_escape",
"(",
"x",
")",
"for",
"x",
"in",
"values",
"]",
")",
"+",
"\"\\n\""
] | From a list of values, make a TSV line. | [
"From",
"a",
"list",
"of",
"values",
"make",
"a",
"TSV",
"line",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/tsv.py#L48-L52 |
RudolfCardinal/pythonlib | cardinal_pythonlib/tsv.py | dictlist_to_tsv | def dictlist_to_tsv(dictlist: List[Dict[str, Any]]) -> str:
"""
From a consistent list of dictionaries mapping fieldnames to values,
make a TSV file.
"""
if not dictlist:
return ""
fieldnames = dictlist[0].keys()
tsv = "\t".join([tsv_escape(f) for f in fieldnames]) + "\n"
for d in dictlist:
tsv += "\t".join([tsv_escape(v) for v in d.values()]) + "\n"
return tsv | python | def dictlist_to_tsv(dictlist: List[Dict[str, Any]]) -> str:
"""
From a consistent list of dictionaries mapping fieldnames to values,
make a TSV file.
"""
if not dictlist:
return ""
fieldnames = dictlist[0].keys()
tsv = "\t".join([tsv_escape(f) for f in fieldnames]) + "\n"
for d in dictlist:
tsv += "\t".join([tsv_escape(v) for v in d.values()]) + "\n"
return tsv | [
"def",
"dictlist_to_tsv",
"(",
"dictlist",
":",
"List",
"[",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
")",
"->",
"str",
":",
"if",
"not",
"dictlist",
":",
"return",
"\"\"",
"fieldnames",
"=",
"dictlist",
"[",
"0",
"]",
".",
"keys",
"(",
")",
"tsv",
"=",
"\"\\t\"",
".",
"join",
"(",
"[",
"tsv_escape",
"(",
"f",
")",
"for",
"f",
"in",
"fieldnames",
"]",
")",
"+",
"\"\\n\"",
"for",
"d",
"in",
"dictlist",
":",
"tsv",
"+=",
"\"\\t\"",
".",
"join",
"(",
"[",
"tsv_escape",
"(",
"v",
")",
"for",
"v",
"in",
"d",
".",
"values",
"(",
")",
"]",
")",
"+",
"\"\\n\"",
"return",
"tsv"
] | From a consistent list of dictionaries mapping fieldnames to values,
make a TSV file. | [
"From",
"a",
"consistent",
"list",
"of",
"dictionaries",
"mapping",
"fieldnames",
"to",
"values",
"make",
"a",
"TSV",
"file",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/tsv.py#L55-L66 |
RudolfCardinal/pythonlib | cardinal_pythonlib/tsv.py | tsv_pairs_to_dict | def tsv_pairs_to_dict(line: str, key_lower: bool = True) -> Dict[str, str]:
r"""
Converts a TSV line into sequential key/value pairs as a dictionary.
For example,
.. code-block:: none
field1\tvalue1\tfield2\tvalue2
becomes
.. code-block:: none
{"field1": "value1", "field2": "value2"}
Args:
line: the line
key_lower: should the keys be forced to lower case?
"""
items = line.split("\t")
d = {} # type: Dict[str, str]
for chunk in chunks(items, 2):
if len(chunk) < 2:
log.warning("Bad chunk, not of length 2: {!r}", chunk)
continue
key = chunk[0]
value = unescape_tabs_newlines(chunk[1])
if key_lower:
key = key.lower()
d[key] = value
return d | python | def tsv_pairs_to_dict(line: str, key_lower: bool = True) -> Dict[str, str]:
r"""
Converts a TSV line into sequential key/value pairs as a dictionary.
For example,
.. code-block:: none
field1\tvalue1\tfield2\tvalue2
becomes
.. code-block:: none
{"field1": "value1", "field2": "value2"}
Args:
line: the line
key_lower: should the keys be forced to lower case?
"""
items = line.split("\t")
d = {} # type: Dict[str, str]
for chunk in chunks(items, 2):
if len(chunk) < 2:
log.warning("Bad chunk, not of length 2: {!r}", chunk)
continue
key = chunk[0]
value = unescape_tabs_newlines(chunk[1])
if key_lower:
key = key.lower()
d[key] = value
return d | [
"def",
"tsv_pairs_to_dict",
"(",
"line",
":",
"str",
",",
"key_lower",
":",
"bool",
"=",
"True",
")",
"->",
"Dict",
"[",
"str",
",",
"str",
"]",
":",
"items",
"=",
"line",
".",
"split",
"(",
"\"\\t\"",
")",
"d",
"=",
"{",
"}",
"# type: Dict[str, str]",
"for",
"chunk",
"in",
"chunks",
"(",
"items",
",",
"2",
")",
":",
"if",
"len",
"(",
"chunk",
")",
"<",
"2",
":",
"log",
".",
"warning",
"(",
"\"Bad chunk, not of length 2: {!r}\"",
",",
"chunk",
")",
"continue",
"key",
"=",
"chunk",
"[",
"0",
"]",
"value",
"=",
"unescape_tabs_newlines",
"(",
"chunk",
"[",
"1",
"]",
")",
"if",
"key_lower",
":",
"key",
"=",
"key",
".",
"lower",
"(",
")",
"d",
"[",
"key",
"]",
"=",
"value",
"return",
"d"
] | r"""
Converts a TSV line into sequential key/value pairs as a dictionary.
For example,
.. code-block:: none
field1\tvalue1\tfield2\tvalue2
becomes
.. code-block:: none
{"field1": "value1", "field2": "value2"}
Args:
line: the line
key_lower: should the keys be forced to lower case? | [
"r",
"Converts",
"a",
"TSV",
"line",
"into",
"sequential",
"key",
"/",
"value",
"pairs",
"as",
"a",
"dictionary",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/tsv.py#L69-L101 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.