We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Replace Exception in st.foo() with StreamlitAPIException
Main places we do this today:
graphviz_chart.py
map.py

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `lib/streamlit/elements/graphviz_chart.py`
Content:
```
1 # Copyright 2018-2020 Streamlit Inc.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 #    http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 
15 """Streamlit support for GraphViz charts."""
16 
17 from streamlit import type_util
18 from streamlit.logger import get_logger
19 from streamlit.proto.GraphVizChart_pb2 import GraphVizChart as GraphVizChartProto
20 
21 LOGGER = get_logger(__name__)
22 
23 
24 class GraphvizMixin:
25     def graphviz_chart(dg, figure_or_dot, width=0, height=0, use_container_width=False):
26         """Display a graph using the dagre-d3 library.
27 
28         Parameters
29         ----------
30         figure_or_dot : graphviz.dot.Graph, graphviz.dot.Digraph, str
31             The Graphlib graph object or dot string to display
32 
33         width : number
34             Deprecated. If != 0 (default), will show an alert.
35             From now on you should set the width directly in the Graphviz
36             spec. Please refer to the Graphviz documentation for details.
37 
38         height : number
39             Deprecated. If != 0 (default), will show an alert.
40             From now on you should set the height directly in the Graphviz
41             spec. Please refer to the Graphviz documentation for details.
42 
43         use_container_width : bool
44             If True, set the chart width to the column width. This takes
45             precedence over the figure's native `width` value.
46 
47         Example
48         -------
49 
50         >>> import streamlit as st
51         >>> import graphviz as graphviz
52         >>>
53         >>> # Create a graphlib graph object
54         >>> graph = graphviz.Digraph()
55         >>> graph.edge('run', 'intr')
56         >>> graph.edge('intr', 'runbl')
57         >>> graph.edge('runbl', 'run')
58         >>> graph.edge('run', 'kernel')
59         >>> graph.edge('kernel', 'zombie')
60         >>> graph.edge('kernel', 'sleep')
61         >>> graph.edge('kernel', 'runmem')
62         >>> graph.edge('sleep', 'swap')
63         >>> graph.edge('swap', 'runswap')
64         >>> graph.edge('runswap', 'new')
65         >>> graph.edge('runswap', 'runmem')
66         >>> graph.edge('new', 'runmem')
67         >>> graph.edge('sleep', 'runmem')
68         >>>
69         >>> st.graphviz_chart(graph)
70 
71         Or you can render the chart from the graph using GraphViz's Dot
72         language:
73 
74         >>> st.graphviz_chart('''
75             digraph {
76                 run -> intr
77                 intr -> runbl
78                 runbl -> run
79                 run -> kernel
80                 kernel -> zombie
81                 kernel -> sleep
82                 kernel -> runmem
83                 sleep -> swap
84                 swap -> runswap
85                 runswap -> new
86                 runswap -> runmem
87                 new -> runmem
88                 sleep -> runmem
89             }
90         ''')
91 
92         .. output::
93            https://share.streamlit.io/0.56.0-xTAd/index.html?id=GBn3GXZie5K1kXuBKe4yQL
94            height: 400px
95 
96         """
97         if width != 0 and height != 0:
98             import streamlit as st
99 
100             st.warning(
101                 "The `width` and `height` arguments in `st.graphviz` are deprecated and will be removed on 2020-03-04"
102             )
103         elif width != 0:
104             import streamlit as st
105 
106             st.warning(
107                 "The `width` argument in `st.graphviz` is deprecated and will be removed on 2020-03-04"
108             )
109         elif height != 0:
110             import streamlit as st
111 
112             st.warning(
113                 "The `height` argument in `st.graphviz` is deprecated and will be removed on 2020-03-04"
114             )
115 
116         graphviz_chart_proto = GraphVizChartProto()
117         marshall(graphviz_chart_proto, figure_or_dot, use_container_width)
118         return dg._enqueue("graphviz_chart", graphviz_chart_proto)  # type: ignore
119 
120 
121 def marshall(proto, figure_or_dot, use_container_width):
122     """Construct a GraphViz chart object.
123 
124     See DeltaGenerator.graphviz_chart for docs.
125     """
126 
127     if type_util.is_graphviz_chart(figure_or_dot):
128         dot = figure_or_dot.source
129     elif isinstance(figure_or_dot, str):
130         dot = figure_or_dot
131     else:
132         raise Exception("Unhandled type for graphviz chart: %s" % type(figure_or_dot))
133 
134     proto.spec = dot
135     proto.use_container_width = use_container_width
136
```

