code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def clear(self):
"""Remove all content from this paragraph.
Paragraph properties are preserved. Content includes runs, line breaks, and fields.
"""
for elm in self._element.content_children:
self._element.remove(elm)
return self | Remove all content from this paragraph.
Paragraph properties are preserved. Content includes runs, line breaks, and fields.
| clear | python | scanny/python-pptx | src/pptx/text/text.py | https://github.com/scanny/python-pptx/blob/master/src/pptx/text/text.py | MIT |
def line_spacing(self) -> int | float | Length | None:
"""The space between baselines in successive lines of this paragraph.
A value of |None| indicates no explicit value is assigned and its effective value is
inherited from the paragraph's style hierarchy. A numeric value, e.g. `2` or `1.5`,
... | The space between baselines in successive lines of this paragraph.
A value of |None| indicates no explicit value is assigned and its effective value is
inherited from the paragraph's style hierarchy. A numeric value, e.g. `2` or `1.5`,
indicates spacing is applied in multiples of line heights. ... | line_spacing | python | scanny/python-pptx | src/pptx/text/text.py | https://github.com/scanny/python-pptx/blob/master/src/pptx/text/text.py | MIT |
def space_after(self) -> Length | None:
"""The spacing to appear between this paragraph and the subsequent paragraph.
A value of |None| indicates no explicit value is assigned and its effective value is
inherited from the paragraph's style hierarchy. |Length| objects provide convenience
... | The spacing to appear between this paragraph and the subsequent paragraph.
A value of |None| indicates no explicit value is assigned and its effective value is
inherited from the paragraph's style hierarchy. |Length| objects provide convenience
properties, such as `.pt` and `.inches`, that allo... | space_after | python | scanny/python-pptx | src/pptx/text/text.py | https://github.com/scanny/python-pptx/blob/master/src/pptx/text/text.py | MIT |
def space_before(self) -> Length | None:
"""The spacing to appear between this paragraph and the prior paragraph.
A value of |None| indicates no explicit value is assigned and its effective value is
inherited from the paragraph's style hierarchy. |Length| objects provide convenience
pro... | The spacing to appear between this paragraph and the prior paragraph.
A value of |None| indicates no explicit value is assigned and its effective value is
inherited from the paragraph's style hierarchy. |Length| objects provide convenience
properties, such as `.pt` and `.cm`, that allow easy co... | space_before | python | scanny/python-pptx | src/pptx/text/text.py | https://github.com/scanny/python-pptx/blob/master/src/pptx/text/text.py | MIT |
def hyperlink(self) -> _Hyperlink:
"""Proxy for any `a:hlinkClick` element under the run properties element.
Created on demand, the hyperlink object is available whether an `a:hlinkClick` element is
present or not, and creates or deletes that element as appropriate in response to actions
... | Proxy for any `a:hlinkClick` element under the run properties element.
Created on demand, the hyperlink object is available whether an `a:hlinkClick` element is
present or not, and creates or deletes that element as appropriate in response to actions
on its methods and attributes.
| hyperlink | python | scanny/python-pptx | src/pptx/text/text.py | https://github.com/scanny/python-pptx/blob/master/src/pptx/text/text.py | MIT |
def make_bubble_chart_data(ser_count, point_count):
"""
Return an |BubbleChartData| object populated with *ser_count* series,
each having *point_count* data points.
"""
points = (
(1.1, 11.1, 10.0),
(2.1, 12.1, 20.0),
(3.1, 13.1, 30.0),
(1.2, 11.2, 40.0),
(2.2... |
Return an |BubbleChartData| object populated with *ser_count* series,
each having *point_count* data points.
| make_bubble_chart_data | python | scanny/python-pptx | tests/chart/test_xmlwriter.py | https://github.com/scanny/python-pptx/blob/master/tests/chart/test_xmlwriter.py | MIT |
def make_category_chart_data(cat_count, cat_type, ser_count):
"""
Return a |CategoryChartData| instance populated with *cat_count*
categories of type *cat_type* and *ser_count* series. Values are
auto-generated.
"""
category_labels = {
date: (date(2016, 12, 27), date(2016, 12, 28), date(... |
Return a |CategoryChartData| instance populated with *cat_count*
categories of type *cat_type* and *ser_count* series. Values are
auto-generated.
| make_category_chart_data | python | scanny/python-pptx | tests/chart/test_xmlwriter.py | https://github.com/scanny/python-pptx/blob/master/tests/chart/test_xmlwriter.py | MIT |
def make_xy_chart_data(ser_count, point_count):
"""
Return an |XyChartData| object populated with *ser_count* series each
having *point_count* data points. Values are auto-generated.
"""
points = (
(1.1, 11.1),
(2.1, 12.1),
(3.1, 13.1),
(1.2, 11.2),
(2.2, 12.2... |
Return an |XyChartData| object populated with *ser_count* series each
having *point_count* data points. Values are auto-generated.
| make_xy_chart_data | python | scanny/python-pptx | tests/chart/test_xmlwriter.py | https://github.com/scanny/python-pptx/blob/master/tests/chart/test_xmlwriter.py | MIT |
def and_it_knows_the_relative_partname_for_an_internal_rel(self, request):
"""Internal relationships have a relative reference for `.target_ref`.
A relative reference looks like "../slideLayouts/slideLayout1.xml". This form
is suitable for writing to a .rels file.
"""
property_m... | Internal relationships have a relative reference for `.target_ref`.
A relative reference looks like "../slideLayouts/slideLayout1.xml". This form
is suitable for writing to a .rels file.
| and_it_knows_the_relative_partname_for_an_internal_rel | python | scanny/python-pptx | tests/opc/test_package.py | https://github.com/scanny/python-pptx/blob/master/tests/opc/test_package.py | MIT |
def it_can_create_a_new_tbl_element_tree(self):
"""
Indirectly tests that column widths are a proportional split of total
width and that row heights a proportional split of total height.
"""
expected_xml = (
'<a:tbl %s>\n <a:tblPr firstRow="1" bandRow="1">\n <a:ta... |
Indirectly tests that column widths are a proportional split of total
width and that row heights a proportional split of total height.
| it_can_create_a_new_tbl_element_tree | python | scanny/python-pptx | tests/oxml/test_table.py | https://github.com/scanny/python-pptx/blob/master/tests/oxml/test_table.py | MIT |
def it_can_create_a_new_pic_element(self, desc, xml_desc):
"""`desc` attr (often filename) is XML-escaped to handle special characters.
In particular, ampersand ('&'), less/greater-than ('</>') etc.
"""
pic = CT_Picture.new_pic(
shape_id=9, name="Picture 8", desc=desc, rId="... | `desc` attr (often filename) is XML-escaped to handle special characters.
In particular, ampersand ('&'), less/greater-than ('</>') etc.
| it_can_create_a_new_pic_element | python | scanny/python-pptx | tests/oxml/shapes/test_picture.py | https://github.com/scanny/python-pptx/blob/master/tests/oxml/shapes/test_picture.py | MIT |
def it_provides_access_to_an_existing_notes_master_part(
self, notes_master_part_, part_related_by_
):
"""This is the first of a two-part test to cover the existing notes master case.
The notes master not-present case follows.
"""
prs_part = PresentationPart(None, None, None... | This is the first of a two-part test to cover the existing notes master case.
The notes master not-present case follows.
| it_provides_access_to_an_existing_notes_master_part | python | scanny/python-pptx | tests/parts/test_presentation.py | https://github.com/scanny/python-pptx/blob/master/tests/parts/test_presentation.py | MIT |
def but_it_adds_a_notes_master_part_when_needed(
self, request, package_, notes_master_part_, part_related_by_, relate_to_
):
"""This is the second of a two-part test to cover notes-master-not-present case.
The notes master present case is just above.
"""
NotesMasterPart_ = ... | This is the second of a two-part test to cover notes-master-not-present case.
The notes master present case is just above.
| but_it_adds_a_notes_master_part_when_needed | python | scanny/python-pptx | tests/parts/test_presentation.py | https://github.com/scanny/python-pptx/blob/master/tests/parts/test_presentation.py | MIT |
def it_should_update_actual_value_on_indexed_assignment(self, indexed_assignment_fixture_):
"""
Assignment to AdjustmentCollection[n] updates nth actual
"""
adjs, idx, new_val, expected = indexed_assignment_fixture_
adjs[idx] = new_val
assert adjs._adjustments[idx].actual... |
Assignment to AdjustmentCollection[n] updates nth actual
| it_should_update_actual_value_on_indexed_assignment | python | scanny/python-pptx | tests/shapes/test_autoshape.py | https://github.com/scanny/python-pptx/blob/master/tests/shapes/test_autoshape.py | MIT |
def it_should_raise_on_assigned_bad_value(self, adjustments):
"""
AdjustmentCollection[n] = val raises on val is not number
"""
with pytest.raises(ValueError):
adjustments[0] = "1.0" |
AdjustmentCollection[n] = val raises on val is not number
| it_should_raise_on_assigned_bad_value | python | scanny/python-pptx | tests/shapes/test_autoshape.py | https://github.com/scanny/python-pptx/blob/master/tests/shapes/test_autoshape.py | MIT |
def in_order(node):
"""
Traverse the tree depth first to produce a list of its values,
in order.
"""
result = []
if node is None:
return result
result.extend(in_order(node._lesser))
result.append(node.value)
... |
Traverse the tree depth first to produce a list of its values,
in order.
| in_order | python | scanny/python-pptx | tests/text/test_layout.py | https://github.com/scanny/python-pptx/blob/master/tests/text/test_layout.py | MIT |
def part_(self, request, url, rId):
"""
Mock Part instance suitable for patching into _Hyperlink.part
property. It returns url for target_ref() and rId for relate_to().
"""
part_ = instance_mock(request, XmlPart)
part_.target_ref.return_value = url
part_.relate_to... |
Mock Part instance suitable for patching into _Hyperlink.part
property. It returns url for target_ref() and rId for relate_to().
| part_ | python | scanny/python-pptx | tests/text/test_text.py | https://github.com/scanny/python-pptx/blob/master/tests/text/test_text.py | MIT |
def nsdecls(*nspfxs):
"""
Return a string containing a namespace declaration for each of *nspfxs*,
in the order they are specified.
"""
nsdecls = ""
for nspfx in nspfxs:
nsdecls += ' xmlns:%s="%s"' % (nspfx, nsmap[nspfx])
return nsdecls |
Return a string containing a namespace declaration for each of *nspfxs*,
in the order they are specified.
| nsdecls | python | scanny/python-pptx | tests/unitutil/cxml.py | https://github.com/scanny/python-pptx/blob/master/tests/unitutil/cxml.py | MIT |
def connect_children(self, child_node_list):
"""
Make each of the elements appearing in *child_node_list* a child of
this element.
"""
for node in child_node_list:
child = node.element
self._children.append(child) |
Make each of the elements appearing in *child_node_list* a child of
this element.
| connect_children | python | scanny/python-pptx | tests/unitutil/cxml.py | https://github.com/scanny/python-pptx/blob/master/tests/unitutil/cxml.py | MIT |
def _xml(self, indent):
"""
Return a string containing the XML of this element and all its
children with a starting indent of *indent* spaces.
"""
self._indent_str = " " * indent
xml = self._start_tag
for child in self._children:
xml += child._xml(inde... |
Return a string containing the XML of this element and all its
children with a starting indent of *indent* spaces.
| _xml | python | scanny/python-pptx | tests/unitutil/cxml.py | https://github.com/scanny/python-pptx/blob/master/tests/unitutil/cxml.py | MIT |
def snippet_bytes(snippet_file_name: str):
"""Return bytes read from snippet file having `snippet_file_name`."""
snippet_file_path = os.path.join(test_file_dir, "snippets", "%s.txt" % snippet_file_name)
with open(snippet_file_path, "rb") as f:
return f.read().strip() | Return bytes read from snippet file having `snippet_file_name`. | snippet_bytes | python | scanny/python-pptx | tests/unitutil/file.py | https://github.com/scanny/python-pptx/blob/master/tests/unitutil/file.py | MIT |
def snippet_text(snippet_file_name: str):
"""
Return the unicode text read from the test snippet file having
*snippet_file_name*.
"""
snippet_file_path = os.path.join(test_file_dir, "snippets", "%s.txt" % snippet_file_name)
with open(snippet_file_path, "rb") as f:
snippet_bytes = f.read(... |
Return the unicode text read from the test snippet file having
*snippet_file_name*.
| snippet_text | python | scanny/python-pptx | tests/unitutil/file.py | https://github.com/scanny/python-pptx/blob/master/tests/unitutil/file.py | MIT |
def testfile_bytes(*segments: str):
"""Return bytes of file at path formed by adding `segments` to test file dir."""
path = os.path.join(test_file_dir, *segments)
with open(path, "rb") as f:
return f.read() | Return bytes of file at path formed by adding `segments` to test file dir. | testfile_bytes | python | scanny/python-pptx | tests/unitutil/file.py | https://github.com/scanny/python-pptx/blob/master/tests/unitutil/file.py | MIT |
def class_mock(
request: FixtureRequest, q_class_name: str, autospec: bool = True, **kwargs: Any
) -> Mock:
"""Return a mock patching the class with qualified name *q_class_name*.
The mock is autospec'ed based on the patched class unless the optional argument
*autospec* is set to False. Any other keywo... | Return a mock patching the class with qualified name *q_class_name*.
The mock is autospec'ed based on the patched class unless the optional argument
*autospec* is set to False. Any other keyword arguments are passed through to
Mock(). Patch is reversed after calling test returns.
| class_mock | python | scanny/python-pptx | tests/unitutil/mock.py | https://github.com/scanny/python-pptx/blob/master/tests/unitutil/mock.py | MIT |
def cls_attr_mock(
request: FixtureRequest, cls: type, attr_name: str, name: str | None = None, **kwargs: Any
) -> Mock:
"""Return a mock for an attribute (class variable) `attr_name` on `cls`.
Patch is reversed after pytest uses it.
"""
name = request.fixturename if name is None else name
_pat... | Return a mock for an attribute (class variable) `attr_name` on `cls`.
Patch is reversed after pytest uses it.
| cls_attr_mock | python | scanny/python-pptx | tests/unitutil/mock.py | https://github.com/scanny/python-pptx/blob/master/tests/unitutil/mock.py | MIT |
def instance_mock(
request: FixtureRequest,
cls: type,
name: str | None = None,
spec_set: bool = True,
**kwargs: Any,
) -> Mock:
"""Return mock for instance of `cls` that draws its spec from that class.
The mock does not allow new attributes to be set on the instance. If `name` is
missi... | Return mock for instance of `cls` that draws its spec from that class.
The mock does not allow new attributes to be set on the instance. If `name` is
missing or |None|, the name of the returned |Mock| instance is set to
`request.fixturename`. Additional keyword arguments are passed through to the Mock()
... | instance_mock | python | scanny/python-pptx | tests/unitutil/mock.py | https://github.com/scanny/python-pptx/blob/master/tests/unitutil/mock.py | MIT |
def open_mock(request: FixtureRequest, module_name: str, **kwargs: Any):
"""Return a mock for the builtin `open()` method in `module_name`."""
target = "%s.open" % module_name
_patch = patch(target, mock_open(), create=True, **kwargs)
request.addfinalizer(_patch.stop)
return _patch.start() | Return a mock for the builtin `open()` method in `module_name`. | open_mock | python | scanny/python-pptx | tests/unitutil/mock.py | https://github.com/scanny/python-pptx/blob/master/tests/unitutil/mock.py | MIT |
def property_mock(request: FixtureRequest, cls: type, prop_name: str, **kwargs: Any):
"""Return a mock for property `prop_name` on class `cls`."""
_patch = patch.object(cls, prop_name, new_callable=PropertyMock, **kwargs)
request.addfinalizer(_patch.stop)
return _patch.start() | Return a mock for property `prop_name` on class `cls`. | property_mock | python | scanny/python-pptx | tests/unitutil/mock.py | https://github.com/scanny/python-pptx/blob/master/tests/unitutil/mock.py | MIT |
def var_mock(request: FixtureRequest, q_var_name: str, **kwargs: Any):
"""Return mock patching the variable with qualified name *q_var_name*."""
_patch = patch(q_var_name, **kwargs)
request.addfinalizer(_patch.stop)
return _patch.start() | Return mock patching the variable with qualified name *q_var_name*. | var_mock | python | scanny/python-pptx | tests/unitutil/mock.py | https://github.com/scanny/python-pptx/blob/master/tests/unitutil/mock.py | MIT |
def count(start=0, step=1):
"""
Local implementation of `itertools.count()` to allow v2.6 compatibility.
"""
n = start
while True:
yield n
n += step |
Local implementation of `itertools.count()` to allow v2.6 compatibility.
| count | python | scanny/python-pptx | tests/unitutil/__init__.py | https://github.com/scanny/python-pptx/blob/master/tests/unitutil/__init__.py | MIT |
def ipynb_2_py(file_name, encoding="utf-8"):
"""
Args:
file_name (str): notebook file path to parse as python script
encoding (str): encoding of file
Returns:
str: parsed string
"""
exporter = PythonExporter()
(body, _) = exporter.from_filename(file_name)
return ... |
Args:
file_name (str): notebook file path to parse as python script
encoding (str): encoding of file
Returns:
str: parsed string
| ipynb_2_py | python | bndr/pipreqs | pipreqs/pipreqs.py | https://github.com/bndr/pipreqs/blob/master/pipreqs/pipreqs.py | Apache-2.0 |
def compare_modules(file_, imports):
"""Compare modules in a file to imported modules in a project.
Args:
file_ (str): File to parse for modules to be compared.
imports (tuple): Modules being imported in the project.
Returns:
set: The modules not imported in the project, but do exi... | Compare modules in a file to imported modules in a project.
Args:
file_ (str): File to parse for modules to be compared.
imports (tuple): Modules being imported in the project.
Returns:
set: The modules not imported in the project, but do exist in the
specified file.
| compare_modules | python | bndr/pipreqs | pipreqs/pipreqs.py | https://github.com/bndr/pipreqs/blob/master/pipreqs/pipreqs.py | Apache-2.0 |
def test_get_imports_info(self):
"""
Test to see that the right number of packages were found on PyPI
"""
imports = pipreqs.get_all_imports(self.project)
with_info = pipreqs.get_imports_info(imports)
# Should contain 10 items without the "nonexistendmodule" and
# ... |
Test to see that the right number of packages were found on PyPI
| test_get_imports_info | python | bndr/pipreqs | tests/test_pipreqs.py | https://github.com/bndr/pipreqs/blob/master/tests/test_pipreqs.py | Apache-2.0 |
def test_get_use_local_only(self):
"""
Test without checking PyPI, check to see if names of local
imports matches what we expect
- Note even though pyflakes isn't in requirements.txt,
It's added to locals since it is a development dependency
for testing
"""
... |
Test without checking PyPI, check to see if names of local
imports matches what we expect
- Note even though pyflakes isn't in requirements.txt,
It's added to locals since it is a development dependency
for testing
| test_get_use_local_only | python | bndr/pipreqs | tests/test_pipreqs.py | https://github.com/bndr/pipreqs/blob/master/tests/test_pipreqs.py | Apache-2.0 |
def test_init(self):
"""
Test that all modules we will test upon are in requirements file
"""
pipreqs.init(
{
"<path>": self.project,
"--savepath": None,
"--print": False,
"--use-local": None,
"--... |
Test that all modules we will test upon are in requirements file
| test_init | python | bndr/pipreqs | tests/test_pipreqs.py | https://github.com/bndr/pipreqs/blob/master/tests/test_pipreqs.py | Apache-2.0 |
def test_init_local_only(self):
"""
Test that items listed in requirements.text are the same
as locals expected
"""
pipreqs.init(
{
"<path>": self.project,
"--savepath": None,
"--print": False,
"--use-loc... |
Test that items listed in requirements.text are the same
as locals expected
| test_init_local_only | python | bndr/pipreqs | tests/test_pipreqs.py | https://github.com/bndr/pipreqs/blob/master/tests/test_pipreqs.py | Apache-2.0 |
def test_init_savepath(self):
"""
Test that we can save requirements.txt correctly
to a different path
"""
pipreqs.init(
{
"<path>": self.project,
"--savepath": self.alt_requirement_path,
"--use-local": None,
... |
Test that we can save requirements.txt correctly
to a different path
| test_init_savepath | python | bndr/pipreqs | tests/test_pipreqs.py | https://github.com/bndr/pipreqs/blob/master/tests/test_pipreqs.py | Apache-2.0 |
def test_init_overwrite(self):
"""
Test that if requiremnts.txt exists, it will not be
automatically overwritten
"""
with open(self.requirements_path, "w") as f:
f.write("should_not_be_overwritten")
pipreqs.init(
{
"<path>": self.pr... |
Test that if requiremnts.txt exists, it will not be
automatically overwritten
| test_init_overwrite | python | bndr/pipreqs | tests/test_pipreqs.py | https://github.com/bndr/pipreqs/blob/master/tests/test_pipreqs.py | Apache-2.0 |
def test_get_import_name_without_alias(self):
"""
Test that function get_name_without_alias()
will work on a string.
- Note: This isn't truly needed when pipreqs is walking
the AST to find imports
"""
import_name_with_alias = "requests as R"
expected_imp... |
Test that function get_name_without_alias()
will work on a string.
- Note: This isn't truly needed when pipreqs is walking
the AST to find imports
| test_get_import_name_without_alias | python | bndr/pipreqs | tests/test_pipreqs.py | https://github.com/bndr/pipreqs/blob/master/tests/test_pipreqs.py | Apache-2.0 |
def test_custom_pypi_server(self):
"""
Test that trying to get a custom pypi sever fails correctly
"""
self.assertRaises(
requests.exceptions.MissingSchema,
pipreqs.init,
{
"<path>": self.project,
"--savepath": None,
... |
Test that trying to get a custom pypi sever fails correctly
| test_custom_pypi_server | python | bndr/pipreqs | tests/test_pipreqs.py | https://github.com/bndr/pipreqs/blob/master/tests/test_pipreqs.py | Apache-2.0 |
def test_clean_with_imports_to_clean(self):
"""
Test --clean parameter when there are imports to clean
"""
cleaned_module = "sqlalchemy"
pipreqs.init(
{
"<path>": self.project,
"--savepath": None,
"--print": False,
... |
Test --clean parameter when there are imports to clean
| test_clean_with_imports_to_clean | python | bndr/pipreqs | tests/test_pipreqs.py | https://github.com/bndr/pipreqs/blob/master/tests/test_pipreqs.py | Apache-2.0 |
def test_output_requirements(self):
"""
Test --print parameter
It should print to stdout the same content as requeriments.txt
"""
capturedOutput = StringIO()
sys.stdout = capturedOutput
pipreqs.init(
{
"<path>": self.project,
... |
Test --print parameter
It should print to stdout the same content as requeriments.txt
| test_output_requirements | python | bndr/pipreqs | tests/test_pipreqs.py | https://github.com/bndr/pipreqs/blob/master/tests/test_pipreqs.py | Apache-2.0 |
def test_import_notebooks(self):
"""
Test the function get_all_imports() using .ipynb file
"""
self.mock_scan_notebooks()
imports = pipreqs.get_all_imports(self.project_with_notebooks)
for item in imports:
self.assertTrue(item.lower() in self.modules, "Import ... |
Test the function get_all_imports() using .ipynb file
| test_import_notebooks | python | bndr/pipreqs | tests/test_pipreqs.py | https://github.com/bndr/pipreqs/blob/master/tests/test_pipreqs.py | Apache-2.0 |
def test_invalid_notebook(self):
"""
Test that invalid notebook files cannot be imported.
"""
self.mock_scan_notebooks()
self.assertRaises(SyntaxError, pipreqs.get_all_imports, self.project_with_invalid_notebooks) |
Test that invalid notebook files cannot be imported.
| test_invalid_notebook | python | bndr/pipreqs | tests/test_pipreqs.py | https://github.com/bndr/pipreqs/blob/master/tests/test_pipreqs.py | Apache-2.0 |
def test_ipynb_2_py(self):
"""
Test the function ipynb_2_py() which converts .ipynb file to .py format
"""
python_imports = pipreqs.get_all_imports(self.python_path_same_imports)
notebook_imports = pipreqs.get_all_imports(self.notebook_path_same_imports)
self.assertEqual(... |
Test the function ipynb_2_py() which converts .ipynb file to .py format
| test_ipynb_2_py | python | bndr/pipreqs | tests/test_pipreqs.py | https://github.com/bndr/pipreqs/blob/master/tests/test_pipreqs.py | Apache-2.0 |
def test_ignore_notebooks(self):
"""
Test if notebooks are ignored when the scan-notebooks parameter is False
"""
notebook_requirement_path = os.path.join(self.project_with_notebooks, "requirements.txt")
pipreqs.init(
{
"<path>": self.project_with_not... |
Test if notebooks are ignored when the scan-notebooks parameter is False
| test_ignore_notebooks | python | bndr/pipreqs | tests/test_pipreqs.py | https://github.com/bndr/pipreqs/blob/master/tests/test_pipreqs.py | Apache-2.0 |
def tearDown(self):
"""
Remove requiremnts.txt files that were written
"""
try:
os.remove(self.requirements_path)
except OSError:
pass
try:
os.remove(self.alt_requirement_path)
except OSError:
pass |
Remove requiremnts.txt files that were written
| tearDown | python | bndr/pipreqs | tests/test_pipreqs.py | https://github.com/bndr/pipreqs/blob/master/tests/test_pipreqs.py | Apache-2.0 |
def find_risky_files(path: str):
"""Searching for risky text in yml files for given path."""
return {
str(file)
for file in Path(path).rglob("*.yml")
if risky_text in file.read_text() and str(file) not in ignore_files
} | Searching for risky text in yml files for given path. | find_risky_files | python | mckinsey/vizro | tools/scan_yaml_for_risky_text.py | https://github.com/mckinsey/vizro/blob/master/tools/scan_yaml_for_risky_text.py | Apache-2.0 |
def post_comment(pr_object, config: PyCafeConfig, comparison_urls_dict: dict[str, dict[str, str]]):
"""Post a comment on the pull request with the PyCafe dashboard links."""
template = """## View the example dashboards of the current commit live on PyCafe :coffee: :rocket:\n
Updated on: {current_utc_time}
Commi... | Post a comment on the pull request with the PyCafe dashboard links. | post_comment | python | mckinsey/vizro | tools/pycafe/create_pycafe_links_comments.py | https://github.com/mckinsey/vizro/blob/master/tools/pycafe/create_pycafe_links_comments.py | Apache-2.0 |
def _get_vizro_requirement(config: PyCafeConfig, use_latest_release: bool = False) -> str:
"""Get the Vizro requirement string for PyCafe."""
if use_latest_release:
return "vizro"
return (
f"{config.pycafe_url}/gh/artifact/mckinsey/vizro/actions/runs/{config.run_id}/"
f"pip/vizro-{co... | Get the Vizro requirement string for PyCafe. | _get_vizro_requirement | python | mckinsey/vizro | tools/pycafe/pycafe_utils.py | https://github.com/mckinsey/vizro/blob/master/tools/pycafe/pycafe_utils.py | Apache-2.0 |
def _get_vizro_ai_requirement(config: PyCafeConfig, use_latest_release: bool = False) -> str:
"""Get the Vizro AI requirement string for PyCafe."""
if use_latest_release:
return "vizro-ai"
return (
f"{config.pycafe_url}/gh/artifact/mckinsey/vizro/actions/runs/{config.run_id}/"
f"pip2... | Get the Vizro AI requirement string for PyCafe. | _get_vizro_ai_requirement | python | mckinsey/vizro | tools/pycafe/pycafe_utils.py | https://github.com/mckinsey/vizro/blob/master/tools/pycafe/pycafe_utils.py | Apache-2.0 |
def _fetch_app_content(base_url: str) -> str:
"""Fetch and process app.py content from the repository."""
response = requests.get(f"{base_url}/app.py", timeout=10)
response.raise_for_status()
app_content = response.text
app_content_split = app_content.split('if __name__ == "__main__":')
if len(... | Fetch and process app.py content from the repository. | _fetch_app_content | python | mckinsey/vizro | tools/pycafe/pycafe_utils.py | https://github.com/mckinsey/vizro/blob/master/tools/pycafe/pycafe_utils.py | Apache-2.0 |
def _fetch_directory_files(config: PyCafeConfig, directory_path: str) -> list[dict]:
"""Fetch files in a directory from GitHub API."""
url = f"https://api.github.com/repos/{config.repo_name}/git/trees/{config.commit_sha}?recursive=1"
response = requests.get(url, timeout=20)
response.raise_for_status()
... | Fetch files in a directory from GitHub API. | _fetch_directory_files | python | mckinsey/vizro | tools/pycafe/pycafe_utils.py | https://github.com/mckinsey/vizro/blob/master/tools/pycafe/pycafe_utils.py | Apache-2.0 |
def generate_link(
config: PyCafeConfig,
directory_path: str,
extra_requirements: Optional[list[str]] = None,
use_latest_release: bool = False,
) -> str:
"""Generate a PyCafe link for the example dashboard."""
base_url = f"{config.vizro_raw_url}/{config.commit_sha}/{directory_path}"
# Requi... | Generate a PyCafe link for the example dashboard. | generate_link | python | mckinsey/vizro | tools/pycafe/pycafe_utils.py | https://github.com/mckinsey/vizro/blob/master/tools/pycafe/pycafe_utils.py | Apache-2.0 |
def create_status_check(
commit: Commit,
directory: str,
url: str,
state: str = "success",
description: str = "Test out the app live on PyCafe",
):
"""Create a GitHub status check for a PyCafe link."""
context = f"PyCafe Example ({directory})"
commit.create_status(state=state, target_url... | Create a GitHub status check for a PyCafe link. | create_status_check | python | mckinsey/vizro | tools/pycafe/pycafe_utils.py | https://github.com/mckinsey/vizro/blob/master/tools/pycafe/pycafe_utils.py | Apache-2.0 |
def get_example_directories() -> dict[str, Optional[list[str]]]:
"""Return a dictionary of example directories and their requirements."""
return {
"vizro-core/examples/scratch_dev": None,
"vizro-core/examples/dev/": ["openpyxl"],
"vizro-core/examples/visual-vocabulary/": [
"a... | Return a dictionary of example directories and their requirements. | get_example_directories | python | mckinsey/vizro | tools/pycafe/pycafe_utils.py | https://github.com/mckinsey/vizro/blob/master/tools/pycafe/pycafe_utils.py | Apache-2.0 |
def run_vizro_ai(user_prompt, n_clicks, data, model, api_key, api_base, vendor_input): # noqa: PLR0913
"""Gets the AI response and adds it to the text window."""
def create_response(ai_response, figure, ai_outputs):
return (ai_response, figure, {"ai_outputs": ai_outputs})
if not n_clicks:
... | Gets the AI response and adds it to the text window. | run_vizro_ai | python | mckinsey/vizro | vizro-ai/examples/dashboard_ui/actions.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/examples/dashboard_ui/actions.py | Apache-2.0 |
def display_filename(data):
"""Custom action to display uploaded filename."""
if data is None:
raise PreventUpdate
display_message = data.get("filename") or data.get("error_message")
return f"Uploaded file name: '{display_message}'" if "filename" in data else display_message | Custom action to display uploaded filename. | display_filename | python | mckinsey/vizro | vizro-ai/examples/dashboard_ui/actions.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/examples/dashboard_ui/actions.py | Apache-2.0 |
def toggle_code(value, data):
"""Callback for switching between vizro and plotly code."""
if not data:
return dash.no_update
ai_code = data["ai_outputs"]["vizro"]["code"] if value else data["ai_outputs"]["plotly"]["code"]
formatted_code = black.format_str(ai_code, mode=black.Mode(line_length=1... | Callback for switching between vizro and plotly code. | toggle_code | python | mckinsey/vizro | vizro-ai/examples/dashboard_ui/app.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/examples/dashboard_ui/app.py | Apache-2.0 |
def build(self):
"""Returns the text area component to display vizro-ai code output."""
return html.Div(
children=[
dcc.Textarea(
id=self.id,
placeholder="Describe the chart you want to create, e.g. "
"'Visualize the... | Returns the text area component to display vizro-ai code output. | build | python | mckinsey/vizro | vizro-ai/examples/dashboard_ui/components.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/examples/dashboard_ui/components.py | Apache-2.0 |
def build(self):
"""Returns the upload component for data upload."""
return html.Div(
[
dcc.Upload(
id=self.id,
children=html.Div(["Drag and Drop or ", html.A("Select Files")], id="data-upload"),
),
]
... | Returns the upload component for data upload. | build | python | mckinsey/vizro | vizro-ai/examples/dashboard_ui/components.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/examples/dashboard_ui/components.py | Apache-2.0 |
def build(self):
"""Returns the code clipboard component inside a output text area."""
code = black.format_str(self.code, mode=black.Mode(line_length=120))
code = code.strip("'\"")
markdown_code = "\n".join(["```python", code, "```"])
return dcc.Loading(
html.Div(
... | Returns the code clipboard component inside a output text area. | build | python | mckinsey/vizro | vizro-ai/examples/dashboard_ui/components.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/examples/dashboard_ui/components.py | Apache-2.0 |
def build(self):
"""Returns custom dropdown component that cannot be cleared."""
dropdown_build_obj = super().build()
dropdown_build_obj.id = f"{self.id}_outer_div"
dropdown_build_obj.children[1].clearable = False
return dropdown_build_obj | Returns custom dropdown component that cannot be cleared. | build | python | mckinsey/vizro | vizro-ai/examples/dashboard_ui/components.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/examples/dashboard_ui/components.py | Apache-2.0 |
def build(self):
"""Returns the off canvas component for settings."""
input_groups = html.Div(
[
dbc.InputGroup(
[
dbc.InputGroupText("API Key"),
dbc.Input(placeholder="API key", type="password", id=f"{self.i... | Returns the off canvas component for settings. | build | python | mckinsey/vizro | vizro-ai/examples/dashboard_ui/components.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/examples/dashboard_ui/components.py | Apache-2.0 |
def build(self):
"""Returns the icon for api settings."""
return html.Div(
children=[html.Span("settings", className="material-symbols-outlined", id=self.id)],
className="settings-div",
) | Returns the icon for api settings. | build | python | mckinsey/vizro | vizro-ai/examples/dashboard_ui/components.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/examples/dashboard_ui/components.py | Apache-2.0 |
def _get_llm_model(model: Optional[Union[BaseChatModel, str]] = None) -> BaseChatModel:
"""Fetches and initializes an instance of the LLM.
Args:
model: Model instance or model name.
Returns:
The initialized instance of the LLM.
Raises:
ValueError: If the provided model string ... | Fetches and initializes an instance of the LLM.
Args:
model: Model instance or model name.
Returns:
The initialized instance of the LLM.
Raises:
ValueError: If the provided model string does not match any pre-defined model
| _get_llm_model | python | mckinsey/vizro | vizro-ai/src/vizro_ai/_llm_models.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/src/vizro_ai/_llm_models.py | Apache-2.0 |
def __init__(self, model: Optional[Union[BaseChatModel, str]] = None):
"""Initialization of VizroAI.
Args:
model: model instance or model name.
"""
self.model = _get_llm_model(model=model)
self.components_instances = {}
# TODO add pending URL link to docs
... | Initialization of VizroAI.
Args:
model: model instance or model name.
| __init__ | python | mckinsey/vizro | vizro-ai/src/vizro_ai/_vizro_ai.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/src/vizro_ai/_vizro_ai.py | Apache-2.0 |
def plot(
self,
df: pd.DataFrame,
user_input: str,
max_debug_retry: int = 1,
return_elements: bool = False,
validate_code: bool = True,
_minimal_output: bool = False,
) -> Union[go.Figure, ChartPlan]:
"""Plot visuals using vizro via english description... | Plot visuals using vizro via english descriptions, english to chart translation.
Args:
df: The dataframe to be analyzed.
user_input: User questions or descriptions of the desired visual.
max_debug_retry: Maximum number of retries to debug errors. Defaults to `1`.
... | plot | python | mckinsey/vizro | vizro-ai/src/vizro_ai/_vizro_ai.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/src/vizro_ai/_vizro_ai.py | Apache-2.0 |
def dashboard(
self,
dfs: list[pd.DataFrame],
user_input: str,
return_elements: bool = False,
) -> Union[DashboardOutputs, vm.Dashboard]:
"""Creates a Vizro dashboard using english descriptions.
Args:
dfs: The dataframes to be analyzed.
user_i... | Creates a Vizro dashboard using english descriptions.
Args:
dfs: The dataframes to be analyzed.
user_input: User questions or descriptions of the desired visual.
return_elements: Flag to return DashboardOutputs dataclass that includes all possible elements generated.
... | dashboard | python | mckinsey/vizro | vizro-ai/src/vizro_ai/_vizro_ai.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/src/vizro_ai/_vizro_ai.py | Apache-2.0 |
def get_schemas_and_samples(self) -> dict[str, dict[str, str]]:
"""Retrieve only the df_schema and df_sample for all datasets."""
return {
name: {"df_schema": metadata.df_schema, "df_sample": metadata.df_sample}
for name, metadata in self.all_df_metadata.items()
} | Retrieve only the df_schema and df_sample for all datasets. | get_schemas_and_samples | python | mckinsey/vizro | vizro-ai/src/vizro_ai/dashboard/utils.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/src/vizro_ai/dashboard/utils.py | Apache-2.0 |
def _register_data(all_df_metadata: AllDfMetadata) -> vm.Dashboard:
"""Register the dashboard data in data manager."""
from vizro.managers import data_manager
for name, metadata in all_df_metadata.all_df_metadata.items():
data_manager[name] = metadata.df | Register the dashboard data in data manager. | _register_data | python | mckinsey/vizro | vizro-ai/src/vizro_ai/dashboard/utils.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/src/vizro_ai/dashboard/utils.py | Apache-2.0 |
def _extract_overall_imports_and_code(
custom_charts_code: list[list[dict[str, str]]], custom_charts_imports: list[list[dict[str, str]]]
) -> tuple[set[str], set[str]]:
"""Extract custom functions and imports from the custom charts code.
Args:
custom_charts_code: A list of lists of dictionaries, wh... | Extract custom functions and imports from the custom charts code.
Args:
custom_charts_code: A list of lists of dictionaries, where each dictionary
contains the custom chart code for a component.
The outer list represents pages, the inner list represents
components on a p... | _extract_overall_imports_and_code | python | mckinsey/vizro | vizro-ai/src/vizro_ai/dashboard/utils.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/src/vizro_ai/dashboard/utils.py | Apache-2.0 |
def _create_prompt_template(additional_info: str) -> ChatPromptTemplate:
"""Create the ChatPromptTemplate from the base prompt and additional info."""
return ChatPromptTemplate.from_messages(
[
("system", BASE_PROMPT.format(df_info="{df_info}", additional_info=additional_info)),
... | Create the ChatPromptTemplate from the base prompt and additional info. | _create_prompt_template | python | mckinsey/vizro | vizro-ai/src/vizro_ai/dashboard/_pydantic_output.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/src/vizro_ai/dashboard/_pydantic_output.py | Apache-2.0 |
def _create_message_content(
query: str, df_info: Any, validation_error: Optional[str] = None, retry: bool = False
) -> dict:
"""Create the message content for the LLM model."""
message_content = {"message": [HumanMessage(content=query)], "df_info": df_info}
if retry:
message_content["validatio... | Create the message content for the LLM model. | _create_message_content | python | mckinsey/vizro | vizro-ai/src/vizro_ai/dashboard/_pydantic_output.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/src/vizro_ai/dashboard/_pydantic_output.py | Apache-2.0 |
def _get_pydantic_model(
query: str,
llm_model: BaseChatModel,
response_model: BaseModel,
df_info: Optional[Any] = None, # TODO: this should potentially not be part of this function.
max_retry: int = 2,
) -> BaseModel:
# TODO: fix typing similar to instructor library, ie the return type should ... | Get the pydantic output from the LLM model with retry logic. | _get_pydantic_model | python | mckinsey/vizro | vizro-ai/src/vizro_ai/dashboard/_pydantic_output.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/src/vizro_ai/dashboard/_pydantic_output.py | Apache-2.0 |
def _continue_to_pages(state: GraphState) -> list[Send]:
"""Map-reduce logic to build pages in parallel."""
all_df_metadata = state.all_df_metadata
return [
Send(node="_build_page", arg={"page_plan": v, "all_df_metadata": all_df_metadata})
for v in state.dashboard_plan.pages
] | Map-reduce logic to build pages in parallel. | _continue_to_pages | python | mckinsey/vizro | vizro-ai/src/vizro_ai/dashboard/_graph/dashboard_creation.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/src/vizro_ai/dashboard/_graph/dashboard_creation.py | Apache-2.0 |
def create(self, model: BaseChatModel, all_df_metadata: AllDfMetadata) -> ComponentResult:
"""Create the component based on its type.
Args:
model: The llm used.
all_df_metadata: Metadata for all available dataframes.
Returns:
ComponentResult containing:
... | Create the component based on its type.
Args:
model: The llm used.
all_df_metadata: Metadata for all available dataframes.
Returns:
ComponentResult containing:
- component: The created component (vm.Card, vm.AgGrid, or vm.Graph)
- code: Optio... | create | python | mckinsey/vizro | vizro-ai/src/vizro_ai/dashboard/_response_models/components.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/src/vizro_ai/dashboard/_response_models/components.py | Apache-2.0 |
def validate_date_picker_column(cls, data: Any):
"""Validate the column for date picker."""
column = data.get("column")
selector = data.get("selector")
if selector and hasattr(selector, "type") and selector.type == "date_picker":
if not pd.api.types.is_datetime64_any_dtype(df... | Validate the column for date picker. | validate_date_picker_column | python | mckinsey/vizro | vizro-ai/src/vizro_ai/dashboard/_response_models/controls.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/src/vizro_ai/dashboard/_response_models/controls.py | Apache-2.0 |
def _get_df_info(df: pd.DataFrame) -> tuple[dict[str, str], pd.DataFrame]:
"""Get the dataframe schema and sample."""
formatted_pairs = dict(df.dtypes.astype(str))
df_sample = df.sample(5, replace=True, random_state=19)
return formatted_pairs, df_sample | Get the dataframe schema and sample. | _get_df_info | python | mckinsey/vizro | vizro-ai/src/vizro_ai/dashboard/_response_models/df_info.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/src/vizro_ai/dashboard/_response_models/df_info.py | Apache-2.0 |
def _validate_component_id_unique(components_list):
"""Validate the component id is unique."""
component_ids = [comp.component_id for comp in components_list]
duplicates = [id for id, count in Counter(component_ids).items() if count > 1]
if duplicates:
raise ValueError(f"Component ids must be un... | Validate the component id is unique. | _validate_component_id_unique | python | mckinsey/vizro | vizro-ai/src/vizro_ai/dashboard/_response_models/page.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/src/vizro_ai/dashboard/_response_models/page.py | Apache-2.0 |
def _strip_markdown(code_string: str) -> str:
"""Remove any code block wrappers (markdown or triple quotes)."""
wrappers = [("```python\n", "```"), ("```py\n", "```"), ("```\n", "```"), ('"""', '"""'), ("'''", "'''")]
for start, end in wrappers:
if code_string.startswith(start) and code_string.ends... | Remove any code block wrappers (markdown or triple quotes). | _strip_markdown | python | mckinsey/vizro | vizro-ai/src/vizro_ai/plot/_response_models.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/src/vizro_ai/plot/_response_models.py | Apache-2.0 |
def _exec_code(code: str, namespace: dict) -> dict:
"""Execute code and return the local dictionary."""
# Need the global namespace for the imports to work for executed code
# Tried just handling it in local scope, ie getting the import statement into ldict, but it didn't work
# TODO: ideally in future ... | Execute code and return the local dictionary. | _exec_code | python | mckinsey/vizro | vizro-ai/src/vizro_ai/plot/_response_models.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/src/vizro_ai/plot/_response_models.py | Apache-2.0 |
def validator_code(v, info: ValidationInfo):
"""Test the execution of the chart code."""
imports = "\n".join(info.data.get("imports", []))
code_to_validate = imports + "\n\n" + v
try:
_safeguard_check(code_to_validate)
except Exception as e:
raise ValueErr... | Test the execution of the chart code. | validator_code | python | mckinsey/vizro | vizro-ai/src/vizro_ai/plot/_response_models.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/src/vizro_ai/plot/_response_models.py | Apache-2.0 |
def get_fig_object(self, data_frame: Union[pd.DataFrame, str], chart_name: Optional[str] = None, vizro=True):
"""Execute code to obtain the plotly go.Figure object. Be sure to check code to be executed before running.
Args:
data_frame: Dataframe or string representation of the dataframe.
... | Execute code to obtain the plotly go.Figure object. Be sure to check code to be executed before running.
Args:
data_frame: Dataframe or string representation of the dataframe.
chart_name: Name of the chart function. Defaults to `None`,
in which case it remains as `custom... | get_fig_object | python | mckinsey/vizro | vizro-ai/src/vizro_ai/plot/_response_models.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/src/vizro_ai/plot/_response_models.py | Apache-2.0 |
def __new__(cls, data_frame: pd.DataFrame, chart_plan: type[BaseChartPlan] = ChartPlan) -> type[BaseChartPlan]:
"""Creates a chart plan model with additional validation.
Args:
data_frame: DataFrame to use for validation
chart_plan: Chart plan model to run extended validation aga... | Creates a chart plan model with additional validation.
Args:
data_frame: DataFrame to use for validation
chart_plan: Chart plan model to run extended validation against. Defaults to ChartPlan.
Returns:
Chart plan model with additional validation
| __new__ | python | mckinsey/vizro | vizro-ai/src/vizro_ai/plot/_response_models.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/src/vizro_ai/plot/_response_models.py | Apache-2.0 |
def _check_data_handling(node: ast.stmt):
"""Check usage of unsafe data file loading and saving."""
code = ast.unparse(node)
redlisted_data_handling = [method for method in REDLISTED_DATA_HANDLING if method in code]
if redlisted_data_handling:
methods_str = ", ".join(redlisted_data_handling)
... | Check usage of unsafe data file loading and saving. | _check_data_handling | python | mckinsey/vizro | vizro-ai/src/vizro_ai/plot/_utils/_safeguard.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/src/vizro_ai/plot/_utils/_safeguard.py | Apache-2.0 |
def _check_class_method_usage(node: ast.stmt):
"""Check usage of unsafe builtin in code."""
code = ast.unparse(node)
redlisted_builtins = [funct for funct in REDLISTED_CLASS_METHODS if funct in code]
if redlisted_builtins:
functions_str = ", ".join(redlisted_builtins)
raise Exception(
... | Check usage of unsafe builtin in code. | _check_class_method_usage | python | mckinsey/vizro | vizro-ai/src/vizro_ai/plot/_utils/_safeguard.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/src/vizro_ai/plot/_utils/_safeguard.py | Apache-2.0 |
def _check_builtin_function_usage(node: ast.stmt):
"""Check usage of unsafe builtin functions."""
code = ast.unparse(node)
builtin_list = [name for name, obj in vars(builtins).items()]
non_whitelisted_builtins = [
builtin
for builtin in builtin_list
if re.search(r"\b" + re.escap... | Check usage of unsafe builtin functions. | _check_builtin_function_usage | python | mckinsey/vizro | vizro-ai/src/vizro_ai/plot/_utils/_safeguard.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/src/vizro_ai/plot/_utils/_safeguard.py | Apache-2.0 |
def _safeguard_check(code: str):
"""Perform safeguard checks to avoid execution of malicious code."""
try:
tree = ast.parse(code)
except (SyntaxError, UnicodeDecodeError):
raise ValueError(f"Generated code is not valid: {code}")
except OverflowError:
raise ValueError(f"Generated ... | Perform safeguard checks to avoid execution of malicious code. | _safeguard_check | python | mckinsey/vizro | vizro-ai/src/vizro_ai/plot/_utils/_safeguard.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/src/vizro_ai/plot/_utils/_safeguard.py | Apache-2.0 |
def _get_df_info(df: pd.DataFrame, n_sample: int = 5) -> tuple[str, str]:
"""Get the dataframe schema and head info as string."""
formatted_pairs = [f"{col_name}: {dtype}" for col_name, dtype in df.dtypes.items()]
schema_string = "\n".join(formatted_pairs)
return schema_string, df.sample(n_sample, repla... | Get the dataframe schema and head info as string. | _get_df_info | python | mckinsey/vizro | vizro-ai/src/vizro_ai/utils/helper.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/src/vizro_ai/utils/helper.py | Apache-2.0 |
def logic( # noqa: PLR0912, PLR0913, PLR0915
dashboard,
model_name,
dash_duo,
prompt_tier,
prompt_name,
prompt_text,
config: dict,
):
"""Calculates all separate scores. Creates csv report.
Attributes:
dashboard: VizroAI generated dashboard
model_name: GenAI model na... | Calculates all separate scores. Creates csv report.
Attributes:
dashboard: VizroAI generated dashboard
model_name: GenAI model name
dash_duo: dash_duo fixture
prompt_tier: complexity of the prompt
prompt_name: short prompt description
prompt_text: prompt text
... | logic | python | mckinsey/vizro | vizro-ai/tests/e2e/test_dashboard.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/tests/e2e/test_dashboard.py | Apache-2.0 |
def test_chart_plan_factory_validation_failure(sample_df):
"""Test factory validation fails with invalid code."""
ValidatedModel = ChartPlanFactory(data_frame=sample_df, chart_plan=BaseChartPlan)
with pytest.raises(ValueError, match="The chart code must be wrapped in a function named"):
ValidatedMo... | Test factory validation fails with invalid code. | test_chart_plan_factory_validation_failure | python | mckinsey/vizro | vizro-ai/tests/unit/vizro-ai/plot/test_response_model.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/tests/unit/vizro-ai/plot/test_response_model.py | Apache-2.0 |
def test_chart_plan_factory_preserves_fields(sample_df, valid_chart_code):
"""Test factory preserves all fields from base class."""
ValidatedModel = ChartPlanFactory(data_frame=sample_df, chart_plan=ChartPlan)
instance = ValidatedModel(
chart_type="scatter",
imports=["import plotly.express ... | Test factory preserves all fields from base class. | test_chart_plan_factory_preserves_fields | python | mckinsey/vizro | vizro-ai/tests/unit/vizro-ai/plot/test_response_model.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/tests/unit/vizro-ai/plot/test_response_model.py | Apache-2.0 |
def test_base_chart_plan_no_explanatory_fields(valid_chart_code):
"""Test BaseChartPlan doesn't have explanatory fields."""
instance = BaseChartPlan(chart_type="scatter", imports=["import plotly.express as px"], chart_code=valid_chart_code)
with pytest.raises(AttributeError):
_ = instance.chart_ins... | Test BaseChartPlan doesn't have explanatory fields. | test_base_chart_plan_no_explanatory_fields | python | mckinsey/vizro | vizro-ai/tests/unit/vizro-ai/plot/test_response_model.py | https://github.com/mckinsey/vizro/blob/master/vizro-ai/tests/unit/vizro-ai/plot/test_response_model.py | Apache-2.0 |
def make_subheading(label, link):
"""Creates a subheading with a link to the docs."""
slug = label.replace(" ", "")
heading = html.H3(
html.Span(
[
label,
html.A(
html.I(className="bi bi-book h4 ms-2"),
href=f"{DBC_D... | Creates a subheading with a link to the docs. | make_subheading | python | mckinsey/vizro | vizro-core/examples/bootstrap/app.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/examples/bootstrap/app.py | Apache-2.0 |
def scatter_with_line(data_frame, x, y, hline=None, title=None):
"""Custom scatter chart based on px."""
fig = px.scatter(data_frame=data_frame, x=x, y=y, title=title)
fig.add_hline(y=hline, line_color="orange")
return fig | Custom scatter chart based on px. | scatter_with_line | python | mckinsey/vizro | vizro-core/examples/dev/app.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/examples/dev/app.py | Apache-2.0 |
def waterfall(data_frame, measure, x, y, text, title=None):
"""Custom waterfall chart based on go."""
fig = go.Figure()
fig.add_traces(
go.Waterfall(
measure=data_frame[measure],
x=data_frame[x],
y=data_frame[y],
text=data_frame[text],
decr... | Custom waterfall chart based on go. | waterfall | python | mckinsey/vizro | vizro-core/examples/dev/app.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/examples/dev/app.py | Apache-2.0 |
def my_custom_table(data_frame=None, chosen_columns: Optional[list[str]] = None):
"""Custom table with added logic to filter on chosen columns."""
columns = [{"name": i, "id": i} for i in chosen_columns]
defaults = {
"style_as_list_view": True,
"style_data": {"border_bottom": "1px solid var(... | Custom table with added logic to filter on chosen columns. | my_custom_table | python | mckinsey/vizro | vizro-core/examples/dev/app.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/examples/dev/app.py | Apache-2.0 |
def build(self):
"""Extend existing component by calling the super build and update properties."""
range_slider_build_obj = super().build()
range_slider_build_obj[self.id].allowCross = False
range_slider_build_obj[self.id].tooltip = {"always_visible": True, "placement": "bottom"}
... | Extend existing component by calling the super build and update properties. | build | python | mckinsey/vizro | vizro-core/examples/dev/app.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/examples/dev/app.py | Apache-2.0 |
def multiple_cards(data_frame: pd.DataFrame, n_rows: Optional[int] = 1) -> html.Div:
"""Creates a list with a variable number of `vm.Card` components from the provided data_frame.
Args:
data_frame: Data frame containing the data.
n_rows: Number of rows to use from the data_frame. Defaults to 1.... | Creates a list with a variable number of `vm.Card` components from the provided data_frame.
Args:
data_frame: Data frame containing the data.
n_rows: Number of rows to use from the data_frame. Defaults to 1.
Returns:
html.Div with a list of dbc.Card objects generated from the data.
... | multiple_cards | python | mckinsey/vizro | vizro-core/examples/dev/app.py | https://github.com/mckinsey/vizro/blob/master/vizro-core/examples/dev/app.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.