body
stringlengths
26
98.2k
body_hash
int64
-9,222,864,604,528,158,000
9,221,803,474B
docstring
stringlengths
1
16.8k
path
stringlengths
5
230
name
stringlengths
1
96
repository_name
stringlengths
7
89
lang
stringclasses
1 value
body_without_docstring
stringlengths
20
98.2k
@_with_element def button(self, element, label, key=None): "Display a button widget.\n\n Parameters\n ----------\n label : str\n A short label explaining to the user what this button is for.\n key : str\n An optional string to use as the unique key for the widget.\n If this is omitted, a key will be generated for the widget\n based on its content. Multiple widgets of the same type may\n not share the same key.\n\n Returns\n -------\n bool\n If the button was clicked on the last run of the app.\n\n Example\n -------\n >>> if st.button('Say hello'):\n ... st.write('Why hello there')\n ... else:\n ... st.write('Goodbye')\n\n " element.button.label = label element.button.default = False ui_value = _get_widget_ui_value('button', element, user_key=key) current_value = (ui_value if (ui_value is not None) else False) return current_value
8,915,156,771,501,557,000
Display a button widget. Parameters ---------- label : str A short label explaining to the user what this button is for. key : str An optional string to use as the unique key for the widget. If this is omitted, a key will be generated for the widget based on its content. Multiple widgets of the same type may not share the same key. Returns ------- bool If the button was clicked on the last run of the app. Example ------- >>> if st.button('Say hello'): ... st.write('Why hello there') ... else: ... st.write('Goodbye')
lib/streamlit/DeltaGenerator.py
button
OakNorthAI/streamlit-base
python
@_with_element def button(self, element, label, key=None): "Display a button widget.\n\n Parameters\n ----------\n label : str\n A short label explaining to the user what this button is for.\n key : str\n An optional string to use as the unique key for the widget.\n If this is omitted, a key will be generated for the widget\n based on its content. Multiple widgets of the same type may\n not share the same key.\n\n Returns\n -------\n bool\n If the button was clicked on the last run of the app.\n\n Example\n -------\n >>> if st.button('Say hello'):\n ... st.write('Why hello there')\n ... else:\n ... st.write('Goodbye')\n\n " element.button.label = label element.button.default = False ui_value = _get_widget_ui_value('button', element, user_key=key) current_value = (ui_value if (ui_value is not None) else False) return current_value
@_with_element def checkbox(self, element, label, value=False, key=None): "Display a checkbox widget.\n\n Parameters\n ----------\n label : str\n A short label explaining to the user what this checkbox is for.\n value : bool\n Preselect the checkbox when it first renders. This will be\n cast to bool internally.\n key : str\n An optional string to use as the unique key for the widget.\n If this is omitted, a key will be generated for the widget\n based on its content. Multiple widgets of the same type may\n not share the same key.\n\n Returns\n -------\n bool\n Whether or not the checkbox is checked.\n\n Example\n -------\n >>> agree = st.checkbox('I agree')\n >>>\n >>> if agree:\n ... st.write('Great!')\n\n " element.checkbox.label = label element.checkbox.default = bool(value) ui_value = _get_widget_ui_value('checkbox', element, user_key=key) current_value = (ui_value if (ui_value is not None) else value) return bool(current_value)
4,435,925,171,239,557,000
Display a checkbox widget. Parameters ---------- label : str A short label explaining to the user what this checkbox is for. value : bool Preselect the checkbox when it first renders. This will be cast to bool internally. key : str An optional string to use as the unique key for the widget. If this is omitted, a key will be generated for the widget based on its content. Multiple widgets of the same type may not share the same key. Returns ------- bool Whether or not the checkbox is checked. Example ------- >>> agree = st.checkbox('I agree') >>> >>> if agree: ... st.write('Great!')
lib/streamlit/DeltaGenerator.py
checkbox
OakNorthAI/streamlit-base
python
@_with_element def checkbox(self, element, label, value=False, key=None): "Display a checkbox widget.\n\n Parameters\n ----------\n label : str\n A short label explaining to the user what this checkbox is for.\n value : bool\n Preselect the checkbox when it first renders. This will be\n cast to bool internally.\n key : str\n An optional string to use as the unique key for the widget.\n If this is omitted, a key will be generated for the widget\n based on its content. Multiple widgets of the same type may\n not share the same key.\n\n Returns\n -------\n bool\n Whether or not the checkbox is checked.\n\n Example\n -------\n >>> agree = st.checkbox('I agree')\n >>>\n >>> if agree:\n ... st.write('Great!')\n\n " element.checkbox.label = label element.checkbox.default = bool(value) ui_value = _get_widget_ui_value('checkbox', element, user_key=key) current_value = (ui_value if (ui_value is not None) else value) return bool(current_value)
@_with_element def multiselect(self, element, label, options, default=None, format_func=str, key=None): "Display a multiselect widget.\n The multiselect widget starts as empty.\n\n Parameters\n ----------\n label : str\n A short label explaining to the user what this select widget is for.\n options : list, tuple, numpy.ndarray, or pandas.Series\n Labels for the select options. This will be cast to str internally\n by default.\n default: [str] or None\n List of default values.\n format_func : function\n Function to modify the display of selectbox options. It receives\n the raw option as an argument and should output the label to be\n shown for that option. This has no impact on the return value of\n the selectbox.\n key : str\n An optional string to use as the unique key for the widget.\n If this is omitted, a key will be generated for the widget\n based on its content. Multiple widgets of the same type may\n not share the same key.\n\n Returns\n -------\n [str]\n A list with the selected options\n\n Example\n -------\n >>> options = st.multiselect(\n ... 'What are your favorite colors',\n ... ['Green', 'Yellow', 'Red', 'Blue'],\n ... ['Yellow', 'Red'])\n >>>\n >>> st.write('You selected:', options)\n\n .. note::\n User experience can be degraded for large lists of `options` (100+), as this widget\n is not designed to handle arbitrary text search efficiently. See this\n `thread <https://discuss.streamlit.io/t/streamlit-loading-column-data-takes-too-much-time/1791>`_\n on the Streamlit community forum for more information and\n `GitHub issue #1059 <https://github.com/streamlit/streamlit/issues/1059>`_ for updates on the issue.\n\n " def _check_and_convert_to_indices(options, default_values): if ((default_values is None) and (None not in options)): return None if (not isinstance(default_values, list)): if (is_type(default_values, 'numpy.ndarray') or is_type(default_values, 'pandas.core.series.Series')): default_values = list(default_values) elif (not default_values): default_values = [default_values] else: default_values = list(default_values) for value in default_values: if (value not in options): raise StreamlitAPIException('Every Multiselect default value must exist in options') return [options.index(value) for value in default_values] indices = _check_and_convert_to_indices(options, default) element.multiselect.label = label default_value = ([] if (indices is None) else indices) element.multiselect.default[:] = default_value element.multiselect.options[:] = [str(format_func(option)) for option in options] ui_value = _get_widget_ui_value('multiselect', element, user_key=key) current_value = (ui_value.value if (ui_value is not None) else default_value) return [options[i] for i in current_value]
-4,061,092,096,204,065,000
Display a multiselect widget. The multiselect widget starts as empty. Parameters ---------- label : str A short label explaining to the user what this select widget is for. options : list, tuple, numpy.ndarray, or pandas.Series Labels for the select options. This will be cast to str internally by default. default: [str] or None List of default values. format_func : function Function to modify the display of selectbox options. It receives the raw option as an argument and should output the label to be shown for that option. This has no impact on the return value of the selectbox. key : str An optional string to use as the unique key for the widget. If this is omitted, a key will be generated for the widget based on its content. Multiple widgets of the same type may not share the same key. Returns ------- [str] A list with the selected options Example ------- >>> options = st.multiselect( ... 'What are your favorite colors', ... ['Green', 'Yellow', 'Red', 'Blue'], ... ['Yellow', 'Red']) >>> >>> st.write('You selected:', options) .. note:: User experience can be degraded for large lists of `options` (100+), as this widget is not designed to handle arbitrary text search efficiently. See this `thread <https://discuss.streamlit.io/t/streamlit-loading-column-data-takes-too-much-time/1791>`_ on the Streamlit community forum for more information and `GitHub issue #1059 <https://github.com/streamlit/streamlit/issues/1059>`_ for updates on the issue.
lib/streamlit/DeltaGenerator.py
multiselect
OakNorthAI/streamlit-base
python
@_with_element def multiselect(self, element, label, options, default=None, format_func=str, key=None): "Display a multiselect widget.\n The multiselect widget starts as empty.\n\n Parameters\n ----------\n label : str\n A short label explaining to the user what this select widget is for.\n options : list, tuple, numpy.ndarray, or pandas.Series\n Labels for the select options. This will be cast to str internally\n by default.\n default: [str] or None\n List of default values.\n format_func : function\n Function to modify the display of selectbox options. It receives\n the raw option as an argument and should output the label to be\n shown for that option. This has no impact on the return value of\n the selectbox.\n key : str\n An optional string to use as the unique key for the widget.\n If this is omitted, a key will be generated for the widget\n based on its content. Multiple widgets of the same type may\n not share the same key.\n\n Returns\n -------\n [str]\n A list with the selected options\n\n Example\n -------\n >>> options = st.multiselect(\n ... 'What are your favorite colors',\n ... ['Green', 'Yellow', 'Red', 'Blue'],\n ... ['Yellow', 'Red'])\n >>>\n >>> st.write('You selected:', options)\n\n .. note::\n User experience can be degraded for large lists of `options` (100+), as this widget\n is not designed to handle arbitrary text search efficiently. See this\n `thread <https://discuss.streamlit.io/t/streamlit-loading-column-data-takes-too-much-time/1791>`_\n on the Streamlit community forum for more information and\n `GitHub issue #1059 <https://github.com/streamlit/streamlit/issues/1059>`_ for updates on the issue.\n\n " def _check_and_convert_to_indices(options, default_values): if ((default_values is None) and (None not in options)): return None if (not isinstance(default_values, list)): if (is_type(default_values, 'numpy.ndarray') or is_type(default_values, 'pandas.core.series.Series')): default_values = list(default_values) elif (not default_values): default_values = [default_values] else: default_values = list(default_values) for value in default_values: if (value not in options): raise StreamlitAPIException('Every Multiselect default value must exist in options') return [options.index(value) for value in default_values] indices = _check_and_convert_to_indices(options, default) element.multiselect.label = label default_value = ([] if (indices is None) else indices) element.multiselect.default[:] = default_value element.multiselect.options[:] = [str(format_func(option)) for option in options] ui_value = _get_widget_ui_value('multiselect', element, user_key=key) current_value = (ui_value.value if (ui_value is not None) else default_value) return [options[i] for i in current_value]
@_with_element def radio(self, element, label, options, index=0, format_func=str, key=None): 'Display a radio button widget.\n\n Parameters\n ----------\n label : str\n A short label explaining to the user what this radio group is for.\n options : list, tuple, numpy.ndarray, or pandas.Series\n Labels for the radio options. This will be cast to str internally\n by default.\n index : int\n The index of the preselected option on first render.\n format_func : function\n Function to modify the display of radio options. It receives\n the raw option as an argument and should output the label to be\n shown for that option. This has no impact on the return value of\n the radio.\n key : str\n An optional string to use as the unique key for the widget.\n If this is omitted, a key will be generated for the widget\n based on its content. Multiple widgets of the same type may\n not share the same key.\n\n Returns\n -------\n any\n The selected option.\n\n Example\n -------\n >>> genre = st.radio(\n ... "What\'s your favorite movie genre",\n ... (\'Comedy\', \'Drama\', \'Documentary\'))\n >>>\n >>> if genre == \'Comedy\':\n ... st.write(\'You selected comedy.\')\n ... else:\n ... st.write("You didn\'t select comedy.")\n\n ' if (not isinstance(index, int)): raise StreamlitAPIException(('Radio Value has invalid type: %s' % type(index).__name__)) if ((len(options) > 0) and (not (0 <= index < len(options)))): raise StreamlitAPIException('Radio index must be between 0 and length of options') element.radio.label = label element.radio.default = index element.radio.options[:] = [str(format_func(option)) for option in options] ui_value = _get_widget_ui_value('radio', element, user_key=key) current_value = (ui_value if (ui_value is not None) else index) return (options[current_value] if ((len(options) > 0) and (options[current_value] is not None)) else NoValue)
-1,261,307,580,793,010,700
Display a radio button widget. Parameters ---------- label : str A short label explaining to the user what this radio group is for. options : list, tuple, numpy.ndarray, or pandas.Series Labels for the radio options. This will be cast to str internally by default. index : int The index of the preselected option on first render. format_func : function Function to modify the display of radio options. It receives the raw option as an argument and should output the label to be shown for that option. This has no impact on the return value of the radio. key : str An optional string to use as the unique key for the widget. If this is omitted, a key will be generated for the widget based on its content. Multiple widgets of the same type may not share the same key. Returns ------- any The selected option. Example ------- >>> genre = st.radio( ... "What's your favorite movie genre", ... ('Comedy', 'Drama', 'Documentary')) >>> >>> if genre == 'Comedy': ... st.write('You selected comedy.') ... else: ... st.write("You didn't select comedy.")
lib/streamlit/DeltaGenerator.py
radio
OakNorthAI/streamlit-base
python
@_with_element def radio(self, element, label, options, index=0, format_func=str, key=None): 'Display a radio button widget.\n\n Parameters\n ----------\n label : str\n A short label explaining to the user what this radio group is for.\n options : list, tuple, numpy.ndarray, or pandas.Series\n Labels for the radio options. This will be cast to str internally\n by default.\n index : int\n The index of the preselected option on first render.\n format_func : function\n Function to modify the display of radio options. It receives\n the raw option as an argument and should output the label to be\n shown for that option. This has no impact on the return value of\n the radio.\n key : str\n An optional string to use as the unique key for the widget.\n If this is omitted, a key will be generated for the widget\n based on its content. Multiple widgets of the same type may\n not share the same key.\n\n Returns\n -------\n any\n The selected option.\n\n Example\n -------\n >>> genre = st.radio(\n ... "What\'s your favorite movie genre",\n ... (\'Comedy\', \'Drama\', \'Documentary\'))\n >>>\n >>> if genre == \'Comedy\':\n ... st.write(\'You selected comedy.\')\n ... else:\n ... st.write("You didn\'t select comedy.")\n\n ' if (not isinstance(index, int)): raise StreamlitAPIException(('Radio Value has invalid type: %s' % type(index).__name__)) if ((len(options) > 0) and (not (0 <= index < len(options)))): raise StreamlitAPIException('Radio index must be between 0 and length of options') element.radio.label = label element.radio.default = index element.radio.options[:] = [str(format_func(option)) for option in options] ui_value = _get_widget_ui_value('radio', element, user_key=key) current_value = (ui_value if (ui_value is not None) else index) return (options[current_value] if ((len(options) > 0) and (options[current_value] is not None)) else NoValue)
@_with_element def selectbox(self, element, label, options, index=0, format_func=str, key=None): "Display a select widget.\n\n Parameters\n ----------\n label : str\n A short label explaining to the user what this select widget is for.\n options : list, tuple, numpy.ndarray, or pandas.Series\n Labels for the select options. This will be cast to str internally\n by default.\n index : int\n The index of the preselected option on first render.\n format_func : function\n Function to modify the display of the labels. It receives the option\n as an argument and its output will be cast to str.\n key : str\n An optional string to use as the unique key for the widget.\n If this is omitted, a key will be generated for the widget\n based on its content. Multiple widgets of the same type may\n not share the same key.\n\n Returns\n -------\n any\n The selected option\n\n Example\n -------\n >>> option = st.selectbox(\n ... 'How would you like to be contacted?',\n ... ('Email', 'Home phone', 'Mobile phone'))\n >>>\n >>> st.write('You selected:', option)\n\n " if (not isinstance(index, int)): raise StreamlitAPIException(('Selectbox Value has invalid type: %s' % type(index).__name__)) if ((len(options) > 0) and (not (0 <= index < len(options)))): raise StreamlitAPIException('Selectbox index must be between 0 and length of options') element.selectbox.label = label element.selectbox.default = index element.selectbox.options[:] = [str(format_func(option)) for option in options] ui_value = _get_widget_ui_value('selectbox', element, user_key=key) current_value = (ui_value if (ui_value is not None) else index) return (options[current_value] if ((len(options) > 0) and (options[current_value] is not None)) else NoValue)
-5,761,214,060,143,018,000
Display a select widget. Parameters ---------- label : str A short label explaining to the user what this select widget is for. options : list, tuple, numpy.ndarray, or pandas.Series Labels for the select options. This will be cast to str internally by default. index : int The index of the preselected option on first render. format_func : function Function to modify the display of the labels. It receives the option as an argument and its output will be cast to str. key : str An optional string to use as the unique key for the widget. If this is omitted, a key will be generated for the widget based on its content. Multiple widgets of the same type may not share the same key. Returns ------- any The selected option Example ------- >>> option = st.selectbox( ... 'How would you like to be contacted?', ... ('Email', 'Home phone', 'Mobile phone')) >>> >>> st.write('You selected:', option)
lib/streamlit/DeltaGenerator.py
selectbox
OakNorthAI/streamlit-base
python
@_with_element def selectbox(self, element, label, options, index=0, format_func=str, key=None): "Display a select widget.\n\n Parameters\n ----------\n label : str\n A short label explaining to the user what this select widget is for.\n options : list, tuple, numpy.ndarray, or pandas.Series\n Labels for the select options. This will be cast to str internally\n by default.\n index : int\n The index of the preselected option on first render.\n format_func : function\n Function to modify the display of the labels. It receives the option\n as an argument and its output will be cast to str.\n key : str\n An optional string to use as the unique key for the widget.\n If this is omitted, a key will be generated for the widget\n based on its content. Multiple widgets of the same type may\n not share the same key.\n\n Returns\n -------\n any\n The selected option\n\n Example\n -------\n >>> option = st.selectbox(\n ... 'How would you like to be contacted?',\n ... ('Email', 'Home phone', 'Mobile phone'))\n >>>\n >>> st.write('You selected:', option)\n\n " if (not isinstance(index, int)): raise StreamlitAPIException(('Selectbox Value has invalid type: %s' % type(index).__name__)) if ((len(options) > 0) and (not (0 <= index < len(options)))): raise StreamlitAPIException('Selectbox index must be between 0 and length of options') element.selectbox.label = label element.selectbox.default = index element.selectbox.options[:] = [str(format_func(option)) for option in options] ui_value = _get_widget_ui_value('selectbox', element, user_key=key) current_value = (ui_value if (ui_value is not None) else index) return (options[current_value] if ((len(options) > 0) and (options[current_value] is not None)) else NoValue)
@_with_element def slider(self, element, label, min_value=None, max_value=None, value=None, step=None, format=None, key=None): 'Display a slider widget.\n\n This also allows you to render a range slider by passing a two-element tuple or list as the `value`.\n\n Parameters\n ----------\n label : str or None\n A short label explaining to the user what this slider is for.\n min_value : int/float or None\n The minimum permitted value.\n Defaults to 0 if the value is an int, 0.0 otherwise.\n max_value : int/float or None\n The maximum permitted value.\n Defaults 100 if the value is an int, 1.0 otherwise.\n value : int/float or a tuple/list of int/float or None\n The value of the slider when it first renders. If a tuple/list\n of two values is passed here, then a range slider with those lower\n and upper bounds is rendered. For example, if set to `(1, 10)` the\n slider will have a selectable range between 1 and 10.\n Defaults to min_value.\n step : int/float or None\n The stepping interval.\n Defaults to 1 if the value is an int, 0.01 otherwise.\n format : str or None\n A printf-style format string controlling how the interface should\n display numbers. This does not impact the return value.\n Valid formatters: %d %e %f %g %i\n key : str\n An optional string to use as the unique key for the widget.\n If this is omitted, a key will be generated for the widget\n based on its content. Multiple widgets of the same type may\n not share the same key.\n\n Returns\n -------\n int/float or tuple of int/float\n The current value of the slider widget. The return type will match\n the data type of the value parameter.\n\n Examples\n --------\n >>> age = st.slider(\'How old are you?\', 0, 130, 25)\n >>> st.write("I\'m ", age, \'years old\')\n\n And here\'s an example of a range slider:\n\n >>> values = st.slider(\n ... \'Select a range of values\',\n ... 0.0, 100.0, (25.0, 75.0))\n >>> st.write(\'Values:\', values)\n\n ' if (value is None): value = (min_value if (min_value is not None) else 0) single_value = isinstance(value, (int, float)) range_value = (isinstance(value, (list, tuple)) and (len(value) in (0, 1, 2))) if ((not single_value) and (not range_value)): raise StreamlitAPIException('Slider value should either be an int/float or a list/tuple of 0 to 2 ints/floats') if single_value: int_value = isinstance(value, int) float_value = isinstance(value, float) else: int_value = all(map((lambda v: isinstance(v, int)), value)) float_value = all(map((lambda v: isinstance(v, float)), value)) if ((not int_value) and (not float_value)): raise StreamlitAPIException('Slider tuple/list components must be of the same type.') if (min_value is None): min_value = (0 if int_value else 0.0) if (max_value is None): max_value = (100 if int_value else 1.0) if (step is None): step = (1 if int_value else 0.01) args = [min_value, max_value, step] int_args = all(map((lambda a: isinstance(a, int)), args)) float_args = all(map((lambda a: isinstance(a, float)), args)) if ((not int_args) and (not float_args)): raise StreamlitAPIException(('Slider value arguments must be of the same type.\n`value` has %(value_type)s type.\n`min_value` has %(min_type)s type.\n`max_value` has %(max_type)s type.' % {'value_type': type(value).__name__, 'min_type': type(min_value).__name__, 'max_type': type(max_value).__name__})) all_ints = (int_value and int_args) all_floats = (float_value and float_args) if ((not all_ints) and (not all_floats)): raise StreamlitAPIException(('Both value and arguments must be of the same type.\n`value` has %(value_type)s type.\n`min_value` has %(min_type)s type.\n`max_value` has %(max_type)s type.' % {'value_type': type(value).__name__, 'min_type': type(min_value).__name__, 'max_type': type(max_value).__name__})) if single_value: if (not (min_value <= value <= max_value)): raise StreamlitAPIException(('The default `value` of %(value)s must lie between the `min_value` of %(min)s and the `max_value` of %(max)s, inclusively.' % {'value': value, 'min': min_value, 'max': max_value})) elif (len(value) == 2): (start, end) = value if (not (min_value <= start <= end <= max_value)): raise StreamlitAPIException('The value and/or arguments are out of range.') else: value = [min_value, max_value] try: if all_ints: JSNumber.validate_int_bounds(min_value, '`min_value`') JSNumber.validate_int_bounds(max_value, '`max_value`') else: JSNumber.validate_float_bounds(min_value, '`min_value`') JSNumber.validate_float_bounds(max_value, '`max_value`') except JSNumberBoundsException as e: raise StreamlitAPIException(str(e)) if (format is None): if all_ints: format = '%d' else: format = '%0.2f' element.slider.label = label element.slider.format = format element.slider.default[:] = ([value] if single_value else value) element.slider.min = min_value element.slider.max = max_value element.slider.step = step ui_value = _get_widget_ui_value('slider', element, user_key=key) current_value = (ui_value if (ui_value is not None) else value) if (ui_value is not None): current_value = getattr(ui_value, 'value') if all_ints: current_value = list(map(int, current_value)) current_value = (current_value[0] if single_value else current_value) return (current_value if single_value else tuple(current_value))
7,022,913,251,441,921,000
Display a slider widget. This also allows you to render a range slider by passing a two-element tuple or list as the `value`. Parameters ---------- label : str or None A short label explaining to the user what this slider is for. min_value : int/float or None The minimum permitted value. Defaults to 0 if the value is an int, 0.0 otherwise. max_value : int/float or None The maximum permitted value. Defaults 100 if the value is an int, 1.0 otherwise. value : int/float or a tuple/list of int/float or None The value of the slider when it first renders. If a tuple/list of two values is passed here, then a range slider with those lower and upper bounds is rendered. For example, if set to `(1, 10)` the slider will have a selectable range between 1 and 10. Defaults to min_value. step : int/float or None The stepping interval. Defaults to 1 if the value is an int, 0.01 otherwise. format : str or None A printf-style format string controlling how the interface should display numbers. This does not impact the return value. Valid formatters: %d %e %f %g %i key : str An optional string to use as the unique key for the widget. If this is omitted, a key will be generated for the widget based on its content. Multiple widgets of the same type may not share the same key. Returns ------- int/float or tuple of int/float The current value of the slider widget. The return type will match the data type of the value parameter. Examples -------- >>> age = st.slider('How old are you?', 0, 130, 25) >>> st.write("I'm ", age, 'years old') And here's an example of a range slider: >>> values = st.slider( ... 'Select a range of values', ... 0.0, 100.0, (25.0, 75.0)) >>> st.write('Values:', values)
lib/streamlit/DeltaGenerator.py
slider
OakNorthAI/streamlit-base
python
@_with_element def slider(self, element, label, min_value=None, max_value=None, value=None, step=None, format=None, key=None): 'Display a slider widget.\n\n This also allows you to render a range slider by passing a two-element tuple or list as the `value`.\n\n Parameters\n ----------\n label : str or None\n A short label explaining to the user what this slider is for.\n min_value : int/float or None\n The minimum permitted value.\n Defaults to 0 if the value is an int, 0.0 otherwise.\n max_value : int/float or None\n The maximum permitted value.\n Defaults 100 if the value is an int, 1.0 otherwise.\n value : int/float or a tuple/list of int/float or None\n The value of the slider when it first renders. If a tuple/list\n of two values is passed here, then a range slider with those lower\n and upper bounds is rendered. For example, if set to `(1, 10)` the\n slider will have a selectable range between 1 and 10.\n Defaults to min_value.\n step : int/float or None\n The stepping interval.\n Defaults to 1 if the value is an int, 0.01 otherwise.\n format : str or None\n A printf-style format string controlling how the interface should\n display numbers. This does not impact the return value.\n Valid formatters: %d %e %f %g %i\n key : str\n An optional string to use as the unique key for the widget.\n If this is omitted, a key will be generated for the widget\n based on its content. Multiple widgets of the same type may\n not share the same key.\n\n Returns\n -------\n int/float or tuple of int/float\n The current value of the slider widget. The return type will match\n the data type of the value parameter.\n\n Examples\n --------\n >>> age = st.slider(\'How old are you?\', 0, 130, 25)\n >>> st.write("I\'m ", age, \'years old\')\n\n And here\'s an example of a range slider:\n\n >>> values = st.slider(\n ... \'Select a range of values\',\n ... 0.0, 100.0, (25.0, 75.0))\n >>> st.write(\'Values:\', values)\n\n ' if (value is None): value = (min_value if (min_value is not None) else 0) single_value = isinstance(value, (int, float)) range_value = (isinstance(value, (list, tuple)) and (len(value) in (0, 1, 2))) if ((not single_value) and (not range_value)): raise StreamlitAPIException('Slider value should either be an int/float or a list/tuple of 0 to 2 ints/floats') if single_value: int_value = isinstance(value, int) float_value = isinstance(value, float) else: int_value = all(map((lambda v: isinstance(v, int)), value)) float_value = all(map((lambda v: isinstance(v, float)), value)) if ((not int_value) and (not float_value)): raise StreamlitAPIException('Slider tuple/list components must be of the same type.') if (min_value is None): min_value = (0 if int_value else 0.0) if (max_value is None): max_value = (100 if int_value else 1.0) if (step is None): step = (1 if int_value else 0.01) args = [min_value, max_value, step] int_args = all(map((lambda a: isinstance(a, int)), args)) float_args = all(map((lambda a: isinstance(a, float)), args)) if ((not int_args) and (not float_args)): raise StreamlitAPIException(('Slider value arguments must be of the same type.\n`value` has %(value_type)s type.\n`min_value` has %(min_type)s type.\n`max_value` has %(max_type)s type.' % {'value_type': type(value).__name__, 'min_type': type(min_value).__name__, 'max_type': type(max_value).__name__})) all_ints = (int_value and int_args) all_floats = (float_value and float_args) if ((not all_ints) and (not all_floats)): raise StreamlitAPIException(('Both value and arguments must be of the same type.\n`value` has %(value_type)s type.\n`min_value` has %(min_type)s type.\n`max_value` has %(max_type)s type.' % {'value_type': type(value).__name__, 'min_type': type(min_value).__name__, 'max_type': type(max_value).__name__})) if single_value: if (not (min_value <= value <= max_value)): raise StreamlitAPIException(('The default `value` of %(value)s must lie between the `min_value` of %(min)s and the `max_value` of %(max)s, inclusively.' % {'value': value, 'min': min_value, 'max': max_value})) elif (len(value) == 2): (start, end) = value if (not (min_value <= start <= end <= max_value)): raise StreamlitAPIException('The value and/or arguments are out of range.') else: value = [min_value, max_value] try: if all_ints: JSNumber.validate_int_bounds(min_value, '`min_value`') JSNumber.validate_int_bounds(max_value, '`max_value`') else: JSNumber.validate_float_bounds(min_value, '`min_value`') JSNumber.validate_float_bounds(max_value, '`max_value`') except JSNumberBoundsException as e: raise StreamlitAPIException(str(e)) if (format is None): if all_ints: format = '%d' else: format = '%0.2f' element.slider.label = label element.slider.format = format element.slider.default[:] = ([value] if single_value else value) element.slider.min = min_value element.slider.max = max_value element.slider.step = step ui_value = _get_widget_ui_value('slider', element, user_key=key) current_value = (ui_value if (ui_value is not None) else value) if (ui_value is not None): current_value = getattr(ui_value, 'value') if all_ints: current_value = list(map(int, current_value)) current_value = (current_value[0] if single_value else current_value) return (current_value if single_value else tuple(current_value))
@_with_element def file_uploader(self, element, label, type=None, encoding='auto', key=None): 'Display a file uploader widget.\n\n By default, uploaded files are limited to 200MB. You can configure\n this using the `server.maxUploadSize` config option.\n\n Parameters\n ----------\n label : str or None\n A short label explaining to the user what this file uploader is for.\n type : str or list of str or None\n Array of allowed extensions. [\'png\', \'jpg\']\n By default, all extensions are allowed.\n encoding : str or None\n The encoding to use when opening textual files (i.e. non-binary).\n For example: \'utf-8\'. If set to \'auto\', will try to guess the\n encoding. If None, will assume the file is binary.\n key : str\n An optional string to use as the unique key for the widget.\n If this is omitted, a key will be generated for the widget\n based on its content. Multiple widgets of the same type may\n not share the same key.\n\n Returns\n -------\n BytesIO or StringIO or or list of BytesIO/StringIO or None\n If no file has been uploaded, returns None. Otherwise, returns\n the data for the uploaded file(s):\n - If the file is in a well-known textual format (or if the encoding\n parameter is set), the file data is a StringIO.\n - Otherwise the file data is BytesIO.\n - If multiple_files is True, a list of file data will be returned.\n\n Note that BytesIO/StringIO are "file-like", which means you can\n pass them anywhere where a file is expected!\n\n Examples\n --------\n >>> uploaded_file = st.file_uploader("Choose a CSV file", type="csv")\n >>> if uploaded_file is not None:\n ... data = pd.read_csv(uploaded_file)\n ... st.write(data)\n\n ' accept_multiple_files = False if isinstance(type, str): type = [type] element.file_uploader.label = label element.file_uploader.type[:] = (type if (type is not None) else []) element.file_uploader.max_upload_size_mb = config.get_option('server.maxUploadSize') element.file_uploader.multiple_files = accept_multiple_files _set_widget_id('file_uploader', element, user_key=key) files = None ctx = get_report_ctx() if (ctx is not None): files = ctx.uploaded_file_mgr.get_files(session_id=ctx.session_id, widget_id=element.file_uploader.id) if (files is None): return NoValue file_datas = [get_encoded_file_data(file.data, encoding) for file in files] return (file_datas if accept_multiple_files else file_datas[0])
-8,024,954,997,992,139,000
Display a file uploader widget. By default, uploaded files are limited to 200MB. You can configure this using the `server.maxUploadSize` config option. Parameters ---------- label : str or None A short label explaining to the user what this file uploader is for. type : str or list of str or None Array of allowed extensions. ['png', 'jpg'] By default, all extensions are allowed. encoding : str or None The encoding to use when opening textual files (i.e. non-binary). For example: 'utf-8'. If set to 'auto', will try to guess the encoding. If None, will assume the file is binary. key : str An optional string to use as the unique key for the widget. If this is omitted, a key will be generated for the widget based on its content. Multiple widgets of the same type may not share the same key. Returns ------- BytesIO or StringIO or or list of BytesIO/StringIO or None If no file has been uploaded, returns None. Otherwise, returns the data for the uploaded file(s): - If the file is in a well-known textual format (or if the encoding parameter is set), the file data is a StringIO. - Otherwise the file data is BytesIO. - If multiple_files is True, a list of file data will be returned. Note that BytesIO/StringIO are "file-like", which means you can pass them anywhere where a file is expected! Examples -------- >>> uploaded_file = st.file_uploader("Choose a CSV file", type="csv") >>> if uploaded_file is not None: ... data = pd.read_csv(uploaded_file) ... st.write(data)
lib/streamlit/DeltaGenerator.py
file_uploader
OakNorthAI/streamlit-base
python
@_with_element def file_uploader(self, element, label, type=None, encoding='auto', key=None): 'Display a file uploader widget.\n\n By default, uploaded files are limited to 200MB. You can configure\n this using the `server.maxUploadSize` config option.\n\n Parameters\n ----------\n label : str or None\n A short label explaining to the user what this file uploader is for.\n type : str or list of str or None\n Array of allowed extensions. [\'png\', \'jpg\']\n By default, all extensions are allowed.\n encoding : str or None\n The encoding to use when opening textual files (i.e. non-binary).\n For example: \'utf-8\'. If set to \'auto\', will try to guess the\n encoding. If None, will assume the file is binary.\n key : str\n An optional string to use as the unique key for the widget.\n If this is omitted, a key will be generated for the widget\n based on its content. Multiple widgets of the same type may\n not share the same key.\n\n Returns\n -------\n BytesIO or StringIO or or list of BytesIO/StringIO or None\n If no file has been uploaded, returns None. Otherwise, returns\n the data for the uploaded file(s):\n - If the file is in a well-known textual format (or if the encoding\n parameter is set), the file data is a StringIO.\n - Otherwise the file data is BytesIO.\n - If multiple_files is True, a list of file data will be returned.\n\n Note that BytesIO/StringIO are "file-like", which means you can\n pass them anywhere where a file is expected!\n\n Examples\n --------\n >>> uploaded_file = st.file_uploader("Choose a CSV file", type="csv")\n >>> if uploaded_file is not None:\n ... data = pd.read_csv(uploaded_file)\n ... st.write(data)\n\n ' accept_multiple_files = False if isinstance(type, str): type = [type] element.file_uploader.label = label element.file_uploader.type[:] = (type if (type is not None) else []) element.file_uploader.max_upload_size_mb = config.get_option('server.maxUploadSize') element.file_uploader.multiple_files = accept_multiple_files _set_widget_id('file_uploader', element, user_key=key) files = None ctx = get_report_ctx() if (ctx is not None): files = ctx.uploaded_file_mgr.get_files(session_id=ctx.session_id, widget_id=element.file_uploader.id) if (files is None): return NoValue file_datas = [get_encoded_file_data(file.data, encoding) for file in files] return (file_datas if accept_multiple_files else file_datas[0])
@_with_element def beta_color_picker(self, element, label, value=None, key=None): "Display a color picker widget.\n\n Note: This is a beta feature. See\n https://docs.streamlit.io/en/latest/pre_release_features.html for more\n information.\n\n Parameters\n ----------\n label : str\n A short label explaining to the user what this input is for.\n value : str or None\n The hex value of this widget when it first renders. If None,\n defaults to black.\n key : str\n An optional string to use as the unique key for the widget.\n If this is omitted, a key will be generated for the widget\n based on its content. Multiple widgets of the same type may\n not share the same key.\n\n Returns\n -------\n str\n The selected color as a hex string.\n\n Example\n -------\n >>> color = st.beta_color_picker('Pick A Color', '#00f900')\n >>> st.write('The current color is', color)\n\n " if (value is None): value = '#000000' if (not isinstance(value, str)): raise StreamlitAPIException(("\n Color Picker Value has invalid type: %s. Expects a hex string\n like '#00FFAA' or '#000'.\n " % type(value).__name__)) match = re.match('^#(?:[0-9a-fA-F]{3}){1,2}$', value) if (not match): raise StreamlitAPIException(("\n '%s' is not a valid hex code for colors. Valid ones are like\n '#00FFAA' or '#000'.\n " % value)) element.color_picker.label = label element.color_picker.default = str(value) ui_value = _get_widget_ui_value('color_picker', element, user_key=key) current_value = (ui_value if (ui_value is not None) else value) return str(current_value)
8,279,966,507,809,524,000
Display a color picker widget. Note: This is a beta feature. See https://docs.streamlit.io/en/latest/pre_release_features.html for more information. Parameters ---------- label : str A short label explaining to the user what this input is for. value : str or None The hex value of this widget when it first renders. If None, defaults to black. key : str An optional string to use as the unique key for the widget. If this is omitted, a key will be generated for the widget based on its content. Multiple widgets of the same type may not share the same key. Returns ------- str The selected color as a hex string. Example ------- >>> color = st.beta_color_picker('Pick A Color', '#00f900') >>> st.write('The current color is', color)
lib/streamlit/DeltaGenerator.py
beta_color_picker
OakNorthAI/streamlit-base
python
@_with_element def beta_color_picker(self, element, label, value=None, key=None): "Display a color picker widget.\n\n Note: This is a beta feature. See\n https://docs.streamlit.io/en/latest/pre_release_features.html for more\n information.\n\n Parameters\n ----------\n label : str\n A short label explaining to the user what this input is for.\n value : str or None\n The hex value of this widget when it first renders. If None,\n defaults to black.\n key : str\n An optional string to use as the unique key for the widget.\n If this is omitted, a key will be generated for the widget\n based on its content. Multiple widgets of the same type may\n not share the same key.\n\n Returns\n -------\n str\n The selected color as a hex string.\n\n Example\n -------\n >>> color = st.beta_color_picker('Pick A Color', '#00f900')\n >>> st.write('The current color is', color)\n\n " if (value is None): value = '#000000' if (not isinstance(value, str)): raise StreamlitAPIException(("\n Color Picker Value has invalid type: %s. Expects a hex string\n like '#00FFAA' or '#000'.\n " % type(value).__name__)) match = re.match('^#(?:[0-9a-fA-F]{3}){1,2}$', value) if (not match): raise StreamlitAPIException(("\n '%s' is not a valid hex code for colors. Valid ones are like\n '#00FFAA' or '#000'.\n " % value)) element.color_picker.label = label element.color_picker.default = str(value) ui_value = _get_widget_ui_value('color_picker', element, user_key=key) current_value = (ui_value if (ui_value is not None) else value) return str(current_value)
@_with_element def text_input(self, element, label, value='', max_chars=None, key=None, type='default'): 'Display a single-line text input widget.\n\n Parameters\n ----------\n label : str\n A short label explaining to the user what this input is for.\n value : any\n The text value of this widget when it first renders. This will be\n cast to str internally.\n max_chars : int or None\n Max number of characters allowed in text input.\n key : str\n An optional string to use as the unique key for the widget.\n If this is omitted, a key will be generated for the widget\n based on its content. Multiple widgets of the same type may\n not share the same key.\n type : str\n The type of the text input. This can be either "default" (for\n a regular text input), or "password" (for a text input that\n masks the user\'s typed value). Defaults to "default".\n\n Returns\n -------\n str\n The current value of the text input widget.\n\n Example\n -------\n >>> title = st.text_input(\'Movie title\', \'Life of Brian\')\n >>> st.write(\'The current movie title is\', title)\n\n ' element.text_input.label = label element.text_input.default = str(value) if (max_chars is not None): element.text_input.max_chars = max_chars if (type == 'default'): element.text_input.type = TextInput.DEFAULT elif (type == 'password'): element.text_input.type = TextInput.PASSWORD else: raise StreamlitAPIException(("'%s' is not a valid text_input type. Valid types are 'default' and 'password'." % type)) ui_value = _get_widget_ui_value('text_input', element, user_key=key) current_value = (ui_value if (ui_value is not None) else value) return str(current_value)
7,888,950,086,938,866,000
Display a single-line text input widget. Parameters ---------- label : str A short label explaining to the user what this input is for. value : any The text value of this widget when it first renders. This will be cast to str internally. max_chars : int or None Max number of characters allowed in text input. key : str An optional string to use as the unique key for the widget. If this is omitted, a key will be generated for the widget based on its content. Multiple widgets of the same type may not share the same key. type : str The type of the text input. This can be either "default" (for a regular text input), or "password" (for a text input that masks the user's typed value). Defaults to "default". Returns ------- str The current value of the text input widget. Example ------- >>> title = st.text_input('Movie title', 'Life of Brian') >>> st.write('The current movie title is', title)
lib/streamlit/DeltaGenerator.py
text_input
OakNorthAI/streamlit-base
python
@_with_element def text_input(self, element, label, value=, max_chars=None, key=None, type='default'): 'Display a single-line text input widget.\n\n Parameters\n ----------\n label : str\n A short label explaining to the user what this input is for.\n value : any\n The text value of this widget when it first renders. This will be\n cast to str internally.\n max_chars : int or None\n Max number of characters allowed in text input.\n key : str\n An optional string to use as the unique key for the widget.\n If this is omitted, a key will be generated for the widget\n based on its content. Multiple widgets of the same type may\n not share the same key.\n type : str\n The type of the text input. This can be either "default" (for\n a regular text input), or "password" (for a text input that\n masks the user\'s typed value). Defaults to "default".\n\n Returns\n -------\n str\n The current value of the text input widget.\n\n Example\n -------\n >>> title = st.text_input(\'Movie title\', \'Life of Brian\')\n >>> st.write(\'The current movie title is\', title)\n\n ' element.text_input.label = label element.text_input.default = str(value) if (max_chars is not None): element.text_input.max_chars = max_chars if (type == 'default'): element.text_input.type = TextInput.DEFAULT elif (type == 'password'): element.text_input.type = TextInput.PASSWORD else: raise StreamlitAPIException(("'%s' is not a valid text_input type. Valid types are 'default' and 'password'." % type)) ui_value = _get_widget_ui_value('text_input', element, user_key=key) current_value = (ui_value if (ui_value is not None) else value) return str(current_value)
@_with_element def text_area(self, element, label, value='', height=None, max_chars=None, key=None): "Display a multi-line text input widget.\n\n Parameters\n ----------\n label : str\n A short label explaining to the user what this input is for.\n value : any\n The text value of this widget when it first renders. This will be\n cast to str internally.\n height : int or None\n Desired height of the UI element expressed in pixels. If None, a\n default height is used.\n max_chars : int or None\n Maximum number of characters allowed in text area.\n key : str\n An optional string to use as the unique key for the widget.\n If this is omitted, a key will be generated for the widget\n based on its content. Multiple widgets of the same type may\n not share the same key.\n\n Returns\n -------\n str\n The current value of the text input widget.\n\n Example\n -------\n >>> txt = st.text_area('Text to analyze', '''\n ... It was the best of times, it was the worst of times, it was\n ... the age of wisdom, it was the age of foolishness, it was\n ... the epoch of belief, it was the epoch of incredulity, it\n ... was the season of Light, it was the season of Darkness, it\n ... was the spring of hope, it was the winter of despair, (...)\n ... ''')\n >>> st.write('Sentiment:', run_sentiment_analysis(txt))\n\n " element.text_area.label = label element.text_area.default = str(value) if (height is not None): element.text_area.height = height if (max_chars is not None): element.text_area.max_chars = max_chars ui_value = _get_widget_ui_value('text_area', element, user_key=key) current_value = (ui_value if (ui_value is not None) else value) return str(current_value)
4,256,666,320,738,230,000
Display a multi-line text input widget. Parameters ---------- label : str A short label explaining to the user what this input is for. value : any The text value of this widget when it first renders. This will be cast to str internally. height : int or None Desired height of the UI element expressed in pixels. If None, a default height is used. max_chars : int or None Maximum number of characters allowed in text area. key : str An optional string to use as the unique key for the widget. If this is omitted, a key will be generated for the widget based on its content. Multiple widgets of the same type may not share the same key. Returns ------- str The current value of the text input widget. Example ------- >>> txt = st.text_area('Text to analyze', ''' ... It was the best of times, it was the worst of times, it was ... the age of wisdom, it was the age of foolishness, it was ... the epoch of belief, it was the epoch of incredulity, it ... was the season of Light, it was the season of Darkness, it ... was the spring of hope, it was the winter of despair, (...) ... ''') >>> st.write('Sentiment:', run_sentiment_analysis(txt))
lib/streamlit/DeltaGenerator.py
text_area
OakNorthAI/streamlit-base
python
@_with_element def text_area(self, element, label, value=, height=None, max_chars=None, key=None): "Display a multi-line text input widget.\n\n Parameters\n ----------\n label : str\n A short label explaining to the user what this input is for.\n value : any\n The text value of this widget when it first renders. This will be\n cast to str internally.\n height : int or None\n Desired height of the UI element expressed in pixels. If None, a\n default height is used.\n max_chars : int or None\n Maximum number of characters allowed in text area.\n key : str\n An optional string to use as the unique key for the widget.\n If this is omitted, a key will be generated for the widget\n based on its content. Multiple widgets of the same type may\n not share the same key.\n\n Returns\n -------\n str\n The current value of the text input widget.\n\n Example\n -------\n >>> txt = st.text_area('Text to analyze', '\n ... It was the best of times, it was the worst of times, it was\n ... the age of wisdom, it was the age of foolishness, it was\n ... the epoch of belief, it was the epoch of incredulity, it\n ... was the season of Light, it was the season of Darkness, it\n ... was the spring of hope, it was the winter of despair, (...)\n ... ')\n >>> st.write('Sentiment:', run_sentiment_analysis(txt))\n\n " element.text_area.label = label element.text_area.default = str(value) if (height is not None): element.text_area.height = height if (max_chars is not None): element.text_area.max_chars = max_chars ui_value = _get_widget_ui_value('text_area', element, user_key=key) current_value = (ui_value if (ui_value is not None) else value) return str(current_value)
@_with_element def time_input(self, element, label, value=None, key=None): "Display a time input widget.\n\n Parameters\n ----------\n label : str\n A short label explaining to the user what this time input is for.\n value : datetime.time/datetime.datetime\n The value of this widget when it first renders. This will be\n cast to str internally. Defaults to the current time.\n key : str\n An optional string to use as the unique key for the widget.\n If this is omitted, a key will be generated for the widget\n based on its content. Multiple widgets of the same type may\n not share the same key.\n\n Returns\n -------\n datetime.time\n The current value of the time input widget.\n\n Example\n -------\n >>> t = st.time_input('Set an alarm for', datetime.time(8, 45))\n >>> st.write('Alarm is set for', t)\n\n " if (value is None): value = datetime.now().time() if ((not isinstance(value, datetime)) and (not isinstance(value, time))): raise StreamlitAPIException('The type of the value should be either datetime or time.') if isinstance(value, datetime): value = value.time() element.time_input.label = label element.time_input.default = time.strftime(value, '%H:%M') ui_value = _get_widget_ui_value('time_input', element, user_key=key) current_value = (datetime.strptime(ui_value, '%H:%M').time() if (ui_value is not None) else value) return current_value
6,452,685,206,723,403,000
Display a time input widget. Parameters ---------- label : str A short label explaining to the user what this time input is for. value : datetime.time/datetime.datetime The value of this widget when it first renders. This will be cast to str internally. Defaults to the current time. key : str An optional string to use as the unique key for the widget. If this is omitted, a key will be generated for the widget based on its content. Multiple widgets of the same type may not share the same key. Returns ------- datetime.time The current value of the time input widget. Example ------- >>> t = st.time_input('Set an alarm for', datetime.time(8, 45)) >>> st.write('Alarm is set for', t)
lib/streamlit/DeltaGenerator.py
time_input
OakNorthAI/streamlit-base
python
@_with_element def time_input(self, element, label, value=None, key=None): "Display a time input widget.\n\n Parameters\n ----------\n label : str\n A short label explaining to the user what this time input is for.\n value : datetime.time/datetime.datetime\n The value of this widget when it first renders. This will be\n cast to str internally. Defaults to the current time.\n key : str\n An optional string to use as the unique key for the widget.\n If this is omitted, a key will be generated for the widget\n based on its content. Multiple widgets of the same type may\n not share the same key.\n\n Returns\n -------\n datetime.time\n The current value of the time input widget.\n\n Example\n -------\n >>> t = st.time_input('Set an alarm for', datetime.time(8, 45))\n >>> st.write('Alarm is set for', t)\n\n " if (value is None): value = datetime.now().time() if ((not isinstance(value, datetime)) and (not isinstance(value, time))): raise StreamlitAPIException('The type of the value should be either datetime or time.') if isinstance(value, datetime): value = value.time() element.time_input.label = label element.time_input.default = time.strftime(value, '%H:%M') ui_value = _get_widget_ui_value('time_input', element, user_key=key) current_value = (datetime.strptime(ui_value, '%H:%M').time() if (ui_value is not None) else value) return current_value
@_with_element def date_input(self, element, label, value=None, min_value=datetime.min, max_value=None, key=None): 'Display a date input widget.\n\n Parameters\n ----------\n label : str\n A short label explaining to the user what this date input is for.\n value : datetime.date or datetime.datetime or list/tuple of datetime.date or datetime.datetime or None\n The value of this widget when it first renders. If a list/tuple with\n 0 to 2 date/datetime values is provided, the datepicker will allow\n users to provide a range. Defaults to today as a single-date picker.\n min_value : datetime.date or datetime.datetime\n The minimum selectable date. Defaults to datetime.min.\n max_value : datetime.date or datetime.datetime\n The maximum selectable date. Defaults to today+10y.\n key : str\n An optional string to use as the unique key for the widget.\n If this is omitted, a key will be generated for the widget\n based on its content. Multiple widgets of the same type may\n not share the same key.\n\n Returns\n -------\n datetime.date\n The current value of the date input widget.\n\n Example\n -------\n >>> d = st.date_input(\n ... "When\'s your birthday",\n ... datetime.date(2019, 7, 6))\n >>> st.write(\'Your birthday is:\', d)\n\n ' if (value is None): value = datetime.now().date() single_value = isinstance(value, (date, datetime)) range_value = (isinstance(value, (list, tuple)) and (len(value) in (0, 1, 2))) if ((not single_value) and (not range_value)): raise StreamlitAPIException('DateInput value should either be an date/datetime or a list/tuple of 0 - 2 date/datetime values') if single_value: value = [value] element.date_input.is_range = range_value value = [(v.date() if isinstance(v, datetime) else v) for v in value] element.date_input.label = label element.date_input.default[:] = [date.strftime(v, '%Y/%m/%d') for v in value] if isinstance(min_value, datetime): min_value = min_value.date() element.date_input.min = date.strftime(min_value, '%Y/%m/%d') if (max_value is None): today = date.today() max_value = date((today.year + 10), today.month, today.day) if isinstance(max_value, datetime): max_value = max_value.date() element.date_input.max = date.strftime(max_value, '%Y/%m/%d') ui_value = _get_widget_ui_value('date_input', element, user_key=key) if (ui_value is not None): value = getattr(ui_value, 'data') value = [datetime.strptime(v, '%Y/%m/%d').date() for v in value] if single_value: return value[0] else: return tuple(value)
-8,081,064,151,479,856,000
Display a date input widget. Parameters ---------- label : str A short label explaining to the user what this date input is for. value : datetime.date or datetime.datetime or list/tuple of datetime.date or datetime.datetime or None The value of this widget when it first renders. If a list/tuple with 0 to 2 date/datetime values is provided, the datepicker will allow users to provide a range. Defaults to today as a single-date picker. min_value : datetime.date or datetime.datetime The minimum selectable date. Defaults to datetime.min. max_value : datetime.date or datetime.datetime The maximum selectable date. Defaults to today+10y. key : str An optional string to use as the unique key for the widget. If this is omitted, a key will be generated for the widget based on its content. Multiple widgets of the same type may not share the same key. Returns ------- datetime.date The current value of the date input widget. Example ------- >>> d = st.date_input( ... "When's your birthday", ... datetime.date(2019, 7, 6)) >>> st.write('Your birthday is:', d)
lib/streamlit/DeltaGenerator.py
date_input
OakNorthAI/streamlit-base
python
@_with_element def date_input(self, element, label, value=None, min_value=datetime.min, max_value=None, key=None): 'Display a date input widget.\n\n Parameters\n ----------\n label : str\n A short label explaining to the user what this date input is for.\n value : datetime.date or datetime.datetime or list/tuple of datetime.date or datetime.datetime or None\n The value of this widget when it first renders. If a list/tuple with\n 0 to 2 date/datetime values is provided, the datepicker will allow\n users to provide a range. Defaults to today as a single-date picker.\n min_value : datetime.date or datetime.datetime\n The minimum selectable date. Defaults to datetime.min.\n max_value : datetime.date or datetime.datetime\n The maximum selectable date. Defaults to today+10y.\n key : str\n An optional string to use as the unique key for the widget.\n If this is omitted, a key will be generated for the widget\n based on its content. Multiple widgets of the same type may\n not share the same key.\n\n Returns\n -------\n datetime.date\n The current value of the date input widget.\n\n Example\n -------\n >>> d = st.date_input(\n ... "When\'s your birthday",\n ... datetime.date(2019, 7, 6))\n >>> st.write(\'Your birthday is:\', d)\n\n ' if (value is None): value = datetime.now().date() single_value = isinstance(value, (date, datetime)) range_value = (isinstance(value, (list, tuple)) and (len(value) in (0, 1, 2))) if ((not single_value) and (not range_value)): raise StreamlitAPIException('DateInput value should either be an date/datetime or a list/tuple of 0 - 2 date/datetime values') if single_value: value = [value] element.date_input.is_range = range_value value = [(v.date() if isinstance(v, datetime) else v) for v in value] element.date_input.label = label element.date_input.default[:] = [date.strftime(v, '%Y/%m/%d') for v in value] if isinstance(min_value, datetime): min_value = min_value.date() element.date_input.min = date.strftime(min_value, '%Y/%m/%d') if (max_value is None): today = date.today() max_value = date((today.year + 10), today.month, today.day) if isinstance(max_value, datetime): max_value = max_value.date() element.date_input.max = date.strftime(max_value, '%Y/%m/%d') ui_value = _get_widget_ui_value('date_input', element, user_key=key) if (ui_value is not None): value = getattr(ui_value, 'data') value = [datetime.strptime(v, '%Y/%m/%d').date() for v in value] if single_value: return value[0] else: return tuple(value)
@_with_element def number_input(self, element, label, min_value=None, max_value=None, value=NoValue(), step=None, format=None, key=None): "Display a numeric input widget.\n\n Parameters\n ----------\n label : str or None\n A short label explaining to the user what this input is for.\n min_value : int or float or None\n The minimum permitted value.\n If None, there will be no minimum.\n max_value : int or float or None\n The maximum permitted value.\n If None, there will be no maximum.\n value : int or float or None\n The value of this widget when it first renders.\n Defaults to min_value, or 0.0 if min_value is None\n step : int or float or None\n The stepping interval.\n Defaults to 1 if the value is an int, 0.01 otherwise.\n If the value is not specified, the format parameter will be used.\n format : str or None\n A printf-style format string controlling how the interface should\n display numbers. Output must be purely numeric. This does not impact\n the return value. Valid formatters: %d %e %f %g %i\n key : str\n An optional string to use as the unique key for the widget.\n If this is omitted, a key will be generated for the widget\n based on its content. Multiple widgets of the same type may\n not share the same key.\n\n Returns\n -------\n int or float\n The current value of the numeric input widget. The return type\n will match the data type of the value parameter.\n\n Example\n -------\n >>> number = st.number_input('Insert a number')\n >>> st.write('The current number is ', number)\n " if isinstance(value, NoValue): if min_value: value = min_value else: value = 0.0 int_value = isinstance(value, numbers.Integral) float_value = isinstance(value, float) if (value is None): raise StreamlitAPIException('Default value for number_input should be an int or a float.') else: if (format is None): format = ('%d' if int_value else '%0.2f') if ((format in ['%d', '%u', '%i']) and float_value): import streamlit as st st.warning('Warning: NumberInput value below is float, but format {} displays as integer.'.format(format)) if (step is None): step = (1 if int_value else 0.01) try: float((format % 2)) except (TypeError, ValueError): raise StreamlitAPIException(('Format string for st.number_input contains invalid characters: %s' % format)) args = [min_value, max_value, step] int_args = all(map((lambda a: (isinstance(a, numbers.Integral) or isinstance(a, type(None)))), args)) float_args = all(map((lambda a: (isinstance(a, float) or isinstance(a, type(None)))), args)) if ((not int_args) and (not float_args)): raise StreamlitAPIException(('All arguments must be of the same type.\n`value` has %(value_type)s type.\n`min_value` has %(min_type)s type.\n`max_value` has %(max_type)s type.' % {'value_type': type(value).__name__, 'min_type': type(min_value).__name__, 'max_type': type(max_value).__name__})) all_ints = (int_value and int_args) all_floats = (float_value and float_args) if ((not all_ints) and (not all_floats)): raise StreamlitAPIException(('All numerical arguments must be of the same type.\n`value` has %(value_type)s type.\n`min_value` has %(min_type)s type.\n`max_value` has %(max_type)s type.\n`step` has %(step_type)s type.' % {'value_type': type(value).__name__, 'min_type': type(min_value).__name__, 'max_type': type(max_value).__name__, 'step_type': type(step).__name__})) if ((min_value and (min_value > value)) or (max_value and (max_value < value))): raise StreamlitAPIException(('The default `value` of %(value)s must lie between the `min_value` of %(min)s and the `max_value` of %(max)s, inclusively.' % {'value': value, 'min': min_value, 'max': max_value})) try: if all_ints: if (min_value is not None): JSNumber.validate_int_bounds(min_value, '`min_value`') if (max_value is not None): JSNumber.validate_int_bounds(max_value, '`max_value`') if (step is not None): JSNumber.validate_int_bounds(step, '`step`') JSNumber.validate_int_bounds(value, '`value`') else: if (min_value is not None): JSNumber.validate_float_bounds(min_value, '`min_value`') if (max_value is not None): JSNumber.validate_float_bounds(max_value, '`max_value`') if (step is not None): JSNumber.validate_float_bounds(step, '`step`') JSNumber.validate_float_bounds(value, '`value`') except JSNumberBoundsException as e: raise StreamlitAPIException(str(e)) number_input = element.number_input number_input.data_type = (NumberInput.INT if all_ints else NumberInput.FLOAT) number_input.label = label number_input.default = value if (min_value is not None): number_input.min = min_value number_input.has_min = True if (max_value is not None): number_input.max = max_value number_input.has_max = True if (step is not None): number_input.step = step if (format is not None): number_input.format = format ui_value = _get_widget_ui_value('number_input', element, user_key=key) return (ui_value if (ui_value is not None) else value)
-85,386,675,137,491,120
Display a numeric input widget. Parameters ---------- label : str or None A short label explaining to the user what this input is for. min_value : int or float or None The minimum permitted value. If None, there will be no minimum. max_value : int or float or None The maximum permitted value. If None, there will be no maximum. value : int or float or None The value of this widget when it first renders. Defaults to min_value, or 0.0 if min_value is None step : int or float or None The stepping interval. Defaults to 1 if the value is an int, 0.01 otherwise. If the value is not specified, the format parameter will be used. format : str or None A printf-style format string controlling how the interface should display numbers. Output must be purely numeric. This does not impact the return value. Valid formatters: %d %e %f %g %i key : str An optional string to use as the unique key for the widget. If this is omitted, a key will be generated for the widget based on its content. Multiple widgets of the same type may not share the same key. Returns ------- int or float The current value of the numeric input widget. The return type will match the data type of the value parameter. Example ------- >>> number = st.number_input('Insert a number') >>> st.write('The current number is ', number)
lib/streamlit/DeltaGenerator.py
number_input
OakNorthAI/streamlit-base
python
@_with_element def number_input(self, element, label, min_value=None, max_value=None, value=NoValue(), step=None, format=None, key=None): "Display a numeric input widget.\n\n Parameters\n ----------\n label : str or None\n A short label explaining to the user what this input is for.\n min_value : int or float or None\n The minimum permitted value.\n If None, there will be no minimum.\n max_value : int or float or None\n The maximum permitted value.\n If None, there will be no maximum.\n value : int or float or None\n The value of this widget when it first renders.\n Defaults to min_value, or 0.0 if min_value is None\n step : int or float or None\n The stepping interval.\n Defaults to 1 if the value is an int, 0.01 otherwise.\n If the value is not specified, the format parameter will be used.\n format : str or None\n A printf-style format string controlling how the interface should\n display numbers. Output must be purely numeric. This does not impact\n the return value. Valid formatters: %d %e %f %g %i\n key : str\n An optional string to use as the unique key for the widget.\n If this is omitted, a key will be generated for the widget\n based on its content. Multiple widgets of the same type may\n not share the same key.\n\n Returns\n -------\n int or float\n The current value of the numeric input widget. The return type\n will match the data type of the value parameter.\n\n Example\n -------\n >>> number = st.number_input('Insert a number')\n >>> st.write('The current number is ', number)\n " if isinstance(value, NoValue): if min_value: value = min_value else: value = 0.0 int_value = isinstance(value, numbers.Integral) float_value = isinstance(value, float) if (value is None): raise StreamlitAPIException('Default value for number_input should be an int or a float.') else: if (format is None): format = ('%d' if int_value else '%0.2f') if ((format in ['%d', '%u', '%i']) and float_value): import streamlit as st st.warning('Warning: NumberInput value below is float, but format {} displays as integer.'.format(format)) if (step is None): step = (1 if int_value else 0.01) try: float((format % 2)) except (TypeError, ValueError): raise StreamlitAPIException(('Format string for st.number_input contains invalid characters: %s' % format)) args = [min_value, max_value, step] int_args = all(map((lambda a: (isinstance(a, numbers.Integral) or isinstance(a, type(None)))), args)) float_args = all(map((lambda a: (isinstance(a, float) or isinstance(a, type(None)))), args)) if ((not int_args) and (not float_args)): raise StreamlitAPIException(('All arguments must be of the same type.\n`value` has %(value_type)s type.\n`min_value` has %(min_type)s type.\n`max_value` has %(max_type)s type.' % {'value_type': type(value).__name__, 'min_type': type(min_value).__name__, 'max_type': type(max_value).__name__})) all_ints = (int_value and int_args) all_floats = (float_value and float_args) if ((not all_ints) and (not all_floats)): raise StreamlitAPIException(('All numerical arguments must be of the same type.\n`value` has %(value_type)s type.\n`min_value` has %(min_type)s type.\n`max_value` has %(max_type)s type.\n`step` has %(step_type)s type.' % {'value_type': type(value).__name__, 'min_type': type(min_value).__name__, 'max_type': type(max_value).__name__, 'step_type': type(step).__name__})) if ((min_value and (min_value > value)) or (max_value and (max_value < value))): raise StreamlitAPIException(('The default `value` of %(value)s must lie between the `min_value` of %(min)s and the `max_value` of %(max)s, inclusively.' % {'value': value, 'min': min_value, 'max': max_value})) try: if all_ints: if (min_value is not None): JSNumber.validate_int_bounds(min_value, '`min_value`') if (max_value is not None): JSNumber.validate_int_bounds(max_value, '`max_value`') if (step is not None): JSNumber.validate_int_bounds(step, '`step`') JSNumber.validate_int_bounds(value, '`value`') else: if (min_value is not None): JSNumber.validate_float_bounds(min_value, '`min_value`') if (max_value is not None): JSNumber.validate_float_bounds(max_value, '`max_value`') if (step is not None): JSNumber.validate_float_bounds(step, '`step`') JSNumber.validate_float_bounds(value, '`value`') except JSNumberBoundsException as e: raise StreamlitAPIException(str(e)) number_input = element.number_input number_input.data_type = (NumberInput.INT if all_ints else NumberInput.FLOAT) number_input.label = label number_input.default = value if (min_value is not None): number_input.min = min_value number_input.has_min = True if (max_value is not None): number_input.max = max_value number_input.has_max = True if (step is not None): number_input.step = step if (format is not None): number_input.format = format ui_value = _get_widget_ui_value('number_input', element, user_key=key) return (ui_value if (ui_value is not None) else value)
@_with_element def progress(self, element, value): 'Display a progress bar.\n\n Parameters\n ----------\n value : int or float\n 0 <= value <= 100 for int\n\n 0.0 <= value <= 1.0 for float\n\n Example\n -------\n Here is an example of a progress bar increasing over time:\n\n >>> import time\n >>>\n >>> my_bar = st.progress(0)\n >>>\n >>> for percent_complete in range(100):\n ... time.sleep(0.1)\n ... my_bar.progress(percent_complete + 1)\n\n ' if isinstance(value, float): if (0.0 <= value <= 1.0): element.progress.value = int((value * 100)) else: raise StreamlitAPIException(('Progress Value has invalid value [0.0, 1.0]: %f' % value)) elif isinstance(value, int): if (0 <= value <= 100): element.progress.value = value else: raise StreamlitAPIException(('Progress Value has invalid value [0, 100]: %d' % value)) else: raise StreamlitAPIException(('Progress Value has invalid type: %s' % type(value).__name__))
-3,351,466,489,674,978,300
Display a progress bar. Parameters ---------- value : int or float 0 <= value <= 100 for int 0.0 <= value <= 1.0 for float Example ------- Here is an example of a progress bar increasing over time: >>> import time >>> >>> my_bar = st.progress(0) >>> >>> for percent_complete in range(100): ... time.sleep(0.1) ... my_bar.progress(percent_complete + 1)
lib/streamlit/DeltaGenerator.py
progress
OakNorthAI/streamlit-base
python
@_with_element def progress(self, element, value): 'Display a progress bar.\n\n Parameters\n ----------\n value : int or float\n 0 <= value <= 100 for int\n\n 0.0 <= value <= 1.0 for float\n\n Example\n -------\n Here is an example of a progress bar increasing over time:\n\n >>> import time\n >>>\n >>> my_bar = st.progress(0)\n >>>\n >>> for percent_complete in range(100):\n ... time.sleep(0.1)\n ... my_bar.progress(percent_complete + 1)\n\n ' if isinstance(value, float): if (0.0 <= value <= 1.0): element.progress.value = int((value * 100)) else: raise StreamlitAPIException(('Progress Value has invalid value [0.0, 1.0]: %f' % value)) elif isinstance(value, int): if (0 <= value <= 100): element.progress.value = value else: raise StreamlitAPIException(('Progress Value has invalid value [0, 100]: %d' % value)) else: raise StreamlitAPIException(('Progress Value has invalid type: %s' % type(value).__name__))
@_with_element def empty(self, element): 'Add a placeholder to the app.\n\n The placeholder can be filled any time by calling methods on the return\n value.\n\n Example\n -------\n >>> my_placeholder = st.empty()\n >>>\n >>> # Now replace the placeholder with some text:\n >>> my_placeholder.text("Hello world!")\n >>>\n >>> # And replace the text with an image:\n >>> my_placeholder.image(my_image_bytes)\n\n ' element.empty.unused = True
-2,141,839,062,786,735,400
Add a placeholder to the app. The placeholder can be filled any time by calling methods on the return value. Example ------- >>> my_placeholder = st.empty() >>> >>> # Now replace the placeholder with some text: >>> my_placeholder.text("Hello world!") >>> >>> # And replace the text with an image: >>> my_placeholder.image(my_image_bytes)
lib/streamlit/DeltaGenerator.py
empty
OakNorthAI/streamlit-base
python
@_with_element def empty(self, element): 'Add a placeholder to the app.\n\n The placeholder can be filled any time by calling methods on the return\n value.\n\n Example\n -------\n >>> my_placeholder = st.empty()\n >>>\n >>> # Now replace the placeholder with some text:\n >>> my_placeholder.text("Hello world!")\n >>>\n >>> # And replace the text with an image:\n >>> my_placeholder.image(my_image_bytes)\n\n ' element.empty.unused = True
@_with_element def map(self, element, data=None, zoom=None, use_container_width=True): "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 " import streamlit.elements.map as streamlit_map element.deck_gl_json_chart.json = streamlit_map.to_deckgl_json(data, zoom) element.deck_gl_json_chart.use_container_width = use_container_width
-8,430,331,400,841,698,000
Display a map with points on it. This is a wrapper around st.pydeck_chart to quickly create scatterplot charts on top of a map, with auto-centering and auto-zoom. When using this command, we advise all users to use a personal Mapbox token. This ensures the map tiles used in this chart are more robust. You can do this with the mapbox.token config option. To get a token for yourself, create an account at https://mapbox.com. It's free! (for moderate usage levels) See https://docs.streamlit.io/en/latest/cli.html#view-all-config-options for more info on how to set config options. Parameters ---------- data : pandas.DataFrame, pandas.Styler, numpy.ndarray, Iterable, dict, or None The data to be plotted. Must have columns called 'lat', 'lon', 'latitude', or 'longitude'. zoom : int Zoom level as specified in https://wiki.openstreetmap.org/wiki/Zoom_levels Example ------- >>> import pandas as pd >>> import numpy as np >>> >>> df = pd.DataFrame( ... np.random.randn(1000, 2) / [50, 50] + [37.76, -122.4], ... columns=['lat', 'lon']) >>> >>> st.map(df) .. output:: https://share.streamlit.io/0.53.0-SULT/index.html?id=9gTiomqPEbvHY2huTLoQtH height: 600px
lib/streamlit/DeltaGenerator.py
map
OakNorthAI/streamlit-base
python
@_with_element def map(self, element, data=None, zoom=None, use_container_width=True): "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 " import streamlit.elements.map as streamlit_map element.deck_gl_json_chart.json = streamlit_map.to_deckgl_json(data, zoom) element.deck_gl_json_chart.use_container_width = use_container_width
@_with_element def deck_gl_chart(self, element, spec=None, use_container_width=False, **kwargs): 'Draw a map chart using the Deck.GL library.\n\n This API closely follows Deck.GL\'s JavaScript API\n (https://deck.gl/#/documentation), with a few small adaptations and\n some syntax sugar.\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\n spec : dict\n Keys in this dict can be:\n\n - Anything accepted by Deck.GL\'s top level element, such as\n "viewport", "height", "width".\n\n - "layers": a list of dicts containing information to build a new\n Deck.GL layer in the map. Each layer accepts the following keys:\n\n - "data" : DataFrame\n The data for the current layer.\n\n - "type" : str\n One of the Deck.GL layer types that are currently supported\n by Streamlit: ArcLayer, GridLayer, HexagonLayer, LineLayer,\n PointCloudLayer, ScatterplotLayer, ScreenGridLayer,\n TextLayer.\n\n - Plus anything accepted by that layer type. The exact keys that\n are accepted depend on the "type" field, above. For example, for\n ScatterplotLayer you can set fields like "opacity", "filled",\n "stroked", and so on.\n\n In addition, Deck.GL"s documentation for ScatterplotLayer\n shows you can use a "getRadius" field to individually set\n the radius of each circle in the plot. So here you would\n set "getRadius": "my_column" where "my_column" is the name\n of the column containing the radius data.\n\n For things like "getPosition", which expect an array rather\n than a scalar value, we provide alternates that make the\n API simpler to use with dataframes:\n\n - Instead of "getPosition" : use "getLatitude" and\n "getLongitude".\n - Instead of "getSourcePosition" : use "getLatitude" and\n "getLongitude".\n - Instead of "getTargetPosition" : use "getTargetLatitude"\n and "getTargetLongitude".\n - Instead of "getColor" : use "getColorR", "getColorG",\n "getColorB", and (optionally) "getColorA", for red,\n green, blue and alpha.\n - Instead of "getSourceColor" : use the same as above.\n - Instead of "getTargetColor" : use "getTargetColorR", etc.\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 **kwargs : any\n Same as spec, but as keywords. Keys are "unflattened" at the\n underscore characters. For example, foo_bar_baz=123 becomes\n foo={\'bar\': {\'bar\': 123}}.\n\n Example\n -------\n >>> st.deck_gl_chart(\n ... viewport={\n ... \'latitude\': 37.76,\n ... \'longitude\': -122.4,\n ... \'zoom\': 11,\n ... \'pitch\': 50,\n ... },\n ... layers=[{\n ... \'type\': \'HexagonLayer\',\n ... \'data\': df,\n ... \'radius\': 200,\n ... \'elevationScale\': 4,\n ... \'elevationRange\': [0, 1000],\n ... \'pickable\': True,\n ... \'extruded\': True,\n ... }, {\n ... \'type\': \'ScatterplotLayer\',\n ... \'data\': df,\n ... }])\n ...\n\n .. output::\n https://share.streamlit.io/0.50.0-td2L/index.html?id=3GfRygWqxuqB5UitZLjz9i\n height: 530px\n\n ' suppress_deprecation_warning = config.get_option('global.suppressDeprecationWarnings') if (not suppress_deprecation_warning): import streamlit as st st.warning('\n The `deck_gl_chart` widget is deprecated and will be removed on\n 2020-05-01. To render a map, you should use `st.pydeck_chart` widget.\n ') import streamlit.elements.deck_gl as deck_gl deck_gl.marshall(element.deck_gl_chart, spec, use_container_width, **kwargs)
-622,602,971,289,724,700
Draw a map chart using the Deck.GL library. This API closely follows Deck.GL's JavaScript API (https://deck.gl/#/documentation), with a few small adaptations and some syntax sugar. When using this command, we advise all users to use a personal Mapbox token. This ensures the map tiles used in this chart are more robust. You can do this with the mapbox.token config option. To get a token for yourself, create an account at https://mapbox.com. It's free! (for moderate usage levels) See https://docs.streamlit.io/en/latest/cli.html#view-all-config-options for more info on how to set config options. Parameters ---------- spec : dict Keys in this dict can be: - Anything accepted by Deck.GL's top level element, such as "viewport", "height", "width". - "layers": a list of dicts containing information to build a new Deck.GL layer in the map. Each layer accepts the following keys: - "data" : DataFrame The data for the current layer. - "type" : str One of the Deck.GL layer types that are currently supported by Streamlit: ArcLayer, GridLayer, HexagonLayer, LineLayer, PointCloudLayer, ScatterplotLayer, ScreenGridLayer, TextLayer. - Plus anything accepted by that layer type. The exact keys that are accepted depend on the "type" field, above. For example, for ScatterplotLayer you can set fields like "opacity", "filled", "stroked", and so on. In addition, Deck.GL"s documentation for ScatterplotLayer shows you can use a "getRadius" field to individually set the radius of each circle in the plot. So here you would set "getRadius": "my_column" where "my_column" is the name of the column containing the radius data. For things like "getPosition", which expect an array rather than a scalar value, we provide alternates that make the API simpler to use with dataframes: - Instead of "getPosition" : use "getLatitude" and "getLongitude". - Instead of "getSourcePosition" : use "getLatitude" and "getLongitude". - Instead of "getTargetPosition" : use "getTargetLatitude" and "getTargetLongitude". - Instead of "getColor" : use "getColorR", "getColorG", "getColorB", and (optionally) "getColorA", for red, green, blue and alpha. - Instead of "getSourceColor" : use the same as above. - Instead of "getTargetColor" : use "getTargetColorR", etc. use_container_width : bool If True, set the chart width to the column width. This takes precedence over the figure's native `width` value. **kwargs : any Same as spec, but as keywords. Keys are "unflattened" at the underscore characters. For example, foo_bar_baz=123 becomes foo={'bar': {'bar': 123}}. Example ------- >>> st.deck_gl_chart( ... viewport={ ... 'latitude': 37.76, ... 'longitude': -122.4, ... 'zoom': 11, ... 'pitch': 50, ... }, ... layers=[{ ... 'type': 'HexagonLayer', ... 'data': df, ... 'radius': 200, ... 'elevationScale': 4, ... 'elevationRange': [0, 1000], ... 'pickable': True, ... 'extruded': True, ... }, { ... 'type': 'ScatterplotLayer', ... 'data': df, ... }]) ... .. output:: https://share.streamlit.io/0.50.0-td2L/index.html?id=3GfRygWqxuqB5UitZLjz9i height: 530px
lib/streamlit/DeltaGenerator.py
deck_gl_chart
OakNorthAI/streamlit-base
python
@_with_element def deck_gl_chart(self, element, spec=None, use_container_width=False, **kwargs): 'Draw a map chart using the Deck.GL library.\n\n This API closely follows Deck.GL\'s JavaScript API\n (https://deck.gl/#/documentation), with a few small adaptations and\n some syntax sugar.\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\n spec : dict\n Keys in this dict can be:\n\n - Anything accepted by Deck.GL\'s top level element, such as\n "viewport", "height", "width".\n\n - "layers": a list of dicts containing information to build a new\n Deck.GL layer in the map. Each layer accepts the following keys:\n\n - "data" : DataFrame\n The data for the current layer.\n\n - "type" : str\n One of the Deck.GL layer types that are currently supported\n by Streamlit: ArcLayer, GridLayer, HexagonLayer, LineLayer,\n PointCloudLayer, ScatterplotLayer, ScreenGridLayer,\n TextLayer.\n\n - Plus anything accepted by that layer type. The exact keys that\n are accepted depend on the "type" field, above. For example, for\n ScatterplotLayer you can set fields like "opacity", "filled",\n "stroked", and so on.\n\n In addition, Deck.GL"s documentation for ScatterplotLayer\n shows you can use a "getRadius" field to individually set\n the radius of each circle in the plot. So here you would\n set "getRadius": "my_column" where "my_column" is the name\n of the column containing the radius data.\n\n For things like "getPosition", which expect an array rather\n than a scalar value, we provide alternates that make the\n API simpler to use with dataframes:\n\n - Instead of "getPosition" : use "getLatitude" and\n "getLongitude".\n - Instead of "getSourcePosition" : use "getLatitude" and\n "getLongitude".\n - Instead of "getTargetPosition" : use "getTargetLatitude"\n and "getTargetLongitude".\n - Instead of "getColor" : use "getColorR", "getColorG",\n "getColorB", and (optionally) "getColorA", for red,\n green, blue and alpha.\n - Instead of "getSourceColor" : use the same as above.\n - Instead of "getTargetColor" : use "getTargetColorR", etc.\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 **kwargs : any\n Same as spec, but as keywords. Keys are "unflattened" at the\n underscore characters. For example, foo_bar_baz=123 becomes\n foo={\'bar\': {\'bar\': 123}}.\n\n Example\n -------\n >>> st.deck_gl_chart(\n ... viewport={\n ... \'latitude\': 37.76,\n ... \'longitude\': -122.4,\n ... \'zoom\': 11,\n ... \'pitch\': 50,\n ... },\n ... layers=[{\n ... \'type\': \'HexagonLayer\',\n ... \'data\': df,\n ... \'radius\': 200,\n ... \'elevationScale\': 4,\n ... \'elevationRange\': [0, 1000],\n ... \'pickable\': True,\n ... \'extruded\': True,\n ... }, {\n ... \'type\': \'ScatterplotLayer\',\n ... \'data\': df,\n ... }])\n ...\n\n .. output::\n https://share.streamlit.io/0.50.0-td2L/index.html?id=3GfRygWqxuqB5UitZLjz9i\n height: 530px\n\n ' suppress_deprecation_warning = config.get_option('global.suppressDeprecationWarnings') if (not suppress_deprecation_warning): import streamlit as st st.warning('\n The `deck_gl_chart` widget is deprecated and will be removed on\n 2020-05-01. To render a map, you should use `st.pydeck_chart` widget.\n ') import streamlit.elements.deck_gl as deck_gl deck_gl.marshall(element.deck_gl_chart, spec, use_container_width, **kwargs)
@_with_element def pydeck_chart(self, element, pydeck_obj=None, use_container_width=False): "Draw a chart using the PyDeck library.\n\n This supports 3D maps, point clouds, and more! More info about PyDeck\n at https://deckgl.readthedocs.io/en/latest/.\n\n These docs are also quite useful:\n\n - DeckGL docs: https://github.com/uber/deck.gl/tree/master/docs\n - DeckGL JSON docs: https://github.com/uber/deck.gl/tree/master/modules/json\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 spec: pydeck.Deck or None\n Object specifying the PyDeck chart to draw.\n\n Example\n -------\n Here's a chart using a HexagonLayer and a ScatterplotLayer on top of\n the light map style:\n\n >>> df = pd.DataFrame(\n ... np.random.randn(1000, 2) / [50, 50] + [37.76, -122.4],\n ... columns=['lat', 'lon'])\n >>>\n >>> st.pydeck_chart(pdk.Deck(\n ... map_style='mapbox://styles/mapbox/light-v9',\n ... initial_view_state=pdk.ViewState(\n ... latitude=37.76,\n ... longitude=-122.4,\n ... zoom=11,\n ... pitch=50,\n ... ),\n ... layers=[\n ... pdk.Layer(\n ... 'HexagonLayer',\n ... data=df,\n ... get_position='[lon, lat]',\n ... radius=200,\n ... elevation_scale=4,\n ... elevation_range=[0, 1000],\n ... pickable=True,\n ... extruded=True,\n ... ),\n ... pdk.Layer(\n ... 'ScatterplotLayer',\n ... data=df,\n ... get_position='[lon, lat]',\n ... get_color='[200, 30, 0, 160]',\n ... get_radius=200,\n ... ),\n ... ],\n ... ))\n\n .. output::\n https://share.streamlit.io/0.25.0-2JkNY/index.html?id=ASTdExBpJ1WxbGceneKN1i\n height: 530px\n\n " import streamlit.elements.deck_gl_json_chart as deck_gl_json_chart deck_gl_json_chart.marshall(element, pydeck_obj, use_container_width)
-2,861,997,039,057,345,500
Draw a chart using the PyDeck library. This supports 3D maps, point clouds, and more! More info about PyDeck at https://deckgl.readthedocs.io/en/latest/. These docs are also quite useful: - DeckGL docs: https://github.com/uber/deck.gl/tree/master/docs - DeckGL JSON docs: https://github.com/uber/deck.gl/tree/master/modules/json When using this command, we advise all users to use a personal Mapbox token. This ensures the map tiles used in this chart are more robust. You can do this with the mapbox.token config option. To get a token for yourself, create an account at https://mapbox.com. It's free! (for moderate usage levels) See https://docs.streamlit.io/en/latest/cli.html#view-all-config-options for more info on how to set config options. Parameters ---------- spec: pydeck.Deck or None Object specifying the PyDeck chart to draw. Example ------- Here's a chart using a HexagonLayer and a ScatterplotLayer on top of the light map style: >>> df = pd.DataFrame( ... np.random.randn(1000, 2) / [50, 50] + [37.76, -122.4], ... columns=['lat', 'lon']) >>> >>> st.pydeck_chart(pdk.Deck( ... map_style='mapbox://styles/mapbox/light-v9', ... initial_view_state=pdk.ViewState( ... latitude=37.76, ... longitude=-122.4, ... zoom=11, ... pitch=50, ... ), ... layers=[ ... pdk.Layer( ... 'HexagonLayer', ... data=df, ... get_position='[lon, lat]', ... radius=200, ... elevation_scale=4, ... elevation_range=[0, 1000], ... pickable=True, ... extruded=True, ... ), ... pdk.Layer( ... 'ScatterplotLayer', ... data=df, ... get_position='[lon, lat]', ... get_color='[200, 30, 0, 160]', ... get_radius=200, ... ), ... ], ... )) .. output:: https://share.streamlit.io/0.25.0-2JkNY/index.html?id=ASTdExBpJ1WxbGceneKN1i height: 530px
lib/streamlit/DeltaGenerator.py
pydeck_chart
OakNorthAI/streamlit-base
python
@_with_element def pydeck_chart(self, element, pydeck_obj=None, use_container_width=False): "Draw a chart using the PyDeck library.\n\n This supports 3D maps, point clouds, and more! More info about PyDeck\n at https://deckgl.readthedocs.io/en/latest/.\n\n These docs are also quite useful:\n\n - DeckGL docs: https://github.com/uber/deck.gl/tree/master/docs\n - DeckGL JSON docs: https://github.com/uber/deck.gl/tree/master/modules/json\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 spec: pydeck.Deck or None\n Object specifying the PyDeck chart to draw.\n\n Example\n -------\n Here's a chart using a HexagonLayer and a ScatterplotLayer on top of\n the light map style:\n\n >>> df = pd.DataFrame(\n ... np.random.randn(1000, 2) / [50, 50] + [37.76, -122.4],\n ... columns=['lat', 'lon'])\n >>>\n >>> st.pydeck_chart(pdk.Deck(\n ... map_style='mapbox://styles/mapbox/light-v9',\n ... initial_view_state=pdk.ViewState(\n ... latitude=37.76,\n ... longitude=-122.4,\n ... zoom=11,\n ... pitch=50,\n ... ),\n ... layers=[\n ... pdk.Layer(\n ... 'HexagonLayer',\n ... data=df,\n ... get_position='[lon, lat]',\n ... radius=200,\n ... elevation_scale=4,\n ... elevation_range=[0, 1000],\n ... pickable=True,\n ... extruded=True,\n ... ),\n ... pdk.Layer(\n ... 'ScatterplotLayer',\n ... data=df,\n ... get_position='[lon, lat]',\n ... get_color='[200, 30, 0, 160]',\n ... get_radius=200,\n ... ),\n ... ],\n ... ))\n\n .. output::\n https://share.streamlit.io/0.25.0-2JkNY/index.html?id=ASTdExBpJ1WxbGceneKN1i\n height: 530px\n\n " import streamlit.elements.deck_gl_json_chart as deck_gl_json_chart deck_gl_json_chart.marshall(element, pydeck_obj, use_container_width)
@_with_element def table(self, element, data=None): "Display a static table.\n\n This differs from `st.dataframe` in that the table in this case is\n static: its entire contents are just laid out directly on the page.\n\n Parameters\n ----------\n data : pandas.DataFrame, pandas.Styler, numpy.ndarray, Iterable, dict,\n or None\n The table data.\n\n Example\n -------\n >>> df = pd.DataFrame(\n ... np.random.randn(10, 5),\n ... columns=('col %d' % i for i in range(5)))\n ...\n >>> st.table(df)\n\n .. output::\n https://share.streamlit.io/0.25.0-2JkNY/index.html?id=KfZvDMprL4JFKXbpjD3fpq\n height: 480px\n\n " import streamlit.elements.data_frame_proto as data_frame_proto data_frame_proto.marshall_data_frame(data, element.table)
-684,845,808,264,782,800
Display a static table. This differs from `st.dataframe` in that the table in this case is static: its entire contents are just laid out directly on the page. Parameters ---------- data : pandas.DataFrame, pandas.Styler, numpy.ndarray, Iterable, dict, or None The table data. Example ------- >>> df = pd.DataFrame( ... np.random.randn(10, 5), ... columns=('col %d' % i for i in range(5))) ... >>> st.table(df) .. output:: https://share.streamlit.io/0.25.0-2JkNY/index.html?id=KfZvDMprL4JFKXbpjD3fpq height: 480px
lib/streamlit/DeltaGenerator.py
table
OakNorthAI/streamlit-base
python
@_with_element def table(self, element, data=None): "Display a static table.\n\n This differs from `st.dataframe` in that the table in this case is\n static: its entire contents are just laid out directly on the page.\n\n Parameters\n ----------\n data : pandas.DataFrame, pandas.Styler, numpy.ndarray, Iterable, dict,\n or None\n The table data.\n\n Example\n -------\n >>> df = pd.DataFrame(\n ... np.random.randn(10, 5),\n ... columns=('col %d' % i for i in range(5)))\n ...\n >>> st.table(df)\n\n .. output::\n https://share.streamlit.io/0.25.0-2JkNY/index.html?id=KfZvDMprL4JFKXbpjD3fpq\n height: 480px\n\n " import streamlit.elements.data_frame_proto as data_frame_proto data_frame_proto.marshall_data_frame(data, element.table)
def add_rows(self, data=None, **kwargs): "Concatenate a dataframe to the bottom of the current one.\n\n Parameters\n ----------\n data : pandas.DataFrame, pandas.Styler, numpy.ndarray, Iterable, dict,\n or None\n Table to concat. Optional.\n\n **kwargs : pandas.DataFrame, numpy.ndarray, Iterable, dict, or None\n The named dataset to concat. Optional. You can only pass in 1\n dataset (including the one in the data parameter).\n\n Example\n -------\n >>> df1 = pd.DataFrame(\n ... np.random.randn(50, 20),\n ... columns=('col %d' % i for i in range(20)))\n ...\n >>> my_table = st.table(df1)\n >>>\n >>> df2 = pd.DataFrame(\n ... np.random.randn(50, 20),\n ... columns=('col %d' % i for i in range(20)))\n ...\n >>> my_table.add_rows(df2)\n >>> # Now the table shown in the Streamlit app contains the data for\n >>> # df1 followed by the data for df2.\n\n You can do the same thing with plots. For example, if you want to add\n more data to a line chart:\n\n >>> # Assuming df1 and df2 from the example above still exist...\n >>> my_chart = st.line_chart(df1)\n >>> my_chart.add_rows(df2)\n >>> # Now the chart shown in the Streamlit app contains the data for\n >>> # df1 followed by the data for df2.\n\n And for plots whose datasets are named, you can pass the data with a\n keyword argument where the key is the name:\n\n >>> my_chart = st.vega_lite_chart({\n ... 'mark': 'line',\n ... 'encoding': {'x': 'a', 'y': 'b'},\n ... 'datasets': {\n ... 'some_fancy_name': df1, # <-- named dataset\n ... },\n ... 'data': {'name': 'some_fancy_name'},\n ... }),\n >>> my_chart.add_rows(some_fancy_name=df2) # <-- name used as keyword\n\n " if ((self._container is None) or (self._cursor is None)): return self if (not self._cursor.is_locked): raise StreamlitAPIException('Only existing elements can `add_rows`.') if ((data is not None) and (len(kwargs) == 0)): name = '' elif (len(kwargs) == 1): (name, data) = kwargs.popitem() else: raise StreamlitAPIException('Wrong number of arguments to add_rows().Command requires exactly one dataset') if ((self._cursor.props['delta_type'] in DELTAS_TYPES_THAT_MELT_DATAFRAMES) and (self._cursor.props['last_index'] is None)): st_method_name = self._cursor.props['delta_type'] st_method = getattr(self, st_method_name) st_method(data, **kwargs) return (data, self._cursor.props['last_index']) = _maybe_melt_data_for_add_rows(data, self._cursor.props['delta_type'], self._cursor.props['last_index']) msg = ForwardMsg_pb2.ForwardMsg() msg.metadata.parent_block.container = self._container msg.metadata.parent_block.path[:] = self._cursor.path msg.metadata.delta_id = self._cursor.index import streamlit.elements.data_frame_proto as data_frame_proto data_frame_proto.marshall_data_frame(data, msg.delta.add_rows.data) if name: msg.delta.add_rows.name = name msg.delta.add_rows.has_name = True _enqueue_message(msg) return self
2,071,386,834,757,964,800
Concatenate a dataframe to the bottom of the current one. Parameters ---------- data : pandas.DataFrame, pandas.Styler, numpy.ndarray, Iterable, dict, or None Table to concat. Optional. **kwargs : pandas.DataFrame, numpy.ndarray, Iterable, dict, or None The named dataset to concat. Optional. You can only pass in 1 dataset (including the one in the data parameter). Example ------- >>> df1 = pd.DataFrame( ... np.random.randn(50, 20), ... columns=('col %d' % i for i in range(20))) ... >>> my_table = st.table(df1) >>> >>> df2 = pd.DataFrame( ... np.random.randn(50, 20), ... columns=('col %d' % i for i in range(20))) ... >>> my_table.add_rows(df2) >>> # Now the table shown in the Streamlit app contains the data for >>> # df1 followed by the data for df2. You can do the same thing with plots. For example, if you want to add more data to a line chart: >>> # Assuming df1 and df2 from the example above still exist... >>> my_chart = st.line_chart(df1) >>> my_chart.add_rows(df2) >>> # Now the chart shown in the Streamlit app contains the data for >>> # df1 followed by the data for df2. And for plots whose datasets are named, you can pass the data with a keyword argument where the key is the name: >>> my_chart = st.vega_lite_chart({ ... 'mark': 'line', ... 'encoding': {'x': 'a', 'y': 'b'}, ... 'datasets': { ... 'some_fancy_name': df1, # <-- named dataset ... }, ... 'data': {'name': 'some_fancy_name'}, ... }), >>> my_chart.add_rows(some_fancy_name=df2) # <-- name used as keyword
lib/streamlit/DeltaGenerator.py
add_rows
OakNorthAI/streamlit-base
python
def add_rows(self, data=None, **kwargs): "Concatenate a dataframe to the bottom of the current one.\n\n Parameters\n ----------\n data : pandas.DataFrame, pandas.Styler, numpy.ndarray, Iterable, dict,\n or None\n Table to concat. Optional.\n\n **kwargs : pandas.DataFrame, numpy.ndarray, Iterable, dict, or None\n The named dataset to concat. Optional. You can only pass in 1\n dataset (including the one in the data parameter).\n\n Example\n -------\n >>> df1 = pd.DataFrame(\n ... np.random.randn(50, 20),\n ... columns=('col %d' % i for i in range(20)))\n ...\n >>> my_table = st.table(df1)\n >>>\n >>> df2 = pd.DataFrame(\n ... np.random.randn(50, 20),\n ... columns=('col %d' % i for i in range(20)))\n ...\n >>> my_table.add_rows(df2)\n >>> # Now the table shown in the Streamlit app contains the data for\n >>> # df1 followed by the data for df2.\n\n You can do the same thing with plots. For example, if you want to add\n more data to a line chart:\n\n >>> # Assuming df1 and df2 from the example above still exist...\n >>> my_chart = st.line_chart(df1)\n >>> my_chart.add_rows(df2)\n >>> # Now the chart shown in the Streamlit app contains the data for\n >>> # df1 followed by the data for df2.\n\n And for plots whose datasets are named, you can pass the data with a\n keyword argument where the key is the name:\n\n >>> my_chart = st.vega_lite_chart({\n ... 'mark': 'line',\n ... 'encoding': {'x': 'a', 'y': 'b'},\n ... 'datasets': {\n ... 'some_fancy_name': df1, # <-- named dataset\n ... },\n ... 'data': {'name': 'some_fancy_name'},\n ... }),\n >>> my_chart.add_rows(some_fancy_name=df2) # <-- name used as keyword\n\n " if ((self._container is None) or (self._cursor is None)): return self if (not self._cursor.is_locked): raise StreamlitAPIException('Only existing elements can `add_rows`.') if ((data is not None) and (len(kwargs) == 0)): name = elif (len(kwargs) == 1): (name, data) = kwargs.popitem() else: raise StreamlitAPIException('Wrong number of arguments to add_rows().Command requires exactly one dataset') if ((self._cursor.props['delta_type'] in DELTAS_TYPES_THAT_MELT_DATAFRAMES) and (self._cursor.props['last_index'] is None)): st_method_name = self._cursor.props['delta_type'] st_method = getattr(self, st_method_name) st_method(data, **kwargs) return (data, self._cursor.props['last_index']) = _maybe_melt_data_for_add_rows(data, self._cursor.props['delta_type'], self._cursor.props['last_index']) msg = ForwardMsg_pb2.ForwardMsg() msg.metadata.parent_block.container = self._container msg.metadata.parent_block.path[:] = self._cursor.path msg.metadata.delta_id = self._cursor.index import streamlit.elements.data_frame_proto as data_frame_proto data_frame_proto.marshall_data_frame(data, msg.delta.add_rows.data) if name: msg.delta.add_rows.name = name msg.delta.add_rows.has_name = True _enqueue_message(msg) return self
def zangle_to_quat(zangle): '\n\t:param zangle in rad\n\t:return: quaternion\n\t' return (Quaternion(axis=[0, 0, 1], angle=np.pi) * Quaternion(axis=[(- 1), 0, 0], angle=zangle)).elements
-907,394,938,173,475,800
:param zangle in rad :return: quaternion
multiworld/envs/mujoco/sawyer_xyz/pickPlace/sawyer_coffee.py
zangle_to_quat
Neo-X/R_multiworld
python
def zangle_to_quat(zangle): '\n\t:param zangle in rad\n\t:return: quaternion\n\t' return (Quaternion(axis=[0, 0, 1], angle=np.pi) * Quaternion(axis=[(- 1), 0, 0], angle=zangle)).elements
def plot_runs(runs): ' Plot population evolutions\n ' ts = range(len(runs[0])) cmap = plt.get_cmap('viridis') for (i, r) in enumerate(runs): (mean, var) = zip(*r) (bm, cm) = zip(*mean) (bv, cv) = zip(*var) color = cmap((float(i) / len(runs))) plt.errorbar(ts, bm, fmt='-', yerr=bv, c=color) plt.errorbar(ts, cm, fmt='--', yerr=cv, c=color) plt.title('population evolution overview') plt.xlabel('time') plt.ylabel('value') plt.ylim((0, 1)) plt.plot(0, 0, '-', c='black', label='benefit value') plt.plot(0, 0, '--', c='black', label='cost value') plt.legend(loc='best') plt.savefig('result.pdf') plt.show()
-7,779,025,106,322,543,000
Plot population evolutions
evolutionary_optimization.py
plot_runs
kpj/PySpaMo
python
def plot_runs(runs): ' \n ' ts = range(len(runs[0])) cmap = plt.get_cmap('viridis') for (i, r) in enumerate(runs): (mean, var) = zip(*r) (bm, cm) = zip(*mean) (bv, cv) = zip(*var) color = cmap((float(i) / len(runs))) plt.errorbar(ts, bm, fmt='-', yerr=bv, c=color) plt.errorbar(ts, cm, fmt='--', yerr=cv, c=color) plt.title('population evolution overview') plt.xlabel('time') plt.ylabel('value') plt.ylim((0, 1)) plt.plot(0, 0, '-', c='black', label='benefit value') plt.plot(0, 0, '--', c='black', label='cost value') plt.legend(loc='best') plt.savefig('result.pdf') plt.show()
def work(i): ' Handle one optimization case\n ' opti = SnowdriftOptimizer() return opti.run(20)
-7,797,655,574,561,887,000
Handle one optimization case
evolutionary_optimization.py
work
kpj/PySpaMo
python
def work(i): ' \n ' opti = SnowdriftOptimizer() return opti.run(20)
def main(): ' Setup environment\n ' core_num = int(((multiprocessing.cpu_count() * 4) / 5)) print(('Using %d cores' % core_num)) with multiprocessing.Pool(core_num) as p: runs = [i for i in p.imap_unordered(work, range(10))] plot_runs(runs)
-2,119,673,749,091,162,600
Setup environment
evolutionary_optimization.py
main
kpj/PySpaMo
python
def main(): ' \n ' core_num = int(((multiprocessing.cpu_count() * 4) / 5)) print(('Using %d cores' % core_num)) with multiprocessing.Pool(core_num) as p: runs = [i for i in p.imap_unordered(work, range(10))] plot_runs(runs)
def __init__(self): ' Set some parameters\n ' self.mutation_probability = 0.02
-3,959,449,045,668,069,400
Set some parameters
evolutionary_optimization.py
__init__
kpj/PySpaMo
python
def __init__(self): ' \n ' self.mutation_probability = 0.02
def init(self, size): ' Generate initial population\n ' raise NotImplementedError
-5,409,400,848,608,050,000
Generate initial population
evolutionary_optimization.py
init
kpj/PySpaMo
python
def init(self, size): ' \n ' raise NotImplementedError
def get_fitness(self, obj): ' Compute fitness of individual of population\n ' raise NotImplementedError
-4,544,634,260,429,295,600
Compute fitness of individual of population
evolutionary_optimization.py
get_fitness
kpj/PySpaMo
python
def get_fitness(self, obj): ' \n ' raise NotImplementedError
def mutate(self, obj): ' Mutate single individual\n ' raise NotImplementedError
7,139,653,781,928,916,000
Mutate single individual
evolutionary_optimization.py
mutate
kpj/PySpaMo
python
def mutate(self, obj): ' \n ' raise NotImplementedError
def crossover(self, mom, dad): ' Generate offspring from parents\n ' raise NotImplementedError
8,467,720,466,242,567,000
Generate offspring from parents
evolutionary_optimization.py
crossover
kpj/PySpaMo
python
def crossover(self, mom, dad): ' \n ' raise NotImplementedError
def run(self, size, max_iter=100): ' Let life begin\n ' population = self.init(size) res = [] for _ in tqdm(range(max_iter)): pop_fitness = [self.get_fitness(o) for o in population] best_indiv = np.argpartition(pop_fitness, (- 2))[(- 2):] (mom, dad) = population[best_indiv] child = self.crossover(mom, dad) worst_indiv = np.argmin(pop_fitness) population[worst_indiv] = child mut = (lambda o: (self.mutate(o) if (random.random() < self.mutation_probability) else o)) population = np.array([mut(o) for o in population]) res.append((np.mean(population, axis=0), np.var(population, axis=0))) return res
2,553,331,538,359,015,400
Let life begin
evolutionary_optimization.py
run
kpj/PySpaMo
python
def run(self, size, max_iter=100): ' \n ' population = self.init(size) res = [] for _ in tqdm(range(max_iter)): pop_fitness = [self.get_fitness(o) for o in population] best_indiv = np.argpartition(pop_fitness, (- 2))[(- 2):] (mom, dad) = population[best_indiv] child = self.crossover(mom, dad) worst_indiv = np.argmin(pop_fitness) population[worst_indiv] = child mut = (lambda o: (self.mutate(o) if (random.random() < self.mutation_probability) else o)) population = np.array([mut(o) for o in population]) res.append((np.mean(population, axis=0), np.var(population, axis=0))) return res
def __init__(self, xid=None, flags=None, miss_send_len=None): 'Create a SetConfig with the optional parameters below.\n\n Args:\n xid (int): xid to be used on the message header.\n flags (~pyof.v0x01.controller2switch.common.ConfigFlag):\n OFPC_* flags.\n miss_send_len (int): UBInt16 max bytes of new flow that the\n datapath should send to the controller.\n ' super().__init__(xid, flags, miss_send_len) self.header.message_type = Type.OFPT_SET_CONFIG
7,739,435,916,392,614,000
Create a SetConfig with the optional parameters below. Args: xid (int): xid to be used on the message header. flags (~pyof.v0x01.controller2switch.common.ConfigFlag): OFPC_* flags. miss_send_len (int): UBInt16 max bytes of new flow that the datapath should send to the controller.
pyof/v0x01/controller2switch/set_config.py
__init__
Niehaus/python-openflow
python
def __init__(self, xid=None, flags=None, miss_send_len=None): 'Create a SetConfig with the optional parameters below.\n\n Args:\n xid (int): xid to be used on the message header.\n flags (~pyof.v0x01.controller2switch.common.ConfigFlag):\n OFPC_* flags.\n miss_send_len (int): UBInt16 max bytes of new flow that the\n datapath should send to the controller.\n ' super().__init__(xid, flags, miss_send_len) self.header.message_type = Type.OFPT_SET_CONFIG
def __init__(self, domain_range=None, n_basis=None, order=4, knots=None): 'Bspline basis constructor.\n\n Args:\n domain_range (tuple, optional): Definition of the interval where\n the basis defines a space. Defaults to (0,1) if knots are not\n specified. If knots are specified defaults to the first and\n last element of the knots.\n n_basis (int, optional): Number of splines that form the basis.\n order (int, optional): Order of the splines. One greater that\n their degree. Defaults to 4 which mean cubic splines.\n knots (array_like): List of knots of the splines. If domain_range\n is specified the first and last elements of the knots have to\n match with it.\n\n ' if (domain_range is not None): domain_range = _domain_range(domain_range) if (len(domain_range) != 1): raise ValueError('Domain range should be unidimensional.') domain_range = domain_range[0] if (knots is None): if (n_basis is None): raise ValueError('Must provide either a list of knots or thenumber of basis.') else: knots = tuple(knots) knots = sorted(knots) if (domain_range is None): domain_range = (knots[0], knots[(- 1)]) elif ((domain_range[0] != knots[0]) or (domain_range[1] != knots[(- 1)])): raise ValueError('The ends of the knots must be the same as the domain_range.') if (n_basis is None): n_basis = ((len(knots) + order) - 2) if (((n_basis - order) + 2) < 2): raise ValueError(f'The number of basis ({n_basis}) minus the order of the bspline ({order}) should be greater than 3.') self._order = order self._knots = (None if (knots is None) else tuple(knots)) super().__init__(domain_range=domain_range, n_basis=n_basis) if (self.n_basis != ((self.order + len(self.knots)) - 2)): raise ValueError(f'The number of basis ({self.n_basis}) has to equal the order ({self.order}) plus the number of knots ({len(self.knots)}) minus 2.')
-2,689,459,971,197,850,000
Bspline basis constructor. Args: domain_range (tuple, optional): Definition of the interval where the basis defines a space. Defaults to (0,1) if knots are not specified. If knots are specified defaults to the first and last element of the knots. n_basis (int, optional): Number of splines that form the basis. order (int, optional): Order of the splines. One greater that their degree. Defaults to 4 which mean cubic splines. knots (array_like): List of knots of the splines. If domain_range is specified the first and last elements of the knots have to match with it.
skfda/representation/basis/_bspline.py
__init__
alejandro-ariza/scikit-fda
python
def __init__(self, domain_range=None, n_basis=None, order=4, knots=None): 'Bspline basis constructor.\n\n Args:\n domain_range (tuple, optional): Definition of the interval where\n the basis defines a space. Defaults to (0,1) if knots are not\n specified. If knots are specified defaults to the first and\n last element of the knots.\n n_basis (int, optional): Number of splines that form the basis.\n order (int, optional): Order of the splines. One greater that\n their degree. Defaults to 4 which mean cubic splines.\n knots (array_like): List of knots of the splines. If domain_range\n is specified the first and last elements of the knots have to\n match with it.\n\n ' if (domain_range is not None): domain_range = _domain_range(domain_range) if (len(domain_range) != 1): raise ValueError('Domain range should be unidimensional.') domain_range = domain_range[0] if (knots is None): if (n_basis is None): raise ValueError('Must provide either a list of knots or thenumber of basis.') else: knots = tuple(knots) knots = sorted(knots) if (domain_range is None): domain_range = (knots[0], knots[(- 1)]) elif ((domain_range[0] != knots[0]) or (domain_range[1] != knots[(- 1)])): raise ValueError('The ends of the knots must be the same as the domain_range.') if (n_basis is None): n_basis = ((len(knots) + order) - 2) if (((n_basis - order) + 2) < 2): raise ValueError(f'The number of basis ({n_basis}) minus the order of the bspline ({order}) should be greater than 3.') self._order = order self._knots = (None if (knots is None) else tuple(knots)) super().__init__(domain_range=domain_range, n_basis=n_basis) if (self.n_basis != ((self.order + len(self.knots)) - 2)): raise ValueError(f'The number of basis ({self.n_basis}) has to equal the order ({self.order}) plus the number of knots ({len(self.knots)}) minus 2.')
def _evaluation_knots(self): '\n Get the knots adding m knots to the boundary in order to allow a\n discontinuous behaviour at the boundaries of the domain [RS05]_.\n\n References:\n .. [RS05] Ramsay, J., Silverman, B. W. (2005). *Functional Data\n Analysis*. Springer. 50-51.\n ' return np.array(((((self.knots[0],) * (self.order - 1)) + self.knots) + ((self.knots[(- 1)],) * (self.order - 1))))
6,353,720,271,965,828,000
Get the knots adding m knots to the boundary in order to allow a discontinuous behaviour at the boundaries of the domain [RS05]_. References: .. [RS05] Ramsay, J., Silverman, B. W. (2005). *Functional Data Analysis*. Springer. 50-51.
skfda/representation/basis/_bspline.py
_evaluation_knots
alejandro-ariza/scikit-fda
python
def _evaluation_knots(self): '\n Get the knots adding m knots to the boundary in order to allow a\n discontinuous behaviour at the boundaries of the domain [RS05]_.\n\n References:\n .. [RS05] Ramsay, J., Silverman, B. W. (2005). *Functional Data\n Analysis*. Springer. 50-51.\n ' return np.array(((((self.knots[0],) * (self.order - 1)) + self.knots) + ((self.knots[(- 1)],) * (self.order - 1))))
def rescale(self, domain_range=None): 'Return a copy of the basis with a new domain range, with the\n corresponding values rescaled to the new bounds.\n The knots of the BSpline will be rescaled in the new interval.\n\n Args:\n domain_range (tuple, optional): Definition of the interval\n where the basis defines a space. Defaults uses the same as\n the original basis.\n ' knots = np.array(self.knots, dtype=np.dtype('float')) if (domain_range is not None): knots -= knots[0] knots *= ((domain_range[1] - domain_range[0]) / (self.knots[(- 1)] - self.knots[0])) knots += domain_range[0] knots[0] = domain_range[0] knots[(- 1)] = domain_range[1] else: domain_range = self.domain_range[0] return BSpline(domain_range, self.n_basis, self.order, knots)
6,704,090,157,816,201,000
Return a copy of the basis with a new domain range, with the corresponding values rescaled to the new bounds. The knots of the BSpline will be rescaled in the new interval. Args: domain_range (tuple, optional): Definition of the interval where the basis defines a space. Defaults uses the same as the original basis.
skfda/representation/basis/_bspline.py
rescale
alejandro-ariza/scikit-fda
python
def rescale(self, domain_range=None): 'Return a copy of the basis with a new domain range, with the\n corresponding values rescaled to the new bounds.\n The knots of the BSpline will be rescaled in the new interval.\n\n Args:\n domain_range (tuple, optional): Definition of the interval\n where the basis defines a space. Defaults uses the same as\n the original basis.\n ' knots = np.array(self.knots, dtype=np.dtype('float')) if (domain_range is not None): knots -= knots[0] knots *= ((domain_range[1] - domain_range[0]) / (self.knots[(- 1)] - self.knots[0])) knots += domain_range[0] knots[0] = domain_range[0] knots[(- 1)] = domain_range[1] else: domain_range = self.domain_range[0] return BSpline(domain_range, self.n_basis, self.order, knots)
def __repr__(self): 'Representation of a BSpline basis.' return f'{self.__class__.__name__}(domain_range={self.domain_range}, n_basis={self.n_basis}, order={self.order}, knots={self.knots})'
6,928,560,861,686,392,000
Representation of a BSpline basis.
skfda/representation/basis/_bspline.py
__repr__
alejandro-ariza/scikit-fda
python
def __repr__(self): return f'{self.__class__.__name__}(domain_range={self.domain_range}, n_basis={self.n_basis}, order={self.order}, knots={self.knots})'
@property def inknots(self): 'Return number of basis.' return self.knots[1:(len(self.knots) - 1)]
-1,807,174,253,610,676,000
Return number of basis.
skfda/representation/basis/_bspline.py
inknots
alejandro-ariza/scikit-fda
python
@property def inknots(self): return self.knots[1:(len(self.knots) - 1)]
def test_boolean(): 'Test boolean validation.' schema = vol.Schema(cv.boolean) for value in ('T', 'negative', 'lock'): with pytest.raises(vol.MultipleInvalid): schema(value) for value in ('true', 'On', '1', 'YES', 'enable', 1, True): assert schema(value) for value in ('false', 'Off', '0', 'NO', 'disable', 0, False): assert (not schema(value))
8,999,340,782,815,011,000
Test boolean validation.
tests/helpers/test_config_validation.py
test_boolean
AidasK/home-assistant
python
def test_boolean(): schema = vol.Schema(cv.boolean) for value in ('T', 'negative', 'lock'): with pytest.raises(vol.MultipleInvalid): schema(value) for value in ('true', 'On', '1', 'YES', 'enable', 1, True): assert schema(value) for value in ('false', 'Off', '0', 'NO', 'disable', 0, False): assert (not schema(value))
def test_latitude(): 'Test latitude validation.' schema = vol.Schema(cv.latitude) for value in ('invalid', None, (- 91), 91, '-91', '91', '123.01A'): with pytest.raises(vol.MultipleInvalid): schema(value) for value in ('-89', 89, '12.34'): schema(value)
5,405,025,922,743,942,000
Test latitude validation.
tests/helpers/test_config_validation.py
test_latitude
AidasK/home-assistant
python
def test_latitude(): schema = vol.Schema(cv.latitude) for value in ('invalid', None, (- 91), 91, '-91', '91', '123.01A'): with pytest.raises(vol.MultipleInvalid): schema(value) for value in ('-89', 89, '12.34'): schema(value)
def test_longitude(): 'Test longitude validation.' schema = vol.Schema(cv.longitude) for value in ('invalid', None, (- 181), 181, '-181', '181', '123.01A'): with pytest.raises(vol.MultipleInvalid): schema(value) for value in ('-179', 179, '12.34'): schema(value)
-8,674,121,212,617,102,000
Test longitude validation.
tests/helpers/test_config_validation.py
test_longitude
AidasK/home-assistant
python
def test_longitude(): schema = vol.Schema(cv.longitude) for value in ('invalid', None, (- 181), 181, '-181', '181', '123.01A'): with pytest.raises(vol.MultipleInvalid): schema(value) for value in ('-179', 179, '12.34'): schema(value)
def test_port(): 'Test TCP/UDP network port.' schema = vol.Schema(cv.port) for value in ('invalid', None, (- 1), 0, 80000, '81000'): with pytest.raises(vol.MultipleInvalid): schema(value) for value in ('1000', 21, 24574): schema(value)
-3,224,789,181,267,330,000
Test TCP/UDP network port.
tests/helpers/test_config_validation.py
test_port
AidasK/home-assistant
python
def test_port(): schema = vol.Schema(cv.port) for value in ('invalid', None, (- 1), 0, 80000, '81000'): with pytest.raises(vol.MultipleInvalid): schema(value) for value in ('1000', 21, 24574): schema(value)
def test_isfile(): 'Validate that the value is an existing file.' schema = vol.Schema(cv.isfile) fake_file = 'this-file-does-not.exist' assert (not os.path.isfile(fake_file)) for value in ('invalid', None, (- 1), 0, 80000, fake_file): with pytest.raises(vol.Invalid): schema(value) with patch('os.path.isfile', Mock(return_value=True)), patch('os.access', Mock(return_value=True)): schema('test.txt')
309,000,967,761,043,600
Validate that the value is an existing file.
tests/helpers/test_config_validation.py
test_isfile
AidasK/home-assistant
python
def test_isfile(): schema = vol.Schema(cv.isfile) fake_file = 'this-file-does-not.exist' assert (not os.path.isfile(fake_file)) for value in ('invalid', None, (- 1), 0, 80000, fake_file): with pytest.raises(vol.Invalid): schema(value) with patch('os.path.isfile', Mock(return_value=True)), patch('os.access', Mock(return_value=True)): schema('test.txt')
def test_url(): 'Test URL.' schema = vol.Schema(cv.url) for value in ('invalid', None, 100, 'htp://ha.io', 'http//ha.io', 'http://??,**', 'https://??,**'): with pytest.raises(vol.MultipleInvalid): schema(value) for value in ('http://localhost', 'https://localhost/test/index.html', 'http://home-assistant.io', 'http://home-assistant.io/test/', 'https://community.home-assistant.io/'): assert schema(value)
6,016,607,326,846,040,000
Test URL.
tests/helpers/test_config_validation.py
test_url
AidasK/home-assistant
python
def test_url(): schema = vol.Schema(cv.url) for value in ('invalid', None, 100, 'htp://ha.io', 'http//ha.io', 'http://??,**', 'https://??,**'): with pytest.raises(vol.MultipleInvalid): schema(value) for value in ('http://localhost', 'https://localhost/test/index.html', 'http://home-assistant.io', 'http://home-assistant.io/test/', 'https://community.home-assistant.io/'): assert schema(value)
def test_platform_config(): 'Test platform config validation.' options = ({}, {'hello': 'world'}) for value in options: with pytest.raises(vol.MultipleInvalid): cv.PLATFORM_SCHEMA(value) options = ({'platform': 'mqtt'}, {'platform': 'mqtt', 'beer': 'yes'}) for value in options: cv.PLATFORM_SCHEMA(value)
-3,896,017,594,280,178,700
Test platform config validation.
tests/helpers/test_config_validation.py
test_platform_config
AidasK/home-assistant
python
def test_platform_config(): options = ({}, {'hello': 'world'}) for value in options: with pytest.raises(vol.MultipleInvalid): cv.PLATFORM_SCHEMA(value) options = ({'platform': 'mqtt'}, {'platform': 'mqtt', 'beer': 'yes'}) for value in options: cv.PLATFORM_SCHEMA(value)
def test_ensure_list(): 'Test ensure_list.' schema = vol.Schema(cv.ensure_list) assert ([] == schema(None)) assert ([1] == schema(1)) assert ([1] == schema([1])) assert (['1'] == schema('1')) assert (['1'] == schema(['1'])) assert ([{'1': '2'}] == schema({'1': '2'}))
8,073,574,953,741,535,000
Test ensure_list.
tests/helpers/test_config_validation.py
test_ensure_list
AidasK/home-assistant
python
def test_ensure_list(): schema = vol.Schema(cv.ensure_list) assert ([] == schema(None)) assert ([1] == schema(1)) assert ([1] == schema([1])) assert (['1'] == schema('1')) assert (['1'] == schema(['1'])) assert ([{'1': '2'}] == schema({'1': '2'}))
def test_entity_id(): 'Test entity ID validation.' schema = vol.Schema(cv.entity_id) with pytest.raises(vol.MultipleInvalid): schema('invalid_entity') assert (schema('sensor.LIGHT') == 'sensor.light')
4,234,418,284,068,444,000
Test entity ID validation.
tests/helpers/test_config_validation.py
test_entity_id
AidasK/home-assistant
python
def test_entity_id(): schema = vol.Schema(cv.entity_id) with pytest.raises(vol.MultipleInvalid): schema('invalid_entity') assert (schema('sensor.LIGHT') == 'sensor.light')
def test_entity_ids(): 'Test entity ID validation.' schema = vol.Schema(cv.entity_ids) options = ('invalid_entity', 'sensor.light,sensor_invalid', ['invalid_entity'], ['sensor.light', 'sensor_invalid'], ['sensor.light,sensor_invalid']) for value in options: with pytest.raises(vol.MultipleInvalid): schema(value) options = ([], ['sensor.light'], 'sensor.light') for value in options: schema(value) assert (schema('sensor.LIGHT, light.kitchen ') == ['sensor.light', 'light.kitchen'])
5,483,656,690,993,181,000
Test entity ID validation.
tests/helpers/test_config_validation.py
test_entity_ids
AidasK/home-assistant
python
def test_entity_ids(): schema = vol.Schema(cv.entity_ids) options = ('invalid_entity', 'sensor.light,sensor_invalid', ['invalid_entity'], ['sensor.light', 'sensor_invalid'], ['sensor.light,sensor_invalid']) for value in options: with pytest.raises(vol.MultipleInvalid): schema(value) options = ([], ['sensor.light'], 'sensor.light') for value in options: schema(value) assert (schema('sensor.LIGHT, light.kitchen ') == ['sensor.light', 'light.kitchen'])
def test_entity_domain(): 'Test entity domain validation.' schema = vol.Schema(cv.entity_domain('sensor')) options = ('invalid_entity', 'cover.demo') for value in options: with pytest.raises(vol.MultipleInvalid): print(value) schema(value) assert (schema('sensor.LIGHT') == 'sensor.light')
4,741,356,306,411,909,000
Test entity domain validation.
tests/helpers/test_config_validation.py
test_entity_domain
AidasK/home-assistant
python
def test_entity_domain(): schema = vol.Schema(cv.entity_domain('sensor')) options = ('invalid_entity', 'cover.demo') for value in options: with pytest.raises(vol.MultipleInvalid): print(value) schema(value) assert (schema('sensor.LIGHT') == 'sensor.light')
def test_entities_domain(): 'Test entities domain validation.' schema = vol.Schema(cv.entities_domain('sensor')) options = (None, '', 'invalid_entity', ['sensor.light', 'cover.demo'], ['sensor.light', 'sensor_invalid']) for value in options: with pytest.raises(vol.MultipleInvalid): schema(value) options = ('sensor.light', ['SENSOR.light'], ['sensor.light', 'sensor.demo']) for value in options: schema(value) assert (schema('sensor.LIGHT, sensor.demo ') == ['sensor.light', 'sensor.demo']) assert (schema(['sensor.light', 'SENSOR.demo']) == ['sensor.light', 'sensor.demo'])
7,033,083,670,923,283,000
Test entities domain validation.
tests/helpers/test_config_validation.py
test_entities_domain
AidasK/home-assistant
python
def test_entities_domain(): schema = vol.Schema(cv.entities_domain('sensor')) options = (None, , 'invalid_entity', ['sensor.light', 'cover.demo'], ['sensor.light', 'sensor_invalid']) for value in options: with pytest.raises(vol.MultipleInvalid): schema(value) options = ('sensor.light', ['SENSOR.light'], ['sensor.light', 'sensor.demo']) for value in options: schema(value) assert (schema('sensor.LIGHT, sensor.demo ') == ['sensor.light', 'sensor.demo']) assert (schema(['sensor.light', 'SENSOR.demo']) == ['sensor.light', 'sensor.demo'])
def test_ensure_list_csv(): 'Test ensure_list_csv.' schema = vol.Schema(cv.ensure_list_csv) options = (None, 12, [], ['string'], 'string1,string2') for value in options: schema(value) assert (schema('string1, string2 ') == ['string1', 'string2'])
-1,662,028,435,425,543,000
Test ensure_list_csv.
tests/helpers/test_config_validation.py
test_ensure_list_csv
AidasK/home-assistant
python
def test_ensure_list_csv(): schema = vol.Schema(cv.ensure_list_csv) options = (None, 12, [], ['string'], 'string1,string2') for value in options: schema(value) assert (schema('string1, string2 ') == ['string1', 'string2'])
def test_event_schema(): 'Test event_schema validation.' options = ({}, None, {'event_data': {}}, {'event': 'state_changed', 'event_data': 1}) for value in options: with pytest.raises(vol.MultipleInvalid): cv.EVENT_SCHEMA(value) options = ({'event': 'state_changed'}, {'event': 'state_changed', 'event_data': {'hello': 'world'}}) for value in options: cv.EVENT_SCHEMA(value)
-7,224,355,690,011,239,000
Test event_schema validation.
tests/helpers/test_config_validation.py
test_event_schema
AidasK/home-assistant
python
def test_event_schema(): options = ({}, None, {'event_data': {}}, {'event': 'state_changed', 'event_data': 1}) for value in options: with pytest.raises(vol.MultipleInvalid): cv.EVENT_SCHEMA(value) options = ({'event': 'state_changed'}, {'event': 'state_changed', 'event_data': {'hello': 'world'}}) for value in options: cv.EVENT_SCHEMA(value)
def test_icon(): 'Test icon validation.' schema = vol.Schema(cv.icon) for value in (False, 'work'): with pytest.raises(vol.MultipleInvalid): schema(value) schema('mdi:work') schema('custom:prefix')
-6,032,756,510,433,722,000
Test icon validation.
tests/helpers/test_config_validation.py
test_icon
AidasK/home-assistant
python
def test_icon(): schema = vol.Schema(cv.icon) for value in (False, 'work'): with pytest.raises(vol.MultipleInvalid): schema(value) schema('mdi:work') schema('custom:prefix')
def test_time_period(): 'Test time_period validation.' schema = vol.Schema(cv.time_period) options = (None, '', 'hello:world', '12:', '12:34:56:78', {}, {'wrong_key': (- 10)}) for value in options: with pytest.raises(vol.MultipleInvalid): schema(value) options = ('8:20', '23:59', '-8:20', '-23:59:59', '-48:00', {'minutes': 5}, 1, '5') for value in options: schema(value) assert (timedelta(seconds=180) == schema('180')) assert (timedelta(hours=23, minutes=59) == schema('23:59')) assert (((- 1) * timedelta(hours=1, minutes=15)) == schema('-1:15'))
5,079,320,819,424,888,000
Test time_period validation.
tests/helpers/test_config_validation.py
test_time_period
AidasK/home-assistant
python
def test_time_period(): schema = vol.Schema(cv.time_period) options = (None, , 'hello:world', '12:', '12:34:56:78', {}, {'wrong_key': (- 10)}) for value in options: with pytest.raises(vol.MultipleInvalid): schema(value) options = ('8:20', '23:59', '-8:20', '-23:59:59', '-48:00', {'minutes': 5}, 1, '5') for value in options: schema(value) assert (timedelta(seconds=180) == schema('180')) assert (timedelta(hours=23, minutes=59) == schema('23:59')) assert (((- 1) * timedelta(hours=1, minutes=15)) == schema('-1:15'))
def test_service(): 'Test service validation.' schema = vol.Schema(cv.service) with pytest.raises(vol.MultipleInvalid): schema('invalid_turn_on') schema('homeassistant.turn_on')
-3,773,440,342,070,571,000
Test service validation.
tests/helpers/test_config_validation.py
test_service
AidasK/home-assistant
python
def test_service(): schema = vol.Schema(cv.service) with pytest.raises(vol.MultipleInvalid): schema('invalid_turn_on') schema('homeassistant.turn_on')
def test_service_schema(): 'Test service_schema validation.' options = ({}, None, {'service': 'homeassistant.turn_on', 'service_template': 'homeassistant.turn_on'}, {'data': {'entity_id': 'light.kitchen'}}, {'service': 'homeassistant.turn_on', 'data': None}, {'service': 'homeassistant.turn_on', 'data_template': {'brightness': '{{ no_end'}}) for value in options: with pytest.raises(vol.MultipleInvalid): cv.SERVICE_SCHEMA(value) options = ({'service': 'homeassistant.turn_on'}, {'service': 'homeassistant.turn_on', 'entity_id': 'light.kitchen'}, {'service': 'homeassistant.turn_on', 'entity_id': ['light.kitchen', 'light.ceiling']}) for value in options: cv.SERVICE_SCHEMA(value)
769,792,067,807,005,000
Test service_schema validation.
tests/helpers/test_config_validation.py
test_service_schema
AidasK/home-assistant
python
def test_service_schema(): options = ({}, None, {'service': 'homeassistant.turn_on', 'service_template': 'homeassistant.turn_on'}, {'data': {'entity_id': 'light.kitchen'}}, {'service': 'homeassistant.turn_on', 'data': None}, {'service': 'homeassistant.turn_on', 'data_template': {'brightness': '{{ no_end'}}) for value in options: with pytest.raises(vol.MultipleInvalid): cv.SERVICE_SCHEMA(value) options = ({'service': 'homeassistant.turn_on'}, {'service': 'homeassistant.turn_on', 'entity_id': 'light.kitchen'}, {'service': 'homeassistant.turn_on', 'entity_id': ['light.kitchen', 'light.ceiling']}) for value in options: cv.SERVICE_SCHEMA(value)
def test_slug(): 'Test slug validation.' schema = vol.Schema(cv.slug) for value in (None, 'hello world'): with pytest.raises(vol.MultipleInvalid): schema(value) for value in (12345, 'hello'): schema(value)
5,634,292,382,389,411,000
Test slug validation.
tests/helpers/test_config_validation.py
test_slug
AidasK/home-assistant
python
def test_slug(): schema = vol.Schema(cv.slug) for value in (None, 'hello world'): with pytest.raises(vol.MultipleInvalid): schema(value) for value in (12345, 'hello'): schema(value)
def test_string(): 'Test string validation.' schema = vol.Schema(cv.string) with pytest.raises(vol.Invalid): schema(None) with pytest.raises(vol.Invalid): schema([]) with pytest.raises(vol.Invalid): schema({}) for value in (True, 1, 'hello'): schema(value)
6,633,445,761,249,542,000
Test string validation.
tests/helpers/test_config_validation.py
test_string
AidasK/home-assistant
python
def test_string(): schema = vol.Schema(cv.string) with pytest.raises(vol.Invalid): schema(None) with pytest.raises(vol.Invalid): schema([]) with pytest.raises(vol.Invalid): schema({}) for value in (True, 1, 'hello'): schema(value)
def test_temperature_unit(): 'Test temperature unit validation.' schema = vol.Schema(cv.temperature_unit) with pytest.raises(vol.MultipleInvalid): schema('K') schema('C') schema('F')
9,216,878,165,514,072,000
Test temperature unit validation.
tests/helpers/test_config_validation.py
test_temperature_unit
AidasK/home-assistant
python
def test_temperature_unit(): schema = vol.Schema(cv.temperature_unit) with pytest.raises(vol.MultipleInvalid): schema('K') schema('C') schema('F')
def test_x10_address(): 'Test x10 addr validator.' schema = vol.Schema(cv.x10_address) with pytest.raises(vol.Invalid): schema('Q1') schema('q55') schema('garbage_addr') schema('a1') schema('C11')
476,064,791,361,012,160
Test x10 addr validator.
tests/helpers/test_config_validation.py
test_x10_address
AidasK/home-assistant
python
def test_x10_address(): schema = vol.Schema(cv.x10_address) with pytest.raises(vol.Invalid): schema('Q1') schema('q55') schema('garbage_addr') schema('a1') schema('C11')
def test_template(): 'Test template validator.' schema = vol.Schema(cv.template) for value in (None, '{{ partial_print }', '{% if True %}Hello', ['test']): with pytest.raises(vol.Invalid, message='{} not considered invalid'.format(value)): schema(value) options = (1, 'Hello', '{{ beer }}', '{% if 1 == 1 %}Hello{% else %}World{% endif %}') for value in options: schema(value)
779,638,051,045,150,500
Test template validator.
tests/helpers/test_config_validation.py
test_template
AidasK/home-assistant
python
def test_template(): schema = vol.Schema(cv.template) for value in (None, '{{ partial_print }', '{% if True %}Hello', ['test']): with pytest.raises(vol.Invalid, message='{} not considered invalid'.format(value)): schema(value) options = (1, 'Hello', '{{ beer }}', '{% if 1 == 1 %}Hello{% else %}World{% endif %}') for value in options: schema(value)
def test_template_complex(): 'Test template_complex validator.' schema = vol.Schema(cv.template_complex) for value in (None, '{{ partial_print }', '{% if True %}Hello'): with pytest.raises(vol.MultipleInvalid): schema(value) options = (1, 'Hello', '{{ beer }}', '{% if 1 == 1 %}Hello{% else %}World{% endif %}', {'test': 1, 'test2': '{{ beer }}'}, ['{{ beer }}', 1]) for value in options: schema(value)
-8,506,853,059,146,775,000
Test template_complex validator.
tests/helpers/test_config_validation.py
test_template_complex
AidasK/home-assistant
python
def test_template_complex(): schema = vol.Schema(cv.template_complex) for value in (None, '{{ partial_print }', '{% if True %}Hello'): with pytest.raises(vol.MultipleInvalid): schema(value) options = (1, 'Hello', '{{ beer }}', '{% if 1 == 1 %}Hello{% else %}World{% endif %}', {'test': 1, 'test2': '{{ beer }}'}, ['{{ beer }}', 1]) for value in options: schema(value)
def test_time_zone(): 'Test time zone validation.' schema = vol.Schema(cv.time_zone) with pytest.raises(vol.MultipleInvalid): schema('America/Do_Not_Exist') schema('America/Los_Angeles') schema('UTC')
-3,777,560,921,499,743,000
Test time zone validation.
tests/helpers/test_config_validation.py
test_time_zone
AidasK/home-assistant
python
def test_time_zone(): schema = vol.Schema(cv.time_zone) with pytest.raises(vol.MultipleInvalid): schema('America/Do_Not_Exist') schema('America/Los_Angeles') schema('UTC')
def test_date(): 'Test date validation.' schema = vol.Schema(cv.date) for value in ['Not a date', '23:42', '2016-11-23T18:59:08']: with pytest.raises(vol.Invalid): schema(value) schema(datetime.now().date()) schema('2016-11-23')
6,884,820,153,883,477,000
Test date validation.
tests/helpers/test_config_validation.py
test_date
AidasK/home-assistant
python
def test_date(): schema = vol.Schema(cv.date) for value in ['Not a date', '23:42', '2016-11-23T18:59:08']: with pytest.raises(vol.Invalid): schema(value) schema(datetime.now().date()) schema('2016-11-23')
def test_time(): 'Test date validation.' schema = vol.Schema(cv.time) for value in ['Not a time', '2016-11-23', '2016-11-23T18:59:08']: with pytest.raises(vol.Invalid): schema(value) schema(datetime.now().time()) schema('23:42:00') schema('23:42')
-3,050,492,042,552,543,700
Test date validation.
tests/helpers/test_config_validation.py
test_time
AidasK/home-assistant
python
def test_time(): schema = vol.Schema(cv.time) for value in ['Not a time', '2016-11-23', '2016-11-23T18:59:08']: with pytest.raises(vol.Invalid): schema(value) schema(datetime.now().time()) schema('23:42:00') schema('23:42')
def test_datetime(): 'Test date time validation.' schema = vol.Schema(cv.datetime) for value in [date.today(), 'Wrong DateTime', '2016-11-23']: with pytest.raises(vol.MultipleInvalid): schema(value) schema(datetime.now()) schema('2016-11-23T18:59:08')
7,137,674,050,958,346,000
Test date time validation.
tests/helpers/test_config_validation.py
test_datetime
AidasK/home-assistant
python
def test_datetime(): schema = vol.Schema(cv.datetime) for value in [date.today(), 'Wrong DateTime', '2016-11-23']: with pytest.raises(vol.MultipleInvalid): schema(value) schema(datetime.now()) schema('2016-11-23T18:59:08')
def test_deprecated(caplog): 'Test deprecation log.' schema = vol.Schema({'venus': cv.boolean, 'mars': cv.boolean}) deprecated_schema = vol.All(cv.deprecated('mars'), schema) deprecated_schema({'venus': True}) assert (len(caplog.records) == 0) deprecated_schema({'mars': True}) assert (len(caplog.records) == 1) assert (caplog.records[0].name == __name__) assert ("The 'mars' option (with value 'True') is deprecated, please remove it from your configuration." in caplog.text)
3,538,743,296,813,699,600
Test deprecation log.
tests/helpers/test_config_validation.py
test_deprecated
AidasK/home-assistant
python
def test_deprecated(caplog): schema = vol.Schema({'venus': cv.boolean, 'mars': cv.boolean}) deprecated_schema = vol.All(cv.deprecated('mars'), schema) deprecated_schema({'venus': True}) assert (len(caplog.records) == 0) deprecated_schema({'mars': True}) assert (len(caplog.records) == 1) assert (caplog.records[0].name == __name__) assert ("The 'mars' option (with value 'True') is deprecated, please remove it from your configuration." in caplog.text)
def test_key_dependency(): 'Test key_dependency validator.' schema = vol.Schema(cv.key_dependency('beer', 'soda')) options = {'beer': None} for value in options: with pytest.raises(vol.MultipleInvalid): schema(value) options = ({'beer': None, 'soda': None}, {'soda': None}, {}) for value in options: schema(value)
2,016,627,324,186,323,000
Test key_dependency validator.
tests/helpers/test_config_validation.py
test_key_dependency
AidasK/home-assistant
python
def test_key_dependency(): schema = vol.Schema(cv.key_dependency('beer', 'soda')) options = {'beer': None} for value in options: with pytest.raises(vol.MultipleInvalid): schema(value) options = ({'beer': None, 'soda': None}, {'soda': None}, {}) for value in options: schema(value)
def test_has_at_least_one_key(): 'Test has_at_least_one_key validator.' schema = vol.Schema(cv.has_at_least_one_key('beer', 'soda')) for value in (None, [], {}, {'wine': None}): with pytest.raises(vol.MultipleInvalid): schema(value) for value in ({'beer': None}, {'soda': None}): schema(value)
1,057,924,061,279,002,200
Test has_at_least_one_key validator.
tests/helpers/test_config_validation.py
test_has_at_least_one_key
AidasK/home-assistant
python
def test_has_at_least_one_key(): schema = vol.Schema(cv.has_at_least_one_key('beer', 'soda')) for value in (None, [], {}, {'wine': None}): with pytest.raises(vol.MultipleInvalid): schema(value) for value in ({'beer': None}, {'soda': None}): schema(value)
def test_enum(): 'Test enum validator.' class TestEnum(enum.Enum): 'Test enum.' value1 = 'Value 1' value2 = 'Value 2' schema = vol.Schema(cv.enum(TestEnum)) with pytest.raises(vol.Invalid): schema('value3')
-2,516,164,131,956,451,300
Test enum validator.
tests/helpers/test_config_validation.py
test_enum
AidasK/home-assistant
python
def test_enum(): class TestEnum(enum.Enum): 'Test enum.' value1 = 'Value 1' value2 = 'Value 2' schema = vol.Schema(cv.enum(TestEnum)) with pytest.raises(vol.Invalid): schema('value3')
def test_socket_timeout(): 'Test socket timeout validator.' schema = vol.Schema(cv.socket_timeout) with pytest.raises(vol.Invalid): schema(0.0) with pytest.raises(vol.Invalid): schema((- 1)) assert (_GLOBAL_DEFAULT_TIMEOUT == schema(None)) assert (schema(1) == 1.0)
352,976,611,970,499,460
Test socket timeout validator.
tests/helpers/test_config_validation.py
test_socket_timeout
AidasK/home-assistant
python
def test_socket_timeout(): schema = vol.Schema(cv.socket_timeout) with pytest.raises(vol.Invalid): schema(0.0) with pytest.raises(vol.Invalid): schema((- 1)) assert (_GLOBAL_DEFAULT_TIMEOUT == schema(None)) assert (schema(1) == 1.0)
def test_matches_regex(): 'Test matches_regex validator.' schema = vol.Schema(cv.matches_regex('.*uiae.*')) with pytest.raises(vol.Invalid): schema(1.0) with pytest.raises(vol.Invalid): schema(' nrtd ') test_str = 'This is a test including uiae.' assert (schema(test_str) == test_str)
-8,264,848,067,278,385,000
Test matches_regex validator.
tests/helpers/test_config_validation.py
test_matches_regex
AidasK/home-assistant
python
def test_matches_regex(): schema = vol.Schema(cv.matches_regex('.*uiae.*')) with pytest.raises(vol.Invalid): schema(1.0) with pytest.raises(vol.Invalid): schema(' nrtd ') test_str = 'This is a test including uiae.' assert (schema(test_str) == test_str)
def test_is_regex(): 'Test the is_regex validator.' schema = vol.Schema(cv.is_regex) with pytest.raises(vol.Invalid): schema('(') with pytest.raises(vol.Invalid): schema({'a dict': 'is not a regex'}) valid_re = '.*' schema(valid_re)
-4,981,124,014,004,099,000
Test the is_regex validator.
tests/helpers/test_config_validation.py
test_is_regex
AidasK/home-assistant
python
def test_is_regex(): schema = vol.Schema(cv.is_regex) with pytest.raises(vol.Invalid): schema('(') with pytest.raises(vol.Invalid): schema({'a dict': 'is not a regex'}) valid_re = '.*' schema(valid_re)
def test_comp_entity_ids(): 'Test config validation for component entity IDs.' schema = vol.Schema(cv.comp_entity_ids) for valid in ('ALL', 'all', 'AlL', 'light.kitchen', ['light.kitchen'], ['light.kitchen', 'light.ceiling'], []): schema(valid) for invalid in (['light.kitchen', 'not-entity-id'], '*', ''): with pytest.raises(vol.Invalid): schema(invalid)
-8,425,774,353,582,209,000
Test config validation for component entity IDs.
tests/helpers/test_config_validation.py
test_comp_entity_ids
AidasK/home-assistant
python
def test_comp_entity_ids(): schema = vol.Schema(cv.comp_entity_ids) for valid in ('ALL', 'all', 'AlL', 'light.kitchen', ['light.kitchen'], ['light.kitchen', 'light.ceiling'], []): schema(valid) for invalid in (['light.kitchen', 'not-entity-id'], '*', ): with pytest.raises(vol.Invalid): schema(invalid)
def ra_dec_format(val): ' Ra/Dec string formatting\n\n Converts the input string format of a right ascension/ declination coordinate\n to one recognizable by astroquery\n\n Args:\n val (str): string; an ra/dec expression formatted as "005313.81 +130955.0".\n\n Returns:\n string: the ra/dec coordinates re-formatted as "00h53m13.81s +13d09m55.0s"\n ' hour = val[0:2] min_ = val[2:4] sec = val[4:9] ra = (((((hour + 'h') + min_) + 'm') + sec) + 's') deg = val[9:13] min_d = val[13:15] sec_d = val[15:] dec = (((((deg + 'd') + min_d) + 'm') + sec_d) + 's') return ((ra + ' ') + dec)
4,864,394,534,267,087,000
Ra/Dec string formatting Converts the input string format of a right ascension/ declination coordinate to one recognizable by astroquery Args: val (str): string; an ra/dec expression formatted as "005313.81 +130955.0". Returns: string: the ra/dec coordinates re-formatted as "00h53m13.81s +13d09m55.0s"
exampledoc/Extractor.py
ra_dec_format
sofiapasquini/Code-Astro-Group-23-Project
python
def ra_dec_format(val): ' Ra/Dec string formatting\n\n Converts the input string format of a right ascension/ declination coordinate\n to one recognizable by astroquery\n\n Args:\n val (str): string; an ra/dec expression formatted as "005313.81 +130955.0".\n\n Returns:\n string: the ra/dec coordinates re-formatted as "00h53m13.81s +13d09m55.0s"\n ' hour = val[0:2] min_ = val[2:4] sec = val[4:9] ra = (((((hour + 'h') + min_) + 'm') + sec) + 's') deg = val[9:13] min_d = val[13:15] sec_d = val[15:] dec = (((((deg + 'd') + min_d) + 'm') + sec_d) + 's') return ((ra + ' ') + dec)
def extractor(position): "\n This function extracts the information from the SDSS database and returns\n a pandas dataframe with the query region. Please ensure that the 'position'\n input is formatted as '005313.81 +130955.0\n\n extractor(str) --> pd.DataFrame\n " position = ra_dec_format(position) pos = coords.SkyCoord(position, frame='icrs') data = SDSS.query_region(pos, spectro=True) return data.to_pandas()
-4,174,108,965,800,909,300
This function extracts the information from the SDSS database and returns a pandas dataframe with the query region. Please ensure that the 'position' input is formatted as '005313.81 +130955.0 extractor(str) --> pd.DataFrame
exampledoc/Extractor.py
extractor
sofiapasquini/Code-Astro-Group-23-Project
python
def extractor(position): "\n This function extracts the information from the SDSS database and returns\n a pandas dataframe with the query region. Please ensure that the 'position'\n input is formatted as '005313.81 +130955.0\n\n extractor(str) --> pd.DataFrame\n " position = ra_dec_format(position) pos = coords.SkyCoord(position, frame='icrs') data = SDSS.query_region(pos, spectro=True) return data.to_pandas()
def downloader(data): '\n This function uses extracted information in order to dwonaload spectra, \n separating the data from th SDSS and BOSS.\n\n downloader(pd.Dataframe) --> [list(fits)]\n ' spec_list = [] for i in range(len(data)): results = SDSS.query_specobj(plate=data['plate'][i], mjd=data['mjd'][i], fiberID=data['fiberID'][i]) try: spec = SDSS.get_spectra(matches=results)[0] spec_list.append(spec) except: results.remove_column('instrument') results.add_column(name='instrument', col='eboss') spec = SDSS.get_spectra(matches=results)[0] spec_list.append(spec) return spec_list
-2,177,232,159,057,139,500
This function uses extracted information in order to dwonaload spectra, separating the data from th SDSS and BOSS. downloader(pd.Dataframe) --> [list(fits)]
exampledoc/Extractor.py
downloader
sofiapasquini/Code-Astro-Group-23-Project
python
def downloader(data): '\n This function uses extracted information in order to dwonaload spectra, \n separating the data from th SDSS and BOSS.\n\n downloader(pd.Dataframe) --> [list(fits)]\n ' spec_list = [] for i in range(len(data)): results = SDSS.query_specobj(plate=data['plate'][i], mjd=data['mjd'][i], fiberID=data['fiberID'][i]) try: spec = SDSS.get_spectra(matches=results)[0] spec_list.append(spec) except: results.remove_column('instrument') results.add_column(name='instrument', col='eboss') spec = SDSS.get_spectra(matches=results)[0] spec_list.append(spec) return spec_list
def extract_msg_headers(self, entity, msg): 'Parse E-Mail headers into FtM properties.' try: entity.add('indexText', msg.values()) except Exception as ex: log.warning('Cannot parse all headers: %r', ex) entity.add('subject', self.get_header(msg, 'Subject')) entity.add('date', self.get_dates(msg, 'Date')) entity.add('mimeType', self.get_header(msg, 'Content-Type')) entity.add('threadTopic', self.get_header(msg, 'Thread-Topic')) entity.add('generator', self.get_header(msg, 'X-Mailer')) entity.add('language', self.get_header(msg, 'Content-Language')) entity.add('keywords', self.get_header(msg, 'Keywords')) entity.add('summary', self.get_header(msg, 'Comments')) message_id = self.get_header(msg, 'Message-ID') entity.add('messageId', self.parse_message_ids(message_id)) references = self.get_header(msg, 'References') in_reply_to = self.get_header(msg, 'In-Reply-To') entity.add('inReplyTo', self.parse_references(references, in_reply_to)) return_path = self.get_header_identities(msg, 'Return-Path') self.apply_identities(entity, return_path) reply_to = self.get_header_identities(msg, 'Reply-To') self.apply_identities(entity, reply_to) sender = self.get_header_identities(msg, 'Sender', 'X-Sender') self.apply_identities(entity, sender, 'emitters', 'sender') froms = self.get_header_identities(msg, 'From', 'X-From') self.apply_identities(entity, froms, 'emitters', 'from') tos = self.get_header_identities(msg, 'To', 'Resent-To') self.apply_identities(entity, tos, 'recipients', 'to') ccs = self.get_header_identities(msg, 'CC', 'Cc', 'Resent-Cc') self.apply_identities(entity, ccs, 'recipients', 'cc') bccs = self.get_header_identities(msg, 'Bcc', 'BCC', 'Resent-Bcc') self.apply_identities(entity, bccs, 'recipients', 'bcc')
-5,171,677,646,401,712,000
Parse E-Mail headers into FtM properties.
services/ingest-file/ingestors/support/email.py
extract_msg_headers
adikadashrieq/aleph
python
def extract_msg_headers(self, entity, msg): try: entity.add('indexText', msg.values()) except Exception as ex: log.warning('Cannot parse all headers: %r', ex) entity.add('subject', self.get_header(msg, 'Subject')) entity.add('date', self.get_dates(msg, 'Date')) entity.add('mimeType', self.get_header(msg, 'Content-Type')) entity.add('threadTopic', self.get_header(msg, 'Thread-Topic')) entity.add('generator', self.get_header(msg, 'X-Mailer')) entity.add('language', self.get_header(msg, 'Content-Language')) entity.add('keywords', self.get_header(msg, 'Keywords')) entity.add('summary', self.get_header(msg, 'Comments')) message_id = self.get_header(msg, 'Message-ID') entity.add('messageId', self.parse_message_ids(message_id)) references = self.get_header(msg, 'References') in_reply_to = self.get_header(msg, 'In-Reply-To') entity.add('inReplyTo', self.parse_references(references, in_reply_to)) return_path = self.get_header_identities(msg, 'Return-Path') self.apply_identities(entity, return_path) reply_to = self.get_header_identities(msg, 'Reply-To') self.apply_identities(entity, reply_to) sender = self.get_header_identities(msg, 'Sender', 'X-Sender') self.apply_identities(entity, sender, 'emitters', 'sender') froms = self.get_header_identities(msg, 'From', 'X-From') self.apply_identities(entity, froms, 'emitters', 'from') tos = self.get_header_identities(msg, 'To', 'Resent-To') self.apply_identities(entity, tos, 'recipients', 'to') ccs = self.get_header_identities(msg, 'CC', 'Cc', 'Resent-Cc') self.apply_identities(entity, ccs, 'recipients', 'cc') bccs = self.get_header_identities(msg, 'Bcc', 'BCC', 'Resent-Bcc') self.apply_identities(entity, bccs, 'recipients', 'bcc')
def __init__(self): ' Initializes this class with VWOLogger and OperandEvaluator ' self.operand_evaluator = OperandEvaluator()
1,181,704,526,880,338,000
Initializes this class with VWOLogger and OperandEvaluator
vwo/services/segmentor/segment_evaluator.py
__init__
MDAkramSiddiqui/vwo-python-sdk
python
def __init__(self): ' ' self.operand_evaluator = OperandEvaluator()
def evaluate(self, segments, custom_variables): 'A parser which recursively evaluates the custom_variables passed against\n the expression tree represented by segments, and returns the result.\n\n Args:\n segments(dict): The segments representing the expression tree\n custom_variables(dict): Key/value pair of variables\n\n Returns:\n bool(result): True or False\n ' (operator, sub_segments) = get_key_value(segments) if (operator == OperatorTypes.NOT): return (not self.evaluate(sub_segments, custom_variables)) elif (operator == OperatorTypes.AND): return all((self.evaluate(y, custom_variables) for y in sub_segments)) elif (operator == OperatorTypes.OR): return any((self.evaluate(y, custom_variables) for y in sub_segments)) elif (operator == OperandTypes.CUSTOM_VARIABLE): return self.operand_evaluator.evaluate_custom_variable(sub_segments, custom_variables) elif (operator == OperandTypes.USER): return self.operand_evaluator.evaluate_user(sub_segments, custom_variables)
-6,698,908,000,189,105,000
A parser which recursively evaluates the custom_variables passed against the expression tree represented by segments, and returns the result. Args: segments(dict): The segments representing the expression tree custom_variables(dict): Key/value pair of variables Returns: bool(result): True or False
vwo/services/segmentor/segment_evaluator.py
evaluate
MDAkramSiddiqui/vwo-python-sdk
python
def evaluate(self, segments, custom_variables): 'A parser which recursively evaluates the custom_variables passed against\n the expression tree represented by segments, and returns the result.\n\n Args:\n segments(dict): The segments representing the expression tree\n custom_variables(dict): Key/value pair of variables\n\n Returns:\n bool(result): True or False\n ' (operator, sub_segments) = get_key_value(segments) if (operator == OperatorTypes.NOT): return (not self.evaluate(sub_segments, custom_variables)) elif (operator == OperatorTypes.AND): return all((self.evaluate(y, custom_variables) for y in sub_segments)) elif (operator == OperatorTypes.OR): return any((self.evaluate(y, custom_variables) for y in sub_segments)) elif (operator == OperandTypes.CUSTOM_VARIABLE): return self.operand_evaluator.evaluate_custom_variable(sub_segments, custom_variables) elif (operator == OperandTypes.USER): return self.operand_evaluator.evaluate_user(sub_segments, custom_variables)
def removeElement(self, nums, val): '\n :type nums: List[int]\n :type val: int\n :rtype: int\n ' j = 0 for i in range(len(nums)): if (nums[i] != val): nums[j] = nums[i] j += 1 return j
-2,103,904,785,688,737,800
:type nums: List[int] :type val: int :rtype: int
1-50/27_remove-element.py
removeElement
ChenhaoJiang/LeetCode-Solution
python
def removeElement(self, nums, val): '\n :type nums: List[int]\n :type val: int\n :rtype: int\n ' j = 0 for i in range(len(nums)): if (nums[i] != val): nums[j] = nums[i] j += 1 return j
def main(): 'Run administrative tasks.' os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'uofthacksemergencyfunds.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError("Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?") from exc execute_from_command_line(sys.argv)
-799,566,234,733,556,400
Run administrative tasks.
manage.py
main
donmin062501/Savings.io
python
def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'uofthacksemergencyfunds.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError("Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?") from exc execute_from_command_line(sys.argv)
def create_view(self, es_ordering_fields): 'Create and return test view class instance\n\n Args:\n es_ordering_fields (tuple): ordering fields\n Returns:\n ElasticAPIView: test view instance\n ' view = ElasticAPIView() view.es_ordering_fields = es_ordering_fields return view
-3,597,215,663,825,731,000
Create and return test view class instance Args: es_ordering_fields (tuple): ordering fields Returns: ElasticAPIView: test view instance
tests/test_filters.py
create_view
ArtemBernatskyy/django-rest-elasticsearch
python
def create_view(self, es_ordering_fields): 'Create and return test view class instance\n\n Args:\n es_ordering_fields (tuple): ordering fields\n Returns:\n ElasticAPIView: test view instance\n ' view = ElasticAPIView() view.es_ordering_fields = es_ordering_fields return view
def create_view(self, es_filter_fields): 'Create and return test view class instance\n\n Args:\n es_filter_fields ([ESFieldFilter]): filtering fields\n Returns:\n ElasticAPIView: test view instance\n ' view = ElasticAPIView() view.es_model = DataDocType view.es_filter_fields = es_filter_fields return view
-1,043,188,655,335,483,900
Create and return test view class instance Args: es_filter_fields ([ESFieldFilter]): filtering fields Returns: ElasticAPIView: test view instance
tests/test_filters.py
create_view
ArtemBernatskyy/django-rest-elasticsearch
python
def create_view(self, es_filter_fields): 'Create and return test view class instance\n\n Args:\n es_filter_fields ([ESFieldFilter]): filtering fields\n Returns:\n ElasticAPIView: test view instance\n ' view = ElasticAPIView() view.es_model = DataDocType view.es_filter_fields = es_filter_fields return view
def create_view(self, es_range_filter_fields): 'Create and return test view class instance\n\n Args:\n es_range_filter_fields ([ESFieldFilter]): filtering range fields\n Returns:\n ElasticAPIView: test view instance\n ' view = ElasticAPIView() view.es_model = DataDocType view.es_range_filter_fields = es_range_filter_fields return view
-2,228,615,635,726,304,500
Create and return test view class instance Args: es_range_filter_fields ([ESFieldFilter]): filtering range fields Returns: ElasticAPIView: test view instance
tests/test_filters.py
create_view
ArtemBernatskyy/django-rest-elasticsearch
python
def create_view(self, es_range_filter_fields): 'Create and return test view class instance\n\n Args:\n es_range_filter_fields ([ESFieldFilter]): filtering range fields\n Returns:\n ElasticAPIView: test view instance\n ' view = ElasticAPIView() view.es_model = DataDocType view.es_range_filter_fields = es_range_filter_fields return view
def create_view(self, es_search_fields): 'Create and return test view class instance\n\n Args:\n es_search_fields ([ESFieldFilter]): search fields\n Returns:\n ElasticAPIView: test view instance\n ' view = ElasticAPIView() view.es_model = DataDocType view.es_search_fields = es_search_fields return view
-447,006,123,439,172,160
Create and return test view class instance Args: es_search_fields ([ESFieldFilter]): search fields Returns: ElasticAPIView: test view instance
tests/test_filters.py
create_view
ArtemBernatskyy/django-rest-elasticsearch
python
def create_view(self, es_search_fields): 'Create and return test view class instance\n\n Args:\n es_search_fields ([ESFieldFilter]): search fields\n Returns:\n ElasticAPIView: test view instance\n ' view = ElasticAPIView() view.es_model = DataDocType view.es_search_fields = es_search_fields return view
def get_expected(): 'Return expected data items sorted by id' items = [(item['_id'], item['_source']['first_name'], item['_source']['is_active']) for item in DATA] items = sorted(items, key=(lambda tup: (tup[1], (not tup[2])))) return items
-3,373,630,689,957,980,000
Return expected data items sorted by id
tests/test_filters.py
get_expected
ArtemBernatskyy/django-rest-elasticsearch
python
def get_expected(): items = [(item['_id'], item['_source']['first_name'], item['_source']['is_active']) for item in DATA] items = sorted(items, key=(lambda tup: (tup[1], (not tup[2])))) return items
def _get_vars(fis): 'Get an encoded version of the parameters of the fuzzy sets in a FIS' for variable in fis.variables: for (value_name, value) in variable.values.items(): for (par, default) in value._get_description().items(): if (par != 'type'): (yield (((((('var_' + variable.name) + '_') + value_name) + '_') + par), default)) for variable in [fis.target]: for (value_name, value) in variable.values.items(): for (par, default) in value._get_description().items(): if (par != 'type'): (yield (((((('target_' + variable.name) + '_') + value_name) + '_') + par), default))
2,506,911,759,605,472,000
Get an encoded version of the parameters of the fuzzy sets in a FIS
zadeh/tune.py
_get_vars
Dih5/zadeh
python
def _get_vars(fis): for variable in fis.variables: for (value_name, value) in variable.values.items(): for (par, default) in value._get_description().items(): if (par != 'type'): (yield (((((('var_' + variable.name) + '_') + value_name) + '_') + par), default)) for variable in [fis.target]: for (value_name, value) in variable.values.items(): for (par, default) in value._get_description().items(): if (par != 'type'): (yield (((((('target_' + variable.name) + '_') + value_name) + '_') + par), default))
def _set_vars(fis, kwargs): 'Return a modified version of the FIS, setting the changes in the parameters described by kwargs' description = fis._get_description() positions = {variable['name']: i for (i, variable) in enumerate(description['variables'])} for (code, parameter_value) in kwargs.items(): if code.startswith('var_'): (_, variable_name, fuzzy_value, parameter) = code.split('_') description['variables'][positions[variable_name]]['values'][fuzzy_value][parameter] = parameter_value elif code.startswith('target_'): (_, _, fuzzy_value, parameter) = code.split('_') description['target']['values'][fuzzy_value][parameter] = parameter_value elif (code in ['defuzzification']): description[code] = parameter_value else: raise ValueError(('Parameter not supported: %s' % code)) return FIS._from_description(description)
1,468,162,519,079,026,700
Return a modified version of the FIS, setting the changes in the parameters described by kwargs
zadeh/tune.py
_set_vars
Dih5/zadeh
python
def _set_vars(fis, kwargs): description = fis._get_description() positions = {variable['name']: i for (i, variable) in enumerate(description['variables'])} for (code, parameter_value) in kwargs.items(): if code.startswith('var_'): (_, variable_name, fuzzy_value, parameter) = code.split('_') description['variables'][positions[variable_name]]['values'][fuzzy_value][parameter] = parameter_value elif code.startswith('target_'): (_, _, fuzzy_value, parameter) = code.split('_') description['target']['values'][fuzzy_value][parameter] = parameter_value elif (code in ['defuzzification']): description[code] = parameter_value else: raise ValueError(('Parameter not supported: %s' % code)) return FIS._from_description(description)
def get_params(self, deep=True): 'Get the parameters in a sklearn-consistent interface' return {'fis': self.fis, 'defuzzification': self.defuzzification, **{parameter: getattr(self, parameter) for (parameter, _) in _get_vars(self.fis)}}
-6,721,509,309,062,285,000
Get the parameters in a sklearn-consistent interface
zadeh/tune.py
get_params
Dih5/zadeh
python
def get_params(self, deep=True): return {'fis': self.fis, 'defuzzification': self.defuzzification, **{parameter: getattr(self, parameter) for (parameter, _) in _get_vars(self.fis)}}
def set_params(self, **parameters): 'Set the parameters in a sklearn-consistent interface' for (parameter, value) in parameters.items(): setattr(self, parameter, value) return self
5,863,062,864,405,496,000
Set the parameters in a sklearn-consistent interface
zadeh/tune.py
set_params
Dih5/zadeh
python
def set_params(self, **parameters): for (parameter, value) in parameters.items(): setattr(self, parameter, value) return self
def fit(self, X=None, y=None): "'Fit' the model (freeze the attributes and compile if available)" self.fis_ = _set_vars(self.fis, {parameter: getattr(self, parameter) for (parameter, _) in _get_vars(self.fis)}) self.fis_.defuzzification = self.defuzzification try: self.fis_ = self.fis_.compile() except Exception: pass return self
-162,376,375,605,532,580
'Fit' the model (freeze the attributes and compile if available)
zadeh/tune.py
fit
Dih5/zadeh
python
def fit(self, X=None, y=None): self.fis_ = _set_vars(self.fis, {parameter: getattr(self, parameter) for (parameter, _) in _get_vars(self.fis)}) self.fis_.defuzzification = self.defuzzification try: self.fis_ = self.fis_.compile() except Exception: pass return self
def predict(self, X): 'A sklearn-like predict method' return self.fis_.batch_predict(X)
-2,083,909,073,260,690,200
A sklearn-like predict method
zadeh/tune.py
predict
Dih5/zadeh
python
def predict(self, X): return self.fis_.batch_predict(X)
def __init__(self, fis, params, scoring='neg_root_mean_squared_error', n_jobs=None): "\n\n Args:\n fis (FIS): The Fuzzy Inference System to tune\n params (dict of str to list): A mapping from encoded parameters to the list of values to explore.\n scoring (str): The metric used for scoring. Must be one of sklearn's regression scorings.\n n_jobs (int): Number of jobs to run in parallel.\n\n " if (GridSearchCV is None): raise ModuleNotFoundError('scikit-learn is required for model tuning') self.fis = fis self.cv = GridSearchCV(ParametrizedFIS(fis), params, scoring=scoring, cv=TrivialSplitter(), refit=False, n_jobs=n_jobs)
7,792,864,546,700,434,000
Args: fis (FIS): The Fuzzy Inference System to tune params (dict of str to list): A mapping from encoded parameters to the list of values to explore. scoring (str): The metric used for scoring. Must be one of sklearn's regression scorings. n_jobs (int): Number of jobs to run in parallel.
zadeh/tune.py
__init__
Dih5/zadeh
python
def __init__(self, fis, params, scoring='neg_root_mean_squared_error', n_jobs=None): "\n\n Args:\n fis (FIS): The Fuzzy Inference System to tune\n params (dict of str to list): A mapping from encoded parameters to the list of values to explore.\n scoring (str): The metric used for scoring. Must be one of sklearn's regression scorings.\n n_jobs (int): Number of jobs to run in parallel.\n\n " if (GridSearchCV is None): raise ModuleNotFoundError('scikit-learn is required for model tuning') self.fis = fis self.cv = GridSearchCV(ParametrizedFIS(fis), params, scoring=scoring, cv=TrivialSplitter(), refit=False, n_jobs=n_jobs)
def fit(self, X, y=None): '\n\n Args:\n X (2D array-like): An object suitable for FIS.batch_predict.\n y (1D array-like): An array with true values. If None, but X is a DataFrame, the values are extracted from\n there.\n\n Returns:\n\n ' if ((y is None) and (pd is not None) and isinstance(X, pd.DataFrame)): y = X[self.fis.target.name] self.cv.fit(X, y) self.best_params_ = self.cv.best_params_ self.results = self.cv.cv_results_ self.tuned_fis_ = _set_vars(self.fis, self.cv.best_params_)
6,407,149,171,949,012,000
Args: X (2D array-like): An object suitable for FIS.batch_predict. y (1D array-like): An array with true values. If None, but X is a DataFrame, the values are extracted from there. Returns:
zadeh/tune.py
fit
Dih5/zadeh
python
def fit(self, X, y=None): '\n\n Args:\n X (2D array-like): An object suitable for FIS.batch_predict.\n y (1D array-like): An array with true values. If None, but X is a DataFrame, the values are extracted from\n there.\n\n Returns:\n\n ' if ((y is None) and (pd is not None) and isinstance(X, pd.DataFrame)): y = X[self.fis.target.name] self.cv.fit(X, y) self.best_params_ = self.cv.best_params_ self.results = self.cv.cv_results_ self.tuned_fis_ = _set_vars(self.fis, self.cv.best_params_)
def parse_arguments(): 'Sets up and parses command-line arguments.\n\n Returns:\n log_level: A logging level to filter log output.\n directory: The directory to search for .cmd files.\n output: Where to write the compile-commands JSON file.\n ' usage = 'Creates a compile_commands.json database from kernel .cmd files' parser = argparse.ArgumentParser(description=usage) directory_help = 'Path to the kernel source directory to search (defaults to the working directory)' parser.add_argument('-d', '--directory', type=str, help=directory_help) output_help = 'The location to write compile_commands.json (defaults to compile_commands.json in the search directory)' parser.add_argument('-o', '--output', type=str, help=output_help) log_level_help = (((('The level of log messages to produce (one of ' + ', '.join(_VALID_LOG_LEVELS)) + '; defaults to ') + _DEFAULT_LOG_LEVEL) + ')') parser.add_argument('--log_level', type=str, default=_DEFAULT_LOG_LEVEL, help=log_level_help) args = parser.parse_args() log_level = args.log_level if (log_level not in _VALID_LOG_LEVELS): raise ValueError(('%s is not a valid log level' % log_level)) directory = (args.directory or os.getcwd()) output = (args.output or os.path.join(directory, _DEFAULT_OUTPUT)) directory = os.path.abspath(directory) return (log_level, directory, output)
-460,389,302,831,116,800
Sets up and parses command-line arguments. Returns: log_level: A logging level to filter log output. directory: The directory to search for .cmd files. output: Where to write the compile-commands JSON file.
ubuntu-bionic-hwe-edge/scripts/gen_compile_commands.py
parse_arguments
Akh1lesh/Object_Detection_using_Intel_Realsense
python
def parse_arguments(): 'Sets up and parses command-line arguments.\n\n Returns:\n log_level: A logging level to filter log output.\n directory: The directory to search for .cmd files.\n output: Where to write the compile-commands JSON file.\n ' usage = 'Creates a compile_commands.json database from kernel .cmd files' parser = argparse.ArgumentParser(description=usage) directory_help = 'Path to the kernel source directory to search (defaults to the working directory)' parser.add_argument('-d', '--directory', type=str, help=directory_help) output_help = 'The location to write compile_commands.json (defaults to compile_commands.json in the search directory)' parser.add_argument('-o', '--output', type=str, help=output_help) log_level_help = (((('The level of log messages to produce (one of ' + ', '.join(_VALID_LOG_LEVELS)) + '; defaults to ') + _DEFAULT_LOG_LEVEL) + ')') parser.add_argument('--log_level', type=str, default=_DEFAULT_LOG_LEVEL, help=log_level_help) args = parser.parse_args() log_level = args.log_level if (log_level not in _VALID_LOG_LEVELS): raise ValueError(('%s is not a valid log level' % log_level)) directory = (args.directory or os.getcwd()) output = (args.output or os.path.join(directory, _DEFAULT_OUTPUT)) directory = os.path.abspath(directory) return (log_level, directory, output)
def process_line(root_directory, file_directory, command_prefix, relative_path): 'Extracts information from a .cmd line and creates an entry from it.\n\n Args:\n root_directory: The directory that was searched for .cmd files. Usually\n used directly in the "directory" entry in compile_commands.json.\n file_directory: The path to the directory the .cmd file was found in.\n command_prefix: The extracted command line, up to the last element.\n relative_path: The .c file from the end of the extracted command.\n Usually relative to root_directory, but sometimes relative to\n file_directory and sometimes neither.\n\n Returns:\n An entry to append to compile_commands.\n\n Raises:\n ValueError: Could not find the extracted file based on relative_path and\n root_directory or file_directory.\n ' prefix = command_prefix.replace('\\#', '#').replace('$(pound)', '#') cur_dir = root_directory expected_path = os.path.join(cur_dir, relative_path) if (not os.path.exists(expected_path)): cur_dir = file_directory expected_path = os.path.join(cur_dir, relative_path) if (not os.path.exists(expected_path)): raise ValueError(('File %s not in %s or %s' % (relative_path, root_directory, file_directory))) return {'directory': cur_dir, 'file': relative_path, 'command': (prefix + relative_path)}
-7,944,255,662,804,624,000
Extracts information from a .cmd line and creates an entry from it. Args: root_directory: The directory that was searched for .cmd files. Usually used directly in the "directory" entry in compile_commands.json. file_directory: The path to the directory the .cmd file was found in. command_prefix: The extracted command line, up to the last element. relative_path: The .c file from the end of the extracted command. Usually relative to root_directory, but sometimes relative to file_directory and sometimes neither. Returns: An entry to append to compile_commands. Raises: ValueError: Could not find the extracted file based on relative_path and root_directory or file_directory.
ubuntu-bionic-hwe-edge/scripts/gen_compile_commands.py
process_line
Akh1lesh/Object_Detection_using_Intel_Realsense
python
def process_line(root_directory, file_directory, command_prefix, relative_path): 'Extracts information from a .cmd line and creates an entry from it.\n\n Args:\n root_directory: The directory that was searched for .cmd files. Usually\n used directly in the "directory" entry in compile_commands.json.\n file_directory: The path to the directory the .cmd file was found in.\n command_prefix: The extracted command line, up to the last element.\n relative_path: The .c file from the end of the extracted command.\n Usually relative to root_directory, but sometimes relative to\n file_directory and sometimes neither.\n\n Returns:\n An entry to append to compile_commands.\n\n Raises:\n ValueError: Could not find the extracted file based on relative_path and\n root_directory or file_directory.\n ' prefix = command_prefix.replace('\\#', '#').replace('$(pound)', '#') cur_dir = root_directory expected_path = os.path.join(cur_dir, relative_path) if (not os.path.exists(expected_path)): cur_dir = file_directory expected_path = os.path.join(cur_dir, relative_path) if (not os.path.exists(expected_path)): raise ValueError(('File %s not in %s or %s' % (relative_path, root_directory, file_directory))) return {'directory': cur_dir, 'file': relative_path, 'command': (prefix + relative_path)}
def main(): 'Walks through the directory and finds and parses .cmd files.' (log_level, directory, output) = parse_arguments() level = getattr(logging, log_level) logging.basicConfig(format='%(levelname)s: %(message)s', level=level) filename_matcher = re.compile(_FILENAME_PATTERN) line_matcher = re.compile(_LINE_PATTERN) compile_commands = [] for (dirpath, _, filenames) in os.walk(directory): for filename in filenames: if (not filename_matcher.match(filename)): continue filepath = os.path.join(dirpath, filename) with open(filepath, 'rt') as f: for line in f: result = line_matcher.match(line) if (not result): continue try: entry = process_line(directory, dirpath, result.group(1), result.group(2)) compile_commands.append(entry) except ValueError as err: logging.info('Could not add line from %s: %s', filepath, err) with open(output, 'wt') as f: json.dump(compile_commands, f, indent=2, sort_keys=True) count = len(compile_commands) if (count < _LOW_COUNT_THRESHOLD): logging.warning('Found %s entries. Have you compiled the kernel?', count)
996,443,708,721,818,600
Walks through the directory and finds and parses .cmd files.
ubuntu-bionic-hwe-edge/scripts/gen_compile_commands.py
main
Akh1lesh/Object_Detection_using_Intel_Realsense
python
def main(): (log_level, directory, output) = parse_arguments() level = getattr(logging, log_level) logging.basicConfig(format='%(levelname)s: %(message)s', level=level) filename_matcher = re.compile(_FILENAME_PATTERN) line_matcher = re.compile(_LINE_PATTERN) compile_commands = [] for (dirpath, _, filenames) in os.walk(directory): for filename in filenames: if (not filename_matcher.match(filename)): continue filepath = os.path.join(dirpath, filename) with open(filepath, 'rt') as f: for line in f: result = line_matcher.match(line) if (not result): continue try: entry = process_line(directory, dirpath, result.group(1), result.group(2)) compile_commands.append(entry) except ValueError as err: logging.info('Could not add line from %s: %s', filepath, err) with open(output, 'wt') as f: json.dump(compile_commands, f, indent=2, sort_keys=True) count = len(compile_commands) if (count < _LOW_COUNT_THRESHOLD): logging.warning('Found %s entries. Have you compiled the kernel?', count)
def setup(self, check_all=None, exclude_private=None, exclude_uppercase=None, exclude_capitalized=None, exclude_unsupported=None, excluded_names=None, truncate=None, minmax=None, remote_editing=None, autorefresh=None): 'Setup the namespace browser' assert (self.shellwidget is not None) self.check_all = check_all self.exclude_private = exclude_private self.exclude_uppercase = exclude_uppercase self.exclude_capitalized = exclude_capitalized self.exclude_unsupported = exclude_unsupported self.excluded_names = excluded_names self.truncate = truncate self.minmax = minmax self.remote_editing = remote_editing self.autorefresh = autorefresh if (self.editor is not None): self.editor.setup_menu(truncate, minmax) self.exclude_private_action.setChecked(exclude_private) self.exclude_uppercase_action.setChecked(exclude_uppercase) self.exclude_capitalized_action.setChecked(exclude_capitalized) self.exclude_unsupported_action.setChecked(exclude_unsupported) if (not self.is_ipykernel): self.auto_refresh_button.setChecked(autorefresh) self.refresh_table() return if self.is_internal_shell: self.editor = DictEditorTableView(self, None, truncate=truncate, minmax=minmax) else: self.editor = RemoteDictEditorTableView(self, None, truncate=truncate, minmax=minmax, remote_editing=remote_editing, get_value_func=self.get_value, set_value_func=self.set_value, new_value_func=self.set_value, remove_values_func=self.remove_values, copy_value_func=self.copy_value, is_list_func=self.is_list, get_len_func=self.get_len, is_array_func=self.is_array, is_image_func=self.is_image, is_dict_func=self.is_dict, is_data_frame_func=self.is_data_frame, is_time_series_func=self.is_time_series, get_array_shape_func=self.get_array_shape, get_array_ndim_func=self.get_array_ndim, oedit_func=self.oedit, plot_func=self.plot, imshow_func=self.imshow, show_image_func=self.show_image) self.editor.sig_option_changed.connect(self.sig_option_changed.emit) self.editor.sig_files_dropped.connect(self.import_data) hlayout = QHBoxLayout() vlayout = QVBoxLayout() toolbar = self.setup_toolbar(exclude_private, exclude_uppercase, exclude_capitalized, exclude_unsupported, autorefresh) vlayout.setAlignment(Qt.AlignTop) for widget in toolbar: vlayout.addWidget(widget) hlayout.addWidget(self.editor) hlayout.addLayout(vlayout) self.setLayout(hlayout) hlayout.setContentsMargins(0, 0, 0, 0) self.sig_option_changed.connect(self.option_changed)
-8,554,207,009,777,978,000
Setup the namespace browser
spyderlib/widgets/externalshell/namespacebrowser.py
setup
junglefunkyman/spectracer
python
def setup(self, check_all=None, exclude_private=None, exclude_uppercase=None, exclude_capitalized=None, exclude_unsupported=None, excluded_names=None, truncate=None, minmax=None, remote_editing=None, autorefresh=None): assert (self.shellwidget is not None) self.check_all = check_all self.exclude_private = exclude_private self.exclude_uppercase = exclude_uppercase self.exclude_capitalized = exclude_capitalized self.exclude_unsupported = exclude_unsupported self.excluded_names = excluded_names self.truncate = truncate self.minmax = minmax self.remote_editing = remote_editing self.autorefresh = autorefresh if (self.editor is not None): self.editor.setup_menu(truncate, minmax) self.exclude_private_action.setChecked(exclude_private) self.exclude_uppercase_action.setChecked(exclude_uppercase) self.exclude_capitalized_action.setChecked(exclude_capitalized) self.exclude_unsupported_action.setChecked(exclude_unsupported) if (not self.is_ipykernel): self.auto_refresh_button.setChecked(autorefresh) self.refresh_table() return if self.is_internal_shell: self.editor = DictEditorTableView(self, None, truncate=truncate, minmax=minmax) else: self.editor = RemoteDictEditorTableView(self, None, truncate=truncate, minmax=minmax, remote_editing=remote_editing, get_value_func=self.get_value, set_value_func=self.set_value, new_value_func=self.set_value, remove_values_func=self.remove_values, copy_value_func=self.copy_value, is_list_func=self.is_list, get_len_func=self.get_len, is_array_func=self.is_array, is_image_func=self.is_image, is_dict_func=self.is_dict, is_data_frame_func=self.is_data_frame, is_time_series_func=self.is_time_series, get_array_shape_func=self.get_array_shape, get_array_ndim_func=self.get_array_ndim, oedit_func=self.oedit, plot_func=self.plot, imshow_func=self.imshow, show_image_func=self.show_image) self.editor.sig_option_changed.connect(self.sig_option_changed.emit) self.editor.sig_files_dropped.connect(self.import_data) hlayout = QHBoxLayout() vlayout = QVBoxLayout() toolbar = self.setup_toolbar(exclude_private, exclude_uppercase, exclude_capitalized, exclude_unsupported, autorefresh) vlayout.setAlignment(Qt.AlignTop) for widget in toolbar: vlayout.addWidget(widget) hlayout.addWidget(self.editor) hlayout.addLayout(vlayout) self.setLayout(hlayout) hlayout.setContentsMargins(0, 0, 0, 0) self.sig_option_changed.connect(self.option_changed)
def set_shellwidget(self, shellwidget): 'Bind shellwidget instance to namespace browser' self.shellwidget = shellwidget from spyderlib.widgets import internalshell self.is_internal_shell = isinstance(self.shellwidget, internalshell.InternalShell) self.is_ipykernel = self.shellwidget.is_ipykernel if (not self.is_internal_shell): shellwidget.set_namespacebrowser(self)
2,561,803,688,112,527,400
Bind shellwidget instance to namespace browser
spyderlib/widgets/externalshell/namespacebrowser.py
set_shellwidget
junglefunkyman/spectracer
python
def set_shellwidget(self, shellwidget): self.shellwidget = shellwidget from spyderlib.widgets import internalshell self.is_internal_shell = isinstance(self.shellwidget, internalshell.InternalShell) self.is_ipykernel = self.shellwidget.is_ipykernel if (not self.is_internal_shell): shellwidget.set_namespacebrowser(self)
def set_ipyclient(self, ipyclient): 'Bind ipyclient instance to namespace browser' self.ipyclient = ipyclient
-7,624,842,523,463,780,000
Bind ipyclient instance to namespace browser
spyderlib/widgets/externalshell/namespacebrowser.py
set_ipyclient
junglefunkyman/spectracer
python
def set_ipyclient(self, ipyclient): self.ipyclient = ipyclient
def setup_toolbar(self, exclude_private, exclude_uppercase, exclude_capitalized, exclude_unsupported, autorefresh): 'Setup toolbar' self.setup_in_progress = True toolbar = [] refresh_button = create_toolbutton(self, text=_('Refresh'), icon=get_icon('reload.png'), triggered=self.refresh_table) self.auto_refresh_button = create_toolbutton(self, text=_('Refresh periodically'), icon=get_icon('auto_reload.png'), toggled=self.toggle_auto_refresh) self.auto_refresh_button.setChecked(autorefresh) load_button = create_toolbutton(self, text=_('Import data'), icon=get_icon('fileimport.png'), triggered=self.import_data) self.save_button = create_toolbutton(self, text=_('Save data'), icon=get_icon('filesave.png'), triggered=(lambda : self.save_data(self.filename))) self.save_button.setEnabled(False) save_as_button = create_toolbutton(self, text=_('Save data as...'), icon=get_icon('filesaveas.png'), triggered=self.save_data) toolbar += [refresh_button, self.auto_refresh_button, load_button, self.save_button, save_as_button] self.exclude_private_action = create_action(self, _('Exclude private references'), tip=_('Exclude references which name starts with an underscore'), toggled=(lambda state: self.sig_option_changed.emit('exclude_private', state))) self.exclude_private_action.setChecked(exclude_private) self.exclude_uppercase_action = create_action(self, _('Exclude all-uppercase references'), tip=_('Exclude references which name is uppercase'), toggled=(lambda state: self.sig_option_changed.emit('exclude_uppercase', state))) self.exclude_uppercase_action.setChecked(exclude_uppercase) self.exclude_capitalized_action = create_action(self, _('Exclude capitalized references'), tip=_('Exclude references which name starts with an uppercase character'), toggled=(lambda state: self.sig_option_changed.emit('exclude_capitalized', state))) self.exclude_capitalized_action.setChecked(exclude_capitalized) self.exclude_unsupported_action = create_action(self, _('Exclude unsupported data types'), tip=_("Exclude references to unsupported data types (i.e. which won't be handled/saved correctly)"), toggled=(lambda state: self.sig_option_changed.emit('exclude_unsupported', state))) self.exclude_unsupported_action.setChecked(exclude_unsupported) options_button = create_toolbutton(self, text=_('Options'), icon=get_icon('tooloptions.png')) toolbar.append(options_button) options_button.setPopupMode(QToolButton.InstantPopup) menu = QMenu(self) editor = self.editor actions = [self.exclude_private_action, self.exclude_uppercase_action, self.exclude_capitalized_action, self.exclude_unsupported_action, None, editor.truncate_action] if is_module_installed('numpy'): actions.append(editor.minmax_action) add_actions(menu, actions) options_button.setMenu(menu) self.setup_in_progress = False return toolbar
-159,748,832,943,028,060
Setup toolbar
spyderlib/widgets/externalshell/namespacebrowser.py
setup_toolbar
junglefunkyman/spectracer
python
def setup_toolbar(self, exclude_private, exclude_uppercase, exclude_capitalized, exclude_unsupported, autorefresh): self.setup_in_progress = True toolbar = [] refresh_button = create_toolbutton(self, text=_('Refresh'), icon=get_icon('reload.png'), triggered=self.refresh_table) self.auto_refresh_button = create_toolbutton(self, text=_('Refresh periodically'), icon=get_icon('auto_reload.png'), toggled=self.toggle_auto_refresh) self.auto_refresh_button.setChecked(autorefresh) load_button = create_toolbutton(self, text=_('Import data'), icon=get_icon('fileimport.png'), triggered=self.import_data) self.save_button = create_toolbutton(self, text=_('Save data'), icon=get_icon('filesave.png'), triggered=(lambda : self.save_data(self.filename))) self.save_button.setEnabled(False) save_as_button = create_toolbutton(self, text=_('Save data as...'), icon=get_icon('filesaveas.png'), triggered=self.save_data) toolbar += [refresh_button, self.auto_refresh_button, load_button, self.save_button, save_as_button] self.exclude_private_action = create_action(self, _('Exclude private references'), tip=_('Exclude references which name starts with an underscore'), toggled=(lambda state: self.sig_option_changed.emit('exclude_private', state))) self.exclude_private_action.setChecked(exclude_private) self.exclude_uppercase_action = create_action(self, _('Exclude all-uppercase references'), tip=_('Exclude references which name is uppercase'), toggled=(lambda state: self.sig_option_changed.emit('exclude_uppercase', state))) self.exclude_uppercase_action.setChecked(exclude_uppercase) self.exclude_capitalized_action = create_action(self, _('Exclude capitalized references'), tip=_('Exclude references which name starts with an uppercase character'), toggled=(lambda state: self.sig_option_changed.emit('exclude_capitalized', state))) self.exclude_capitalized_action.setChecked(exclude_capitalized) self.exclude_unsupported_action = create_action(self, _('Exclude unsupported data types'), tip=_("Exclude references to unsupported data types (i.e. which won't be handled/saved correctly)"), toggled=(lambda state: self.sig_option_changed.emit('exclude_unsupported', state))) self.exclude_unsupported_action.setChecked(exclude_unsupported) options_button = create_toolbutton(self, text=_('Options'), icon=get_icon('tooloptions.png')) toolbar.append(options_button) options_button.setPopupMode(QToolButton.InstantPopup) menu = QMenu(self) editor = self.editor actions = [self.exclude_private_action, self.exclude_uppercase_action, self.exclude_capitalized_action, self.exclude_unsupported_action, None, editor.truncate_action] if is_module_installed('numpy'): actions.append(editor.minmax_action) add_actions(menu, actions) options_button.setMenu(menu) self.setup_in_progress = False return toolbar