Path: `lib/streamlit/elements/map.py`
Content:
```
1 # Copyright 2018-2020 Streamlit Inc.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 #    http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 
15 """A wrapper for simple PyDeck scatter charts."""
16 
17 import copy
18 import json
19 from typing import Any, Dict
20 
21 import pandas as pd
22 
23 from streamlit.proto.DeckGlJsonChart_pb2 import DeckGlJsonChart as DeckGlJsonChartProto
24 import streamlit.elements.deck_gl_json_chart as deck_gl_json_chart
25 
26 
27 class MapMixin:
28     def map(dg, data=None, zoom=None, use_container_width=True):
29         """Display a map with points on it.
30 
31         This is a wrapper around st.pydeck_chart to quickly create scatterplot
32         charts on top of a map, with auto-centering and auto-zoom.
33 
34         When using this command, we advise all users to use a personal Mapbox
35         token. This ensures the map tiles used in this chart are more
36         robust. You can do this with the mapbox.token config option.
37 
38         To get a token for yourself, create an account at
39         https://mapbox.com. It's free! (for moderate usage levels) See
40         https://docs.streamlit.io/en/latest/cli.html#view-all-config-options for more
41         info on how to set config options.
42 
43         Parameters
44         ----------
45         data : pandas.DataFrame, pandas.Styler, numpy.ndarray, Iterable, dict,
46             or None
47             The data to be plotted. Must have columns called 'lat', 'lon',
48             'latitude', or 'longitude'.
49         zoom : int
50             Zoom level as specified in
51             https://wiki.openstreetmap.org/wiki/Zoom_levels
52 
53         Example
54         -------
55         >>> import pandas as pd
56         >>> import numpy as np
57         >>>
58         >>> df = pd.DataFrame(
59         ...     np.random.randn(1000, 2) / [50, 50] + [37.76, -122.4],
60         ...     columns=['lat', 'lon'])
61         >>>
62         >>> st.map(df)
63 
64         .. output::
65            https://share.streamlit.io/0.53.0-SULT/index.html?id=9gTiomqPEbvHY2huTLoQtH
66            height: 600px
67 
68         """
69         map_proto = DeckGlJsonChartProto()
70         map_proto.json = to_deckgl_json(data, zoom)
71         map_proto.use_container_width = use_container_width
72         return dg._enqueue("deck_gl_json_chart", map_proto)  # type: ignore
73 
74 
75 # Map used as the basis for st.map.
76 _DEFAULT_MAP = dict(deck_gl_json_chart.EMPTY_MAP)  # type: Dict[str, Any]
77 _DEFAULT_MAP["mapStyle"] = "mapbox://styles/mapbox/light-v10"
78 
79 # Other default parameters for st.map.
80 _DEFAULT_COLOR = [200, 30, 0, 160]
81 _ZOOM_LEVELS = [
82     360,
83     180,
84     90,
85     45,
86     22.5,
87     11.25,
88     5.625,
89     2.813,
90     1.406,
91     0.703,
92     0.352,
93     0.176,
94     0.088,
95     0.044,
96     0.022,
97     0.011,
98     0.005,
99     0.003,
100     0.001,
101     0.0005,
102 ]
103 
104 
105 def _get_zoom_level(distance):
106     """Get the zoom level for a given distance in degrees.
107 
108     See https://wiki.openstreetmap.org/wiki/Zoom_levels for reference.
109 
110     Parameters
111     ----------
112     distance : float
113         How many degrees of longitude should fit in the map.
114 
115     Returns
116     -------
117     int
118         The zoom level, from 0 to 29.
119 
120     """
121 
122     for i in range(len(_ZOOM_LEVELS) - 1):
123         if _ZOOM_LEVELS[i + 1] < distance <= _ZOOM_LEVELS[i]:
124             return i
125 
126 
127 def to_deckgl_json(data, zoom):
128 
129     if data is None or data.empty:
130         return json.dumps(_DEFAULT_MAP)
131 
132     if "lat" in data:
133         lat = "lat"
134     elif "latitude" in data:
135         lat = "latitude"
136     else:
137         raise Exception('Map data must contain a column named "latitude" or "lat".')
138 
139     if "lon" in data:
140         lon = "lon"
141     elif "longitude" in data:
142         lon = "longitude"
143     else:
144         raise Exception('Map data must contain a column called "longitude" or "lon".')
145 
146     if data[lon].isnull().values.any() or data[lat].isnull().values.any():
147         raise Exception("Latitude and longitude data must be numeric.")
148 
149     data = pd.DataFrame(data)
150 
151     min_lat = data[lat].min()
152     max_lat = data[lat].max()
153     min_lon = data[lon].min()
154     max_lon = data[lon].max()
155     center_lat = (max_lat + min_lat) / 2.0
156     center_lon = (max_lon + min_lon) / 2.0
157     range_lon = abs(max_lon - min_lon)
158     range_lat = abs(max_lat - min_lat)
159 
160     if zoom == None:
161         if range_lon > range_lat:
162             longitude_distance = range_lon
163         else:
164             longitude_distance = range_lat
165         zoom = _get_zoom_level(longitude_distance)
166 
167     # "+1" because itertuples includes the row index.
168     lon_col_index = data.columns.get_loc(lon) + 1
169     lat_col_index = data.columns.get_loc(lat) + 1
170     final_data = []
171     for row in data.itertuples():
172         final_data.append(
173             {"lon": float(row[lon_col_index]), "lat": float(row[lat_col_index])}
174         )
175 
176     default = copy.deepcopy(_DEFAULT_MAP)
177     default["initialViewState"]["latitude"] = center_lat
178     default["initialViewState"]["longitude"] = center_lon
179     default["initialViewState"]["zoom"] = zoom
180     default["layers"] = [
181         {
182             "@@type": "ScatterplotLayer",
183             "getPosition": "@@=[lon, lat]",
184             "getRadius": 10,
185             "radiusScale": 10,
186             "radiusMinPixels": 3,
187             "getFillColor": _DEFAULT_COLOR,
188             "data": final_data,
189         }
190     ]
191     return json.dumps(default)
192
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/lib/streamlit/elements/graphviz_chart.py b/lib/streamlit/elements/graphviz_chart.py
--- a/lib/streamlit/elements/graphviz_chart.py
+++ b/lib/streamlit/elements/graphviz_chart.py
@@ -17,6 +17,7 @@
 from streamlit import type_util
 from streamlit.logger import get_logger
 from streamlit.proto.GraphVizChart_pb2 import GraphVizChart as GraphVizChartProto
+from streamlit.errors import StreamlitAPIException
 
 LOGGER = get_logger(__name__)
 
@@ -129,7 +130,9 @@
     elif isinstance(figure_or_dot, str):
         dot = figure_or_dot
     else:
-        raise Exception("Unhandled type for graphviz chart: %s" % type(figure_or_dot))
+        raise StreamlitAPIException(
+            "Unhandled type for graphviz chart: %s" % type(figure_or_dot)
+        )
 
     proto.spec = dot
     proto.use_container_width = use_container_width
diff --git a/lib/streamlit/elements/map.py b/lib/streamlit/elements/map.py
--- a/lib/streamlit/elements/map.py
+++ b/lib/streamlit/elements/map.py
@@ -22,6 +22,7 @@
 
 from streamlit.proto.DeckGlJsonChart_pb2 import DeckGlJsonChart as DeckGlJsonChartProto
 import streamlit.elements.deck_gl_json_chart as deck_gl_json_chart
+from streamlit.errors import StreamlitAPIException
 
 
 class MapMixin:
@@ -134,17 +135,21 @@
     elif "latitude" in data:
         lat = "latitude"
     else:
-        raise Exception('Map data must contain a column named "latitude" or "lat".')
+        raise StreamlitAPIException(
+            'Map data must contain a column named "latitude" or "lat".'
+        )
 
     if "lon" in data:
         lon = "lon"
     elif "longitude" in data:
         lon = "longitude"
     else:
-        raise Exception('Map data must contain a column called "longitude" or "lon".')
+        raise StreamlitAPIException(
+            'Map data must contain a column called "longitude" or "lon".'
+        )
 
     if data[lon].isnull().values.any() or data[lat].isnull().values.any():
-        raise Exception("Latitude and longitude data must be numeric.")
+        raise StreamlitAPIException("Latitude and longitude data must be numeric.")
 
     data = pd.DataFrame(data)

{"golden_diff": "diff --git a/lib/streamlit/elements/graphviz_chart.py b/lib/streamlit/elements/graphviz_chart.py\n--- a/lib/streamlit/elements/graphviz_chart.py\n+++ b/lib/streamlit/elements/graphviz_chart.py\n@@ -17,6 +17,7 @@\n from streamlit import type_util\n from streamlit.logger import get_logger\n from streamlit.proto.GraphVizChart_pb2 import GraphVizChart as GraphVizChartProto\n+from streamlit.errors import StreamlitAPIException\n \n LOGGER = get_logger(__name__)\n \n@@ -129,7 +130,9 @@\n     elif isinstance(figure_or_dot, str):\n         dot = figure_or_dot\n     else:\n-        raise Exception(\"Unhandled type for graphviz chart: %s\" % type(figure_or_dot))\n+        raise StreamlitAPIException(\n+            \"Unhandled type for graphviz chart: %s\" % type(figure_or_dot)\n+        )\n \n     proto.spec = dot\n     proto.use_container_width = use_container_width\ndiff --git a/lib/streamlit/elements/map.py b/lib/streamlit/elements/map.py\n--- a/lib/streamlit/elements/map.py\n+++ b/lib/streamlit/elements/map.py\n@@ -22,6 +22,7 @@\n \n from streamlit.proto.DeckGlJsonChart_pb2 import DeckGlJsonChart as DeckGlJsonChartProto\n import streamlit.elements.deck_gl_json_chart as deck_gl_json_chart\n+from streamlit.errors import StreamlitAPIException\n \n \n class MapMixin:\n@@ -134,17 +135,21 @@\n     elif \"latitude\" in data:\n         lat = \"latitude\"\n     else:\n-        raise Exception('Map data must contain a column named \"latitude\" or \"lat\".')\n+        raise StreamlitAPIException(\n+            'Map data must contain a column named \"latitude\" or \"lat\".'\n+        )\n \n     if \"lon\" in data:\n         lon = \"lon\"\n     elif \"longitude\" in data:\n         lon = \"longitude\"\n     else:\n-        raise Exception('Map data must contain a column called \"longitude\" or \"lon\".')\n+        raise StreamlitAPIException(\n+            'Map data must contain a column called \"longitude\" or \"lon\".'\n+        )\n \n     if data[lon].isnull().values.any() or data[lat].isnull().values.any():\n-        raise Exception(\"Latitude and longitude data must be numeric.\")\n+        raise StreamlitAPIException(\"Latitude and longitude data must be numeric.\")\n \n     data = pd.DataFrame(data)\n", "issue": "Replace Exception in st.foo() with StreamlitAPIException\nMain places we do this today:\r\ngraphviz_chart.py\r\nmap.py\n", "before_files": [{"content": "# Copyright 2018-2020 Streamlit Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#    http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Streamlit support for GraphViz charts.\"\"\"\n\nfrom streamlit import type_util\nfrom streamlit.logger import get_logger\nfrom streamlit.proto.GraphVizChart_pb2 import GraphVizChart as GraphVizChartProto\n\nLOGGER = get_logger(__name__)\n\n\nclass GraphvizMixin:\n    def graphviz_chart(dg, figure_or_dot, width=0, height=0, use_container_width=False):\n        \"\"\"Display a graph using the dagre-d3 library.\n\n        Parameters\n        ----------\n        figure_or_dot : graphviz.dot.Graph, graphviz.dot.Digraph, str\n            The Graphlib graph object or dot string to display\n\n        width : number\n            Deprecated. If != 0 (default), will show an alert.\n            From now on you should set the width directly in the Graphviz\n            spec. Please refer to the Graphviz documentation for details.\n\n        height : number\n            Deprecated. If != 0 (default), will show an alert.\n            From now on you should set the height directly in the Graphviz\n            spec. Please refer to the Graphviz documentation for details.\n\n        use_container_width : bool\n            If True, set the chart width to the column width. This takes\n            precedence over the figure's native `width` value.\n\n        Example\n        -------\n\n        >>> import streamlit as st\n        >>> import graphviz as graphviz\n        >>>\n        >>> # Create a graphlib graph object\n        >>> graph = graphviz.Digraph()\n        >>> graph.edge('run', 'intr')\n        >>> graph.edge('intr', 'runbl')\n        >>> graph.edge('runbl', 'run')\n        >>> graph.edge('run', 'kernel')\n        >>> graph.edge('kernel', 'zombie')\n        >>> graph.edge('kernel', 'sleep')\n        >>> graph.edge('kernel', 'runmem')\n        >>> graph.edge('sleep', 'swap')\n        >>> graph.edge('swap', 'runswap')\n        >>> graph.edge('runswap', 'new')\n        >>> graph.edge('runswap', 'runmem')\n        >>> graph.edge('new', 'runmem')\n        >>> graph.edge('sleep', 'runmem')\n        >>>\n        >>> st.graphviz_chart(graph)\n\n        Or you can render the chart from the graph using GraphViz's Dot\n        language:\n\n        >>> st.graphviz_chart('''\n            digraph {\n                run -> intr\n                intr -> runbl\n                runbl -> run\n                run -> kernel\n                kernel -> zombie\n                kernel -> sleep\n                kernel -> runmem\n                sleep -> swap\n                swap -> runswap\n                runswap -> new\n                runswap -> runmem\n                new -> runmem\n                sleep -> runmem\n            }\n        ''')\n\n        .. output::\n           https://share.streamlit.io/0.56.0-xTAd/index.html?id=GBn3GXZie5K1kXuBKe4yQL\n           height: 400px\n\n        \"\"\"\n        if width != 0 and height != 0:\n            import streamlit as st\n\n            st.warning(\n                \"The `width` and `height` arguments in `st.graphviz` are deprecated and will be removed on 2020-03-04\"\n            )\n        elif width != 0:\n            import streamlit as st\n\n            st.warning(\n                \"The `width` argument in `st.graphviz` is deprecated and will be removed on 2020-03-04\"\n            )\n        elif height != 0:\n            import streamlit as st\n\n            st.warning(\n                \"The `height` argument in `st.graphviz` is deprecated and will be removed on 2020-03-04\"\n            )\n\n        graphviz_chart_proto = GraphVizChartProto()\n        marshall(graphviz_chart_proto, figure_or_dot, use_container_width)\n        return dg._enqueue(\"graphviz_chart\", graphviz_chart_proto)  # type: ignore\n\n\ndef marshall(proto, figure_or_dot, use_container_width):\n    \"\"\"Construct a GraphViz chart object.\n\n    See DeltaGenerator.graphviz_chart for docs.\n    \"\"\"\n\n    if type_util.is_graphviz_chart(figure_or_dot):\n        dot = figure_or_dot.source\n    elif isinstance(figure_or_dot, str):\n        dot = figure_or_dot\n    else:\n        raise Exception(\"Unhandled type for graphviz chart: %s\" % type(figure_or_dot))\n\n    proto.spec = dot\n    proto.use_container_width = use_container_width\n", "path": "lib/streamlit/elements/graphviz_chart.py"}, {"content": "# Copyright 2018-2020 Streamlit Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#    http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"A wrapper for simple PyDeck scatter charts.\"\"\"\n\nimport copy\nimport json\nfrom typing import Any, Dict\n\nimport pandas as pd\n\nfrom streamlit.proto.DeckGlJsonChart_pb2 import DeckGlJsonChart as DeckGlJsonChartProto\nimport streamlit.elements.deck_gl_json_chart as deck_gl_json_chart\n\n\nclass MapMixin:\n    def map(dg, data=None, zoom=None, use_container_width=True):\n        \"\"\"Display a map with points on it.\n\n        This is a wrapper around st.pydeck_chart to quickly create scatterplot\n        charts on top of a map, with auto-centering and auto-zoom.\n\n        When using this command, we advise all users to use a personal Mapbox\n        token. This ensures the map tiles used in this chart are more\n        robust. You can do this with the mapbox.token config option.\n\n        To get a token for yourself, create an account at\n        https://mapbox.com. It's free! (for moderate usage levels) See\n        https://docs.streamlit.io/en/latest/cli.html#view-all-config-options for more\n        info on how to set config options.\n\n        Parameters\n        ----------\n        data : pandas.DataFrame, pandas.Styler, numpy.ndarray, Iterable, dict,\n            or None\n            The data to be plotted. Must have columns called 'lat', 'lon',\n            'latitude', or 'longitude'.\n        zoom : int\n            Zoom level as specified in\n            https://wiki.openstreetmap.org/wiki/Zoom_levels\n\n        Example\n        -------\n        >>> import pandas as pd\n        >>> import numpy as np\n        >>>\n        >>> df = pd.DataFrame(\n        ...     np.random.randn(1000, 2) / [50, 50] + [37.76, -122.4],\n        ...     columns=['lat', 'lon'])\n        >>>\n        >>> st.map(df)\n\n        .. output::\n           https://share.streamlit.io/0.53.0-SULT/index.html?id=9gTiomqPEbvHY2huTLoQtH\n           height: 600px\n\n        \"\"\"\n        map_proto = DeckGlJsonChartProto()\n        map_proto.json = to_deckgl_json(data, zoom)\n        map_proto.use_container_width = use_container_width\n        return dg._enqueue(\"deck_gl_json_chart\", map_proto)  # type: ignore\n\n\n# Map used as the basis for st.map.\n_DEFAULT_MAP = dict(deck_gl_json_chart.EMPTY_MAP)  # type: Dict[str, Any]\n_DEFAULT_MAP[\"mapStyle\"] = \"mapbox://styles/mapbox/light-v10\"\n\n# Other default parameters for st.map.\n_DEFAULT_COLOR = [200, 30, 0, 160]\n_ZOOM_LEVELS = [\n    360,\n    180,\n    90,\n    45,\n    22.5,\n    11.25,\n    5.625,\n    2.813,\n    1.406,\n    0.703,\n    0.352,\n    0.176,\n    0.088,\n    0.044,\n    0.022,\n    0.011,\n    0.005,\n    0.003,\n    0.001,\n    0.0005,\n]\n\n\ndef _get_zoom_level(distance):\n    \"\"\"Get the zoom level for a given distance in degrees.\n\n    See https://wiki.openstreetmap.org/wiki/Zoom_levels for reference.\n\n    Parameters\n    ----------\n    distance : float\n        How many degrees of longitude should fit in the map.\n\n    Returns\n    -------\n    int\n        The zoom level, from 0 to 29.\n\n    \"\"\"\n\n    for i in range(len(_ZOOM_LEVELS) - 1):\n        if _ZOOM_LEVELS[i + 1] < distance <= _ZOOM_LEVELS[i]:\n            return i\n\n\ndef to_deckgl_json(data, zoom):\n\n    if data is None or data.empty:\n        return json.dumps(_DEFAULT_MAP)\n\n    if \"lat\" in data:\n        lat = \"lat\"\n    elif \"latitude\" in data:\n        lat = \"latitude\"\n    else:\n        raise Exception('Map data must contain a column named \"latitude\" or \"lat\".')\n\n    if \"lon\" in data:\n        lon = \"lon\"\n    elif \"longitude\" in data:\n        lon = \"longitude\"\n    else:\n        raise Exception('Map data must contain a column called \"longitude\" or \"lon\".')\n\n    if data[lon].isnull().values.any() or data[lat].isnull().values.any():\n        raise Exception(\"Latitude and longitude data must be numeric.\")\n\n    data = pd.DataFrame(data)\n\n    min_lat = data[lat].min()\n    max_lat = data[lat].max()\n    min_lon = data[lon].min()\n    max_lon = data[lon].max()\n    center_lat = (max_lat + min_lat) / 2.0\n    center_lon = (max_lon + min_lon) / 2.0\n    range_lon = abs(max_lon - min_lon)\n    range_lat = abs(max_lat - min_lat)\n\n    if zoom == None:\n        if range_lon > range_lat:\n            longitude_distance = range_lon\n        else:\n            longitude_distance = range_lat\n        zoom = _get_zoom_level(longitude_distance)\n\n    # \"+1\" because itertuples includes the row index.\n    lon_col_index = data.columns.get_loc(lon) + 1\n    lat_col_index = data.columns.get_loc(lat) + 1\n    final_data = []\n    for row in data.itertuples():\n        final_data.append(\n            {\"lon\": float(row[lon_col_index]), \"lat\": float(row[lat_col_index])}\n        )\n\n    default = copy.deepcopy(_DEFAULT_MAP)\n    default[\"initialViewState\"][\"latitude\"] = center_lat\n    default[\"initialViewState\"][\"longitude\"] = center_lon\n    default[\"initialViewState\"][\"zoom\"] = zoom\n    default[\"layers\"] = [\n        {\n            \"@@type\": \"ScatterplotLayer\",\n            \"getPosition\": \"@@=[lon, lat]\",\n            \"getRadius\": 10,\n            \"radiusScale\": 10,\n            \"radiusMinPixels\": 3,\n            \"getFillColor\": _DEFAULT_COLOR,\n            \"data\": final_data,\n        }\n    ]\n    return json.dumps(default)\n", "path": "lib/streamlit/elements/map.py"}], "after_files": [{"content": "# Copyright 2018-2020 Streamlit Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#    http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Streamlit support for GraphViz charts.\"\"\"\n\nfrom streamlit import type_util\nfrom streamlit.logger import get_logger\nfrom streamlit.proto.GraphVizChart_pb2 import GraphVizChart as GraphVizChartProto\nfrom streamlit.errors import StreamlitAPIException\n\nLOGGER = get_logger(__name__)\n\n\nclass GraphvizMixin:\n    def graphviz_chart(dg, figure_or_dot, width=0, height=0, use_container_width=False):\n        \"\"\"Display a graph using the dagre-d3 library.\n\n        Parameters\n        ----------\n        figure_or_dot : graphviz.dot.Graph, graphviz.dot.Digraph, str\n            The Graphlib graph object or dot string to display\n\n        width : number\n            Deprecated. If != 0 (default), will show an alert.\n            From now on you should set the width directly in the Graphviz\n            spec. Please refer to the Graphviz documentation for details.\n\n        height : number\n            Deprecated. If != 0 (default), will show an alert.\n            From now on you should set the height directly in the Graphviz\n            spec. Please refer to the Graphviz documentation for details.\n\n        use_container_width : bool\n            If True, set the chart width to the column width. This takes\n            precedence over the figure's native `width` value.\n\n        Example\n        -------\n\n        >>> import streamlit as st\n        >>> import graphviz as graphviz\n        >>>\n        >>> # Create a graphlib graph object\n        >>> graph = graphviz.Digraph()\n        >>> graph.edge('run', 'intr')\n        >>> graph.edge('intr', 'runbl')\n        >>> graph.edge('runbl', 'run')\n        >>> graph.edge('run', 'kernel')\n        >>> graph.edge('kernel', 'zombie')\n        >>> graph.edge('kernel', 'sleep')\n        >>> graph.edge('kernel', 'runmem')\n        >>> graph.edge('sleep', 'swap')\n        >>> graph.edge('swap', 'runswap')\n        >>> graph.edge('runswap', 'new')\n        >>> graph.edge('runswap', 'runmem')\n        >>> graph.edge('new', 'runmem')\n        >>> graph.edge('sleep', 'runmem')\n        >>>\n        >>> st.graphviz_chart(graph)\n\n        Or you can render the chart from the graph using GraphViz's Dot\n        language:\n\n        >>> st.graphviz_chart('''\n            digraph {\n                run -> intr\n                intr -> runbl\n                runbl -> run\n                run -> kernel\n                kernel -> zombie\n                kernel -> sleep\n                kernel -> runmem\n                sleep -> swap\n                swap -> runswap\n                runswap -> new\n                runswap -> runmem\n                new -> runmem\n                sleep -> runmem\n            }\n        ''')\n\n        .. output::\n           https://share.streamlit.io/0.56.0-xTAd/index.html?id=GBn3GXZie5K1kXuBKe4yQL\n           height: 400px\n\n        \"\"\"\n        if width != 0 and height != 0:\n            import streamlit as st\n\n            st.warning(\n                \"The `width` and `height` arguments in `st.graphviz` are deprecated and will be removed on 2020-03-04\"\n            )\n        elif width != 0:\n            import streamlit as st\n\n            st.warning(\n                \"The `width` argument in `st.graphviz` is deprecated and will be removed on 2020-03-04\"\n            )\n        elif height != 0:\n            import streamlit as st\n\n            st.warning(\n                \"The `height` argument in `st.graphviz` is deprecated and will be removed on 2020-03-04\"\n            )\n\n        graphviz_chart_proto = GraphVizChartProto()\n        marshall(graphviz_chart_proto, figure_or_dot, use_container_width)\n        return dg._enqueue(\"graphviz_chart\", graphviz_chart_proto)  # type: ignore\n\n\ndef marshall(proto, figure_or_dot, use_container_width):\n    \"\"\"Construct a GraphViz chart object.\n\n    See DeltaGenerator.graphviz_chart for docs.\n    \"\"\"\n\n    if type_util.is_graphviz_chart(figure_or_dot):\n        dot = figure_or_dot.source\n    elif isinstance(figure_or_dot, str):\n        dot = figure_or_dot\n    else:\n        raise StreamlitAPIException(\n            \"Unhandled type for graphviz chart: %s\" % type(figure_or_dot)\n        )\n\n    proto.spec = dot\n    proto.use_container_width = use_container_width\n", "path": "lib/streamlit/elements/graphviz_chart.py"}, {"content": "# Copyright 2018-2020 Streamlit Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#    http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"A wrapper for simple PyDeck scatter charts.\"\"\"\n\nimport copy\nimport json\nfrom typing import Any, Dict\n\nimport pandas as pd\n\nfrom streamlit.proto.DeckGlJsonChart_pb2 import DeckGlJsonChart as DeckGlJsonChartProto\nimport streamlit.elements.deck_gl_json_chart as deck_gl_json_chart\nfrom streamlit.errors import StreamlitAPIException\n\n\nclass MapMixin:\n    def map(dg, data=None, zoom=None, use_container_width=True):\n        \"\"\"Display a map with points on it.\n\n        This is a wrapper around st.pydeck_chart to quickly create scatterplot\n        charts on top of a map, with auto-centering and auto-zoom.\n\n        When using this command, we advise all users to use a personal Mapbox\n        token. This ensures the map tiles used in this chart are more\n        robust. You can do this with the mapbox.token config option.\n\n        To get a token for yourself, create an account at\n        https://mapbox.com. It's free! (for moderate usage levels) See\n        https://docs.streamlit.io/en/latest/cli.html#view-all-config-options for more\n        info on how to set config options.\n\n        Parameters\n        ----------\n        data : pandas.DataFrame, pandas.Styler, numpy.ndarray, Iterable, dict,\n            or None\n            The data to be plotted. Must have columns called 'lat', 'lon',\n            'latitude', or 'longitude'.\n        zoom : int\n            Zoom level as specified in\n            https://wiki.openstreetmap.org/wiki/Zoom_levels\n\n        Example\n        -------\n        >>> import pandas as pd\n        >>> import numpy as np\n        >>>\n        >>> df = pd.DataFrame(\n        ...     np.random.randn(1000, 2) / [50, 50] + [37.76, -122.4],\n        ...     columns=['lat', 'lon'])\n        >>>\n        >>> st.map(df)\n\n        .. output::\n           https://share.streamlit.io/0.53.0-SULT/index.html?id=9gTiomqPEbvHY2huTLoQtH\n           height: 600px\n\n        \"\"\"\n        map_proto = DeckGlJsonChartProto()\n        map_proto.json = to_deckgl_json(data, zoom)\n        map_proto.use_container_width = use_container_width\n        return dg._enqueue(\"deck_gl_json_chart\", map_proto)  # type: ignore\n\n\n# Map used as the basis for st.map.\n_DEFAULT_MAP = dict(deck_gl_json_chart.EMPTY_MAP)  # type: Dict[str, Any]\n_DEFAULT_MAP[\"mapStyle\"] = \"mapbox://styles/mapbox/light-v10\"\n\n# Other default parameters for st.map.\n_DEFAULT_COLOR = [200, 30, 0, 160]\n_ZOOM_LEVELS = [\n    360,\n    180,\n    90,\n    45,\n    22.5,\n    11.25,\n    5.625,\n    2.813,\n    1.406,\n    0.703,\n    0.352,\n    0.176,\n    0.088,\n    0.044,\n    0.022,\n    0.011,\n    0.005,\n    0.003,\n    0.001,\n    0.0005,\n]\n\n\ndef _get_zoom_level(distance):\n    \"\"\"Get the zoom level for a given distance in degrees.\n\n    See https://wiki.openstreetmap.org/wiki/Zoom_levels for reference.\n\n    Parameters\n    ----------\n    distance : float\n        How many degrees of longitude should fit in the map.\n\n    Returns\n    -------\n    int\n        The zoom level, from 0 to 29.\n\n    \"\"\"\n\n    for i in range(len(_ZOOM_LEVELS) - 1):\n        if _ZOOM_LEVELS[i + 1] < distance <= _ZOOM_LEVELS[i]:\n            return i\n\n\ndef to_deckgl_json(data, zoom):\n\n    if data is None or data.empty:\n        return json.dumps(_DEFAULT_MAP)\n\n    if \"lat\" in data:\n        lat = \"lat\"\n    elif \"latitude\" in data:\n        lat = \"latitude\"\n    else:\n        raise StreamlitAPIException(\n            'Map data must contain a column named \"latitude\" or \"lat\".'\n        )\n\n    if \"lon\" in data:\n        lon = \"lon\"\n    elif \"longitude\" in data:\n        lon = \"longitude\"\n    else:\n        raise StreamlitAPIException(\n            'Map data must contain a column called \"longitude\" or \"lon\".'\n        )\n\n    if data[lon].isnull().values.any() or data[lat].isnull().values.any():\n        raise StreamlitAPIException(\"Latitude and longitude data must be numeric.\")\n\n    data = pd.DataFrame(data)\n\n    min_lat = data[lat].min()\n    max_lat = data[lat].max()\n    min_lon = data[lon].min()\n    max_lon = data[lon].max()\n    center_lat = (max_lat + min_lat) / 2.0\n    center_lon = (max_lon + min_lon) / 2.0\n    range_lon = abs(max_lon - min_lon)\n    range_lat = abs(max_lat - min_lat)\n\n    if zoom == None:\n        if range_lon > range_lat:\n            longitude_distance = range_lon\n        else:\n            longitude_distance = range_lat\n        zoom = _get_zoom_level(longitude_distance)\n\n    # \"+1\" because itertuples includes the row index.\n    lon_col_index = data.columns.get_loc(lon) + 1\n    lat_col_index = data.columns.get_loc(lat) + 1\n    final_data = []\n    for row in data.itertuples():\n        final_data.append(\n            {\"lon\": float(row[lon_col_index]), \"lat\": float(row[lat_col_index])}\n        )\n\n    default = copy.deepcopy(_DEFAULT_MAP)\n    default[\"initialViewState\"][\"latitude\"] = center_lat\n    default[\"initialViewState\"][\"longitude\"] = center_lon\n    default[\"initialViewState\"][\"zoom\"] = zoom\n    default[\"layers\"] = [\n        {\n            \"@@type\": \"ScatterplotLayer\",\n            \"getPosition\": \"@@=[lon, lat]\",\n            \"getRadius\": 10,\n            \"radiusScale\": 10,\n            \"radiusMinPixels\": 3,\n            \"getFillColor\": _DEFAULT_COLOR,\n            \"data\": final_data,\n        }\n    ]\n    return json.dumps(default)\n", "path": "lib/streamlit/elements/map.py"}]}