code
stringlengths 26
870k
| docstring
stringlengths 1
65.6k
| func_name
stringlengths 1
194
| language
stringclasses 1
value | repo
stringlengths 8
68
| path
stringlengths 5
194
| url
stringlengths 46
254
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
def default_config():
"""Return the default config for reflow tests."""
return FluffConfig(overrides={"dialect": "ansi"}) | Return the default config for reflow tests. | default_config | python | sqlfluff/sqlfluff | test/utils/reflow/conftest.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/utils/reflow/conftest.py | MIT |
def parse_ansi_string(sql, config):
"""Parse an ansi sql string for testing."""
linter = Linter(config=config)
return linter.parse_string(sql).tree | Parse an ansi sql string for testing. | parse_ansi_string | python | sqlfluff/sqlfluff | test/utils/reflow/rebreak_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/utils/reflow/rebreak_test.py | MIT |
def test_reflow__sequence_rebreak_root(raw_sql_in, raw_sql_out, default_config, caplog):
"""Test the ReflowSequence.rebreak() method directly.
Focused around a whole segment.
"""
root = parse_ansi_string(raw_sql_in, default_config)
print(root.stringify())
seq = ReflowSequence.from_root(root, config=default_config)
for idx, elem in enumerate(seq.elements):
print(idx, elem)
with caplog.at_level(logging.DEBUG, logger="sqlfluff.rules.reflow"):
new_seq = seq.rebreak()
print(new_seq.get_fixes())
assert new_seq.get_raw() == raw_sql_out | Test the ReflowSequence.rebreak() method directly.
Focused around a whole segment. | test_reflow__sequence_rebreak_root | python | sqlfluff/sqlfluff | test/utils/reflow/rebreak_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/utils/reflow/rebreak_test.py | MIT |
def test_reflow__sequence_rebreak_target(
raw_sql_in, target_idx, seq_sql_in, seq_sql_out, default_config, caplog
):
"""Test the ReflowSequence.rebreak() method directly.
Focused around a target segment. This intentionally
stretches some of the span logic.
"""
root = parse_ansi_string(raw_sql_in, default_config)
print(root.stringify())
target = root.raw_segments[target_idx]
print("Target: ", target)
seq = ReflowSequence.from_around_target(target, root, config=default_config)
for idx, elem in enumerate(seq.elements):
print(idx, elem)
assert seq.get_raw() == seq_sql_in
with caplog.at_level(logging.DEBUG, logger="sqlfluff.rules.reflow"):
new_seq = seq.rebreak()
print(new_seq.get_fixes())
assert new_seq.get_raw() == seq_sql_out | Test the ReflowSequence.rebreak() method directly.
Focused around a target segment. This intentionally
stretches some of the span logic. | test_reflow__sequence_rebreak_target | python | sqlfluff/sqlfluff | test/utils/reflow/rebreak_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/utils/reflow/rebreak_test.py | MIT |
def parse_ansi_string(sql, config):
"""Parse an ansi sql string for testing."""
linter = Linter(config=config)
return linter.parse_string(sql).tree | Parse an ansi sql string for testing. | parse_ansi_string | python | sqlfluff/sqlfluff | test/utils/reflow/respace_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/utils/reflow/respace_test.py | MIT |
def test_reflow__sequence_respace(
raw_sql_in, kwargs, raw_sql_out, default_config, caplog
):
"""Test the ReflowSequence.respace() method directly."""
root = parse_ansi_string(raw_sql_in, default_config)
seq = ReflowSequence.from_root(root, config=default_config)
with caplog.at_level(logging.DEBUG, logger="sqlfluff.rules.reflow"):
new_seq = seq.respace(**kwargs)
assert new_seq.get_raw() == raw_sql_out | Test the ReflowSequence.respace() method directly. | test_reflow__sequence_respace | python | sqlfluff/sqlfluff | test/utils/reflow/respace_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/utils/reflow/respace_test.py | MIT |
def test_reflow__point_respace_point(
raw_sql_in, point_idx, kwargs, raw_point_sql_out, fixes_out, default_config, caplog
):
"""Test the ReflowPoint.respace_point() method directly.
NOTE: This doesn't check any pre-existing fixes.
That should be a separate more specific test.
"""
root = parse_ansi_string(raw_sql_in, default_config)
seq = ReflowSequence.from_root(root, config=default_config)
pnt = seq.elements[point_idx]
assert isinstance(pnt, ReflowPoint)
with caplog.at_level(logging.DEBUG, logger="sqlfluff.rules.reflow"):
results, new_pnt = pnt.respace_point(
prev_block=seq.elements[point_idx - 1],
next_block=seq.elements[point_idx + 1],
root_segment=root,
lint_results=[],
**kwargs,
)
assert new_pnt.raw == raw_point_sql_out
# NOTE: We use set comparison, because ordering isn't important for fixes.
assert {
(fix.edit_type, fix.anchor.raw) for fix in fixes_from_results(results)
} == fixes_out | Test the ReflowPoint.respace_point() method directly.
NOTE: This doesn't check any pre-existing fixes.
That should be a separate more specific test. | test_reflow__point_respace_point | python | sqlfluff/sqlfluff | test/utils/reflow/respace_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/utils/reflow/respace_test.py | MIT |
def parse_ansi_string(sql, config):
"""Parse an ansi sql string for testing."""
linter = Linter(config=config)
return linter.parse_string(sql).tree | Parse an ansi sql string for testing. | parse_ansi_string | python | sqlfluff/sqlfluff | test/utils/reflow/sequence_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/utils/reflow/sequence_test.py | MIT |
def assert_reflow_structure(sequence, StartClass, raw_elems):
"""Assert a ReflowSequence has the defined structure."""
assert [
[seg.raw for seg in elem.segments] for elem in sequence.elements
] == raw_elems
# We can assert all the classes just by knowing which we should start with
assert all(type(elem) is StartClass for elem in sequence.elements[::2])
OtherClass = ReflowBlock if StartClass is ReflowPoint else ReflowPoint
assert all(type(elem) is OtherClass for elem in sequence.elements[1::2]) | Assert a ReflowSequence has the defined structure. | assert_reflow_structure | python | sqlfluff/sqlfluff | test/utils/reflow/sequence_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/utils/reflow/sequence_test.py | MIT |
def test_reflow_sequence_from_segments(
raw_sql, StartClass, raw_elems, default_config, caplog
):
"""Test direct sequence construction from segments."""
root = parse_ansi_string(raw_sql, default_config)
with caplog.at_level(logging.DEBUG, logger="sqlfluff.rules.reflow"):
result = ReflowSequence.from_raw_segments(
root.raw_segments, root, config=default_config
)
assert_reflow_structure(result, StartClass, raw_elems) | Test direct sequence construction from segments. | test_reflow_sequence_from_segments | python | sqlfluff/sqlfluff | test/utils/reflow/sequence_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/utils/reflow/sequence_test.py | MIT |
def test_reflow_sequence_from_around_target(
raw_sql,
sides,
target_idx,
target_raw,
StartClass,
raw_elems,
default_config,
caplog,
):
"""Test direct sequence construction from a target."""
root = parse_ansi_string(raw_sql, default_config)
print("Raw Segments:", root.raw_segments)
target = root.raw_segments[target_idx]
# Check we're aiming at the right place
assert target.raw == target_raw
with caplog.at_level(logging.DEBUG, logger="sqlfluff.rules.reflow"):
result = ReflowSequence.from_around_target(
target, root, config=default_config, sides=sides
)
assert_reflow_structure(result, StartClass, raw_elems) | Test direct sequence construction from a target. | test_reflow_sequence_from_around_target | python | sqlfluff/sqlfluff | test/utils/reflow/sequence_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/utils/reflow/sequence_test.py | MIT |
def test_reflow_sequence_from_around_target_non_raw(default_config, caplog):
"""Test direct sequence construction from a target.
This time we use a target which isn't a RawSegment.
"""
sql = " SELECT 1 "
root = parse_ansi_string(sql, default_config)
# We should have a statement as a first level child.
statement = root.segments[1]
assert statement.is_type("statement")
assert statement.raw == "SELECT 1"
with caplog.at_level(logging.DEBUG, logger="sqlfluff.rules.reflow"):
result = ReflowSequence.from_around_target(
statement, root, config=default_config
)
# We should start with a point, because we hit the start of the file.
# It should also hit the end of the file and effectively cover all
# the raw segments of the file.
assert_reflow_structure(
result,
ReflowPoint,
[
[" "],
["SELECT"],
["", " "],
["1"],
# dedent - ws
["", " "],
# end of file
[""],
],
) | Test direct sequence construction from a target.
This time we use a target which isn't a RawSegment. | test_reflow_sequence_from_around_target_non_raw | python | sqlfluff/sqlfluff | test/utils/reflow/sequence_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/utils/reflow/sequence_test.py | MIT |
def test_reflow_sequence_respace_filter(
raw_sql, filter, delete_indices, edit_indices, default_config, caplog
):
"""Test iteration of trailing whitespace fixes."""
root = parse_ansi_string(raw_sql, default_config)
with caplog.at_level(logging.DEBUG, logger="sqlfluff.rules.reflow"):
sequence = ReflowSequence.from_root(root, config=default_config)
fixes = sequence.respace(filter=filter).get_fixes()
# assert deletes
assert [fix for fix in fixes if fix.edit_type == "delete"] == [
LintFix("delete", root.raw_segments[idx]) for idx in delete_indices
]
# assert edits (with slightly less detail)
assert [
root.raw_segments.index(fix.anchor)
for fix in fixes
if fix.edit_type == "replace"
] == edit_indices | Test iteration of trailing whitespace fixes. | test_reflow_sequence_respace_filter | python | sqlfluff/sqlfluff | test/utils/reflow/sequence_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/utils/reflow/sequence_test.py | MIT |
def parse_ansi_string(sql, config):
"""Parse an ansi sql string for testing."""
linter = Linter(config=config)
return linter.parse_string(sql).tree | Parse an ansi sql string for testing. | parse_ansi_string | python | sqlfluff/sqlfluff | test/utils/reflow/depthmap_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/utils/reflow/depthmap_test.py | MIT |
def test_reflow_depthmap_from_parent(default_config):
"""Test map construction from a root segment."""
sql = "SELECT 1"
root = parse_ansi_string(sql, default_config)
dm = DepthMap.from_parent(root)
# We use UUIDS in the depth map so we can't assert their value.
# What we can do is use them.
# Check that we get the right depths.
assert [dm.depth_info[seg.uuid].stack_depth for seg in root.raw_segments] == [
4,
4,
4,
5,
4,
1,
]
# Check they all share the same first three hash and
# class type elements (except the end of file marker at the end).
# These should be the file, statement and select statement.
expected = ({"file", "base"}, {"statement", "base"}, {"select_statement", "base"})
assert all(
dm.depth_info[seg.uuid].stack_class_types[:3] == expected
for seg in root.raw_segments[:-1]
)
first_hashes = dm.depth_info[root.raw_segments[0].uuid].stack_hashes[:3]
assert all(
dm.depth_info[seg.uuid].stack_hashes[:3] == first_hashes
for seg in root.raw_segments[:-1]
)
# While we're here, test the DepthInfo.common_with method
select_keyword_di = dm.depth_info[root.raw_segments[0].uuid]
numeric_one_di = dm.depth_info[root.raw_segments[3].uuid]
assert len(select_keyword_di.common_with(numeric_one_di)) == 4 | Test map construction from a root segment. | test_reflow_depthmap_from_parent | python | sqlfluff/sqlfluff | test/utils/reflow/depthmap_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/utils/reflow/depthmap_test.py | MIT |
def test_reflow_depthmap_from_raws_and_root(default_config):
"""Test that the indirect route is equivalent to the direct route."""
sql = "SELECT 1"
root = parse_ansi_string(sql, default_config)
# Direct route
dm_direct = DepthMap.from_parent(root)
# Indirect route.
dm_indirect = DepthMap.from_raws_and_root(root.raw_segments, root)
# The depth info dict depends on the sequence so we only need
# to check those are equal.
assert dm_direct.depth_info == dm_indirect.depth_info | Test that the indirect route is equivalent to the direct route. | test_reflow_depthmap_from_raws_and_root | python | sqlfluff/sqlfluff | test/utils/reflow/depthmap_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/utils/reflow/depthmap_test.py | MIT |
def test_reflow_depthmap_order_by(default_config):
"""Test depth mapping of an order by clause."""
sql = "SELECT * FROM foo ORDER BY bar DESC\n"
root = parse_ansi_string(sql, default_config)
# Get the `ORDER` and `DESC` segments.
order_seg = None
desc_seg = None
for raw in root.raw_segments:
if raw.raw_upper == "ORDER":
order_seg = raw
elif raw.raw_upper == "DESC":
desc_seg = raw
# Make sure we find them
assert order_seg
assert desc_seg
# Generate a depth map
depth_map = DepthMap.from_parent(root)
# Check their depth info
order_seg_di = depth_map.get_depth_info(order_seg)
desc_seg_di = depth_map.get_depth_info(desc_seg)
# Make sure they both contain an order by clause.
assert frozenset({"base", "orderby_clause"}) in order_seg_di.stack_class_types
assert frozenset({"base", "orderby_clause"}) in desc_seg_di.stack_class_types
# Get the ID of one and make sure it's in the other
order_by_hash = order_seg_di.stack_hashes[
order_seg_di.stack_class_types.index(frozenset({"base", "orderby_clause"}))
]
assert order_by_hash in order_seg_di.stack_hashes
assert order_by_hash in desc_seg_di.stack_hashes
# Get the position information
order_stack_pos = order_seg_di.stack_positions[order_by_hash]
desc_stack_pos = desc_seg_di.stack_positions[order_by_hash]
# Make sure the position information is correct
print(order_stack_pos)
print(desc_stack_pos)
assert order_stack_pos == StackPosition(idx=0, len=9, type="start")
# NOTE: Even though idx 7 is not the end, the _type_ of this location
# is still an "end" because the following elements are non-code.
assert desc_stack_pos == StackPosition(idx=7, len=9, type="end") | Test depth mapping of an order by clause. | test_reflow_depthmap_order_by | python | sqlfluff/sqlfluff | test/utils/reflow/depthmap_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/utils/reflow/depthmap_test.py | MIT |
def parse_ansi_string(sql, config):
"""Parse an ansi sql string for testing."""
linter = Linter(config=config)
return linter.parse_string(sql).tree | Parse an ansi sql string for testing. | parse_ansi_string | python | sqlfluff/sqlfluff | test/utils/reflow/reindent_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/utils/reflow/reindent_test.py | MIT |
def slice_file(
self, raw_str: str, render_func: Callable[[str], str], config=None
) -> Tuple[List[RawFileSlice], List[TemplatedFileSlice], str]:
"""Patch a sliced file returned by the superclass."""
raw_sliced, sliced_file, templated_str = super().slice_file(
raw_str, render_func, config
)
patched_sliced_file = []
for templated_slice in sliced_file:
patched_sliced_file.append(templated_slice)
# Add an EMPTY special_marker slice after every block_start.
if templated_slice.slice_type == "block_start":
# Note that both the source_slice AND the templated_slice are empty.
source_pos = templated_slice.source_slice.stop
templated_pos = templated_slice.templated_slice.stop
patched_sliced_file.append(
TemplatedFileSlice(
"special_marker",
slice(source_pos, source_pos),
slice(templated_pos, templated_pos),
)
)
return raw_sliced, patched_sliced_file, templated_str | Patch a sliced file returned by the superclass. | slice_file | python | sqlfluff/sqlfluff | test/utils/reflow/reindent_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/utils/reflow/reindent_test.py | MIT |
def get_templaters() -> List[Type[RawTemplater]]:
"""Return templaters provided by this test module."""
return [SpecialMarkerInserter] | Return templaters provided by this test module. | get_templaters | python | sqlfluff/sqlfluff | test/utils/reflow/reindent_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/utils/reflow/reindent_test.py | MIT |
def test_reflow__point_indent_to(
raw_sql_in, elem_idx, indent_to, point_sql_out, default_config, caplog
):
"""Test the ReflowPoint.indent_to() method directly."""
root = parse_ansi_string(raw_sql_in, default_config)
print(root.stringify())
seq = ReflowSequence.from_root(root, config=default_config)
elem = seq.elements[elem_idx]
print("Element: ", elem)
with caplog.at_level(logging.DEBUG, logger="sqlfluff.rules.reflow"):
new_fixes, new_point = elem.indent_to(
indent_to,
before=seq.elements[elem_idx - 1].segments[-1],
after=seq.elements[elem_idx + 1].segments[0],
)
print(new_fixes)
assert new_point.raw == point_sql_out | Test the ReflowPoint.indent_to() method directly. | test_reflow__point_indent_to | python | sqlfluff/sqlfluff | test/utils/reflow/reindent_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/utils/reflow/reindent_test.py | MIT |
def test_reflow__point_get_indent(
raw_sql_in, elem_idx, indent_out, default_config, caplog
):
"""Test the ReflowPoint.get_indent() method directly."""
root = parse_ansi_string(raw_sql_in, default_config)
print(root.stringify())
seq = ReflowSequence.from_root(root, config=default_config)
elem = seq.elements[elem_idx]
print("Element: ", elem)
with caplog.at_level(logging.DEBUG, logger="sqlfluff.rules.reflow"):
result = elem.get_indent()
assert result == indent_out | Test the ReflowPoint.get_indent() method directly. | test_reflow__point_get_indent | python | sqlfluff/sqlfluff | test/utils/reflow/reindent_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/utils/reflow/reindent_test.py | MIT |
def test_reflow__deduce_line_indent(
raw_sql_in, target_raw, indent_out, default_config, caplog
):
"""Test the deduce_line_indent() method directly."""
root = parse_ansi_string(raw_sql_in, default_config)
print(root.stringify())
for target_seg in root.raw_segments:
if target_seg.raw == target_raw:
break
else:
raise ValueError("Target Raw Not Found")
print("Target: ", target_seg)
with caplog.at_level(logging.DEBUG, logger="sqlfluff.rules.reflow"):
result = deduce_line_indent(target_seg, root)
assert result == indent_out | Test the deduce_line_indent() method directly. | test_reflow__deduce_line_indent | python | sqlfluff/sqlfluff | test/utils/reflow/reindent_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/utils/reflow/reindent_test.py | MIT |
def test_reflow__crawl_indent_points(raw_sql_in, templater, points_out, caplog):
"""Test _crawl_indent_points directly."""
# Register the mock templater in this module.
purge_plugin_manager()
get_plugin_manager().register(sys.modules[__name__], name="reindent_test")
config = FluffConfig(overrides={"dialect": "ansi", "templater": templater})
root = parse_ansi_string(raw_sql_in, config)
print(root.stringify())
seq = ReflowSequence.from_root(root, config=config)
with caplog.at_level(logging.DEBUG, logger="sqlfluff.rules.reflow"):
points = list(_crawl_indent_points(seq.elements))
assert points == points_out | Test _crawl_indent_points directly. | test_reflow__crawl_indent_points | python | sqlfluff/sqlfluff | test/utils/reflow/reindent_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/utils/reflow/reindent_test.py | MIT |
def test_reflow__lint_indent_points(raw_sql_in, raw_sql_out, default_config, caplog):
"""Test the lint_indent_points() method directly.
Rather than testing directly, for brevity we check
the raw output it produces. This results in a more
compact test.
"""
root = parse_ansi_string(raw_sql_in, default_config)
print(root.stringify())
seq = ReflowSequence.from_root(root, config=default_config)
with caplog.at_level(logging.DEBUG, logger="sqlfluff.rules.reflow"):
elements, results = lint_indent_points(seq.elements, single_indent=" ")
result_raw = "".join(elem.raw for elem in elements)
assert result_raw == raw_sql_out, "Raw Element Check Failed!"
# Now we've checked the elements - check that applying the fixes gets us to
# the same place.
print("Results:", results)
anchor_info = compute_anchor_edit_info(fixes_from_results(results))
fixed_tree, _, _, valid = apply_fixes(
root, default_config.get("dialect_obj"), "TEST", anchor_info
)
assert valid, f"Reparse check failed: {fixed_tree.raw!r}"
assert fixed_tree.raw == raw_sql_out, "Element check passed - but fix check failed!" | Test the lint_indent_points() method directly.
Rather than testing directly, for brevity we check
the raw output it produces. This results in a more
compact test. | test_reflow__lint_indent_points | python | sqlfluff/sqlfluff | test/utils/reflow/reindent_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/utils/reflow/reindent_test.py | MIT |
def test_reflow__desired_indent_units(indent_line, forced_indents, expected_units):
"""Test _IndentLine.desired_indent_units() directly."""
assert indent_line.desired_indent_units(forced_indents) == expected_units | Test _IndentLine.desired_indent_units() directly. | test_reflow__desired_indent_units | python | sqlfluff/sqlfluff | test/utils/reflow/reindent_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/utils/reflow/reindent_test.py | MIT |
def _parse_and_crawl_outer(sql):
"""Helper function for select crawlers.
Given a SQL statement this crawls the SQL and instantiates
a Query on the outer relevant segment.
"""
linter = Linter(dialect="ansi")
parsed = linter.parse_string(sql)
# Make sure it's fully parsable.
assert "unparsable" not in parsed.tree.descendant_type_set
# Create a crawler from the root segment.
query = Query.from_root(parsed.tree, linter.dialect)
# Analyse the segment.
return query, linter | Helper function for select crawlers.
Given a SQL statement this crawls the SQL and instantiates
a Query on the outer relevant segment. | _parse_and_crawl_outer | python | sqlfluff/sqlfluff | test/utils/analysis/query_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/utils/analysis/query_test.py | MIT |
def test_select_crawler_constructor(sql, expected_json):
"""Test Query when created using constructor."""
query, _ = _parse_and_crawl_outer(sql)
assert all(cte.cte_definition_segment is not None for cte in query.ctes.values())
query_dict = query.as_dict()
assert expected_json == query_dict | Test Query when created using constructor. | test_select_crawler_constructor | python | sqlfluff/sqlfluff | test/utils/analysis/query_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/utils/analysis/query_test.py | MIT |
def test_select_crawler_nested():
"""Test invoking with an outer from_expression_segment."""
sql = """
select
a.x, a.y, b.z
from a
join (
with d as (
select x, z from b
)
select * from d
) using (x)
"""
query, linter = _parse_and_crawl_outer(sql)
inner_from = (
query.selectables[0].select_info.table_aliases[1].from_expression_element
)
inner_select = next(inner_from.recursive_crawl("with_compound_statement"))
inner_query = Query.from_segment(inner_select, linter.dialect)
assert inner_query.as_dict() == {
"selectables": [
"select * from d",
],
"ctes": {"D": {"selectables": ["select x, z from b"]}},
"query_type": "WithCompound",
} | Test invoking with an outer from_expression_segment. | test_select_crawler_nested | python | sqlfluff/sqlfluff | test/utils/analysis/query_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/utils/analysis/query_test.py | MIT |
def table(name):
"""Return the parameter with foo_ in front of it."""
return f"foo_{name}" | Return the parameter with foo_ in front of it. | table | python | sqlfluff/sqlfluff | test/fixtures/templater/jinja_r_library_in_macro/libs/foo.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/fixtures/templater/jinja_r_library_in_macro/libs/foo.py | MIT |
def equals(col, val):
"""Return a string that has col = val."""
return f"{col} = {val}" | Return a string that has col = val. | equals | python | sqlfluff/sqlfluff | test/fixtures/templater/jinja_r_library_in_macro/libs/bar.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/fixtures/templater/jinja_r_library_in_macro/libs/bar.py | MIT |
def ds_filter(value: datetime.date | datetime.time | None) -> str | None:
"""Date filter."""
if value is None:
return None
return value.strftime("%Y-%m-%d") | Date filter. | ds_filter | python | sqlfluff/sqlfluff | test/fixtures/templater/jinja_s_filters_in_library/libs/__init__.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/fixtures/templater/jinja_s_filters_in_library/libs/__init__.py | MIT |
def table(name):
"""Return the parameter with foo_ in front of it."""
return f"foo_{name}" | Return the parameter with foo_ in front of it. | table | python | sqlfluff/sqlfluff | test/fixtures/templater/jinja_j_libraries/libs/foo.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/fixtures/templater/jinja_j_libraries/libs/foo.py | MIT |
def equals(col, val):
"""Return a string that has col = val."""
return f"{col} = {val}" | Return a string that has col = val. | equals | python | sqlfluff/sqlfluff | test/fixtures/templater/jinja_j_libraries/libs/bar.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/fixtures/templater/jinja_j_libraries/libs/bar.py | MIT |
def root_equals(col: str, val: str) -> str:
"""Return a string that has col = val."""
return f"{col} = {val}" | Return a string that has col = val. | root_equals | python | sqlfluff/sqlfluff | test/fixtures/templater/jinja_m_libraries_module/libs/__init__.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/fixtures/templater/jinja_m_libraries_module/libs/__init__.py | MIT |
def table(name):
"""Return the parameter with foo_ in front of it."""
return f"foo_{name}" | Return the parameter with foo_ in front of it. | table | python | sqlfluff/sqlfluff | test/fixtures/templater/jinja_m_libraries_module/libs/foo/__init__.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/fixtures/templater/jinja_m_libraries_module/libs/foo/__init__.py | MIT |
def equals(col, val):
"""Return a string that has col = val."""
return f"{col} = {val}" | Return a string that has col = val. | equals | python | sqlfluff/sqlfluff | test/fixtures/templater/jinja_m_libraries_module/libs/foo/bar/baz.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/fixtures/templater/jinja_m_libraries_module/libs/foo/bar/baz.py | MIT |
def time_function(func, name, iterations=20):
"""A basic timing function."""
# Do the timing
time = timeit.timeit(func, number=iterations) / iterations
# Output the result
print(
"{:<35} {:.6}s [{} iterations]".format(
f"Time to {name}:",
time,
iterations,
)
) | A basic timing function. | time_function | python | sqlfluff/sqlfluff | examples/02_timing_api_steps.py | https://github.com/sqlfluff/sqlfluff/blob/master/examples/02_timing_api_steps.py | MIT |
def get_json_segment(
parse_result: Dict[str, Any], segment_type: str
) -> Iterator[Union[str, Dict[str, Any], List[Dict[str, Any]]]]:
"""Recursively search JSON parse result for specified segment type.
Args:
parse_result (Dict[str, Any]): JSON parse result from `sqlfluff.fix`.
segment_type (str): The segment type to search for.
Yields:
Iterator[Union[str, Dict[str, Any], List[Dict[str, Any]]]]:
Retrieves children of specified segment type as either a string for a raw
segment or as JSON or an array of JSON for non-raw segments.
"""
for k, v in parse_result.items():
if k == segment_type:
yield v
elif isinstance(v, dict):
yield from get_json_segment(v, segment_type)
elif isinstance(v, list):
for s in v:
yield from get_json_segment(s, segment_type) | Recursively search JSON parse result for specified segment type.
Args:
parse_result (Dict[str, Any]): JSON parse result from `sqlfluff.fix`.
segment_type (str): The segment type to search for.
Yields:
Iterator[Union[str, Dict[str, Any], List[Dict[str, Any]]]]:
Retrieves children of specified segment type as either a string for a raw
segment or as JSON or an array of JSON for non-raw segments. | get_json_segment | python | sqlfluff/sqlfluff | examples/01_basic_api_usage.py | https://github.com/sqlfluff/sqlfluff/blob/master/examples/01_basic_api_usage.py | MIT |
def add(self, *args, **kwargs):
"""The actual handler of the signal."""
self.heard.append((args, kwargs)) | The actual handler of the signal. | listen_to.add | python | maxcountryman/flask-login | tests/test_login.py | https://github.com/maxcountryman/flask-login/blob/master/tests/test_login.py | MIT |
def assert_heard_one(self, *args, **kwargs):
"""The signal fired once, and with the arguments given"""
if len(self.heard) == 0:
raise AssertionError("No signals were fired")
elif len(self.heard) > 1:
msg = f"{len(self.heard)} signals were fired"
raise AssertionError(msg)
elif self.heard[0] != (args, kwargs):
raise AssertionError(
"One signal was heard, but with incorrect"
f" arguments: Got ({self.heard[0]}) expected"
f" ({args}, {kwargs})"
) | The signal fired once, and with the arguments given | listen_to.assert_heard_one | python | maxcountryman/flask-login | tests/test_login.py | https://github.com/maxcountryman/flask-login/blob/master/tests/test_login.py | MIT |
def assert_heard_none(self, *args, **kwargs):
"""The signal fired no times"""
if len(self.heard) >= 1:
msg = f"{len(self.heard)} signals were fired"
raise AssertionError(msg) | The signal fired no times | listen_to.assert_heard_none | python | maxcountryman/flask-login | tests/test_login.py | https://github.com/maxcountryman/flask-login/blob/master/tests/test_login.py | MIT |
def listen_to(signal):
"""Context Manager that listens to signals and records emissions
Example:
with listen_to(user_logged_in) as listener:
login_user(user)
# Assert that a single emittance of the specific args was seen.
listener.assert_heard_one(app, user=user))
# Of course, you can always just look at the list yourself
self.assertEqual(1, len(listener.heard))
"""
class _SignalsCaught:
def __init__(self):
self.heard = []
def add(self, *args, **kwargs):
"""The actual handler of the signal."""
self.heard.append((args, kwargs))
def assert_heard_one(self, *args, **kwargs):
"""The signal fired once, and with the arguments given"""
if len(self.heard) == 0:
raise AssertionError("No signals were fired")
elif len(self.heard) > 1:
msg = f"{len(self.heard)} signals were fired"
raise AssertionError(msg)
elif self.heard[0] != (args, kwargs):
raise AssertionError(
"One signal was heard, but with incorrect"
f" arguments: Got ({self.heard[0]}) expected"
f" ({args}, {kwargs})"
)
def assert_heard_none(self, *args, **kwargs):
"""The signal fired no times"""
if len(self.heard) >= 1:
msg = f"{len(self.heard)} signals were fired"
raise AssertionError(msg)
results = _SignalsCaught()
signal.connect(results.add)
try:
yield results
finally:
signal.disconnect(results.add) | Context Manager that listens to signals and records emissions
Example:
with listen_to(user_logged_in) as listener:
login_user(user)
# Assert that a single emittance of the specific args was seen.
listener.assert_heard_one(app, user=user))
# Of course, you can always just look at the list yourself
self.assertEqual(1, len(listener.heard)) | listen_to | python | maxcountryman/flask-login | tests/test_login.py | https://github.com/maxcountryman/flask-login/blob/master/tests/test_login.py | MIT |
def encode_cookie(payload, key=None):
"""
This will encode a ``str`` value into a cookie, and sign that cookie
with the app's secret key.
:param payload: The value to encode, as `str`.
:type payload: str
:param key: The key to use when creating the cookie digest. If not
specified, the SECRET_KEY value from app config will be used.
:type key: str
"""
return f"{payload}|{_cookie_digest(payload, key=key)}" | This will encode a ``str`` value into a cookie, and sign that cookie
with the app's secret key.
:param payload: The value to encode, as `str`.
:type payload: str
:param key: The key to use when creating the cookie digest. If not
specified, the SECRET_KEY value from app config will be used.
:type key: str | encode_cookie | python | maxcountryman/flask-login | src/flask_login/utils.py | https://github.com/maxcountryman/flask-login/blob/master/src/flask_login/utils.py | MIT |
def decode_cookie(cookie, key=None):
"""
This decodes a cookie given by `encode_cookie`. If verification of the
cookie fails, ``None`` will be implicitly returned.
:param cookie: An encoded cookie.
:type cookie: str
:param key: The key to use when creating the cookie digest. If not
specified, the SECRET_KEY value from app config will be used.
:type key: str
"""
try:
payload, digest = cookie.rsplit("|", 1)
if hasattr(digest, "decode"):
digest = digest.decode("ascii") # pragma: no cover
except ValueError:
return
if hmac.compare_digest(_cookie_digest(payload, key=key), digest):
return payload | This decodes a cookie given by `encode_cookie`. If verification of the
cookie fails, ``None`` will be implicitly returned.
:param cookie: An encoded cookie.
:type cookie: str
:param key: The key to use when creating the cookie digest. If not
specified, the SECRET_KEY value from app config will be used.
:type key: str | decode_cookie | python | maxcountryman/flask-login | src/flask_login/utils.py | https://github.com/maxcountryman/flask-login/blob/master/src/flask_login/utils.py | MIT |
def make_next_param(login_url, current_url):
"""
Reduces the scheme and host from a given URL so it can be passed to
the given `login` URL more efficiently.
:param login_url: The login URL being redirected to.
:type login_url: str
:param current_url: The URL to reduce.
:type current_url: str
"""
l_url = urlsplit(login_url)
c_url = urlsplit(current_url)
if (not l_url.scheme or l_url.scheme == c_url.scheme) and (
not l_url.netloc or l_url.netloc == c_url.netloc
):
return urlunsplit(("", "", c_url.path, c_url.query, ""))
return current_url | Reduces the scheme and host from a given URL so it can be passed to
the given `login` URL more efficiently.
:param login_url: The login URL being redirected to.
:type login_url: str
:param current_url: The URL to reduce.
:type current_url: str | make_next_param | python | maxcountryman/flask-login | src/flask_login/utils.py | https://github.com/maxcountryman/flask-login/blob/master/src/flask_login/utils.py | MIT |
def expand_login_view(login_view):
"""
Returns the url for the login view, expanding the view name to a url if
needed.
:param login_view: The name of the login view or a URL for the login view.
:type login_view: str
"""
if login_view.startswith(("https://", "http://", "/")):
return login_view
return url_for(login_view) | Returns the url for the login view, expanding the view name to a url if
needed.
:param login_view: The name of the login view or a URL for the login view.
:type login_view: str | expand_login_view | python | maxcountryman/flask-login | src/flask_login/utils.py | https://github.com/maxcountryman/flask-login/blob/master/src/flask_login/utils.py | MIT |
def login_url(login_view, next_url=None, next_field="next"):
"""
Creates a URL for redirecting to a login page. If only `login_view` is
provided, this will just return the URL for it. If `next_url` is provided,
however, this will append a ``next=URL`` parameter to the query string
so that the login view can redirect back to that URL. Flask-Login's default
unauthorized handler uses this function when redirecting to your login url.
To force the host name used, set `FORCE_HOST_FOR_REDIRECTS` to a host. This
prevents from redirecting to external sites if `SERVER_NAME` is not configured.
:param login_view: The name of the login view. (Alternately, the actual
URL to the login view.)
:type login_view: str
:param next_url: The URL to give the login view for redirection.
:type next_url: str
:param next_field: What field to store the next URL in. (It defaults to
``next``.)
:type next_field: str
"""
base = expand_login_view(login_view)
if next_url is None:
return base
parsed_result = urlsplit(base)
md = parse_qs(parsed_result.query, keep_blank_values=True)
md[next_field] = make_next_param(base, next_url)
netloc = current_app.config.get("FORCE_HOST_FOR_REDIRECTS") or parsed_result.netloc
parsed_result = parsed_result._replace(
netloc=netloc, query=urlencode(md, doseq=True)
)
return urlunsplit(parsed_result) | Creates a URL for redirecting to a login page. If only `login_view` is
provided, this will just return the URL for it. If `next_url` is provided,
however, this will append a ``next=URL`` parameter to the query string
so that the login view can redirect back to that URL. Flask-Login's default
unauthorized handler uses this function when redirecting to your login url.
To force the host name used, set `FORCE_HOST_FOR_REDIRECTS` to a host. This
prevents from redirecting to external sites if `SERVER_NAME` is not configured.
:param login_view: The name of the login view. (Alternately, the actual
URL to the login view.)
:type login_view: str
:param next_url: The URL to give the login view for redirection.
:type next_url: str
:param next_field: What field to store the next URL in. (It defaults to
``next``.)
:type next_field: str | login_url | python | maxcountryman/flask-login | src/flask_login/utils.py | https://github.com/maxcountryman/flask-login/blob/master/src/flask_login/utils.py | MIT |
def login_fresh():
"""
This returns ``True`` if the current login is fresh.
"""
return session.get("_fresh", False) | This returns ``True`` if the current login is fresh. | login_fresh | python | maxcountryman/flask-login | src/flask_login/utils.py | https://github.com/maxcountryman/flask-login/blob/master/src/flask_login/utils.py | MIT |
def login_remembered():
"""
This returns ``True`` if the current login is remembered across sessions.
"""
config = current_app.config
cookie_name = config.get("REMEMBER_COOKIE_NAME", COOKIE_NAME)
has_cookie = cookie_name in request.cookies and session.get("_remember") != "clear"
if has_cookie:
cookie = request.cookies[cookie_name]
user_id = decode_cookie(cookie)
return user_id is not None
return False | This returns ``True`` if the current login is remembered across sessions. | login_remembered | python | maxcountryman/flask-login | src/flask_login/utils.py | https://github.com/maxcountryman/flask-login/blob/master/src/flask_login/utils.py | MIT |
def login_user(user, remember=False, duration=None, force=False, fresh=True):
"""
Logs a user in. You should pass the actual user object to this. If the
user's `is_active` property is ``False``, they will not be logged in
unless `force` is ``True``.
This will return ``True`` if the log in attempt succeeds, and ``False`` if
it fails (i.e. because the user is inactive).
:param user: The user object to log in.
:type user: object
:param remember: Whether to remember the user after their session expires.
Defaults to ``False``.
:type remember: bool
:param duration: The amount of time before the remember cookie expires. If
``None`` the value set in the settings is used. Defaults to ``None``.
:type duration: :class:`datetime.timedelta`
:param force: If the user is inactive, setting this to ``True`` will log
them in regardless. Defaults to ``False``.
:type force: bool
:param fresh: setting this to ``False`` will log in the user with a session
marked as not "fresh". Defaults to ``True``.
:type fresh: bool
"""
if not force and not user.is_active:
return False
user_id = getattr(user, current_app.login_manager.id_attribute)()
session["_user_id"] = user_id
session["_fresh"] = fresh
session["_id"] = current_app.login_manager._session_identifier_generator()
if remember:
session["_remember"] = "set"
if duration is not None:
try:
# equal to timedelta.total_seconds() but works with Python 2.6
session["_remember_seconds"] = (
duration.microseconds
+ (duration.seconds + duration.days * 24 * 3600) * 10**6
) / 10.0**6
except AttributeError as e:
raise Exception(
f"duration must be a datetime.timedelta, instead got: {duration}"
) from e
current_app.login_manager._update_request_context_with_user(user)
user_logged_in.send(current_app._get_current_object(), user=_get_user())
return True | Logs a user in. You should pass the actual user object to this. If the
user's `is_active` property is ``False``, they will not be logged in
unless `force` is ``True``.
This will return ``True`` if the log in attempt succeeds, and ``False`` if
it fails (i.e. because the user is inactive).
:param user: The user object to log in.
:type user: object
:param remember: Whether to remember the user after their session expires.
Defaults to ``False``.
:type remember: bool
:param duration: The amount of time before the remember cookie expires. If
``None`` the value set in the settings is used. Defaults to ``None``.
:type duration: :class:`datetime.timedelta`
:param force: If the user is inactive, setting this to ``True`` will log
them in regardless. Defaults to ``False``.
:type force: bool
:param fresh: setting this to ``False`` will log in the user with a session
marked as not "fresh". Defaults to ``True``.
:type fresh: bool | login_user | python | maxcountryman/flask-login | src/flask_login/utils.py | https://github.com/maxcountryman/flask-login/blob/master/src/flask_login/utils.py | MIT |
def logout_user():
"""
Logs a user out. (You do not need to pass the actual user.) This will
also clean up the remember me cookie if it exists.
"""
user = _get_user()
if "_user_id" in session:
session.pop("_user_id")
if "_fresh" in session:
session.pop("_fresh")
if "_id" in session:
session.pop("_id")
cookie_name = current_app.config.get("REMEMBER_COOKIE_NAME", COOKIE_NAME)
if cookie_name in request.cookies:
session["_remember"] = "clear"
if "_remember_seconds" in session:
session.pop("_remember_seconds")
user_logged_out.send(current_app._get_current_object(), user=user)
current_app.login_manager._update_request_context_with_user()
return True | Logs a user out. (You do not need to pass the actual user.) This will
also clean up the remember me cookie if it exists. | logout_user | python | maxcountryman/flask-login | src/flask_login/utils.py | https://github.com/maxcountryman/flask-login/blob/master/src/flask_login/utils.py | MIT |
def confirm_login():
"""
This sets the current session as fresh. Sessions become stale when they
are reloaded from a cookie.
"""
session["_fresh"] = True
session["_id"] = current_app.login_manager._session_identifier_generator()
user_login_confirmed.send(current_app._get_current_object()) | This sets the current session as fresh. Sessions become stale when they
are reloaded from a cookie. | confirm_login | python | maxcountryman/flask-login | src/flask_login/utils.py | https://github.com/maxcountryman/flask-login/blob/master/src/flask_login/utils.py | MIT |
def login_required(func):
"""
If you decorate a view with this, it will ensure that the current user is
logged in and authenticated before calling the actual view. (If they are
not, it calls the :attr:`LoginManager.unauthorized` callback.) For
example::
@app.route('/post')
@login_required
def post():
pass
If there are only certain times you need to require that your user is
logged in, you can do so with::
if not current_user.is_authenticated:
return current_app.login_manager.unauthorized()
...which is essentially the code that this function adds to your views.
.. Note ::
Per `W3 guidelines for CORS preflight requests
<http://www.w3.org/TR/cors/#cross-origin-request-with-preflight-0>`_,
HTTP ``OPTIONS`` requests are exempt from login checks.
:param func: The view function to decorate.
:type func: function
"""
@wraps(func)
def decorated_view(*args, **kwargs):
if request.method in EXEMPT_METHODS:
pass
elif not current_user.is_authenticated:
return current_app.login_manager.unauthorized()
# flask 1.x compatibility
# current_app.ensure_sync is only available in Flask >= 2.0
if callable(getattr(current_app, "ensure_sync", None)):
return current_app.ensure_sync(func)(*args, **kwargs)
return func(*args, **kwargs)
return decorated_view | If you decorate a view with this, it will ensure that the current user is
logged in and authenticated before calling the actual view. (If they are
not, it calls the :attr:`LoginManager.unauthorized` callback.) For
example::
@app.route('/post')
@login_required
def post():
pass
If there are only certain times you need to require that your user is
logged in, you can do so with::
if not current_user.is_authenticated:
return current_app.login_manager.unauthorized()
...which is essentially the code that this function adds to your views.
.. Note ::
Per `W3 guidelines for CORS preflight requests
<http://www.w3.org/TR/cors/#cross-origin-request-with-preflight-0>`_,
HTTP ``OPTIONS`` requests are exempt from login checks.
:param func: The view function to decorate.
:type func: function | login_required | python | maxcountryman/flask-login | src/flask_login/utils.py | https://github.com/maxcountryman/flask-login/blob/master/src/flask_login/utils.py | MIT |
def fresh_login_required(func):
"""
If you decorate a view with this, it will ensure that the current user's
login is fresh - i.e. their session was not restored from a 'remember me'
cookie. Sensitive operations, like changing a password or e-mail, should
be protected with this, to impede the efforts of cookie thieves.
If the user is not authenticated, :meth:`LoginManager.unauthorized` is
called as normal. If they are authenticated, but their session is not
fresh, it will call :meth:`LoginManager.needs_refresh` instead. (In that
case, you will need to provide a :attr:`LoginManager.refresh_view`.)
Behaves identically to the :func:`login_required` decorator with respect
to configuration variables.
.. Note ::
Per `W3 guidelines for CORS preflight requests
<http://www.w3.org/TR/cors/#cross-origin-request-with-preflight-0>`_,
HTTP ``OPTIONS`` requests are exempt from login checks.
:param func: The view function to decorate.
:type func: function
"""
@wraps(func)
def decorated_view(*args, **kwargs):
if request.method in EXEMPT_METHODS:
pass
elif not current_user.is_authenticated:
return current_app.login_manager.unauthorized()
elif not login_fresh():
return current_app.login_manager.needs_refresh()
try:
# current_app.ensure_sync available in Flask >= 2.0
return current_app.ensure_sync(func)(*args, **kwargs)
except AttributeError: # pragma: no cover
return func(*args, **kwargs)
return decorated_view | If you decorate a view with this, it will ensure that the current user's
login is fresh - i.e. their session was not restored from a 'remember me'
cookie. Sensitive operations, like changing a password or e-mail, should
be protected with this, to impede the efforts of cookie thieves.
If the user is not authenticated, :meth:`LoginManager.unauthorized` is
called as normal. If they are authenticated, but their session is not
fresh, it will call :meth:`LoginManager.needs_refresh` instead. (In that
case, you will need to provide a :attr:`LoginManager.refresh_view`.)
Behaves identically to the :func:`login_required` decorator with respect
to configuration variables.
.. Note ::
Per `W3 guidelines for CORS preflight requests
<http://www.w3.org/TR/cors/#cross-origin-request-with-preflight-0>`_,
HTTP ``OPTIONS`` requests are exempt from login checks.
:param func: The view function to decorate.
:type func: function | fresh_login_required | python | maxcountryman/flask-login | src/flask_login/utils.py | https://github.com/maxcountryman/flask-login/blob/master/src/flask_login/utils.py | MIT |
def set_login_view(login_view, blueprint=None):
"""
Sets the login view for the app or blueprint. If a blueprint is passed,
the login view is set for this blueprint on ``blueprint_login_views``.
:param login_view: The user object to log in.
:type login_view: str
:param blueprint: The blueprint which this login view should be set on.
Defaults to ``None``.
:type blueprint: object
"""
num_login_views = len(current_app.login_manager.blueprint_login_views)
if blueprint is not None or num_login_views != 0:
(current_app.login_manager.blueprint_login_views[blueprint.name]) = login_view
if (
current_app.login_manager.login_view is not None
and None not in current_app.login_manager.blueprint_login_views
):
(
current_app.login_manager.blueprint_login_views[None]
) = current_app.login_manager.login_view
current_app.login_manager.login_view = None
else:
current_app.login_manager.login_view = login_view | Sets the login view for the app or blueprint. If a blueprint is passed,
the login view is set for this blueprint on ``blueprint_login_views``.
:param login_view: The user object to log in.
:type login_view: str
:param blueprint: The blueprint which this login view should be set on.
Defaults to ``None``.
:type blueprint: object | set_login_view | python | maxcountryman/flask-login | src/flask_login/utils.py | https://github.com/maxcountryman/flask-login/blob/master/src/flask_login/utils.py | MIT |
def init_app(self, app, add_context_processor=True):
"""
Configures an application. This registers an `after_request` call, and
attaches this `LoginManager` to it as `app.login_manager`.
:param app: The :class:`flask.Flask` object to configure.
:type app: :class:`flask.Flask`
:param add_context_processor: Whether to add a context processor to
the app that adds a `current_user` variable to the template.
Defaults to ``True``.
:type add_context_processor: bool
"""
app.login_manager = self
app.after_request(self._update_remember_cookie)
if add_context_processor:
app.context_processor(_user_context_processor) | Configures an application. This registers an `after_request` call, and
attaches this `LoginManager` to it as `app.login_manager`.
:param app: The :class:`flask.Flask` object to configure.
:type app: :class:`flask.Flask`
:param add_context_processor: Whether to add a context processor to
the app that adds a `current_user` variable to the template.
Defaults to ``True``.
:type add_context_processor: bool | init_app | python | maxcountryman/flask-login | src/flask_login/login_manager.py | https://github.com/maxcountryman/flask-login/blob/master/src/flask_login/login_manager.py | MIT |
def unauthorized(self):
"""
This is called when the user is required to log in. If you register a
callback with :meth:`LoginManager.unauthorized_handler`, then it will
be called. Otherwise, it will take the following actions:
- Flash :attr:`LoginManager.login_message` to the user.
- If the app is using blueprints find the login view for
the current blueprint using `blueprint_login_views`. If the app
is not using blueprints or the login view for the current
blueprint is not specified use the value of `login_view`.
- Redirect the user to the login view. (The page they were
attempting to access will be passed in the ``next`` query
string variable, so you can redirect there if present instead
of the homepage. Alternatively, it will be added to the session
as ``next`` if USE_SESSION_FOR_NEXT is set.)
If :attr:`LoginManager.login_view` is not defined, then it will simply
raise a HTTP 401 (Unauthorized) error instead.
This should be returned from a view or before/after_request function,
otherwise the redirect will have no effect.
"""
user_unauthorized.send(current_app._get_current_object())
if self.unauthorized_callback:
return self.unauthorized_callback()
if request.blueprint in self.blueprint_login_views:
login_view = self.blueprint_login_views[request.blueprint]
else:
login_view = self.login_view
if not login_view:
abort(401)
if self.login_message:
if self.localize_callback is not None:
flash(
self.localize_callback(self.login_message),
category=self.login_message_category,
)
else:
flash(self.login_message, category=self.login_message_category)
config = current_app.config
if config.get("USE_SESSION_FOR_NEXT", USE_SESSION_FOR_NEXT):
login_url = expand_login_view(login_view)
session["_id"] = self._session_identifier_generator()
session["next"] = make_next_param(login_url, request.url)
redirect_url = make_login_url(login_view)
else:
redirect_url = make_login_url(login_view, next_url=request.url)
return redirect(redirect_url) | This is called when the user is required to log in. If you register a
callback with :meth:`LoginManager.unauthorized_handler`, then it will
be called. Otherwise, it will take the following actions:
- Flash :attr:`LoginManager.login_message` to the user.
- If the app is using blueprints find the login view for
the current blueprint using `blueprint_login_views`. If the app
is not using blueprints or the login view for the current
blueprint is not specified use the value of `login_view`.
- Redirect the user to the login view. (The page they were
attempting to access will be passed in the ``next`` query
string variable, so you can redirect there if present instead
of the homepage. Alternatively, it will be added to the session
as ``next`` if USE_SESSION_FOR_NEXT is set.)
If :attr:`LoginManager.login_view` is not defined, then it will simply
raise a HTTP 401 (Unauthorized) error instead.
This should be returned from a view or before/after_request function,
otherwise the redirect will have no effect. | unauthorized | python | maxcountryman/flask-login | src/flask_login/login_manager.py | https://github.com/maxcountryman/flask-login/blob/master/src/flask_login/login_manager.py | MIT |
def user_loader(self, callback):
"""
This sets the callback for reloading a user from the session. The
function you set should take a user ID (a ``str``) and return a
user object, or ``None`` if the user does not exist.
:param callback: The callback for retrieving a user object.
:type callback: callable
"""
self._user_callback = callback
return self.user_callback | This sets the callback for reloading a user from the session. The
function you set should take a user ID (a ``str``) and return a
user object, or ``None`` if the user does not exist.
:param callback: The callback for retrieving a user object.
:type callback: callable | user_loader | python | maxcountryman/flask-login | src/flask_login/login_manager.py | https://github.com/maxcountryman/flask-login/blob/master/src/flask_login/login_manager.py | MIT |
def user_callback(self):
"""Gets the user_loader callback set by user_loader decorator."""
return self._user_callback | Gets the user_loader callback set by user_loader decorator. | user_callback | python | maxcountryman/flask-login | src/flask_login/login_manager.py | https://github.com/maxcountryman/flask-login/blob/master/src/flask_login/login_manager.py | MIT |
def request_loader(self, callback):
"""
This sets the callback for loading a user from a Flask request.
The function you set should take Flask request object and
return a user object, or `None` if the user does not exist.
:param callback: The callback for retrieving a user object.
:type callback: callable
"""
self._request_callback = callback
return self.request_callback | This sets the callback for loading a user from a Flask request.
The function you set should take Flask request object and
return a user object, or `None` if the user does not exist.
:param callback: The callback for retrieving a user object.
:type callback: callable | request_loader | python | maxcountryman/flask-login | src/flask_login/login_manager.py | https://github.com/maxcountryman/flask-login/blob/master/src/flask_login/login_manager.py | MIT |
def request_callback(self):
"""Gets the request_loader callback set by request_loader decorator."""
return self._request_callback | Gets the request_loader callback set by request_loader decorator. | request_callback | python | maxcountryman/flask-login | src/flask_login/login_manager.py | https://github.com/maxcountryman/flask-login/blob/master/src/flask_login/login_manager.py | MIT |
def unauthorized_handler(self, callback):
"""
This will set the callback for the `unauthorized` method, which among
other things is used by `login_required`. It takes no arguments, and
should return a response to be sent to the user instead of their
normal view.
:param callback: The callback for unauthorized users.
:type callback: callable
"""
self.unauthorized_callback = callback
return callback | This will set the callback for the `unauthorized` method, which among
other things is used by `login_required`. It takes no arguments, and
should return a response to be sent to the user instead of their
normal view.
:param callback: The callback for unauthorized users.
:type callback: callable | unauthorized_handler | python | maxcountryman/flask-login | src/flask_login/login_manager.py | https://github.com/maxcountryman/flask-login/blob/master/src/flask_login/login_manager.py | MIT |
def needs_refresh_handler(self, callback):
"""
This will set the callback for the `needs_refresh` method, which among
other things is used by `fresh_login_required`. It takes no arguments,
and should return a response to be sent to the user instead of their
normal view.
:param callback: The callback for unauthorized users.
:type callback: callable
"""
self.needs_refresh_callback = callback
return callback | This will set the callback for the `needs_refresh` method, which among
other things is used by `fresh_login_required`. It takes no arguments,
and should return a response to be sent to the user instead of their
normal view.
:param callback: The callback for unauthorized users.
:type callback: callable | needs_refresh_handler | python | maxcountryman/flask-login | src/flask_login/login_manager.py | https://github.com/maxcountryman/flask-login/blob/master/src/flask_login/login_manager.py | MIT |
def needs_refresh(self):
"""
This is called when the user is logged in, but they need to be
reauthenticated because their session is stale. If you register a
callback with `needs_refresh_handler`, then it will be called.
Otherwise, it will take the following actions:
- Flash :attr:`LoginManager.needs_refresh_message` to the user.
- Redirect the user to :attr:`LoginManager.refresh_view`. (The page
they were attempting to access will be passed in the ``next``
query string variable, so you can redirect there if present
instead of the homepage.)
If :attr:`LoginManager.refresh_view` is not defined, then it will
simply raise a HTTP 401 (Unauthorized) error instead.
This should be returned from a view or before/after_request function,
otherwise the redirect will have no effect.
"""
user_needs_refresh.send(current_app._get_current_object())
if self.needs_refresh_callback:
return self.needs_refresh_callback()
if not self.refresh_view:
abort(401)
if self.needs_refresh_message:
if self.localize_callback is not None:
flash(
self.localize_callback(self.needs_refresh_message),
category=self.needs_refresh_message_category,
)
else:
flash(
self.needs_refresh_message,
category=self.needs_refresh_message_category,
)
config = current_app.config
if config.get("USE_SESSION_FOR_NEXT", USE_SESSION_FOR_NEXT):
login_url = expand_login_view(self.refresh_view)
session["_id"] = self._session_identifier_generator()
session["next"] = make_next_param(login_url, request.url)
redirect_url = make_login_url(self.refresh_view)
else:
login_url = self.refresh_view
redirect_url = make_login_url(login_url, next_url=request.url)
return redirect(redirect_url) | This is called when the user is logged in, but they need to be
reauthenticated because their session is stale. If you register a
callback with `needs_refresh_handler`, then it will be called.
Otherwise, it will take the following actions:
- Flash :attr:`LoginManager.needs_refresh_message` to the user.
- Redirect the user to :attr:`LoginManager.refresh_view`. (The page
they were attempting to access will be passed in the ``next``
query string variable, so you can redirect there if present
instead of the homepage.)
If :attr:`LoginManager.refresh_view` is not defined, then it will
simply raise a HTTP 401 (Unauthorized) error instead.
This should be returned from a view or before/after_request function,
otherwise the redirect will have no effect. | needs_refresh | python | maxcountryman/flask-login | src/flask_login/login_manager.py | https://github.com/maxcountryman/flask-login/blob/master/src/flask_login/login_manager.py | MIT |
def _update_request_context_with_user(self, user=None):
"""Store the given user as ctx.user."""
if user is None:
user = self.anonymous_user()
g._login_user = user | Store the given user as ctx.user. | _update_request_context_with_user | python | maxcountryman/flask-login | src/flask_login/login_manager.py | https://github.com/maxcountryman/flask-login/blob/master/src/flask_login/login_manager.py | MIT |
def _load_user(self):
"""Loads user from session or remember_me cookie as applicable"""
if self._user_callback is None and self._request_callback is None:
raise Exception(
"Missing user_loader or request_loader. Refer to "
"http://flask-login.readthedocs.io/#how-it-works "
"for more info."
)
user_accessed.send(current_app._get_current_object())
# Check SESSION_PROTECTION
if self._session_protection_failed():
return self._update_request_context_with_user()
user = None
# Load user from Flask Session
user_id = session.get("_user_id")
if user_id is not None and self._user_callback is not None:
user = self._user_callback(user_id)
# Load user from Remember Me Cookie or Request Loader
if user is None:
config = current_app.config
cookie_name = config.get("REMEMBER_COOKIE_NAME", COOKIE_NAME)
has_cookie = (
cookie_name in request.cookies and session.get("_remember") != "clear"
)
if has_cookie:
cookie = request.cookies[cookie_name]
user = self._load_user_from_remember_cookie(cookie)
elif self._request_callback:
user = self._load_user_from_request(request)
return self._update_request_context_with_user(user) | Loads user from session or remember_me cookie as applicable | _load_user | python | maxcountryman/flask-login | src/flask_login/login_manager.py | https://github.com/maxcountryman/flask-login/blob/master/src/flask_login/login_manager.py | MIT |
def __eq__(self, other):
"""
Checks the equality of two `UserMixin` objects using `get_id`.
"""
if isinstance(other, UserMixin):
return self.get_id() == other.get_id()
return NotImplemented | Checks the equality of two `UserMixin` objects using `get_id`. | __eq__ | python | maxcountryman/flask-login | src/flask_login/mixins.py | https://github.com/maxcountryman/flask-login/blob/master/src/flask_login/mixins.py | MIT |
def __ne__(self, other):
"""
Checks the inequality of two `UserMixin` objects using `get_id`.
"""
equal = self.__eq__(other)
if equal is NotImplemented:
return NotImplemented
return not equal | Checks the inequality of two `UserMixin` objects using `get_id`. | __ne__ | python | maxcountryman/flask-login | src/flask_login/mixins.py | https://github.com/maxcountryman/flask-login/blob/master/src/flask_login/mixins.py | MIT |
def vector_shape(n_inducing: int) -> Tuple[int, int]:
"""Shape of a vector with n_inducing rows and 1 column."""
return (n_inducing, 1) | Shape of a vector with n_inducing rows and 1 column. | vector_shape | python | JaxGaussianProcesses/GPJax | tests/test_variational_families.py | https://github.com/JaxGaussianProcesses/GPJax/blob/master/tests/test_variational_families.py | Apache-2.0 |
def matrix_shape(n_inducing: int) -> Tuple[int, int]:
"""Shape of a matrix with n_inducing rows and 1 column."""
return (n_inducing, n_inducing) | Shape of a matrix with n_inducing rows and 1 column. | matrix_shape | python | JaxGaussianProcesses/GPJax | tests/test_variational_families.py | https://github.com/JaxGaussianProcesses/GPJax/blob/master/tests/test_variational_families.py | Apache-2.0 |
def vector_val(val: float) -> Callable[[int], Float[Array, "n_inducing 1"]]:
"""Vector of shape (n_inducing, 1) filled with val."""
def vector_val_fn(n_inducing: int):
return val * jnp.ones(vector_shape(n_inducing))
return vector_val_fn | Vector of shape (n_inducing, 1) filled with val. | vector_val | python | JaxGaussianProcesses/GPJax | tests/test_variational_families.py | https://github.com/JaxGaussianProcesses/GPJax/blob/master/tests/test_variational_families.py | Apache-2.0 |
def diag_matrix_val(
val: float,
) -> Callable[[int], Float[Array, "n_inducing n_inducing"]]:
"""Diagonal matrix of shape (n_inducing, n_inducing) filled with val."""
def diag_matrix_fn(n_inducing: int) -> Float[Array, "n_inducing n_inducing"]:
return jnp.eye(n_inducing) * val
return diag_matrix_fn | Diagonal matrix of shape (n_inducing, n_inducing) filled with val. | diag_matrix_val | python | JaxGaussianProcesses/GPJax | tests/test_variational_families.py | https://github.com/JaxGaussianProcesses/GPJax/blob/master/tests/test_variational_families.py | Apache-2.0 |
def fun(x, y):
"""In practice, the first argument will be the latent function values"""
return x**2 + y | In practice, the first argument will be the latent function values | test_quadrature.test_quadrature.test.fun | python | JaxGaussianProcesses/GPJax | tests/test_integrators.py | https://github.com/JaxGaussianProcesses/GPJax/blob/master/tests/test_integrators.py | Apache-2.0 |
def test():
def fun(x, y):
"""In practice, the first argument will be the latent function values"""
return x**2 + y
mean = jnp.array([[2.0]])
variance = jnp.array([[1.0]])
fn_val = GHQuadratureIntegrator(num_points=num_points).integrate(
fun=fun,
mean=mean,
variance=variance,
y=jnp.ones_like(mean),
likelihood=None,
)
return fn_val.squeeze().round(1) | In practice, the first argument will be the latent function values | test_quadrature.test | python | JaxGaussianProcesses/GPJax | tests/test_integrators.py | https://github.com/JaxGaussianProcesses/GPJax/blob/master/tests/test_integrators.py | Apache-2.0 |
def test_quadrature(jit: bool, num_points: int):
def test():
def fun(x, y):
"""In practice, the first argument will be the latent function values"""
return x**2 + y
mean = jnp.array([[2.0]])
variance = jnp.array([[1.0]])
fn_val = GHQuadratureIntegrator(num_points=num_points).integrate(
fun=fun,
mean=mean,
variance=variance,
y=jnp.ones_like(mean),
likelihood=None,
)
return fn_val.squeeze().round(1)
if jit:
test = jax.jit(test)
assert test() == 6.0 | In practice, the first argument will be the latent function values | test_quadrature | python | JaxGaussianProcesses/GPJax | tests/test_integrators.py | https://github.com/JaxGaussianProcesses/GPJax/blob/master/tests/test_integrators.py | Apache-2.0 |
def approx_equal(res: jnp.ndarray, actual: jnp.ndarray) -> bool:
"""Check if two arrays are approximately equal."""
return jnp.linalg.norm(res - actual) < 1e-5 | Check if two arrays are approximately equal. | approx_equal | python | JaxGaussianProcesses/GPJax | tests/test_gaussian_distribution.py | https://github.com/JaxGaussianProcesses/GPJax/blob/master/tests/test_gaussian_distribution.py | Apache-2.0 |
def test_arccosine_special_case(order: int):
"""For certain values of weight variance (1.0) and bias variance (0.0), we can test
our calculations using the Monte Carlo expansion of the arccosine kernel, e.g.
see Eq. (1) of https://cseweb.ucsd.edu/~saul/papers/nips09_kernel.pdf.
"""
kernel = ArcCosine(
weight_variance=jnp.array([1.0, 1.0]), bias_variance=1e-25, order=order
)
# Inputs close(ish) together
a = jnp.array([[0.0, 0.0]])
b = jnp.array([[2.0, 2.0]])
# calc cross-covariance exactly
Kab_exact = kernel.cross_covariance(a, b)
# calc cross-covariance using samples
weights = jax.random.normal(jr.PRNGKey(123), (10_000, 2)) # [S, d]
weights_a = jnp.matmul(weights, a.T) # [S, 1]
weights_b = jnp.matmul(weights, b.T) # [S, 1]
H_a = jnp.heaviside(weights_a, 0.5)
H_b = jnp.heaviside(weights_b, 0.5)
integrands = H_a * H_b * (weights_a**order) * (weights_b**order)
Kab_approx = 2.0 * jnp.mean(integrands)
assert jnp.max(Kab_approx - Kab_exact) < 1e-4 | For certain values of weight variance (1.0) and bias variance (0.0), we can test
our calculations using the Monte Carlo expansion of the arccosine kernel, e.g.
see Eq. (1) of https://cseweb.ucsd.edu/~saul/papers/nips09_kernel.pdf. | test_arccosine_special_case | python | JaxGaussianProcesses/GPJax | tests/test_kernels/test_nonstationary.py | https://github.com/JaxGaussianProcesses/GPJax/blob/master/tests/test_kernels/test_nonstationary.py | Apache-2.0 |
def __init__(
self,
num_datapoints: int,
integrator: AbstractIntegrator = GHQuadratureIntegrator(),
):
"""Initializes the likelihood.
Args:
num_datapoints (int): the number of data points.
integrator (AbstractIntegrator): The integrator to be used for computing expected log
likelihoods. Must be an instance of `AbstractIntegrator`.
"""
self.num_datapoints = num_datapoints
self.integrator = integrator | Initializes the likelihood.
Args:
num_datapoints (int): the number of data points.
integrator (AbstractIntegrator): The integrator to be used for computing expected log
likelihoods. Must be an instance of `AbstractIntegrator`. | __init__ | python | JaxGaussianProcesses/GPJax | gpjax/likelihoods.py | https://github.com/JaxGaussianProcesses/GPJax/blob/master/gpjax/likelihoods.py | Apache-2.0 |
def _do_callback(_) -> int:
"""Perform the callback."""
jax.debug.callback(func, *args)
return _dummy_result | Perform the callback. | _callback._do_callback | python | JaxGaussianProcesses/GPJax | gpjax/scan.py | https://github.com/JaxGaussianProcesses/GPJax/blob/master/gpjax/scan.py | Apache-2.0 |
def _not_callback(_) -> int:
"""Do nothing."""
return _dummy_result | Do nothing. | _callback._not_callback | python | JaxGaussianProcesses/GPJax | gpjax/scan.py | https://github.com/JaxGaussianProcesses/GPJax/blob/master/gpjax/scan.py | Apache-2.0 |
def _callback(cond: ScalarBool, func: Callable, *args: Any) -> None:
r"""Callback a function for a given argument if a condition is true.
Args:
cond (bool): The condition.
func (Callable): The function to call.
*args (Any): The arguments to pass to the function.
"""
# lax.cond requires a result, so we use a dummy result.
_dummy_result = 0
def _do_callback(_) -> int:
"""Perform the callback."""
jax.debug.callback(func, *args)
return _dummy_result
def _not_callback(_) -> int:
"""Do nothing."""
return _dummy_result
_ = lax.cond(cond, _do_callback, _not_callback, operand=None) | # lax.cond requires a result, so we use a dummy result.
_dummy_result = 0
def _do_callback(_) -> int:
"""Perform the callback. | _callback | python | JaxGaussianProcesses/GPJax | gpjax/scan.py | https://github.com/JaxGaussianProcesses/GPJax/blob/master/gpjax/scan.py | Apache-2.0 |
def _set_running(*args: Any) -> None:
"""Set the tqdm progress bar to running."""
_progress_bar.set_description("Running", refresh=False) | Set the tqdm progress bar to running. | _set_running | python | JaxGaussianProcesses/GPJax | gpjax/scan.py | https://github.com/JaxGaussianProcesses/GPJax/blob/master/gpjax/scan.py | Apache-2.0 |
def _update_tqdm(*args: Any) -> None:
"""Update the tqdm progress bar with the latest objective value."""
_value, _iter_num = args
_progress_bar.update(_iter_num.item())
if log_value and _value is not None:
_progress_bar.set_postfix({"Value": f"{_value: .2f}"}) | Update the tqdm progress bar with the latest objective value. | _update_tqdm | python | JaxGaussianProcesses/GPJax | gpjax/scan.py | https://github.com/JaxGaussianProcesses/GPJax/blob/master/gpjax/scan.py | Apache-2.0 |
def _close_tqdm(*args: Any) -> None:
"""Close the tqdm progress bar."""
_progress_bar.close() | Close the tqdm progress bar. | _close_tqdm | python | JaxGaussianProcesses/GPJax | gpjax/scan.py | https://github.com/JaxGaussianProcesses/GPJax/blob/master/gpjax/scan.py | Apache-2.0 |
def get_batch(train_data: Dataset, batch_size: int, key: KeyArray) -> Dataset:
"""Batch the data into mini-batches. Sampling is done with replacement.
Args:
train_data (Dataset): The training dataset.
batch_size (int): The batch size.
key (KeyArray): The random key to use for the batch selection.
Returns
-------
Dataset: The batched dataset.
"""
x, y, n = train_data.X, train_data.y, train_data.n
# Subsample mini-batch indices with replacement.
indices = jr.choice(key, n, (batch_size,), replace=True)
return Dataset(X=x[indices], y=y[indices]) | Batch the data into mini-batches. Sampling is done with replacement.
Args:
train_data (Dataset): The training dataset.
batch_size (int): The batch size.
key (KeyArray): The random key to use for the batch selection.
Returns
-------
Dataset: The batched dataset. | get_batch | python | JaxGaussianProcesses/GPJax | gpjax/fit.py | https://github.com/JaxGaussianProcesses/GPJax/blob/master/gpjax/fit.py | Apache-2.0 |
def _check_model(model: tp.Any) -> None:
"""Check that the model is a subclass of nnx.Module."""
if not isinstance(model, nnx.Module):
raise TypeError(
"Expected model to be a subclass of nnx.Module. "
f"Got {model} of type {type(model)}."
) | Check that the model is a subclass of nnx.Module. | _check_model | python | JaxGaussianProcesses/GPJax | gpjax/fit.py | https://github.com/JaxGaussianProcesses/GPJax/blob/master/gpjax/fit.py | Apache-2.0 |
def _check_train_data(train_data: tp.Any) -> None:
"""Check that the train_data is of type gpjax.Dataset."""
if not isinstance(train_data, Dataset):
raise TypeError(
"Expected train_data to be of type gpjax.Dataset. "
f"Got {train_data} of type {type(train_data)}."
) | Check that the train_data is of type gpjax.Dataset. | _check_train_data | python | JaxGaussianProcesses/GPJax | gpjax/fit.py | https://github.com/JaxGaussianProcesses/GPJax/blob/master/gpjax/fit.py | Apache-2.0 |
def _check_optim(optim: tp.Any) -> None:
"""Check that the optimiser is of type GradientTransformation."""
if not isinstance(optim, ox.GradientTransformation):
raise TypeError(
"Expected optim to be of type optax.GradientTransformation. "
f"Got {optim} of type {type(optim)}."
) | Check that the optimiser is of type GradientTransformation. | _check_optim | python | JaxGaussianProcesses/GPJax | gpjax/fit.py | https://github.com/JaxGaussianProcesses/GPJax/blob/master/gpjax/fit.py | Apache-2.0 |
def _check_num_iters(num_iters: tp.Any) -> None:
"""Check that the number of iterations is of type int and positive."""
if not isinstance(num_iters, int):
raise TypeError(
"Expected num_iters to be of type int. "
f"Got {num_iters} of type {type(num_iters)}."
)
if num_iters <= 0:
raise ValueError(f"Expected num_iters to be positive. Got {num_iters}.") | Check that the number of iterations is of type int and positive. | _check_num_iters | python | JaxGaussianProcesses/GPJax | gpjax/fit.py | https://github.com/JaxGaussianProcesses/GPJax/blob/master/gpjax/fit.py | Apache-2.0 |
def _check_log_rate(log_rate: tp.Any) -> None:
"""Check that the log rate is of type int and positive."""
if not isinstance(log_rate, int):
raise TypeError(
"Expected log_rate to be of type int. "
f"Got {log_rate} of type {type(log_rate)}."
)
if not log_rate > 0:
raise ValueError(f"Expected log_rate to be positive. Got {log_rate}.") | Check that the log rate is of type int and positive. | _check_log_rate | python | JaxGaussianProcesses/GPJax | gpjax/fit.py | https://github.com/JaxGaussianProcesses/GPJax/blob/master/gpjax/fit.py | Apache-2.0 |
def _check_verbose(verbose: tp.Any) -> None:
"""Check that the verbose is of type bool."""
if not isinstance(verbose, bool):
raise TypeError(
"Expected verbose to be of type bool. "
f"Got {verbose} of type {type(verbose)}."
) | Check that the verbose is of type bool. | _check_verbose | python | JaxGaussianProcesses/GPJax | gpjax/fit.py | https://github.com/JaxGaussianProcesses/GPJax/blob/master/gpjax/fit.py | Apache-2.0 |
def _check_batch_size(batch_size: tp.Any) -> None:
"""Check that the batch size is of type int and positive if not minus 1."""
if not isinstance(batch_size, int):
raise TypeError(
"Expected batch_size to be of type int. "
f"Got {batch_size} of type {type(batch_size)}."
)
if not batch_size == -1 and not batch_size > 0:
raise ValueError(f"Expected batch_size to be positive or -1. Got {batch_size}.") | Check that the batch size is of type int and positive if not minus 1. | _check_batch_size | python | JaxGaussianProcesses/GPJax | gpjax/fit.py | https://github.com/JaxGaussianProcesses/GPJax/blob/master/gpjax/fit.py | Apache-2.0 |
def lower_cholesky(A: LinearOperator) -> Triangular: # noqa: F811
"""Returns the lower Cholesky factor of a linear operator.
Args:
A: The input linear operator.
Returns:
Triangular: The lower Cholesky factor of A.
"""
if PSD not in A.annotations:
raise ValueError(
"Expected LinearOperator to be PSD, did you forget to use cola.PSD?"
)
return Triangular(jnp.linalg.cholesky(A.to_dense()), lower=True) | Returns the lower Cholesky factor of a linear operator.
Args:
A: The input linear operator.
Returns:
Triangular: The lower Cholesky factor of A. | lower_cholesky | python | JaxGaussianProcesses/GPJax | gpjax/lower_cholesky.py | https://github.com/JaxGaussianProcesses/GPJax/blob/master/gpjax/lower_cholesky.py | Apache-2.0 |
def num_inducing(self) -> int:
"""The number of inducing inputs."""
return self.inducing_inputs.value.shape[0] | The number of inducing inputs. | num_inducing | python | JaxGaussianProcesses/GPJax | gpjax/variational_families.py | https://github.com/JaxGaussianProcesses/GPJax/blob/master/gpjax/variational_families.py | Apache-2.0 |
def __init__(
self,
active_dims: tp.Union[list[int], slice, None] = None,
n_dims: tp.Union[int, None] = None,
compute_engine: AbstractKernelComputation = DenseKernelComputation(),
):
"""Initialise the AbstractKernel class.
Args:
active_dims: the indices of the input dimensions
that are active in the kernel's evaluation, represented by a list of
integers or a slice object. Defaults to a full slice.
n_dims: the number of input dimensions of the kernel.
compute_engine: the computation engine that is used to compute the kernel's
cross-covariance and gram matrices. Defaults to DenseKernelComputation.
"""
active_dims = active_dims or slice(None)
_check_active_dims(active_dims)
_check_n_dims(n_dims)
self.active_dims, self.n_dims = _check_dims_compat(active_dims, n_dims)
self.compute_engine = compute_engine | Initialise the AbstractKernel class.
Args:
active_dims: the indices of the input dimensions
that are active in the kernel's evaluation, represented by a list of
integers or a slice object. Defaults to a full slice.
n_dims: the number of input dimensions of the kernel.
compute_engine: the computation engine that is used to compute the kernel's
cross-covariance and gram matrices. Defaults to DenseKernelComputation. | __init__ | python | JaxGaussianProcesses/GPJax | gpjax/kernels/base.py | https://github.com/JaxGaussianProcesses/GPJax/blob/master/gpjax/kernels/base.py | Apache-2.0 |
def __init__(
self,
active_dims: tp.Union[list[int], slice, None] = None,
degree: int = 2,
shift: tp.Union[ScalarFloat, nnx.Variable[ScalarArray]] = 0.0,
variance: tp.Union[ScalarFloat, nnx.Variable[ScalarArray]] = 1.0,
n_dims: tp.Union[int, None] = None,
compute_engine: AbstractKernelComputation = DenseKernelComputation(),
):
"""Initializes the kernel.
Args:
active_dims: The indices of the input dimensions that the kernel operates on.
degree: The degree of the polynomial.
shift: The shift parameter of the kernel.
variance: The variance of the kernel.
n_dims: The number of input dimensions.
compute_engine: The computation engine that the kernel uses to compute the
covariance matrix.
"""
super().__init__(active_dims, n_dims, compute_engine)
self.degree = degree
if isinstance(shift, nnx.Variable):
self.shift = shift
else:
self.shift = PositiveReal(shift)
if tp.TYPE_CHECKING:
self.shift = tp.cast(PositiveReal[ScalarArray], self.shift)
if isinstance(variance, nnx.Variable):
self.variance = variance
else:
self.variance = PositiveReal(variance)
if tp.TYPE_CHECKING:
self.variance = tp.cast(PositiveReal[ScalarArray], self.variance)
self.name = f"Polynomial (degree {self.degree})" | Initializes the kernel.
Args:
active_dims: The indices of the input dimensions that the kernel operates on.
degree: The degree of the polynomial.
shift: The shift parameter of the kernel.
variance: The variance of the kernel.
n_dims: The number of input dimensions.
compute_engine: The computation engine that the kernel uses to compute the
covariance matrix. | __init__ | python | JaxGaussianProcesses/GPJax | gpjax/kernels/nonstationary/polynomial.py | https://github.com/JaxGaussianProcesses/GPJax/blob/master/gpjax/kernels/nonstationary/polynomial.py | Apache-2.0 |
def __init__(
self,
active_dims: tp.Union[list[int], slice, None] = None,
order: tp.Literal[0, 1, 2] = 0,
variance: tp.Union[ScalarFloat, nnx.Variable[ScalarArray]] = 1.0,
weight_variance: tp.Union[
WeightVarianceCompatible, nnx.Variable[WeightVariance]
] = 1.0,
bias_variance: tp.Union[ScalarFloat, nnx.Variable[ScalarArray]] = 1.0,
n_dims: tp.Union[int, None] = None,
compute_engine: AbstractKernelComputation = DenseKernelComputation(),
):
"""Initializes the kernel.
Args:
active_dims: The indices of the input dimensions that the kernel operates on.
order: The order of the kernel. Must be 0, 1 or 2.
variance: The variance of the kernel σ.
weight_variance: The weight variance of the kernel.
bias_variance: The bias variance of the kernel.
n_dims: The number of input dimensions. If `lengthscale` is an array, this
argument is ignored.
compute_engine: The computation engine that the kernel uses to compute the
covariance matrix.
"""
if order not in [0, 1, 2]:
raise ValueError("ArcCosine kernel only implemented for orders 0, 1 and 2.")
self.order = order
if isinstance(weight_variance, nnx.Variable):
self.weight_variance = weight_variance
else:
self.weight_variance = PositiveReal(weight_variance)
if tp.TYPE_CHECKING:
self.weight_variance = tp.cast(
PositiveReal[WeightVariance], self.weight_variance
)
if isinstance(variance, nnx.Variable):
self.variance = variance
else:
self.variance = PositiveReal(variance)
if tp.TYPE_CHECKING:
self.variance = tp.cast(PositiveReal[ScalarArray], self.variance)
if isinstance(bias_variance, nnx.Variable):
self.bias_variance = bias_variance
else:
self.bias_variance = PositiveReal(bias_variance)
if tp.TYPE_CHECKING:
self.bias_variance = tp.cast(
PositiveReal[ScalarArray], self.bias_variance
)
self.name = f"ArcCosine (order {self.order})"
super().__init__(active_dims, n_dims, compute_engine) | Initializes the kernel.
Args:
active_dims: The indices of the input dimensions that the kernel operates on.
order: The order of the kernel. Must be 0, 1 or 2.
variance: The variance of the kernel σ.
weight_variance: The weight variance of the kernel.
bias_variance: The bias variance of the kernel.
n_dims: The number of input dimensions. If `lengthscale` is an array, this
argument is ignored.
compute_engine: The computation engine that the kernel uses to compute the
covariance matrix. | __init__ | python | JaxGaussianProcesses/GPJax | gpjax/kernels/nonstationary/arccosine.py | https://github.com/JaxGaussianProcesses/GPJax/blob/master/gpjax/kernels/nonstationary/arccosine.py | Apache-2.0 |
def __init__(
self,
active_dims: tp.Union[list[int], slice, None] = None,
variance: tp.Union[ScalarFloat, nnx.Variable[ScalarArray]] = 1.0,
n_dims: tp.Union[int, None] = None,
compute_engine: AbstractKernelComputation = DenseKernelComputation(),
):
"""Initializes the kernel.
Args:
active_dims: The indices of the input dimensions that the kernel operates on.
variance: the variance of the kernel σ.
n_dims: The number of input dimensions.
compute_engine: The computation engine that the kernel uses to compute the
covariance matrix.
"""
super().__init__(active_dims, n_dims, compute_engine)
if isinstance(variance, nnx.Variable):
self.variance = variance
else:
self.variance = PositiveReal(variance)
if tp.TYPE_CHECKING:
self.variance = tp.cast(PositiveReal[ScalarArray], self.variance) | Initializes the kernel.
Args:
active_dims: The indices of the input dimensions that the kernel operates on.
variance: the variance of the kernel σ.
n_dims: The number of input dimensions.
compute_engine: The computation engine that the kernel uses to compute the
covariance matrix. | __init__ | python | JaxGaussianProcesses/GPJax | gpjax/kernels/nonstationary/linear.py | https://github.com/JaxGaussianProcesses/GPJax/blob/master/gpjax/kernels/nonstationary/linear.py | Apache-2.0 |
def __call__(self, x: Float[Array, "D 1"], y: Float[Array, "D 1"]) -> None:
"""Superfluous for RFFs."""
raise RuntimeError("RFFs do not have a kernel function.") | Superfluous for RFFs. | __call__ | python | JaxGaussianProcesses/GPJax | gpjax/kernels/approximations/rff.py | https://github.com/JaxGaussianProcesses/GPJax/blob/master/gpjax/kernels/approximations/rff.py | Apache-2.0 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.