Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Using the snippet: <|code_start|>"""
tests.test_yaspin
~~~~~~~~~~~~~~~~~
Basic unittests.
"""
@pytest.mark.parametrize(
"spinner, expected",
[
# None
<|code_end|>
, determine the next line of code. You have imports:
from collections import namedtuple
from yaspin import Spinner, yaspin
from yaspin.base_spinner import default_spinner
import pytest
and context (class names, function names, or code) available:
# Path: yaspin/api.py
# def yaspin(*args, **kwargs):
# """Display spinner in stdout.
#
# Can be used as a context manager or as a function decorator.
#
# Arguments:
# spinner (base_spinner.Spinner, optional): Spinner object to use.
# text (str, optional): Text to show along with spinner.
# color (str, optional): Spinner color.
# on_color (str, optional): Color highlight for the spinner.
# attrs (list, optional): Color attributes for the spinner.
# reversal (bool, optional): Reverse spin direction.
# side (str, optional): Place spinner to the right or left end
# of the text string.
# sigmap (dict, optional): Maps POSIX signals to their respective
# handlers.
# timer (bool, optional): Prints a timer showing the elapsed time.
#
# Returns:
# core.Yaspin: instance of the Yaspin class.
#
# Raises:
# ValueError: If unsupported ``color`` is specified.
# ValueError: If unsupported ``on_color`` is specified.
# ValueError: If unsupported color attribute in ``attrs``
# is specified.
# ValueError: If trying to register handler for SIGKILL signal.
# ValueError: If unsupported ``side`` is specified.
#
# Available text colors:
# red, green, yellow, blue, magenta, cyan, white.
#
# Available text highlights:
# on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan,
# on_white, on_grey.
#
# Available attributes:
# bold, dark, underline, blink, reverse, concealed.
#
# Example::
#
# # Use as a context manager
# with yaspin():
# some_operations()
#
# # Context manager with text
# with yaspin(text="Processing..."):
# some_operations()
#
# # Context manager with custom sequence
# with yaspin(Spinner('-\\|/', 150)):
# some_operations()
#
# # As decorator
# @yaspin(text="Loading...")
# def foo():
# time.sleep(5)
#
# foo()
#
# """
# return Yaspin(*args, **kwargs)
#
# Path: yaspin/base_spinner.py
# class Spinner:
# frames: str
# interval: int
#
# Path: yaspin/base_spinner.py
# class Spinner:
. Output only the next line. | (None, default_spinner), |
Given the code snippet: <|code_start|>"""
examples.spinner_properties
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Updating spinner on the fly.
"""
def manual_setup():
<|code_end|>
, generate the next line using the imports in this file:
import time
from yaspin import yaspin
from yaspin.spinners import Spinners
and context (functions, classes, or occasionally code) from other files:
# Path: yaspin/api.py
# def yaspin(*args, **kwargs):
# """Display spinner in stdout.
#
# Can be used as a context manager or as a function decorator.
#
# Arguments:
# spinner (base_spinner.Spinner, optional): Spinner object to use.
# text (str, optional): Text to show along with spinner.
# color (str, optional): Spinner color.
# on_color (str, optional): Color highlight for the spinner.
# attrs (list, optional): Color attributes for the spinner.
# reversal (bool, optional): Reverse spin direction.
# side (str, optional): Place spinner to the right or left end
# of the text string.
# sigmap (dict, optional): Maps POSIX signals to their respective
# handlers.
# timer (bool, optional): Prints a timer showing the elapsed time.
#
# Returns:
# core.Yaspin: instance of the Yaspin class.
#
# Raises:
# ValueError: If unsupported ``color`` is specified.
# ValueError: If unsupported ``on_color`` is specified.
# ValueError: If unsupported color attribute in ``attrs``
# is specified.
# ValueError: If trying to register handler for SIGKILL signal.
# ValueError: If unsupported ``side`` is specified.
#
# Available text colors:
# red, green, yellow, blue, magenta, cyan, white.
#
# Available text highlights:
# on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan,
# on_white, on_grey.
#
# Available attributes:
# bold, dark, underline, blink, reverse, concealed.
#
# Example::
#
# # Use as a context manager
# with yaspin():
# some_operations()
#
# # Context manager with text
# with yaspin(text="Processing..."):
# some_operations()
#
# # Context manager with custom sequence
# with yaspin(Spinner('-\\|/', 150)):
# some_operations()
#
# # As decorator
# @yaspin(text="Loading...")
# def foo():
# time.sleep(5)
#
# foo()
#
# """
# return Yaspin(*args, **kwargs)
#
# Path: yaspin/spinners.py
# SPINNERS_DATA = pkgutil.get_data(__name__, "data/spinners.json").decode("utf-8")
# def _hook(dct):
. Output only the next line. | sp = yaspin(text="Default spinner") |
Given snippet: <|code_start|>"""
examples.spinner_properties
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Updating spinner on the fly.
"""
def manual_setup():
sp = yaspin(text="Default spinner")
sp.start()
time.sleep(2)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import time
from yaspin import yaspin
from yaspin.spinners import Spinners
and context:
# Path: yaspin/api.py
# def yaspin(*args, **kwargs):
# """Display spinner in stdout.
#
# Can be used as a context manager or as a function decorator.
#
# Arguments:
# spinner (base_spinner.Spinner, optional): Spinner object to use.
# text (str, optional): Text to show along with spinner.
# color (str, optional): Spinner color.
# on_color (str, optional): Color highlight for the spinner.
# attrs (list, optional): Color attributes for the spinner.
# reversal (bool, optional): Reverse spin direction.
# side (str, optional): Place spinner to the right or left end
# of the text string.
# sigmap (dict, optional): Maps POSIX signals to their respective
# handlers.
# timer (bool, optional): Prints a timer showing the elapsed time.
#
# Returns:
# core.Yaspin: instance of the Yaspin class.
#
# Raises:
# ValueError: If unsupported ``color`` is specified.
# ValueError: If unsupported ``on_color`` is specified.
# ValueError: If unsupported color attribute in ``attrs``
# is specified.
# ValueError: If trying to register handler for SIGKILL signal.
# ValueError: If unsupported ``side`` is specified.
#
# Available text colors:
# red, green, yellow, blue, magenta, cyan, white.
#
# Available text highlights:
# on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan,
# on_white, on_grey.
#
# Available attributes:
# bold, dark, underline, blink, reverse, concealed.
#
# Example::
#
# # Use as a context manager
# with yaspin():
# some_operations()
#
# # Context manager with text
# with yaspin(text="Processing..."):
# some_operations()
#
# # Context manager with custom sequence
# with yaspin(Spinner('-\\|/', 150)):
# some_operations()
#
# # As decorator
# @yaspin(text="Loading...")
# def foo():
# time.sleep(5)
#
# foo()
#
# """
# return Yaspin(*args, **kwargs)
#
# Path: yaspin/spinners.py
# SPINNERS_DATA = pkgutil.get_data(__name__, "data/spinners.json").decode("utf-8")
# def _hook(dct):
which might include code, classes, or functions. Output only the next line. | sp.spinner = Spinners.arc |
Next line prediction: <|code_start|>"""
tests.test_spinners
~~~~~~~~~~~~~~~~~~~
Tests for spinners collection.
"""
<|code_end|>
. Use current file imports:
(import json
import pytest
from collections import OrderedDict
from yaspin.spinners import SPINNERS_DATA, Spinners)
and context including class names, function names, or small code snippets from other files:
# Path: yaspin/spinners.py
# SPINNERS_DATA = pkgutil.get_data(__name__, "data/spinners.json").decode("utf-8")
# def _hook(dct):
. Output only the next line. | spinners_dict = OrderedDict(json.loads(SPINNERS_DATA)) |
Predict the next line after this snippet: <|code_start|>"""
tests.test_spinners
~~~~~~~~~~~~~~~~~~~
Tests for spinners collection.
"""
spinners_dict = OrderedDict(json.loads(SPINNERS_DATA))
test_cases = [(name, v["frames"], v["interval"]) for name, v in spinners_dict.items()]
def test_len():
<|code_end|>
using the current file's imports:
import json
import pytest
from collections import OrderedDict
from yaspin.spinners import SPINNERS_DATA, Spinners
and any relevant context from other files:
# Path: yaspin/spinners.py
# SPINNERS_DATA = pkgutil.get_data(__name__, "data/spinners.json").decode("utf-8")
# def _hook(dct):
. Output only the next line. | assert len(Spinners) == len(spinners_dict) |
Here is a snippet: <|code_start|>"""
examples.reverse_spinner
~~~~~~~~~~~~~~~~~~~~~~~~
Reverse spinner rotation.
"""
def main():
<|code_end|>
. Write the next line using the current file imports:
import time
from yaspin import yaspin
from yaspin.spinners import Spinners
and context from other files:
# Path: yaspin/api.py
# def yaspin(*args, **kwargs):
# """Display spinner in stdout.
#
# Can be used as a context manager or as a function decorator.
#
# Arguments:
# spinner (base_spinner.Spinner, optional): Spinner object to use.
# text (str, optional): Text to show along with spinner.
# color (str, optional): Spinner color.
# on_color (str, optional): Color highlight for the spinner.
# attrs (list, optional): Color attributes for the spinner.
# reversal (bool, optional): Reverse spin direction.
# side (str, optional): Place spinner to the right or left end
# of the text string.
# sigmap (dict, optional): Maps POSIX signals to their respective
# handlers.
# timer (bool, optional): Prints a timer showing the elapsed time.
#
# Returns:
# core.Yaspin: instance of the Yaspin class.
#
# Raises:
# ValueError: If unsupported ``color`` is specified.
# ValueError: If unsupported ``on_color`` is specified.
# ValueError: If unsupported color attribute in ``attrs``
# is specified.
# ValueError: If trying to register handler for SIGKILL signal.
# ValueError: If unsupported ``side`` is specified.
#
# Available text colors:
# red, green, yellow, blue, magenta, cyan, white.
#
# Available text highlights:
# on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan,
# on_white, on_grey.
#
# Available attributes:
# bold, dark, underline, blink, reverse, concealed.
#
# Example::
#
# # Use as a context manager
# with yaspin():
# some_operations()
#
# # Context manager with text
# with yaspin(text="Processing..."):
# some_operations()
#
# # Context manager with custom sequence
# with yaspin(Spinner('-\\|/', 150)):
# some_operations()
#
# # As decorator
# @yaspin(text="Loading...")
# def foo():
# time.sleep(5)
#
# foo()
#
# """
# return Yaspin(*args, **kwargs)
#
# Path: yaspin/spinners.py
# SPINNERS_DATA = pkgutil.get_data(__name__, "data/spinners.json").decode("utf-8")
# def _hook(dct):
, which may include functions, classes, or code. Output only the next line. | with yaspin(Spinners.clock, text="Clockwise") as sp: |
Based on the snippet: <|code_start|>"""
examples.reverse_spinner
~~~~~~~~~~~~~~~~~~~~~~~~
Reverse spinner rotation.
"""
def main():
<|code_end|>
, predict the immediate next line with the help of imports:
import time
from yaspin import yaspin
from yaspin.spinners import Spinners
and context (classes, functions, sometimes code) from other files:
# Path: yaspin/api.py
# def yaspin(*args, **kwargs):
# """Display spinner in stdout.
#
# Can be used as a context manager or as a function decorator.
#
# Arguments:
# spinner (base_spinner.Spinner, optional): Spinner object to use.
# text (str, optional): Text to show along with spinner.
# color (str, optional): Spinner color.
# on_color (str, optional): Color highlight for the spinner.
# attrs (list, optional): Color attributes for the spinner.
# reversal (bool, optional): Reverse spin direction.
# side (str, optional): Place spinner to the right or left end
# of the text string.
# sigmap (dict, optional): Maps POSIX signals to their respective
# handlers.
# timer (bool, optional): Prints a timer showing the elapsed time.
#
# Returns:
# core.Yaspin: instance of the Yaspin class.
#
# Raises:
# ValueError: If unsupported ``color`` is specified.
# ValueError: If unsupported ``on_color`` is specified.
# ValueError: If unsupported color attribute in ``attrs``
# is specified.
# ValueError: If trying to register handler for SIGKILL signal.
# ValueError: If unsupported ``side`` is specified.
#
# Available text colors:
# red, green, yellow, blue, magenta, cyan, white.
#
# Available text highlights:
# on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan,
# on_white, on_grey.
#
# Available attributes:
# bold, dark, underline, blink, reverse, concealed.
#
# Example::
#
# # Use as a context manager
# with yaspin():
# some_operations()
#
# # Context manager with text
# with yaspin(text="Processing..."):
# some_operations()
#
# # Context manager with custom sequence
# with yaspin(Spinner('-\\|/', 150)):
# some_operations()
#
# # As decorator
# @yaspin(text="Loading...")
# def foo():
# time.sleep(5)
#
# foo()
#
# """
# return Yaspin(*args, **kwargs)
#
# Path: yaspin/spinners.py
# SPINNERS_DATA = pkgutil.get_data(__name__, "data/spinners.json").decode("utf-8")
# def _hook(dct):
. Output only the next line. | with yaspin(Spinners.clock, text="Clockwise") as sp: |
Here is a snippet: <|code_start|>"""
examples.advanced_colors
~~~~~~~~~~~~~~~~~~~~~~~~
Use familiar API of the `termcolor.colored` function to apply any
color, highlight, attribute or their mix to your yaspin spinner.
"""
def white_shark():
# Set with attributes
<|code_end|>
. Write the next line using the current file imports:
import time
from yaspin import yaspin
and context from other files:
# Path: yaspin/api.py
# def yaspin(*args, **kwargs):
# """Display spinner in stdout.
#
# Can be used as a context manager or as a function decorator.
#
# Arguments:
# spinner (base_spinner.Spinner, optional): Spinner object to use.
# text (str, optional): Text to show along with spinner.
# color (str, optional): Spinner color.
# on_color (str, optional): Color highlight for the spinner.
# attrs (list, optional): Color attributes for the spinner.
# reversal (bool, optional): Reverse spin direction.
# side (str, optional): Place spinner to the right or left end
# of the text string.
# sigmap (dict, optional): Maps POSIX signals to their respective
# handlers.
# timer (bool, optional): Prints a timer showing the elapsed time.
#
# Returns:
# core.Yaspin: instance of the Yaspin class.
#
# Raises:
# ValueError: If unsupported ``color`` is specified.
# ValueError: If unsupported ``on_color`` is specified.
# ValueError: If unsupported color attribute in ``attrs``
# is specified.
# ValueError: If trying to register handler for SIGKILL signal.
# ValueError: If unsupported ``side`` is specified.
#
# Available text colors:
# red, green, yellow, blue, magenta, cyan, white.
#
# Available text highlights:
# on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan,
# on_white, on_grey.
#
# Available attributes:
# bold, dark, underline, blink, reverse, concealed.
#
# Example::
#
# # Use as a context manager
# with yaspin():
# some_operations()
#
# # Context manager with text
# with yaspin(text="Processing..."):
# some_operations()
#
# # Context manager with custom sequence
# with yaspin(Spinner('-\\|/', 150)):
# some_operations()
#
# # As decorator
# @yaspin(text="Loading...")
# def foo():
# time.sleep(5)
#
# foo()
#
# """
# return Yaspin(*args, **kwargs)
, which may include functions, classes, or code. Output only the next line. | with yaspin().white.bold.shark.on_blue as sp: |
Given the following code snippet before the placeholder: <|code_start|>"""
examples.colors
~~~~~~~~~~~~~~~
Basic usage of the 'color', 'on_color' and 'attrs' arguments.
"""
def all_colors():
<|code_end|>
, predict the next line using imports from the current file:
import time
from yaspin import yaspin
and context including class names, function names, and sometimes code from other files:
# Path: yaspin/api.py
# def yaspin(*args, **kwargs):
# """Display spinner in stdout.
#
# Can be used as a context manager or as a function decorator.
#
# Arguments:
# spinner (base_spinner.Spinner, optional): Spinner object to use.
# text (str, optional): Text to show along with spinner.
# color (str, optional): Spinner color.
# on_color (str, optional): Color highlight for the spinner.
# attrs (list, optional): Color attributes for the spinner.
# reversal (bool, optional): Reverse spin direction.
# side (str, optional): Place spinner to the right or left end
# of the text string.
# sigmap (dict, optional): Maps POSIX signals to their respective
# handlers.
# timer (bool, optional): Prints a timer showing the elapsed time.
#
# Returns:
# core.Yaspin: instance of the Yaspin class.
#
# Raises:
# ValueError: If unsupported ``color`` is specified.
# ValueError: If unsupported ``on_color`` is specified.
# ValueError: If unsupported color attribute in ``attrs``
# is specified.
# ValueError: If trying to register handler for SIGKILL signal.
# ValueError: If unsupported ``side`` is specified.
#
# Available text colors:
# red, green, yellow, blue, magenta, cyan, white.
#
# Available text highlights:
# on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan,
# on_white, on_grey.
#
# Available attributes:
# bold, dark, underline, blink, reverse, concealed.
#
# Example::
#
# # Use as a context manager
# with yaspin():
# some_operations()
#
# # Context manager with text
# with yaspin(text="Processing..."):
# some_operations()
#
# # Context manager with custom sequence
# with yaspin(Spinner('-\\|/', 150)):
# some_operations()
#
# # As decorator
# @yaspin(text="Loading...")
# def foo():
# time.sleep(5)
#
# foo()
#
# """
# return Yaspin(*args, **kwargs)
. Output only the next line. | with yaspin(text="Colors!").bouncingBar as sp: |
Here is a snippet: <|code_start|>"""
examples.basic_usage
~~~~~~~~~~~~~~~~~~~~
Common usage patterns for the yaspin spinner.
"""
def context_manager_default():
<|code_end|>
. Write the next line using the current file imports:
import signal
import time
from yaspin import Spinner, yaspin
from yaspin.signal_handlers import fancy_handler
from yaspin.spinners import Spinners
and context from other files:
# Path: yaspin/api.py
# def yaspin(*args, **kwargs):
# """Display spinner in stdout.
#
# Can be used as a context manager or as a function decorator.
#
# Arguments:
# spinner (base_spinner.Spinner, optional): Spinner object to use.
# text (str, optional): Text to show along with spinner.
# color (str, optional): Spinner color.
# on_color (str, optional): Color highlight for the spinner.
# attrs (list, optional): Color attributes for the spinner.
# reversal (bool, optional): Reverse spin direction.
# side (str, optional): Place spinner to the right or left end
# of the text string.
# sigmap (dict, optional): Maps POSIX signals to their respective
# handlers.
# timer (bool, optional): Prints a timer showing the elapsed time.
#
# Returns:
# core.Yaspin: instance of the Yaspin class.
#
# Raises:
# ValueError: If unsupported ``color`` is specified.
# ValueError: If unsupported ``on_color`` is specified.
# ValueError: If unsupported color attribute in ``attrs``
# is specified.
# ValueError: If trying to register handler for SIGKILL signal.
# ValueError: If unsupported ``side`` is specified.
#
# Available text colors:
# red, green, yellow, blue, magenta, cyan, white.
#
# Available text highlights:
# on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan,
# on_white, on_grey.
#
# Available attributes:
# bold, dark, underline, blink, reverse, concealed.
#
# Example::
#
# # Use as a context manager
# with yaspin():
# some_operations()
#
# # Context manager with text
# with yaspin(text="Processing..."):
# some_operations()
#
# # Context manager with custom sequence
# with yaspin(Spinner('-\\|/', 150)):
# some_operations()
#
# # As decorator
# @yaspin(text="Loading...")
# def foo():
# time.sleep(5)
#
# foo()
#
# """
# return Yaspin(*args, **kwargs)
#
# Path: yaspin/base_spinner.py
# class Spinner:
# frames: str
# interval: int
#
# Path: yaspin/signal_handlers.py
# def fancy_handler(signum, frame, spinner): # pylint: disable=unused-argument
# """Signal handler, used to gracefully shut down the ``spinner`` instance
# when specified signal is received by the process running the ``spinner``.
#
# ``signum`` and ``frame`` are mandatory arguments. Check ``signal.signal``
# function for more details.
# """
# spinner.red.fail("✘")
# spinner.stop()
# sys.exit(0)
#
# Path: yaspin/spinners.py
# SPINNERS_DATA = pkgutil.get_data(__name__, "data/spinners.json").decode("utf-8")
# def _hook(dct):
, which may include functions, classes, or code. Output only the next line. | with yaspin(text="Braille"): |
Predict the next line after this snippet: <|code_start|>"""
examples.basic_usage
~~~~~~~~~~~~~~~~~~~~
Common usage patterns for the yaspin spinner.
"""
def context_manager_default():
with yaspin(text="Braille"):
time.sleep(3)
def context_manager_line():
<|code_end|>
using the current file's imports:
import signal
import time
from yaspin import Spinner, yaspin
from yaspin.signal_handlers import fancy_handler
from yaspin.spinners import Spinners
and any relevant context from other files:
# Path: yaspin/api.py
# def yaspin(*args, **kwargs):
# """Display spinner in stdout.
#
# Can be used as a context manager or as a function decorator.
#
# Arguments:
# spinner (base_spinner.Spinner, optional): Spinner object to use.
# text (str, optional): Text to show along with spinner.
# color (str, optional): Spinner color.
# on_color (str, optional): Color highlight for the spinner.
# attrs (list, optional): Color attributes for the spinner.
# reversal (bool, optional): Reverse spin direction.
# side (str, optional): Place spinner to the right or left end
# of the text string.
# sigmap (dict, optional): Maps POSIX signals to their respective
# handlers.
# timer (bool, optional): Prints a timer showing the elapsed time.
#
# Returns:
# core.Yaspin: instance of the Yaspin class.
#
# Raises:
# ValueError: If unsupported ``color`` is specified.
# ValueError: If unsupported ``on_color`` is specified.
# ValueError: If unsupported color attribute in ``attrs``
# is specified.
# ValueError: If trying to register handler for SIGKILL signal.
# ValueError: If unsupported ``side`` is specified.
#
# Available text colors:
# red, green, yellow, blue, magenta, cyan, white.
#
# Available text highlights:
# on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan,
# on_white, on_grey.
#
# Available attributes:
# bold, dark, underline, blink, reverse, concealed.
#
# Example::
#
# # Use as a context manager
# with yaspin():
# some_operations()
#
# # Context manager with text
# with yaspin(text="Processing..."):
# some_operations()
#
# # Context manager with custom sequence
# with yaspin(Spinner('-\\|/', 150)):
# some_operations()
#
# # As decorator
# @yaspin(text="Loading...")
# def foo():
# time.sleep(5)
#
# foo()
#
# """
# return Yaspin(*args, **kwargs)
#
# Path: yaspin/base_spinner.py
# class Spinner:
# frames: str
# interval: int
#
# Path: yaspin/signal_handlers.py
# def fancy_handler(signum, frame, spinner): # pylint: disable=unused-argument
# """Signal handler, used to gracefully shut down the ``spinner`` instance
# when specified signal is received by the process running the ``spinner``.
#
# ``signum`` and ``frame`` are mandatory arguments. Check ``signal.signal``
# function for more details.
# """
# spinner.red.fail("✘")
# spinner.stop()
# sys.exit(0)
#
# Path: yaspin/spinners.py
# SPINNERS_DATA = pkgutil.get_data(__name__, "data/spinners.json").decode("utf-8")
# def _hook(dct):
. Output only the next line. | line_spinner = Spinner("-\\|/", 150) |
Given snippet: <|code_start|>~~~~~~~~~~~~~~~~~~~~
Common usage patterns for the yaspin spinner.
"""
def context_manager_default():
with yaspin(text="Braille"):
time.sleep(3)
def context_manager_line():
line_spinner = Spinner("-\\|/", 150)
with yaspin(line_spinner, "line"):
time.sleep(3)
@yaspin(Spinner("⢄⢂⢁⡁⡈⡐⡠", 80), text="Dots")
def decorated_function():
time.sleep(3)
def pre_setup_example():
swirl = yaspin(
spinner=Spinners.simpleDotsScrolling,
text="swirl",
color="red",
side="right",
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import signal
import time
from yaspin import Spinner, yaspin
from yaspin.signal_handlers import fancy_handler
from yaspin.spinners import Spinners
and context:
# Path: yaspin/api.py
# def yaspin(*args, **kwargs):
# """Display spinner in stdout.
#
# Can be used as a context manager or as a function decorator.
#
# Arguments:
# spinner (base_spinner.Spinner, optional): Spinner object to use.
# text (str, optional): Text to show along with spinner.
# color (str, optional): Spinner color.
# on_color (str, optional): Color highlight for the spinner.
# attrs (list, optional): Color attributes for the spinner.
# reversal (bool, optional): Reverse spin direction.
# side (str, optional): Place spinner to the right or left end
# of the text string.
# sigmap (dict, optional): Maps POSIX signals to their respective
# handlers.
# timer (bool, optional): Prints a timer showing the elapsed time.
#
# Returns:
# core.Yaspin: instance of the Yaspin class.
#
# Raises:
# ValueError: If unsupported ``color`` is specified.
# ValueError: If unsupported ``on_color`` is specified.
# ValueError: If unsupported color attribute in ``attrs``
# is specified.
# ValueError: If trying to register handler for SIGKILL signal.
# ValueError: If unsupported ``side`` is specified.
#
# Available text colors:
# red, green, yellow, blue, magenta, cyan, white.
#
# Available text highlights:
# on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan,
# on_white, on_grey.
#
# Available attributes:
# bold, dark, underline, blink, reverse, concealed.
#
# Example::
#
# # Use as a context manager
# with yaspin():
# some_operations()
#
# # Context manager with text
# with yaspin(text="Processing..."):
# some_operations()
#
# # Context manager with custom sequence
# with yaspin(Spinner('-\\|/', 150)):
# some_operations()
#
# # As decorator
# @yaspin(text="Loading...")
# def foo():
# time.sleep(5)
#
# foo()
#
# """
# return Yaspin(*args, **kwargs)
#
# Path: yaspin/base_spinner.py
# class Spinner:
# frames: str
# interval: int
#
# Path: yaspin/signal_handlers.py
# def fancy_handler(signum, frame, spinner): # pylint: disable=unused-argument
# """Signal handler, used to gracefully shut down the ``spinner`` instance
# when specified signal is received by the process running the ``spinner``.
#
# ``signum`` and ``frame`` are mandatory arguments. Check ``signal.signal``
# function for more details.
# """
# spinner.red.fail("✘")
# spinner.stop()
# sys.exit(0)
#
# Path: yaspin/spinners.py
# SPINNERS_DATA = pkgutil.get_data(__name__, "data/spinners.json").decode("utf-8")
# def _hook(dct):
which might include code, classes, or functions. Output only the next line. | sigmap={signal.SIGINT: fancy_handler}, |
Given the code snippet: <|code_start|>"""
examples.basic_usage
~~~~~~~~~~~~~~~~~~~~
Common usage patterns for the yaspin spinner.
"""
def context_manager_default():
with yaspin(text="Braille"):
time.sleep(3)
def context_manager_line():
line_spinner = Spinner("-\\|/", 150)
with yaspin(line_spinner, "line"):
time.sleep(3)
@yaspin(Spinner("⢄⢂⢁⡁⡈⡐⡠", 80), text="Dots")
def decorated_function():
time.sleep(3)
def pre_setup_example():
swirl = yaspin(
<|code_end|>
, generate the next line using the imports in this file:
import signal
import time
from yaspin import Spinner, yaspin
from yaspin.signal_handlers import fancy_handler
from yaspin.spinners import Spinners
and context (functions, classes, or occasionally code) from other files:
# Path: yaspin/api.py
# def yaspin(*args, **kwargs):
# """Display spinner in stdout.
#
# Can be used as a context manager or as a function decorator.
#
# Arguments:
# spinner (base_spinner.Spinner, optional): Spinner object to use.
# text (str, optional): Text to show along with spinner.
# color (str, optional): Spinner color.
# on_color (str, optional): Color highlight for the spinner.
# attrs (list, optional): Color attributes for the spinner.
# reversal (bool, optional): Reverse spin direction.
# side (str, optional): Place spinner to the right or left end
# of the text string.
# sigmap (dict, optional): Maps POSIX signals to their respective
# handlers.
# timer (bool, optional): Prints a timer showing the elapsed time.
#
# Returns:
# core.Yaspin: instance of the Yaspin class.
#
# Raises:
# ValueError: If unsupported ``color`` is specified.
# ValueError: If unsupported ``on_color`` is specified.
# ValueError: If unsupported color attribute in ``attrs``
# is specified.
# ValueError: If trying to register handler for SIGKILL signal.
# ValueError: If unsupported ``side`` is specified.
#
# Available text colors:
# red, green, yellow, blue, magenta, cyan, white.
#
# Available text highlights:
# on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan,
# on_white, on_grey.
#
# Available attributes:
# bold, dark, underline, blink, reverse, concealed.
#
# Example::
#
# # Use as a context manager
# with yaspin():
# some_operations()
#
# # Context manager with text
# with yaspin(text="Processing..."):
# some_operations()
#
# # Context manager with custom sequence
# with yaspin(Spinner('-\\|/', 150)):
# some_operations()
#
# # As decorator
# @yaspin(text="Loading...")
# def foo():
# time.sleep(5)
#
# foo()
#
# """
# return Yaspin(*args, **kwargs)
#
# Path: yaspin/base_spinner.py
# class Spinner:
# frames: str
# interval: int
#
# Path: yaspin/signal_handlers.py
# def fancy_handler(signum, frame, spinner): # pylint: disable=unused-argument
# """Signal handler, used to gracefully shut down the ``spinner`` instance
# when specified signal is received by the process running the ``spinner``.
#
# ``signum`` and ``frame`` are mandatory arguments. Check ``signal.signal``
# function for more details.
# """
# spinner.red.fail("✘")
# spinner.stop()
# sys.exit(0)
#
# Path: yaspin/spinners.py
# SPINNERS_DATA = pkgutil.get_data(__name__, "data/spinners.json").decode("utf-8")
# def _hook(dct):
. Output only the next line. | spinner=Spinners.simpleDotsScrolling, |
Predict the next line for this snippet: <|code_start|>
Handling signals.
Reference
---------
- Signals in a nutshell:
https://twitter.com/b0rk/status/981678748763414529
- More detailed overview:
https://jvns.ca/blog/2016/06/13/should-you-be-scared-of-signals/
- Python signal module examples:
https://pymotw.com/3/signal/index.html
- Linux signals reference:
https://www.computerhope.com/unix/signals.htm#linux
"""
DEFAULT_TEXT = "Press Control+C to send SIGINT (Keyboard Interrupt) signal"
#
# Basic usage
#
def simple_keyboard_interrupt_handling():
<|code_end|>
with the help of current file imports:
import os
import random
import signal
import sys
import time
from yaspin import kbi_safe_yaspin, yaspin
from yaspin.signal_handlers import fancy_handler
from yaspin.spinners import Spinners
and context from other files:
# Path: yaspin/api.py
# def kbi_safe_yaspin(*args, **kwargs):
# kwargs["sigmap"] = {signal.SIGINT: default_handler}
# return Yaspin(*args, **kwargs)
#
# def yaspin(*args, **kwargs):
# """Display spinner in stdout.
#
# Can be used as a context manager or as a function decorator.
#
# Arguments:
# spinner (base_spinner.Spinner, optional): Spinner object to use.
# text (str, optional): Text to show along with spinner.
# color (str, optional): Spinner color.
# on_color (str, optional): Color highlight for the spinner.
# attrs (list, optional): Color attributes for the spinner.
# reversal (bool, optional): Reverse spin direction.
# side (str, optional): Place spinner to the right or left end
# of the text string.
# sigmap (dict, optional): Maps POSIX signals to their respective
# handlers.
# timer (bool, optional): Prints a timer showing the elapsed time.
#
# Returns:
# core.Yaspin: instance of the Yaspin class.
#
# Raises:
# ValueError: If unsupported ``color`` is specified.
# ValueError: If unsupported ``on_color`` is specified.
# ValueError: If unsupported color attribute in ``attrs``
# is specified.
# ValueError: If trying to register handler for SIGKILL signal.
# ValueError: If unsupported ``side`` is specified.
#
# Available text colors:
# red, green, yellow, blue, magenta, cyan, white.
#
# Available text highlights:
# on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan,
# on_white, on_grey.
#
# Available attributes:
# bold, dark, underline, blink, reverse, concealed.
#
# Example::
#
# # Use as a context manager
# with yaspin():
# some_operations()
#
# # Context manager with text
# with yaspin(text="Processing..."):
# some_operations()
#
# # Context manager with custom sequence
# with yaspin(Spinner('-\\|/', 150)):
# some_operations()
#
# # As decorator
# @yaspin(text="Loading...")
# def foo():
# time.sleep(5)
#
# foo()
#
# """
# return Yaspin(*args, **kwargs)
#
# Path: yaspin/signal_handlers.py
# def fancy_handler(signum, frame, spinner): # pylint: disable=unused-argument
# """Signal handler, used to gracefully shut down the ``spinner`` instance
# when specified signal is received by the process running the ``spinner``.
#
# ``signum`` and ``frame`` are mandatory arguments. Check ``signal.signal``
# function for more details.
# """
# spinner.red.fail("✘")
# spinner.stop()
# sys.exit(0)
#
# Path: yaspin/spinners.py
# SPINNERS_DATA = pkgutil.get_data(__name__, "data/spinners.json").decode("utf-8")
# def _hook(dct):
, which may contain function names, class names, or code. Output only the next line. | with kbi_safe_yaspin(text=DEFAULT_TEXT): |
Based on the snippet: <|code_start|>
- More detailed overview:
https://jvns.ca/blog/2016/06/13/should-you-be-scared-of-signals/
- Python signal module examples:
https://pymotw.com/3/signal/index.html
- Linux signals reference:
https://www.computerhope.com/unix/signals.htm#linux
"""
DEFAULT_TEXT = "Press Control+C to send SIGINT (Keyboard Interrupt) signal"
#
# Basic usage
#
def simple_keyboard_interrupt_handling():
with kbi_safe_yaspin(text=DEFAULT_TEXT):
time.sleep(5)
# Set the handler for signal signalnum to the function handler.
# Handler can be a callable Python object taking two arguments,
# or one of the special values signal.SIG_IGN or signal.SIG_DFL.
def fancy_keyboard_interrupt_handler():
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import random
import signal
import sys
import time
from yaspin import kbi_safe_yaspin, yaspin
from yaspin.signal_handlers import fancy_handler
from yaspin.spinners import Spinners
and context (classes, functions, sometimes code) from other files:
# Path: yaspin/api.py
# def kbi_safe_yaspin(*args, **kwargs):
# kwargs["sigmap"] = {signal.SIGINT: default_handler}
# return Yaspin(*args, **kwargs)
#
# def yaspin(*args, **kwargs):
# """Display spinner in stdout.
#
# Can be used as a context manager or as a function decorator.
#
# Arguments:
# spinner (base_spinner.Spinner, optional): Spinner object to use.
# text (str, optional): Text to show along with spinner.
# color (str, optional): Spinner color.
# on_color (str, optional): Color highlight for the spinner.
# attrs (list, optional): Color attributes for the spinner.
# reversal (bool, optional): Reverse spin direction.
# side (str, optional): Place spinner to the right or left end
# of the text string.
# sigmap (dict, optional): Maps POSIX signals to their respective
# handlers.
# timer (bool, optional): Prints a timer showing the elapsed time.
#
# Returns:
# core.Yaspin: instance of the Yaspin class.
#
# Raises:
# ValueError: If unsupported ``color`` is specified.
# ValueError: If unsupported ``on_color`` is specified.
# ValueError: If unsupported color attribute in ``attrs``
# is specified.
# ValueError: If trying to register handler for SIGKILL signal.
# ValueError: If unsupported ``side`` is specified.
#
# Available text colors:
# red, green, yellow, blue, magenta, cyan, white.
#
# Available text highlights:
# on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan,
# on_white, on_grey.
#
# Available attributes:
# bold, dark, underline, blink, reverse, concealed.
#
# Example::
#
# # Use as a context manager
# with yaspin():
# some_operations()
#
# # Context manager with text
# with yaspin(text="Processing..."):
# some_operations()
#
# # Context manager with custom sequence
# with yaspin(Spinner('-\\|/', 150)):
# some_operations()
#
# # As decorator
# @yaspin(text="Loading...")
# def foo():
# time.sleep(5)
#
# foo()
#
# """
# return Yaspin(*args, **kwargs)
#
# Path: yaspin/signal_handlers.py
# def fancy_handler(signum, frame, spinner): # pylint: disable=unused-argument
# """Signal handler, used to gracefully shut down the ``spinner`` instance
# when specified signal is received by the process running the ``spinner``.
#
# ``signum`` and ``frame`` are mandatory arguments. Check ``signal.signal``
# function for more details.
# """
# spinner.red.fail("✘")
# spinner.stop()
# sys.exit(0)
#
# Path: yaspin/spinners.py
# SPINNERS_DATA = pkgutil.get_data(__name__, "data/spinners.json").decode("utf-8")
# def _hook(dct):
. Output only the next line. | with yaspin(sigmap={signal.SIGINT: fancy_handler}, text=DEFAULT_TEXT): |
Based on the snippet: <|code_start|>
- More detailed overview:
https://jvns.ca/blog/2016/06/13/should-you-be-scared-of-signals/
- Python signal module examples:
https://pymotw.com/3/signal/index.html
- Linux signals reference:
https://www.computerhope.com/unix/signals.htm#linux
"""
DEFAULT_TEXT = "Press Control+C to send SIGINT (Keyboard Interrupt) signal"
#
# Basic usage
#
def simple_keyboard_interrupt_handling():
with kbi_safe_yaspin(text=DEFAULT_TEXT):
time.sleep(5)
# Set the handler for signal signalnum to the function handler.
# Handler can be a callable Python object taking two arguments,
# or one of the special values signal.SIG_IGN or signal.SIG_DFL.
def fancy_keyboard_interrupt_handler():
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import random
import signal
import sys
import time
from yaspin import kbi_safe_yaspin, yaspin
from yaspin.signal_handlers import fancy_handler
from yaspin.spinners import Spinners
and context (classes, functions, sometimes code) from other files:
# Path: yaspin/api.py
# def kbi_safe_yaspin(*args, **kwargs):
# kwargs["sigmap"] = {signal.SIGINT: default_handler}
# return Yaspin(*args, **kwargs)
#
# def yaspin(*args, **kwargs):
# """Display spinner in stdout.
#
# Can be used as a context manager or as a function decorator.
#
# Arguments:
# spinner (base_spinner.Spinner, optional): Spinner object to use.
# text (str, optional): Text to show along with spinner.
# color (str, optional): Spinner color.
# on_color (str, optional): Color highlight for the spinner.
# attrs (list, optional): Color attributes for the spinner.
# reversal (bool, optional): Reverse spin direction.
# side (str, optional): Place spinner to the right or left end
# of the text string.
# sigmap (dict, optional): Maps POSIX signals to their respective
# handlers.
# timer (bool, optional): Prints a timer showing the elapsed time.
#
# Returns:
# core.Yaspin: instance of the Yaspin class.
#
# Raises:
# ValueError: If unsupported ``color`` is specified.
# ValueError: If unsupported ``on_color`` is specified.
# ValueError: If unsupported color attribute in ``attrs``
# is specified.
# ValueError: If trying to register handler for SIGKILL signal.
# ValueError: If unsupported ``side`` is specified.
#
# Available text colors:
# red, green, yellow, blue, magenta, cyan, white.
#
# Available text highlights:
# on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan,
# on_white, on_grey.
#
# Available attributes:
# bold, dark, underline, blink, reverse, concealed.
#
# Example::
#
# # Use as a context manager
# with yaspin():
# some_operations()
#
# # Context manager with text
# with yaspin(text="Processing..."):
# some_operations()
#
# # Context manager with custom sequence
# with yaspin(Spinner('-\\|/', 150)):
# some_operations()
#
# # As decorator
# @yaspin(text="Loading...")
# def foo():
# time.sleep(5)
#
# foo()
#
# """
# return Yaspin(*args, **kwargs)
#
# Path: yaspin/signal_handlers.py
# def fancy_handler(signum, frame, spinner): # pylint: disable=unused-argument
# """Signal handler, used to gracefully shut down the ``spinner`` instance
# when specified signal is received by the process running the ``spinner``.
#
# ``signum`` and ``frame`` are mandatory arguments. Check ``signal.signal``
# function for more details.
# """
# spinner.red.fail("✘")
# spinner.stop()
# sys.exit(0)
#
# Path: yaspin/spinners.py
# SPINNERS_DATA = pkgutil.get_data(__name__, "data/spinners.json").decode("utf-8")
# def _hook(dct):
. Output only the next line. | with yaspin(sigmap={signal.SIGINT: fancy_handler}, text=DEFAULT_TEXT): |
Given the code snippet: <|code_start|> sp.write("E.g. $ kill -USR1 {0}".format(os.getpid()))
time.sleep(60)
sp.write("No signal received")
def ignore_signal():
with yaspin(sigmap={signal.SIGINT: signal.SIG_IGN}, text="You can't interrupt me!"):
time.sleep(5)
def default_os_handler_for_sigint():
# Python sets ``signal.default_int_handler`` as a default handler
# for SIGINT. It raises KeyboardInterrupt exception. It is also
# possible to set default OS behavior for SIGINT by setting
# ``signal.SIG_DFL`` as a signal handler.
#
# Generally ``signal.SIG_DFL`` performs the default function for the
# signal.
with yaspin(
sigmap={signal.SIGINT: signal.SIG_DFL},
text="Default OS handler for SIGINT",
):
time.sleep(5)
#
# Real-world examples
#
def unpacker():
swirl = yaspin(
<|code_end|>
, generate the next line using the imports in this file:
import os
import random
import signal
import sys
import time
from yaspin import kbi_safe_yaspin, yaspin
from yaspin.signal_handlers import fancy_handler
from yaspin.spinners import Spinners
and context (functions, classes, or occasionally code) from other files:
# Path: yaspin/api.py
# def kbi_safe_yaspin(*args, **kwargs):
# kwargs["sigmap"] = {signal.SIGINT: default_handler}
# return Yaspin(*args, **kwargs)
#
# def yaspin(*args, **kwargs):
# """Display spinner in stdout.
#
# Can be used as a context manager or as a function decorator.
#
# Arguments:
# spinner (base_spinner.Spinner, optional): Spinner object to use.
# text (str, optional): Text to show along with spinner.
# color (str, optional): Spinner color.
# on_color (str, optional): Color highlight for the spinner.
# attrs (list, optional): Color attributes for the spinner.
# reversal (bool, optional): Reverse spin direction.
# side (str, optional): Place spinner to the right or left end
# of the text string.
# sigmap (dict, optional): Maps POSIX signals to their respective
# handlers.
# timer (bool, optional): Prints a timer showing the elapsed time.
#
# Returns:
# core.Yaspin: instance of the Yaspin class.
#
# Raises:
# ValueError: If unsupported ``color`` is specified.
# ValueError: If unsupported ``on_color`` is specified.
# ValueError: If unsupported color attribute in ``attrs``
# is specified.
# ValueError: If trying to register handler for SIGKILL signal.
# ValueError: If unsupported ``side`` is specified.
#
# Available text colors:
# red, green, yellow, blue, magenta, cyan, white.
#
# Available text highlights:
# on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan,
# on_white, on_grey.
#
# Available attributes:
# bold, dark, underline, blink, reverse, concealed.
#
# Example::
#
# # Use as a context manager
# with yaspin():
# some_operations()
#
# # Context manager with text
# with yaspin(text="Processing..."):
# some_operations()
#
# # Context manager with custom sequence
# with yaspin(Spinner('-\\|/', 150)):
# some_operations()
#
# # As decorator
# @yaspin(text="Loading...")
# def foo():
# time.sleep(5)
#
# foo()
#
# """
# return Yaspin(*args, **kwargs)
#
# Path: yaspin/signal_handlers.py
# def fancy_handler(signum, frame, spinner): # pylint: disable=unused-argument
# """Signal handler, used to gracefully shut down the ``spinner`` instance
# when specified signal is received by the process running the ``spinner``.
#
# ``signum`` and ``frame`` are mandatory arguments. Check ``signal.signal``
# function for more details.
# """
# spinner.red.fail("✘")
# spinner.stop()
# sys.exit(0)
#
# Path: yaspin/spinners.py
# SPINNERS_DATA = pkgutil.get_data(__name__, "data/spinners.json").decode("utf-8")
# def _hook(dct):
. Output only the next line. | spinner=Spinners.simpleDotsScrolling, |
Predict the next line after this snippet: <|code_start|>"""
tests.test_properties
~~~~~~~~~~~~~~~~~~~~~
Test getters and setters.
"""
#
# Yaspin.spinner
#
def test_spinner_getter(frames, interval):
<|code_end|>
using the current file's imports:
import pytest
from yaspin import Spinner, yaspin
from yaspin.base_spinner import default_spinner
from yaspin.helpers import to_unicode
and any relevant context from other files:
# Path: yaspin/api.py
# def yaspin(*args, **kwargs):
# """Display spinner in stdout.
#
# Can be used as a context manager or as a function decorator.
#
# Arguments:
# spinner (base_spinner.Spinner, optional): Spinner object to use.
# text (str, optional): Text to show along with spinner.
# color (str, optional): Spinner color.
# on_color (str, optional): Color highlight for the spinner.
# attrs (list, optional): Color attributes for the spinner.
# reversal (bool, optional): Reverse spin direction.
# side (str, optional): Place spinner to the right or left end
# of the text string.
# sigmap (dict, optional): Maps POSIX signals to their respective
# handlers.
# timer (bool, optional): Prints a timer showing the elapsed time.
#
# Returns:
# core.Yaspin: instance of the Yaspin class.
#
# Raises:
# ValueError: If unsupported ``color`` is specified.
# ValueError: If unsupported ``on_color`` is specified.
# ValueError: If unsupported color attribute in ``attrs``
# is specified.
# ValueError: If trying to register handler for SIGKILL signal.
# ValueError: If unsupported ``side`` is specified.
#
# Available text colors:
# red, green, yellow, blue, magenta, cyan, white.
#
# Available text highlights:
# on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan,
# on_white, on_grey.
#
# Available attributes:
# bold, dark, underline, blink, reverse, concealed.
#
# Example::
#
# # Use as a context manager
# with yaspin():
# some_operations()
#
# # Context manager with text
# with yaspin(text="Processing..."):
# some_operations()
#
# # Context manager with custom sequence
# with yaspin(Spinner('-\\|/', 150)):
# some_operations()
#
# # As decorator
# @yaspin(text="Loading...")
# def foo():
# time.sleep(5)
#
# foo()
#
# """
# return Yaspin(*args, **kwargs)
#
# Path: yaspin/base_spinner.py
# class Spinner:
# frames: str
# interval: int
#
# Path: yaspin/base_spinner.py
# class Spinner:
#
# Path: yaspin/helpers.py
# def to_unicode(text_type, encoding=ENCODING):
# if isinstance(text_type, bytes):
# return text_type.decode(encoding)
# return text_type
. Output only the next line. | sp = yaspin() |
Predict the next line for this snippet: <|code_start|>"""
tests.test_properties
~~~~~~~~~~~~~~~~~~~~~
Test getters and setters.
"""
#
# Yaspin.spinner
#
def test_spinner_getter(frames, interval):
sp = yaspin()
assert sp.spinner == default_spinner
<|code_end|>
with the help of current file imports:
import pytest
from yaspin import Spinner, yaspin
from yaspin.base_spinner import default_spinner
from yaspin.helpers import to_unicode
and context from other files:
# Path: yaspin/api.py
# def yaspin(*args, **kwargs):
# """Display spinner in stdout.
#
# Can be used as a context manager or as a function decorator.
#
# Arguments:
# spinner (base_spinner.Spinner, optional): Spinner object to use.
# text (str, optional): Text to show along with spinner.
# color (str, optional): Spinner color.
# on_color (str, optional): Color highlight for the spinner.
# attrs (list, optional): Color attributes for the spinner.
# reversal (bool, optional): Reverse spin direction.
# side (str, optional): Place spinner to the right or left end
# of the text string.
# sigmap (dict, optional): Maps POSIX signals to their respective
# handlers.
# timer (bool, optional): Prints a timer showing the elapsed time.
#
# Returns:
# core.Yaspin: instance of the Yaspin class.
#
# Raises:
# ValueError: If unsupported ``color`` is specified.
# ValueError: If unsupported ``on_color`` is specified.
# ValueError: If unsupported color attribute in ``attrs``
# is specified.
# ValueError: If trying to register handler for SIGKILL signal.
# ValueError: If unsupported ``side`` is specified.
#
# Available text colors:
# red, green, yellow, blue, magenta, cyan, white.
#
# Available text highlights:
# on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan,
# on_white, on_grey.
#
# Available attributes:
# bold, dark, underline, blink, reverse, concealed.
#
# Example::
#
# # Use as a context manager
# with yaspin():
# some_operations()
#
# # Context manager with text
# with yaspin(text="Processing..."):
# some_operations()
#
# # Context manager with custom sequence
# with yaspin(Spinner('-\\|/', 150)):
# some_operations()
#
# # As decorator
# @yaspin(text="Loading...")
# def foo():
# time.sleep(5)
#
# foo()
#
# """
# return Yaspin(*args, **kwargs)
#
# Path: yaspin/base_spinner.py
# class Spinner:
# frames: str
# interval: int
#
# Path: yaspin/base_spinner.py
# class Spinner:
#
# Path: yaspin/helpers.py
# def to_unicode(text_type, encoding=ENCODING):
# if isinstance(text_type, bytes):
# return text_type.decode(encoding)
# return text_type
, which may contain function names, class names, or code. Output only the next line. | new_spinner = Spinner(frames, interval) |
Using the snippet: <|code_start|>"""
tests.test_properties
~~~~~~~~~~~~~~~~~~~~~
Test getters and setters.
"""
#
# Yaspin.spinner
#
def test_spinner_getter(frames, interval):
sp = yaspin()
<|code_end|>
, determine the next line of code. You have imports:
import pytest
from yaspin import Spinner, yaspin
from yaspin.base_spinner import default_spinner
from yaspin.helpers import to_unicode
and context (class names, function names, or code) available:
# Path: yaspin/api.py
# def yaspin(*args, **kwargs):
# """Display spinner in stdout.
#
# Can be used as a context manager or as a function decorator.
#
# Arguments:
# spinner (base_spinner.Spinner, optional): Spinner object to use.
# text (str, optional): Text to show along with spinner.
# color (str, optional): Spinner color.
# on_color (str, optional): Color highlight for the spinner.
# attrs (list, optional): Color attributes for the spinner.
# reversal (bool, optional): Reverse spin direction.
# side (str, optional): Place spinner to the right or left end
# of the text string.
# sigmap (dict, optional): Maps POSIX signals to their respective
# handlers.
# timer (bool, optional): Prints a timer showing the elapsed time.
#
# Returns:
# core.Yaspin: instance of the Yaspin class.
#
# Raises:
# ValueError: If unsupported ``color`` is specified.
# ValueError: If unsupported ``on_color`` is specified.
# ValueError: If unsupported color attribute in ``attrs``
# is specified.
# ValueError: If trying to register handler for SIGKILL signal.
# ValueError: If unsupported ``side`` is specified.
#
# Available text colors:
# red, green, yellow, blue, magenta, cyan, white.
#
# Available text highlights:
# on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan,
# on_white, on_grey.
#
# Available attributes:
# bold, dark, underline, blink, reverse, concealed.
#
# Example::
#
# # Use as a context manager
# with yaspin():
# some_operations()
#
# # Context manager with text
# with yaspin(text="Processing..."):
# some_operations()
#
# # Context manager with custom sequence
# with yaspin(Spinner('-\\|/', 150)):
# some_operations()
#
# # As decorator
# @yaspin(text="Loading...")
# def foo():
# time.sleep(5)
#
# foo()
#
# """
# return Yaspin(*args, **kwargs)
#
# Path: yaspin/base_spinner.py
# class Spinner:
# frames: str
# interval: int
#
# Path: yaspin/base_spinner.py
# class Spinner:
#
# Path: yaspin/helpers.py
# def to_unicode(text_type, encoding=ENCODING):
# if isinstance(text_type, bytes):
# return text_type.decode(encoding)
# return text_type
. Output only the next line. | assert sp.spinner == default_spinner |
Next line prediction: <|code_start|> new_spinner = Spinner(frames, interval)
sp.spinner = new_spinner
assert sp.spinner == sp._set_spinner(new_spinner)
def test_spinner_setter(frames, interval):
sp = yaspin()
assert sp._spinner == default_spinner
assert isinstance(sp._frames, str)
assert sp._interval == sp._spinner.interval * 0.001
assert isinstance(repr(sp), str)
new_spinner = Spinner(frames, interval)
sp.spinner = new_spinner
assert sp._spinner == sp._set_spinner(new_spinner)
assert not isinstance(sp._frames, bytes)
if isinstance(sp._frames, (list, tuple)):
assert isinstance(sp._frames[0], str)
assert sp._interval == sp._spinner.interval * 0.001
assert isinstance(repr(sp), str)
#
# Yaspin.text
#
def test_text_getter(text):
sp = yaspin(text=text)
<|code_end|>
. Use current file imports:
(import pytest
from yaspin import Spinner, yaspin
from yaspin.base_spinner import default_spinner
from yaspin.helpers import to_unicode)
and context including class names, function names, or small code snippets from other files:
# Path: yaspin/api.py
# def yaspin(*args, **kwargs):
# """Display spinner in stdout.
#
# Can be used as a context manager or as a function decorator.
#
# Arguments:
# spinner (base_spinner.Spinner, optional): Spinner object to use.
# text (str, optional): Text to show along with spinner.
# color (str, optional): Spinner color.
# on_color (str, optional): Color highlight for the spinner.
# attrs (list, optional): Color attributes for the spinner.
# reversal (bool, optional): Reverse spin direction.
# side (str, optional): Place spinner to the right or left end
# of the text string.
# sigmap (dict, optional): Maps POSIX signals to their respective
# handlers.
# timer (bool, optional): Prints a timer showing the elapsed time.
#
# Returns:
# core.Yaspin: instance of the Yaspin class.
#
# Raises:
# ValueError: If unsupported ``color`` is specified.
# ValueError: If unsupported ``on_color`` is specified.
# ValueError: If unsupported color attribute in ``attrs``
# is specified.
# ValueError: If trying to register handler for SIGKILL signal.
# ValueError: If unsupported ``side`` is specified.
#
# Available text colors:
# red, green, yellow, blue, magenta, cyan, white.
#
# Available text highlights:
# on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan,
# on_white, on_grey.
#
# Available attributes:
# bold, dark, underline, blink, reverse, concealed.
#
# Example::
#
# # Use as a context manager
# with yaspin():
# some_operations()
#
# # Context manager with text
# with yaspin(text="Processing..."):
# some_operations()
#
# # Context manager with custom sequence
# with yaspin(Spinner('-\\|/', 150)):
# some_operations()
#
# # As decorator
# @yaspin(text="Loading...")
# def foo():
# time.sleep(5)
#
# foo()
#
# """
# return Yaspin(*args, **kwargs)
#
# Path: yaspin/base_spinner.py
# class Spinner:
# frames: str
# interval: int
#
# Path: yaspin/base_spinner.py
# class Spinner:
#
# Path: yaspin/helpers.py
# def to_unicode(text_type, encoding=ENCODING):
# if isinstance(text_type, bytes):
# return text_type.decode(encoding)
# return text_type
. Output only the next line. | assert sp.text == to_unicode(text) |
Given the following code snippet before the placeholder: <|code_start|>"""
tests.test_timer
~~~~~~~~~~~~~~~~
Test timer feature.
"""
def test_no_timer():
<|code_end|>
, predict the next line using imports from the current file:
import re
import time
import pytest
from yaspin import yaspin
and context including class names, function names, and sometimes code from other files:
# Path: yaspin/api.py
# def yaspin(*args, **kwargs):
# """Display spinner in stdout.
#
# Can be used as a context manager or as a function decorator.
#
# Arguments:
# spinner (base_spinner.Spinner, optional): Spinner object to use.
# text (str, optional): Text to show along with spinner.
# color (str, optional): Spinner color.
# on_color (str, optional): Color highlight for the spinner.
# attrs (list, optional): Color attributes for the spinner.
# reversal (bool, optional): Reverse spin direction.
# side (str, optional): Place spinner to the right or left end
# of the text string.
# sigmap (dict, optional): Maps POSIX signals to their respective
# handlers.
# timer (bool, optional): Prints a timer showing the elapsed time.
#
# Returns:
# core.Yaspin: instance of the Yaspin class.
#
# Raises:
# ValueError: If unsupported ``color`` is specified.
# ValueError: If unsupported ``on_color`` is specified.
# ValueError: If unsupported color attribute in ``attrs``
# is specified.
# ValueError: If trying to register handler for SIGKILL signal.
# ValueError: If unsupported ``side`` is specified.
#
# Available text colors:
# red, green, yellow, blue, magenta, cyan, white.
#
# Available text highlights:
# on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan,
# on_white, on_grey.
#
# Available attributes:
# bold, dark, underline, blink, reverse, concealed.
#
# Example::
#
# # Use as a context manager
# with yaspin():
# some_operations()
#
# # Context manager with text
# with yaspin(text="Processing..."):
# some_operations()
#
# # Context manager with custom sequence
# with yaspin(Spinner('-\\|/', 150)):
# some_operations()
#
# # As decorator
# @yaspin(text="Loading...")
# def foo():
# time.sleep(5)
#
# foo()
#
# """
# return Yaspin(*args, **kwargs)
. Output only the next line. | sp = yaspin(timer=False) |
Continue the code snippet: <|code_start|>"""
tests.test_pipes
~~~~~~~~~~~~~~~~
Checks that scripts with yaspin are safe
for pipes and redirects:
$ python script_that_uses_yaspin.py > script.log
$ python script_that_uses_yaspin.py | grep ERROR
"""
TEST_CODE = """\
import time
from yaspin import yaspin, Spinner
with yaspin(Spinner(%s, %s), '%s') as sp:
time.sleep(0.5)
sp.fail('🙀')
"""
<|code_end|>
. Use current file imports:
import os
import sys
import uuid
import pytest
from yaspin.constants import ENCODING
and context (classes, functions, or code) from other files:
# Path: yaspin/constants.py
# ENCODING = "utf-8"
. Output only the next line. | def to_bytes(str_or_bytes, encoding=ENCODING): |
Predict the next line after this snippet: <|code_start|>"""
tests.test_in_out
~~~~~~~~~~~~~~~~~
Checks that all input data is converted to unicode.
And all output data is converted to builtin str type.
"""
def test_input_converted_to_unicode(text, frames, interval, reversal, side):
sp = Spinner(frames, interval)
<|code_end|>
using the current file's imports:
import re
import sys
import time
import pytest
from yaspin import Spinner, yaspin
and any relevant context from other files:
# Path: yaspin/api.py
# def yaspin(*args, **kwargs):
# """Display spinner in stdout.
#
# Can be used as a context manager or as a function decorator.
#
# Arguments:
# spinner (base_spinner.Spinner, optional): Spinner object to use.
# text (str, optional): Text to show along with spinner.
# color (str, optional): Spinner color.
# on_color (str, optional): Color highlight for the spinner.
# attrs (list, optional): Color attributes for the spinner.
# reversal (bool, optional): Reverse spin direction.
# side (str, optional): Place spinner to the right or left end
# of the text string.
# sigmap (dict, optional): Maps POSIX signals to their respective
# handlers.
# timer (bool, optional): Prints a timer showing the elapsed time.
#
# Returns:
# core.Yaspin: instance of the Yaspin class.
#
# Raises:
# ValueError: If unsupported ``color`` is specified.
# ValueError: If unsupported ``on_color`` is specified.
# ValueError: If unsupported color attribute in ``attrs``
# is specified.
# ValueError: If trying to register handler for SIGKILL signal.
# ValueError: If unsupported ``side`` is specified.
#
# Available text colors:
# red, green, yellow, blue, magenta, cyan, white.
#
# Available text highlights:
# on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan,
# on_white, on_grey.
#
# Available attributes:
# bold, dark, underline, blink, reverse, concealed.
#
# Example::
#
# # Use as a context manager
# with yaspin():
# some_operations()
#
# # Context manager with text
# with yaspin(text="Processing..."):
# some_operations()
#
# # Context manager with custom sequence
# with yaspin(Spinner('-\\|/', 150)):
# some_operations()
#
# # As decorator
# @yaspin(text="Loading...")
# def foo():
# time.sleep(5)
#
# foo()
#
# """
# return Yaspin(*args, **kwargs)
#
# Path: yaspin/base_spinner.py
# class Spinner:
# frames: str
# interval: int
. Output only the next line. | sp = yaspin(sp, text, side=side, reversal=reversal) |
Here is a snippet: <|code_start|>"""
tests.test_in_out
~~~~~~~~~~~~~~~~~
Checks that all input data is converted to unicode.
And all output data is converted to builtin str type.
"""
def test_input_converted_to_unicode(text, frames, interval, reversal, side):
<|code_end|>
. Write the next line using the current file imports:
import re
import sys
import time
import pytest
from yaspin import Spinner, yaspin
and context from other files:
# Path: yaspin/api.py
# def yaspin(*args, **kwargs):
# """Display spinner in stdout.
#
# Can be used as a context manager or as a function decorator.
#
# Arguments:
# spinner (base_spinner.Spinner, optional): Spinner object to use.
# text (str, optional): Text to show along with spinner.
# color (str, optional): Spinner color.
# on_color (str, optional): Color highlight for the spinner.
# attrs (list, optional): Color attributes for the spinner.
# reversal (bool, optional): Reverse spin direction.
# side (str, optional): Place spinner to the right or left end
# of the text string.
# sigmap (dict, optional): Maps POSIX signals to their respective
# handlers.
# timer (bool, optional): Prints a timer showing the elapsed time.
#
# Returns:
# core.Yaspin: instance of the Yaspin class.
#
# Raises:
# ValueError: If unsupported ``color`` is specified.
# ValueError: If unsupported ``on_color`` is specified.
# ValueError: If unsupported color attribute in ``attrs``
# is specified.
# ValueError: If trying to register handler for SIGKILL signal.
# ValueError: If unsupported ``side`` is specified.
#
# Available text colors:
# red, green, yellow, blue, magenta, cyan, white.
#
# Available text highlights:
# on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan,
# on_white, on_grey.
#
# Available attributes:
# bold, dark, underline, blink, reverse, concealed.
#
# Example::
#
# # Use as a context manager
# with yaspin():
# some_operations()
#
# # Context manager with text
# with yaspin(text="Processing..."):
# some_operations()
#
# # Context manager with custom sequence
# with yaspin(Spinner('-\\|/', 150)):
# some_operations()
#
# # As decorator
# @yaspin(text="Loading...")
# def foo():
# time.sleep(5)
#
# foo()
#
# """
# return Yaspin(*args, **kwargs)
#
# Path: yaspin/base_spinner.py
# class Spinner:
# frames: str
# interval: int
, which may include functions, classes, or code. Output only the next line. | sp = Spinner(frames, interval) |
Continue the code snippet: <|code_start|>"""
examples.timer_spinner
~~~~~~~~~~~~~~~~~~~~~~
Show elapsed time at the end of the line.
"""
def main():
<|code_end|>
. Use current file imports:
import time
from yaspin import yaspin
and context (classes, functions, or code) from other files:
# Path: yaspin/api.py
# def yaspin(*args, **kwargs):
# """Display spinner in stdout.
#
# Can be used as a context manager or as a function decorator.
#
# Arguments:
# spinner (base_spinner.Spinner, optional): Spinner object to use.
# text (str, optional): Text to show along with spinner.
# color (str, optional): Spinner color.
# on_color (str, optional): Color highlight for the spinner.
# attrs (list, optional): Color attributes for the spinner.
# reversal (bool, optional): Reverse spin direction.
# side (str, optional): Place spinner to the right or left end
# of the text string.
# sigmap (dict, optional): Maps POSIX signals to their respective
# handlers.
# timer (bool, optional): Prints a timer showing the elapsed time.
#
# Returns:
# core.Yaspin: instance of the Yaspin class.
#
# Raises:
# ValueError: If unsupported ``color`` is specified.
# ValueError: If unsupported ``on_color`` is specified.
# ValueError: If unsupported color attribute in ``attrs``
# is specified.
# ValueError: If trying to register handler for SIGKILL signal.
# ValueError: If unsupported ``side`` is specified.
#
# Available text colors:
# red, green, yellow, blue, magenta, cyan, white.
#
# Available text highlights:
# on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan,
# on_white, on_grey.
#
# Available attributes:
# bold, dark, underline, blink, reverse, concealed.
#
# Example::
#
# # Use as a context manager
# with yaspin():
# some_operations()
#
# # Context manager with text
# with yaspin(text="Processing..."):
# some_operations()
#
# # Context manager with custom sequence
# with yaspin(Spinner('-\\|/', 150)):
# some_operations()
#
# # As decorator
# @yaspin(text="Loading...")
# def foo():
# time.sleep(5)
#
# foo()
#
# """
# return Yaspin(*args, **kwargs)
. Output only the next line. | with yaspin(text="elapsed time", timer=True) as sp: |
Given the code snippet: <|code_start|>Starting from yaspin v1.1.0 handled by ``hidden`` context manager.
Requires python-prompt-tooklit >= 2.0.1
https://github.com/jonathanslenders/python-prompt-toolkit/
.. code:: bash
pip install "prompt_toolkit>=2.0.1"
"""
try:
except ImportError:
print(
"This example requires python-prompt-tooklit >= 2.0.1:\n"
"https://github.com/jonathanslenders/python-prompt-toolkit/\n"
"\nTo install it, run:\n"
'pip install "prompt_toolkit>=2.0.1"'
)
sys.exit(1)
# override print with feature-rich ``print_formatted_text`` from prompt_toolkit
print = print_formatted_text
# build a basic prompt_toolkit style for styling the HTML wrapped text
style = Style.from_dict({"msg": "#4caf50 bold", "sub-msg": "#616161 italic"})
<|code_end|>
, generate the next line using the imports in this file:
import sys
import time
from yaspin import yaspin
from prompt_toolkit import HTML, print_formatted_text
from prompt_toolkit.styles import Style
and context (functions, classes, or occasionally code) from other files:
# Path: yaspin/api.py
# def yaspin(*args, **kwargs):
# """Display spinner in stdout.
#
# Can be used as a context manager or as a function decorator.
#
# Arguments:
# spinner (base_spinner.Spinner, optional): Spinner object to use.
# text (str, optional): Text to show along with spinner.
# color (str, optional): Spinner color.
# on_color (str, optional): Color highlight for the spinner.
# attrs (list, optional): Color attributes for the spinner.
# reversal (bool, optional): Reverse spin direction.
# side (str, optional): Place spinner to the right or left end
# of the text string.
# sigmap (dict, optional): Maps POSIX signals to their respective
# handlers.
# timer (bool, optional): Prints a timer showing the elapsed time.
#
# Returns:
# core.Yaspin: instance of the Yaspin class.
#
# Raises:
# ValueError: If unsupported ``color`` is specified.
# ValueError: If unsupported ``on_color`` is specified.
# ValueError: If unsupported color attribute in ``attrs``
# is specified.
# ValueError: If trying to register handler for SIGKILL signal.
# ValueError: If unsupported ``side`` is specified.
#
# Available text colors:
# red, green, yellow, blue, magenta, cyan, white.
#
# Available text highlights:
# on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan,
# on_white, on_grey.
#
# Available attributes:
# bold, dark, underline, blink, reverse, concealed.
#
# Example::
#
# # Use as a context manager
# with yaspin():
# some_operations()
#
# # Context manager with text
# with yaspin(text="Processing..."):
# some_operations()
#
# # Context manager with custom sequence
# with yaspin(Spinner('-\\|/', 150)):
# some_operations()
#
# # As decorator
# @yaspin(text="Loading...")
# def foo():
# time.sleep(5)
#
# foo()
#
# """
# return Yaspin(*args, **kwargs)
. Output only the next line. | with yaspin(text="Downloading images") as sp: |
Given the following code snippet before the placeholder: <|code_start|>"""
examples.hide_show
~~~~~~~~~~~~~~~~~~
Basic usage of the ``hide`` and ``show`` methods.
Starting from yaspin v1.1.0 handled by ``hidden`` context manager.
"""
def main():
<|code_end|>
, predict the next line using imports from the current file:
import sys
import time
from yaspin import yaspin
and context including class names, function names, and sometimes code from other files:
# Path: yaspin/api.py
# def yaspin(*args, **kwargs):
# """Display spinner in stdout.
#
# Can be used as a context manager or as a function decorator.
#
# Arguments:
# spinner (base_spinner.Spinner, optional): Spinner object to use.
# text (str, optional): Text to show along with spinner.
# color (str, optional): Spinner color.
# on_color (str, optional): Color highlight for the spinner.
# attrs (list, optional): Color attributes for the spinner.
# reversal (bool, optional): Reverse spin direction.
# side (str, optional): Place spinner to the right or left end
# of the text string.
# sigmap (dict, optional): Maps POSIX signals to their respective
# handlers.
# timer (bool, optional): Prints a timer showing the elapsed time.
#
# Returns:
# core.Yaspin: instance of the Yaspin class.
#
# Raises:
# ValueError: If unsupported ``color`` is specified.
# ValueError: If unsupported ``on_color`` is specified.
# ValueError: If unsupported color attribute in ``attrs``
# is specified.
# ValueError: If trying to register handler for SIGKILL signal.
# ValueError: If unsupported ``side`` is specified.
#
# Available text colors:
# red, green, yellow, blue, magenta, cyan, white.
#
# Available text highlights:
# on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan,
# on_white, on_grey.
#
# Available attributes:
# bold, dark, underline, blink, reverse, concealed.
#
# Example::
#
# # Use as a context manager
# with yaspin():
# some_operations()
#
# # Context manager with text
# with yaspin(text="Processing..."):
# some_operations()
#
# # Context manager with custom sequence
# with yaspin(Spinner('-\\|/', 150)):
# some_operations()
#
# # As decorator
# @yaspin(text="Loading...")
# def foo():
# time.sleep(5)
#
# foo()
#
# """
# return Yaspin(*args, **kwargs)
. Output only the next line. | with yaspin(text="Downloading images") as sp: |
Predict the next line for this snippet: <|code_start|> available_values = [k for k, v in COLOR_MAP.items() if v == "attrs"]
for attr in attrs:
if attr not in available_values:
raise ValueError(
"'{0}': unsupported attribute value. "
"Use one of the: {1}".format(attr, ", ".join(available_values))
)
return set(attrs)
@staticmethod
def _set_spinner(spinner):
if hasattr(spinner, "frames") and hasattr(spinner, "interval"):
if not spinner.frames or not spinner.interval:
sp = default_spinner
else:
sp = spinner
else:
sp = default_spinner
return sp
@staticmethod
def _set_side(side: str) -> str:
if side not in ("left", "right"):
raise ValueError(
"'{0}': unsupported side value. " "Use either 'left' or 'right'."
)
return side
@staticmethod
<|code_end|>
with the help of current file imports:
import contextlib
import datetime
import functools
import itertools
import signal
import sys
import threading
import time
from typing import List, Set, Union
from termcolor import colored
from .base_spinner import Spinner, default_spinner
from .constants import COLOR_ATTRS, COLOR_MAP, SPINNER_ATTRS
from .helpers import to_unicode
from .spinners import Spinners # pylint: disable=import-outside-toplevel
and context from other files:
# Path: yaspin/base_spinner.py
# class Spinner:
#
# Path: yaspin/constants.py
# COLOR_ATTRS = COLOR_MAP.keys()
#
# COLOR_MAP = {
# # name: type
# "blink": "attrs",
# "bold": "attrs",
# "concealed": "attrs",
# "dark": "attrs",
# "reverse": "attrs",
# "underline": "attrs",
# "blue": "color",
# "cyan": "color",
# "green": "color",
# "magenta": "color",
# "red": "color",
# "white": "color",
# "yellow": "color",
# "on_blue": "on_color",
# "on_cyan": "on_color",
# "on_green": "on_color",
# "on_grey": "on_color",
# "on_magenta": "on_color",
# "on_red": "on_color",
# "on_white": "on_color",
# "on_yellow": "on_color",
# }
#
# SPINNER_ATTRS = [
# "aesthetic",
# "arc",
# "arrow",
# "arrow2",
# "arrow3",
# "balloon",
# "balloon2",
# "betaWave",
# "bluePulse",
# "bounce",
# "bouncingBall",
# "bouncingBar",
# "boxBounce",
# "boxBounce2",
# "christmas",
# "circle",
# "circleHalves",
# "circleQuarters",
# "clock",
# "dots",
# "dots10",
# "dots11",
# "dots12",
# "dots2",
# "dots3",
# "dots4",
# "dots5",
# "dots6",
# "dots7",
# "dots8",
# "dots8Bit",
# "dots9",
# "dqpb",
# "earth",
# "fingerDance",
# "fistBump",
# "flip",
# "grenade",
# "growHorizontal",
# "growVertical",
# "hamburger",
# "hearts",
# "layer",
# "line",
# "line2",
# "material",
# "mindblown",
# "monkey",
# "moon",
# "noise",
# "orangeBluePulse",
# "orangePulse",
# "pipe",
# "point",
# "pong",
# "runner",
# "shark",
# "simpleDots",
# "simpleDotsScrolling",
# "smiley",
# "soccerHeader",
# "speaker",
# "squareCorners",
# "squish",
# "star",
# "star2",
# "timeTravel",
# "toggle",
# "toggle10",
# "toggle11",
# "toggle12",
# "toggle13",
# "toggle2",
# "toggle3",
# "toggle4",
# "toggle5",
# "toggle6",
# "toggle7",
# "toggle8",
# "toggle9",
# "triangle",
# "weather",
# ]
#
# Path: yaspin/helpers.py
# def to_unicode(text_type, encoding=ENCODING):
# if isinstance(text_type, bytes):
# return text_type.decode(encoding)
# return text_type
, which may contain function names, class names, or code. Output only the next line. | def _set_frames(spinner: Spinner, reversal: bool) -> Union[str, List]: |
Given snippet: <|code_start|> value, ", ".join(available_values)
)
)
return value
@staticmethod
def _set_on_color(value: str) -> str:
available_values = [k for k, v in COLOR_MAP.items() if v == "on_color"]
if value not in available_values:
raise ValueError(
"'{0}': unsupported on_color value. "
"Use one of the: {1}".format(value, ", ".join(available_values))
)
return value
@staticmethod
def _set_attrs(attrs: List[str]) -> Set[str]:
available_values = [k for k, v in COLOR_MAP.items() if v == "attrs"]
for attr in attrs:
if attr not in available_values:
raise ValueError(
"'{0}': unsupported attribute value. "
"Use one of the: {1}".format(attr, ", ".join(available_values))
)
return set(attrs)
@staticmethod
def _set_spinner(spinner):
if hasattr(spinner, "frames") and hasattr(spinner, "interval"):
if not spinner.frames or not spinner.interval:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import contextlib
import datetime
import functools
import itertools
import signal
import sys
import threading
import time
from typing import List, Set, Union
from termcolor import colored
from .base_spinner import Spinner, default_spinner
from .constants import COLOR_ATTRS, COLOR_MAP, SPINNER_ATTRS
from .helpers import to_unicode
from .spinners import Spinners # pylint: disable=import-outside-toplevel
and context:
# Path: yaspin/base_spinner.py
# class Spinner:
#
# Path: yaspin/constants.py
# COLOR_ATTRS = COLOR_MAP.keys()
#
# COLOR_MAP = {
# # name: type
# "blink": "attrs",
# "bold": "attrs",
# "concealed": "attrs",
# "dark": "attrs",
# "reverse": "attrs",
# "underline": "attrs",
# "blue": "color",
# "cyan": "color",
# "green": "color",
# "magenta": "color",
# "red": "color",
# "white": "color",
# "yellow": "color",
# "on_blue": "on_color",
# "on_cyan": "on_color",
# "on_green": "on_color",
# "on_grey": "on_color",
# "on_magenta": "on_color",
# "on_red": "on_color",
# "on_white": "on_color",
# "on_yellow": "on_color",
# }
#
# SPINNER_ATTRS = [
# "aesthetic",
# "arc",
# "arrow",
# "arrow2",
# "arrow3",
# "balloon",
# "balloon2",
# "betaWave",
# "bluePulse",
# "bounce",
# "bouncingBall",
# "bouncingBar",
# "boxBounce",
# "boxBounce2",
# "christmas",
# "circle",
# "circleHalves",
# "circleQuarters",
# "clock",
# "dots",
# "dots10",
# "dots11",
# "dots12",
# "dots2",
# "dots3",
# "dots4",
# "dots5",
# "dots6",
# "dots7",
# "dots8",
# "dots8Bit",
# "dots9",
# "dqpb",
# "earth",
# "fingerDance",
# "fistBump",
# "flip",
# "grenade",
# "growHorizontal",
# "growVertical",
# "hamburger",
# "hearts",
# "layer",
# "line",
# "line2",
# "material",
# "mindblown",
# "monkey",
# "moon",
# "noise",
# "orangeBluePulse",
# "orangePulse",
# "pipe",
# "point",
# "pong",
# "runner",
# "shark",
# "simpleDots",
# "simpleDotsScrolling",
# "smiley",
# "soccerHeader",
# "speaker",
# "squareCorners",
# "squish",
# "star",
# "star2",
# "timeTravel",
# "toggle",
# "toggle10",
# "toggle11",
# "toggle12",
# "toggle13",
# "toggle2",
# "toggle3",
# "toggle4",
# "toggle5",
# "toggle6",
# "toggle7",
# "toggle8",
# "toggle9",
# "triangle",
# "weather",
# ]
#
# Path: yaspin/helpers.py
# def to_unicode(text_type, encoding=ENCODING):
# if isinstance(text_type, bytes):
# return text_type.decode(encoding)
# return text_type
which might include code, classes, or functions. Output only the next line. | sp = default_spinner |
Here is a snippet: <|code_start|> # Dunders
#
def __repr__(self):
return "<Yaspin frames={0!s}>".format(self._frames)
def __enter__(self):
self.start()
return self
def __exit__(self, exc_type, exc_val, traceback):
# Avoid stop() execution for the 2nd time
if self._spin_thread.is_alive():
self.stop()
return False # nothing is handled
def __call__(self, fn):
@functools.wraps(fn)
def inner(*args, **kwargs):
with self:
return fn(*args, **kwargs)
return inner
def __getattr__(self, name):
# CLI spinners
if name in SPINNER_ATTRS:
sp = getattr(Spinners, name)
self.spinner = sp
# Color Attributes: "color", "on_color", "attrs"
<|code_end|>
. Write the next line using the current file imports:
import contextlib
import datetime
import functools
import itertools
import signal
import sys
import threading
import time
from typing import List, Set, Union
from termcolor import colored
from .base_spinner import Spinner, default_spinner
from .constants import COLOR_ATTRS, COLOR_MAP, SPINNER_ATTRS
from .helpers import to_unicode
from .spinners import Spinners # pylint: disable=import-outside-toplevel
and context from other files:
# Path: yaspin/base_spinner.py
# class Spinner:
#
# Path: yaspin/constants.py
# COLOR_ATTRS = COLOR_MAP.keys()
#
# COLOR_MAP = {
# # name: type
# "blink": "attrs",
# "bold": "attrs",
# "concealed": "attrs",
# "dark": "attrs",
# "reverse": "attrs",
# "underline": "attrs",
# "blue": "color",
# "cyan": "color",
# "green": "color",
# "magenta": "color",
# "red": "color",
# "white": "color",
# "yellow": "color",
# "on_blue": "on_color",
# "on_cyan": "on_color",
# "on_green": "on_color",
# "on_grey": "on_color",
# "on_magenta": "on_color",
# "on_red": "on_color",
# "on_white": "on_color",
# "on_yellow": "on_color",
# }
#
# SPINNER_ATTRS = [
# "aesthetic",
# "arc",
# "arrow",
# "arrow2",
# "arrow3",
# "balloon",
# "balloon2",
# "betaWave",
# "bluePulse",
# "bounce",
# "bouncingBall",
# "bouncingBar",
# "boxBounce",
# "boxBounce2",
# "christmas",
# "circle",
# "circleHalves",
# "circleQuarters",
# "clock",
# "dots",
# "dots10",
# "dots11",
# "dots12",
# "dots2",
# "dots3",
# "dots4",
# "dots5",
# "dots6",
# "dots7",
# "dots8",
# "dots8Bit",
# "dots9",
# "dqpb",
# "earth",
# "fingerDance",
# "fistBump",
# "flip",
# "grenade",
# "growHorizontal",
# "growVertical",
# "hamburger",
# "hearts",
# "layer",
# "line",
# "line2",
# "material",
# "mindblown",
# "monkey",
# "moon",
# "noise",
# "orangeBluePulse",
# "orangePulse",
# "pipe",
# "point",
# "pong",
# "runner",
# "shark",
# "simpleDots",
# "simpleDotsScrolling",
# "smiley",
# "soccerHeader",
# "speaker",
# "squareCorners",
# "squish",
# "star",
# "star2",
# "timeTravel",
# "toggle",
# "toggle10",
# "toggle11",
# "toggle12",
# "toggle13",
# "toggle2",
# "toggle3",
# "toggle4",
# "toggle5",
# "toggle6",
# "toggle7",
# "toggle8",
# "toggle9",
# "triangle",
# "weather",
# ]
#
# Path: yaspin/helpers.py
# def to_unicode(text_type, encoding=ENCODING):
# if isinstance(text_type, bytes):
# return text_type.decode(encoding)
# return text_type
, which may include functions, classes, or code. Output only the next line. | elif name in COLOR_ATTRS: |
Given the following code snippet before the placeholder: <|code_start|> #
def __repr__(self):
return "<Yaspin frames={0!s}>".format(self._frames)
def __enter__(self):
self.start()
return self
def __exit__(self, exc_type, exc_val, traceback):
# Avoid stop() execution for the 2nd time
if self._spin_thread.is_alive():
self.stop()
return False # nothing is handled
def __call__(self, fn):
@functools.wraps(fn)
def inner(*args, **kwargs):
with self:
return fn(*args, **kwargs)
return inner
def __getattr__(self, name):
# CLI spinners
if name in SPINNER_ATTRS:
sp = getattr(Spinners, name)
self.spinner = sp
# Color Attributes: "color", "on_color", "attrs"
elif name in COLOR_ATTRS:
<|code_end|>
, predict the next line using imports from the current file:
import contextlib
import datetime
import functools
import itertools
import signal
import sys
import threading
import time
from typing import List, Set, Union
from termcolor import colored
from .base_spinner import Spinner, default_spinner
from .constants import COLOR_ATTRS, COLOR_MAP, SPINNER_ATTRS
from .helpers import to_unicode
from .spinners import Spinners # pylint: disable=import-outside-toplevel
and context including class names, function names, and sometimes code from other files:
# Path: yaspin/base_spinner.py
# class Spinner:
#
# Path: yaspin/constants.py
# COLOR_ATTRS = COLOR_MAP.keys()
#
# COLOR_MAP = {
# # name: type
# "blink": "attrs",
# "bold": "attrs",
# "concealed": "attrs",
# "dark": "attrs",
# "reverse": "attrs",
# "underline": "attrs",
# "blue": "color",
# "cyan": "color",
# "green": "color",
# "magenta": "color",
# "red": "color",
# "white": "color",
# "yellow": "color",
# "on_blue": "on_color",
# "on_cyan": "on_color",
# "on_green": "on_color",
# "on_grey": "on_color",
# "on_magenta": "on_color",
# "on_red": "on_color",
# "on_white": "on_color",
# "on_yellow": "on_color",
# }
#
# SPINNER_ATTRS = [
# "aesthetic",
# "arc",
# "arrow",
# "arrow2",
# "arrow3",
# "balloon",
# "balloon2",
# "betaWave",
# "bluePulse",
# "bounce",
# "bouncingBall",
# "bouncingBar",
# "boxBounce",
# "boxBounce2",
# "christmas",
# "circle",
# "circleHalves",
# "circleQuarters",
# "clock",
# "dots",
# "dots10",
# "dots11",
# "dots12",
# "dots2",
# "dots3",
# "dots4",
# "dots5",
# "dots6",
# "dots7",
# "dots8",
# "dots8Bit",
# "dots9",
# "dqpb",
# "earth",
# "fingerDance",
# "fistBump",
# "flip",
# "grenade",
# "growHorizontal",
# "growVertical",
# "hamburger",
# "hearts",
# "layer",
# "line",
# "line2",
# "material",
# "mindblown",
# "monkey",
# "moon",
# "noise",
# "orangeBluePulse",
# "orangePulse",
# "pipe",
# "point",
# "pong",
# "runner",
# "shark",
# "simpleDots",
# "simpleDotsScrolling",
# "smiley",
# "soccerHeader",
# "speaker",
# "squareCorners",
# "squish",
# "star",
# "star2",
# "timeTravel",
# "toggle",
# "toggle10",
# "toggle11",
# "toggle12",
# "toggle13",
# "toggle2",
# "toggle3",
# "toggle4",
# "toggle5",
# "toggle6",
# "toggle7",
# "toggle8",
# "toggle9",
# "triangle",
# "weather",
# ]
#
# Path: yaspin/helpers.py
# def to_unicode(text_type, encoding=ENCODING):
# if isinstance(text_type, bytes):
# return text_type.decode(encoding)
# return text_type
. Output only the next line. | attr_type = COLOR_MAP[name] |
Continue the code snippet: <|code_start|> # Maps signals to their default handlers in order to reset
# custom handlers set by ``sigmap`` at the cleanup phase.
self._dfl_sigmap = {} # Dict[Signal, SigHandler]
#
# Dunders
#
def __repr__(self):
return "<Yaspin frames={0!s}>".format(self._frames)
def __enter__(self):
self.start()
return self
def __exit__(self, exc_type, exc_val, traceback):
# Avoid stop() execution for the 2nd time
if self._spin_thread.is_alive():
self.stop()
return False # nothing is handled
def __call__(self, fn):
@functools.wraps(fn)
def inner(*args, **kwargs):
with self:
return fn(*args, **kwargs)
return inner
def __getattr__(self, name):
# CLI spinners
<|code_end|>
. Use current file imports:
import contextlib
import datetime
import functools
import itertools
import signal
import sys
import threading
import time
from typing import List, Set, Union
from termcolor import colored
from .base_spinner import Spinner, default_spinner
from .constants import COLOR_ATTRS, COLOR_MAP, SPINNER_ATTRS
from .helpers import to_unicode
from .spinners import Spinners # pylint: disable=import-outside-toplevel
and context (classes, functions, or code) from other files:
# Path: yaspin/base_spinner.py
# class Spinner:
#
# Path: yaspin/constants.py
# COLOR_ATTRS = COLOR_MAP.keys()
#
# COLOR_MAP = {
# # name: type
# "blink": "attrs",
# "bold": "attrs",
# "concealed": "attrs",
# "dark": "attrs",
# "reverse": "attrs",
# "underline": "attrs",
# "blue": "color",
# "cyan": "color",
# "green": "color",
# "magenta": "color",
# "red": "color",
# "white": "color",
# "yellow": "color",
# "on_blue": "on_color",
# "on_cyan": "on_color",
# "on_green": "on_color",
# "on_grey": "on_color",
# "on_magenta": "on_color",
# "on_red": "on_color",
# "on_white": "on_color",
# "on_yellow": "on_color",
# }
#
# SPINNER_ATTRS = [
# "aesthetic",
# "arc",
# "arrow",
# "arrow2",
# "arrow3",
# "balloon",
# "balloon2",
# "betaWave",
# "bluePulse",
# "bounce",
# "bouncingBall",
# "bouncingBar",
# "boxBounce",
# "boxBounce2",
# "christmas",
# "circle",
# "circleHalves",
# "circleQuarters",
# "clock",
# "dots",
# "dots10",
# "dots11",
# "dots12",
# "dots2",
# "dots3",
# "dots4",
# "dots5",
# "dots6",
# "dots7",
# "dots8",
# "dots8Bit",
# "dots9",
# "dqpb",
# "earth",
# "fingerDance",
# "fistBump",
# "flip",
# "grenade",
# "growHorizontal",
# "growVertical",
# "hamburger",
# "hearts",
# "layer",
# "line",
# "line2",
# "material",
# "mindblown",
# "monkey",
# "moon",
# "noise",
# "orangeBluePulse",
# "orangePulse",
# "pipe",
# "point",
# "pong",
# "runner",
# "shark",
# "simpleDots",
# "simpleDotsScrolling",
# "smiley",
# "soccerHeader",
# "speaker",
# "squareCorners",
# "squish",
# "star",
# "star2",
# "timeTravel",
# "toggle",
# "toggle10",
# "toggle11",
# "toggle12",
# "toggle13",
# "toggle2",
# "toggle3",
# "toggle4",
# "toggle5",
# "toggle6",
# "toggle7",
# "toggle8",
# "toggle9",
# "triangle",
# "weather",
# ]
#
# Path: yaspin/helpers.py
# def to_unicode(text_type, encoding=ENCODING):
# if isinstance(text_type, bytes):
# return text_type.decode(encoding)
# return text_type
. Output only the next line. | if name in SPINNER_ATTRS: |
Based on the snippet: <|code_start|>
try:
yield
finally:
self._hidden_level -= 1
if self._hidden_level == 0:
self.show()
def show(self):
"""Show the hidden spinner."""
thr_is_alive = self._spin_thread and self._spin_thread.is_alive()
if thr_is_alive and self._hide_spin.is_set():
with self._stdout_lock:
# clear the hidden spinner flag
self._hide_spin.clear()
# clear the current line so the spinner is not appended to it
sys.stdout.write("\r")
self._clear_line()
def write(self, text):
"""Write text in the terminal without breaking the spinner."""
# similar to tqdm.write()
# https://pypi.python.org/pypi/tqdm#writing-messages
with self._stdout_lock:
sys.stdout.write("\r")
self._clear_line()
if isinstance(text, (str, bytes)):
<|code_end|>
, predict the immediate next line with the help of imports:
import contextlib
import datetime
import functools
import itertools
import signal
import sys
import threading
import time
from typing import List, Set, Union
from termcolor import colored
from .base_spinner import Spinner, default_spinner
from .constants import COLOR_ATTRS, COLOR_MAP, SPINNER_ATTRS
from .helpers import to_unicode
from .spinners import Spinners # pylint: disable=import-outside-toplevel
and context (classes, functions, sometimes code) from other files:
# Path: yaspin/base_spinner.py
# class Spinner:
#
# Path: yaspin/constants.py
# COLOR_ATTRS = COLOR_MAP.keys()
#
# COLOR_MAP = {
# # name: type
# "blink": "attrs",
# "bold": "attrs",
# "concealed": "attrs",
# "dark": "attrs",
# "reverse": "attrs",
# "underline": "attrs",
# "blue": "color",
# "cyan": "color",
# "green": "color",
# "magenta": "color",
# "red": "color",
# "white": "color",
# "yellow": "color",
# "on_blue": "on_color",
# "on_cyan": "on_color",
# "on_green": "on_color",
# "on_grey": "on_color",
# "on_magenta": "on_color",
# "on_red": "on_color",
# "on_white": "on_color",
# "on_yellow": "on_color",
# }
#
# SPINNER_ATTRS = [
# "aesthetic",
# "arc",
# "arrow",
# "arrow2",
# "arrow3",
# "balloon",
# "balloon2",
# "betaWave",
# "bluePulse",
# "bounce",
# "bouncingBall",
# "bouncingBar",
# "boxBounce",
# "boxBounce2",
# "christmas",
# "circle",
# "circleHalves",
# "circleQuarters",
# "clock",
# "dots",
# "dots10",
# "dots11",
# "dots12",
# "dots2",
# "dots3",
# "dots4",
# "dots5",
# "dots6",
# "dots7",
# "dots8",
# "dots8Bit",
# "dots9",
# "dqpb",
# "earth",
# "fingerDance",
# "fistBump",
# "flip",
# "grenade",
# "growHorizontal",
# "growVertical",
# "hamburger",
# "hearts",
# "layer",
# "line",
# "line2",
# "material",
# "mindblown",
# "monkey",
# "moon",
# "noise",
# "orangeBluePulse",
# "orangePulse",
# "pipe",
# "point",
# "pong",
# "runner",
# "shark",
# "simpleDots",
# "simpleDotsScrolling",
# "smiley",
# "soccerHeader",
# "speaker",
# "squareCorners",
# "squish",
# "star",
# "star2",
# "timeTravel",
# "toggle",
# "toggle10",
# "toggle11",
# "toggle12",
# "toggle13",
# "toggle2",
# "toggle3",
# "toggle4",
# "toggle5",
# "toggle6",
# "toggle7",
# "toggle8",
# "toggle9",
# "triangle",
# "weather",
# ]
#
# Path: yaspin/helpers.py
# def to_unicode(text_type, encoding=ENCODING):
# if isinstance(text_type, bytes):
# return text_type.decode(encoding)
# return text_type
. Output only the next line. | _text = to_unicode(text) |
Given snippet: <|code_start|>"""
tests.test_finalizers
~~~~~~~~~~~~~~~~~~~~~
"""
def test_freeze(final_text):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from yaspin import yaspin
and context:
# Path: yaspin/api.py
# def yaspin(*args, **kwargs):
# """Display spinner in stdout.
#
# Can be used as a context manager or as a function decorator.
#
# Arguments:
# spinner (base_spinner.Spinner, optional): Spinner object to use.
# text (str, optional): Text to show along with spinner.
# color (str, optional): Spinner color.
# on_color (str, optional): Color highlight for the spinner.
# attrs (list, optional): Color attributes for the spinner.
# reversal (bool, optional): Reverse spin direction.
# side (str, optional): Place spinner to the right or left end
# of the text string.
# sigmap (dict, optional): Maps POSIX signals to their respective
# handlers.
# timer (bool, optional): Prints a timer showing the elapsed time.
#
# Returns:
# core.Yaspin: instance of the Yaspin class.
#
# Raises:
# ValueError: If unsupported ``color`` is specified.
# ValueError: If unsupported ``on_color`` is specified.
# ValueError: If unsupported color attribute in ``attrs``
# is specified.
# ValueError: If trying to register handler for SIGKILL signal.
# ValueError: If unsupported ``side`` is specified.
#
# Available text colors:
# red, green, yellow, blue, magenta, cyan, white.
#
# Available text highlights:
# on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan,
# on_white, on_grey.
#
# Available attributes:
# bold, dark, underline, blink, reverse, concealed.
#
# Example::
#
# # Use as a context manager
# with yaspin():
# some_operations()
#
# # Context manager with text
# with yaspin(text="Processing..."):
# some_operations()
#
# # Context manager with custom sequence
# with yaspin(Spinner('-\\|/', 150)):
# some_operations()
#
# # As decorator
# @yaspin(text="Loading...")
# def foo():
# time.sleep(5)
#
# foo()
#
# """
# return Yaspin(*args, **kwargs)
which might include code, classes, or functions. Output only the next line. | sp = yaspin() |
Based on the snippet: <|code_start|>"""
tests.test_attrs
~~~~~~~~~~~~~~~~
Test Yaspin attributes magic hidden in __getattr__.
"""
@pytest.mark.parametrize("attr_name", SPINNER_ATTRS)
def test_set_spinner_by_name(attr_name):
<|code_end|>
, predict the immediate next line with the help of imports:
import pytest
from yaspin import yaspin
from yaspin.constants import COLOR_MAP, SPINNER_ATTRS
from yaspin.spinners import Spinners
and context (classes, functions, sometimes code) from other files:
# Path: yaspin/api.py
# def yaspin(*args, **kwargs):
# """Display spinner in stdout.
#
# Can be used as a context manager or as a function decorator.
#
# Arguments:
# spinner (base_spinner.Spinner, optional): Spinner object to use.
# text (str, optional): Text to show along with spinner.
# color (str, optional): Spinner color.
# on_color (str, optional): Color highlight for the spinner.
# attrs (list, optional): Color attributes for the spinner.
# reversal (bool, optional): Reverse spin direction.
# side (str, optional): Place spinner to the right or left end
# of the text string.
# sigmap (dict, optional): Maps POSIX signals to their respective
# handlers.
# timer (bool, optional): Prints a timer showing the elapsed time.
#
# Returns:
# core.Yaspin: instance of the Yaspin class.
#
# Raises:
# ValueError: If unsupported ``color`` is specified.
# ValueError: If unsupported ``on_color`` is specified.
# ValueError: If unsupported color attribute in ``attrs``
# is specified.
# ValueError: If trying to register handler for SIGKILL signal.
# ValueError: If unsupported ``side`` is specified.
#
# Available text colors:
# red, green, yellow, blue, magenta, cyan, white.
#
# Available text highlights:
# on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan,
# on_white, on_grey.
#
# Available attributes:
# bold, dark, underline, blink, reverse, concealed.
#
# Example::
#
# # Use as a context manager
# with yaspin():
# some_operations()
#
# # Context manager with text
# with yaspin(text="Processing..."):
# some_operations()
#
# # Context manager with custom sequence
# with yaspin(Spinner('-\\|/', 150)):
# some_operations()
#
# # As decorator
# @yaspin(text="Loading...")
# def foo():
# time.sleep(5)
#
# foo()
#
# """
# return Yaspin(*args, **kwargs)
#
# Path: yaspin/constants.py
# COLOR_MAP = {
# # name: type
# "blink": "attrs",
# "bold": "attrs",
# "concealed": "attrs",
# "dark": "attrs",
# "reverse": "attrs",
# "underline": "attrs",
# "blue": "color",
# "cyan": "color",
# "green": "color",
# "magenta": "color",
# "red": "color",
# "white": "color",
# "yellow": "color",
# "on_blue": "on_color",
# "on_cyan": "on_color",
# "on_green": "on_color",
# "on_grey": "on_color",
# "on_magenta": "on_color",
# "on_red": "on_color",
# "on_white": "on_color",
# "on_yellow": "on_color",
# }
#
# SPINNER_ATTRS = [
# "aesthetic",
# "arc",
# "arrow",
# "arrow2",
# "arrow3",
# "balloon",
# "balloon2",
# "betaWave",
# "bluePulse",
# "bounce",
# "bouncingBall",
# "bouncingBar",
# "boxBounce",
# "boxBounce2",
# "christmas",
# "circle",
# "circleHalves",
# "circleQuarters",
# "clock",
# "dots",
# "dots10",
# "dots11",
# "dots12",
# "dots2",
# "dots3",
# "dots4",
# "dots5",
# "dots6",
# "dots7",
# "dots8",
# "dots8Bit",
# "dots9",
# "dqpb",
# "earth",
# "fingerDance",
# "fistBump",
# "flip",
# "grenade",
# "growHorizontal",
# "growVertical",
# "hamburger",
# "hearts",
# "layer",
# "line",
# "line2",
# "material",
# "mindblown",
# "monkey",
# "moon",
# "noise",
# "orangeBluePulse",
# "orangePulse",
# "pipe",
# "point",
# "pong",
# "runner",
# "shark",
# "simpleDots",
# "simpleDotsScrolling",
# "smiley",
# "soccerHeader",
# "speaker",
# "squareCorners",
# "squish",
# "star",
# "star2",
# "timeTravel",
# "toggle",
# "toggle10",
# "toggle11",
# "toggle12",
# "toggle13",
# "toggle2",
# "toggle3",
# "toggle4",
# "toggle5",
# "toggle6",
# "toggle7",
# "toggle8",
# "toggle9",
# "triangle",
# "weather",
# ]
#
# Path: yaspin/spinners.py
# SPINNERS_DATA = pkgutil.get_data(__name__, "data/spinners.json").decode("utf-8")
# def _hook(dct):
. Output only the next line. | sp = getattr(yaspin(), attr_name) |
Continue the code snippet: <|code_start|> with pytest.raises(AttributeError):
getattr(sp, color)
else:
getattr(sp, color)
assert sp.color == expected
assert sp._color_func.keywords["color"] == expected # pylint: disable=no-member
# Values for ``on_color`` argument
def test_on_color(on_color_test_cases):
on_color, expected = on_color_test_cases
# ``None`` and ``""`` are skipped
if not on_color:
pytest.skip("{0} - unsupported case".format(repr(on_color)))
sp = yaspin()
if isinstance(expected, Exception):
with pytest.raises(AttributeError):
getattr(sp, on_color)
else:
getattr(sp, on_color)
assert sp.on_color == expected
assert (
sp._color_func.keywords["on_color"] == expected
) # pylint: disable=no-member
# Values for ``attrs`` argument
@pytest.mark.parametrize(
<|code_end|>
. Use current file imports:
import pytest
from yaspin import yaspin
from yaspin.constants import COLOR_MAP, SPINNER_ATTRS
from yaspin.spinners import Spinners
and context (classes, functions, or code) from other files:
# Path: yaspin/api.py
# def yaspin(*args, **kwargs):
# """Display spinner in stdout.
#
# Can be used as a context manager or as a function decorator.
#
# Arguments:
# spinner (base_spinner.Spinner, optional): Spinner object to use.
# text (str, optional): Text to show along with spinner.
# color (str, optional): Spinner color.
# on_color (str, optional): Color highlight for the spinner.
# attrs (list, optional): Color attributes for the spinner.
# reversal (bool, optional): Reverse spin direction.
# side (str, optional): Place spinner to the right or left end
# of the text string.
# sigmap (dict, optional): Maps POSIX signals to their respective
# handlers.
# timer (bool, optional): Prints a timer showing the elapsed time.
#
# Returns:
# core.Yaspin: instance of the Yaspin class.
#
# Raises:
# ValueError: If unsupported ``color`` is specified.
# ValueError: If unsupported ``on_color`` is specified.
# ValueError: If unsupported color attribute in ``attrs``
# is specified.
# ValueError: If trying to register handler for SIGKILL signal.
# ValueError: If unsupported ``side`` is specified.
#
# Available text colors:
# red, green, yellow, blue, magenta, cyan, white.
#
# Available text highlights:
# on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan,
# on_white, on_grey.
#
# Available attributes:
# bold, dark, underline, blink, reverse, concealed.
#
# Example::
#
# # Use as a context manager
# with yaspin():
# some_operations()
#
# # Context manager with text
# with yaspin(text="Processing..."):
# some_operations()
#
# # Context manager with custom sequence
# with yaspin(Spinner('-\\|/', 150)):
# some_operations()
#
# # As decorator
# @yaspin(text="Loading...")
# def foo():
# time.sleep(5)
#
# foo()
#
# """
# return Yaspin(*args, **kwargs)
#
# Path: yaspin/constants.py
# COLOR_MAP = {
# # name: type
# "blink": "attrs",
# "bold": "attrs",
# "concealed": "attrs",
# "dark": "attrs",
# "reverse": "attrs",
# "underline": "attrs",
# "blue": "color",
# "cyan": "color",
# "green": "color",
# "magenta": "color",
# "red": "color",
# "white": "color",
# "yellow": "color",
# "on_blue": "on_color",
# "on_cyan": "on_color",
# "on_green": "on_color",
# "on_grey": "on_color",
# "on_magenta": "on_color",
# "on_red": "on_color",
# "on_white": "on_color",
# "on_yellow": "on_color",
# }
#
# SPINNER_ATTRS = [
# "aesthetic",
# "arc",
# "arrow",
# "arrow2",
# "arrow3",
# "balloon",
# "balloon2",
# "betaWave",
# "bluePulse",
# "bounce",
# "bouncingBall",
# "bouncingBar",
# "boxBounce",
# "boxBounce2",
# "christmas",
# "circle",
# "circleHalves",
# "circleQuarters",
# "clock",
# "dots",
# "dots10",
# "dots11",
# "dots12",
# "dots2",
# "dots3",
# "dots4",
# "dots5",
# "dots6",
# "dots7",
# "dots8",
# "dots8Bit",
# "dots9",
# "dqpb",
# "earth",
# "fingerDance",
# "fistBump",
# "flip",
# "grenade",
# "growHorizontal",
# "growVertical",
# "hamburger",
# "hearts",
# "layer",
# "line",
# "line2",
# "material",
# "mindblown",
# "monkey",
# "moon",
# "noise",
# "orangeBluePulse",
# "orangePulse",
# "pipe",
# "point",
# "pong",
# "runner",
# "shark",
# "simpleDots",
# "simpleDotsScrolling",
# "smiley",
# "soccerHeader",
# "speaker",
# "squareCorners",
# "squish",
# "star",
# "star2",
# "timeTravel",
# "toggle",
# "toggle10",
# "toggle11",
# "toggle12",
# "toggle13",
# "toggle2",
# "toggle3",
# "toggle4",
# "toggle5",
# "toggle6",
# "toggle7",
# "toggle8",
# "toggle9",
# "triangle",
# "weather",
# ]
#
# Path: yaspin/spinners.py
# SPINNERS_DATA = pkgutil.get_data(__name__, "data/spinners.json").decode("utf-8")
# def _hook(dct):
. Output only the next line. | "attr", sorted([k for k, v in COLOR_MAP.items() if v == "attrs"]) |
Based on the snippet: <|code_start|>"""
tests.test_attrs
~~~~~~~~~~~~~~~~
Test Yaspin attributes magic hidden in __getattr__.
"""
<|code_end|>
, predict the immediate next line with the help of imports:
import pytest
from yaspin import yaspin
from yaspin.constants import COLOR_MAP, SPINNER_ATTRS
from yaspin.spinners import Spinners
and context (classes, functions, sometimes code) from other files:
# Path: yaspin/api.py
# def yaspin(*args, **kwargs):
# """Display spinner in stdout.
#
# Can be used as a context manager or as a function decorator.
#
# Arguments:
# spinner (base_spinner.Spinner, optional): Spinner object to use.
# text (str, optional): Text to show along with spinner.
# color (str, optional): Spinner color.
# on_color (str, optional): Color highlight for the spinner.
# attrs (list, optional): Color attributes for the spinner.
# reversal (bool, optional): Reverse spin direction.
# side (str, optional): Place spinner to the right or left end
# of the text string.
# sigmap (dict, optional): Maps POSIX signals to their respective
# handlers.
# timer (bool, optional): Prints a timer showing the elapsed time.
#
# Returns:
# core.Yaspin: instance of the Yaspin class.
#
# Raises:
# ValueError: If unsupported ``color`` is specified.
# ValueError: If unsupported ``on_color`` is specified.
# ValueError: If unsupported color attribute in ``attrs``
# is specified.
# ValueError: If trying to register handler for SIGKILL signal.
# ValueError: If unsupported ``side`` is specified.
#
# Available text colors:
# red, green, yellow, blue, magenta, cyan, white.
#
# Available text highlights:
# on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan,
# on_white, on_grey.
#
# Available attributes:
# bold, dark, underline, blink, reverse, concealed.
#
# Example::
#
# # Use as a context manager
# with yaspin():
# some_operations()
#
# # Context manager with text
# with yaspin(text="Processing..."):
# some_operations()
#
# # Context manager with custom sequence
# with yaspin(Spinner('-\\|/', 150)):
# some_operations()
#
# # As decorator
# @yaspin(text="Loading...")
# def foo():
# time.sleep(5)
#
# foo()
#
# """
# return Yaspin(*args, **kwargs)
#
# Path: yaspin/constants.py
# COLOR_MAP = {
# # name: type
# "blink": "attrs",
# "bold": "attrs",
# "concealed": "attrs",
# "dark": "attrs",
# "reverse": "attrs",
# "underline": "attrs",
# "blue": "color",
# "cyan": "color",
# "green": "color",
# "magenta": "color",
# "red": "color",
# "white": "color",
# "yellow": "color",
# "on_blue": "on_color",
# "on_cyan": "on_color",
# "on_green": "on_color",
# "on_grey": "on_color",
# "on_magenta": "on_color",
# "on_red": "on_color",
# "on_white": "on_color",
# "on_yellow": "on_color",
# }
#
# SPINNER_ATTRS = [
# "aesthetic",
# "arc",
# "arrow",
# "arrow2",
# "arrow3",
# "balloon",
# "balloon2",
# "betaWave",
# "bluePulse",
# "bounce",
# "bouncingBall",
# "bouncingBar",
# "boxBounce",
# "boxBounce2",
# "christmas",
# "circle",
# "circleHalves",
# "circleQuarters",
# "clock",
# "dots",
# "dots10",
# "dots11",
# "dots12",
# "dots2",
# "dots3",
# "dots4",
# "dots5",
# "dots6",
# "dots7",
# "dots8",
# "dots8Bit",
# "dots9",
# "dqpb",
# "earth",
# "fingerDance",
# "fistBump",
# "flip",
# "grenade",
# "growHorizontal",
# "growVertical",
# "hamburger",
# "hearts",
# "layer",
# "line",
# "line2",
# "material",
# "mindblown",
# "monkey",
# "moon",
# "noise",
# "orangeBluePulse",
# "orangePulse",
# "pipe",
# "point",
# "pong",
# "runner",
# "shark",
# "simpleDots",
# "simpleDotsScrolling",
# "smiley",
# "soccerHeader",
# "speaker",
# "squareCorners",
# "squish",
# "star",
# "star2",
# "timeTravel",
# "toggle",
# "toggle10",
# "toggle11",
# "toggle12",
# "toggle13",
# "toggle2",
# "toggle3",
# "toggle4",
# "toggle5",
# "toggle6",
# "toggle7",
# "toggle8",
# "toggle9",
# "triangle",
# "weather",
# ]
#
# Path: yaspin/spinners.py
# SPINNERS_DATA = pkgutil.get_data(__name__, "data/spinners.json").decode("utf-8")
# def _hook(dct):
. Output only the next line. | @pytest.mark.parametrize("attr_name", SPINNER_ATTRS) |
Using the snippet: <|code_start|>"""
tests.test_attrs
~~~~~~~~~~~~~~~~
Test Yaspin attributes magic hidden in __getattr__.
"""
@pytest.mark.parametrize("attr_name", SPINNER_ATTRS)
def test_set_spinner_by_name(attr_name):
sp = getattr(yaspin(), attr_name)
<|code_end|>
, determine the next line of code. You have imports:
import pytest
from yaspin import yaspin
from yaspin.constants import COLOR_MAP, SPINNER_ATTRS
from yaspin.spinners import Spinners
and context (class names, function names, or code) available:
# Path: yaspin/api.py
# def yaspin(*args, **kwargs):
# """Display spinner in stdout.
#
# Can be used as a context manager or as a function decorator.
#
# Arguments:
# spinner (base_spinner.Spinner, optional): Spinner object to use.
# text (str, optional): Text to show along with spinner.
# color (str, optional): Spinner color.
# on_color (str, optional): Color highlight for the spinner.
# attrs (list, optional): Color attributes for the spinner.
# reversal (bool, optional): Reverse spin direction.
# side (str, optional): Place spinner to the right or left end
# of the text string.
# sigmap (dict, optional): Maps POSIX signals to their respective
# handlers.
# timer (bool, optional): Prints a timer showing the elapsed time.
#
# Returns:
# core.Yaspin: instance of the Yaspin class.
#
# Raises:
# ValueError: If unsupported ``color`` is specified.
# ValueError: If unsupported ``on_color`` is specified.
# ValueError: If unsupported color attribute in ``attrs``
# is specified.
# ValueError: If trying to register handler for SIGKILL signal.
# ValueError: If unsupported ``side`` is specified.
#
# Available text colors:
# red, green, yellow, blue, magenta, cyan, white.
#
# Available text highlights:
# on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan,
# on_white, on_grey.
#
# Available attributes:
# bold, dark, underline, blink, reverse, concealed.
#
# Example::
#
# # Use as a context manager
# with yaspin():
# some_operations()
#
# # Context manager with text
# with yaspin(text="Processing..."):
# some_operations()
#
# # Context manager with custom sequence
# with yaspin(Spinner('-\\|/', 150)):
# some_operations()
#
# # As decorator
# @yaspin(text="Loading...")
# def foo():
# time.sleep(5)
#
# foo()
#
# """
# return Yaspin(*args, **kwargs)
#
# Path: yaspin/constants.py
# COLOR_MAP = {
# # name: type
# "blink": "attrs",
# "bold": "attrs",
# "concealed": "attrs",
# "dark": "attrs",
# "reverse": "attrs",
# "underline": "attrs",
# "blue": "color",
# "cyan": "color",
# "green": "color",
# "magenta": "color",
# "red": "color",
# "white": "color",
# "yellow": "color",
# "on_blue": "on_color",
# "on_cyan": "on_color",
# "on_green": "on_color",
# "on_grey": "on_color",
# "on_magenta": "on_color",
# "on_red": "on_color",
# "on_white": "on_color",
# "on_yellow": "on_color",
# }
#
# SPINNER_ATTRS = [
# "aesthetic",
# "arc",
# "arrow",
# "arrow2",
# "arrow3",
# "balloon",
# "balloon2",
# "betaWave",
# "bluePulse",
# "bounce",
# "bouncingBall",
# "bouncingBar",
# "boxBounce",
# "boxBounce2",
# "christmas",
# "circle",
# "circleHalves",
# "circleQuarters",
# "clock",
# "dots",
# "dots10",
# "dots11",
# "dots12",
# "dots2",
# "dots3",
# "dots4",
# "dots5",
# "dots6",
# "dots7",
# "dots8",
# "dots8Bit",
# "dots9",
# "dqpb",
# "earth",
# "fingerDance",
# "fistBump",
# "flip",
# "grenade",
# "growHorizontal",
# "growVertical",
# "hamburger",
# "hearts",
# "layer",
# "line",
# "line2",
# "material",
# "mindblown",
# "monkey",
# "moon",
# "noise",
# "orangeBluePulse",
# "orangePulse",
# "pipe",
# "point",
# "pong",
# "runner",
# "shark",
# "simpleDots",
# "simpleDotsScrolling",
# "smiley",
# "soccerHeader",
# "speaker",
# "squareCorners",
# "squish",
# "star",
# "star2",
# "timeTravel",
# "toggle",
# "toggle10",
# "toggle11",
# "toggle12",
# "toggle13",
# "toggle2",
# "toggle3",
# "toggle4",
# "toggle5",
# "toggle6",
# "toggle7",
# "toggle8",
# "toggle9",
# "triangle",
# "weather",
# ]
#
# Path: yaspin/spinners.py
# SPINNERS_DATA = pkgutil.get_data(__name__, "data/spinners.json").decode("utf-8")
# def _hook(dct):
. Output only the next line. | assert sp.spinner == getattr(Spinners, attr_name) |
Given the following code snippet before the placeholder: <|code_start|># :copyright: (c) 2021 by Pavlo Dmytrenko.
# :license: MIT, see LICENSE for more details.
"""
yaspin.helpers
~~~~~~~~~~~~~~
Helper functions.
"""
<|code_end|>
, predict the next line using imports from the current file:
from .constants import ENCODING
and context including class names, function names, and sometimes code from other files:
# Path: yaspin/constants.py
# ENCODING = "utf-8"
. Output only the next line. | def to_unicode(text_type, encoding=ENCODING): |
Predict the next line after this snippet: <|code_start|>"""
examples.write_method
~~~~~~~~~~~~~~~~~~~~~
Basic usage of ``write`` method.
"""
def main():
<|code_end|>
using the current file's imports:
import time
from yaspin import yaspin
and any relevant context from other files:
# Path: yaspin/api.py
# def yaspin(*args, **kwargs):
# """Display spinner in stdout.
#
# Can be used as a context manager or as a function decorator.
#
# Arguments:
# spinner (base_spinner.Spinner, optional): Spinner object to use.
# text (str, optional): Text to show along with spinner.
# color (str, optional): Spinner color.
# on_color (str, optional): Color highlight for the spinner.
# attrs (list, optional): Color attributes for the spinner.
# reversal (bool, optional): Reverse spin direction.
# side (str, optional): Place spinner to the right or left end
# of the text string.
# sigmap (dict, optional): Maps POSIX signals to their respective
# handlers.
# timer (bool, optional): Prints a timer showing the elapsed time.
#
# Returns:
# core.Yaspin: instance of the Yaspin class.
#
# Raises:
# ValueError: If unsupported ``color`` is specified.
# ValueError: If unsupported ``on_color`` is specified.
# ValueError: If unsupported color attribute in ``attrs``
# is specified.
# ValueError: If trying to register handler for SIGKILL signal.
# ValueError: If unsupported ``side`` is specified.
#
# Available text colors:
# red, green, yellow, blue, magenta, cyan, white.
#
# Available text highlights:
# on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan,
# on_white, on_grey.
#
# Available attributes:
# bold, dark, underline, blink, reverse, concealed.
#
# Example::
#
# # Use as a context manager
# with yaspin():
# some_operations()
#
# # Context manager with text
# with yaspin(text="Processing..."):
# some_operations()
#
# # Context manager with custom sequence
# with yaspin(Spinner('-\\|/', 150)):
# some_operations()
#
# # As decorator
# @yaspin(text="Loading...")
# def foo():
# time.sleep(5)
#
# foo()
#
# """
# return Yaspin(*args, **kwargs)
. Output only the next line. | with yaspin(text="Downloading images") as sp: |
Using the snippet: <|code_start|>"""
examples.finalizers
~~~~~~~~~~~~~~~~~~~
Success and Failure finalizers.
"""
def default_finalizers():
<|code_end|>
, determine the next line of code. You have imports:
import time
from yaspin import yaspin
and context (class names, function names, or code) available:
# Path: yaspin/api.py
# def yaspin(*args, **kwargs):
# """Display spinner in stdout.
#
# Can be used as a context manager or as a function decorator.
#
# Arguments:
# spinner (base_spinner.Spinner, optional): Spinner object to use.
# text (str, optional): Text to show along with spinner.
# color (str, optional): Spinner color.
# on_color (str, optional): Color highlight for the spinner.
# attrs (list, optional): Color attributes for the spinner.
# reversal (bool, optional): Reverse spin direction.
# side (str, optional): Place spinner to the right or left end
# of the text string.
# sigmap (dict, optional): Maps POSIX signals to their respective
# handlers.
# timer (bool, optional): Prints a timer showing the elapsed time.
#
# Returns:
# core.Yaspin: instance of the Yaspin class.
#
# Raises:
# ValueError: If unsupported ``color`` is specified.
# ValueError: If unsupported ``on_color`` is specified.
# ValueError: If unsupported color attribute in ``attrs``
# is specified.
# ValueError: If trying to register handler for SIGKILL signal.
# ValueError: If unsupported ``side`` is specified.
#
# Available text colors:
# red, green, yellow, blue, magenta, cyan, white.
#
# Available text highlights:
# on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan,
# on_white, on_grey.
#
# Available attributes:
# bold, dark, underline, blink, reverse, concealed.
#
# Example::
#
# # Use as a context manager
# with yaspin():
# some_operations()
#
# # Context manager with text
# with yaspin(text="Processing..."):
# some_operations()
#
# # Context manager with custom sequence
# with yaspin(Spinner('-\\|/', 150)):
# some_operations()
#
# # As decorator
# @yaspin(text="Loading...")
# def foo():
# time.sleep(5)
#
# foo()
#
# """
# return Yaspin(*args, **kwargs)
. Output only the next line. | with yaspin(text="Downloading...") as sp: |
Given snippet: <|code_start|>"""
examples.dynamic_text
~~~~~~~~~~~~~~~~~~~~~
Evaluates text on every spinner frame.
"""
class TimedText:
def __init__(self, text):
self.text = text
self._start = datetime.now()
def __str__(self):
now = datetime.now()
delta = now - self._start
return f"{self.text} ({round(delta.total_seconds(), 1)}s)"
def main():
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import time
from datetime import datetime
from yaspin import yaspin
and context:
# Path: yaspin/api.py
# def yaspin(*args, **kwargs):
# """Display spinner in stdout.
#
# Can be used as a context manager or as a function decorator.
#
# Arguments:
# spinner (base_spinner.Spinner, optional): Spinner object to use.
# text (str, optional): Text to show along with spinner.
# color (str, optional): Spinner color.
# on_color (str, optional): Color highlight for the spinner.
# attrs (list, optional): Color attributes for the spinner.
# reversal (bool, optional): Reverse spin direction.
# side (str, optional): Place spinner to the right or left end
# of the text string.
# sigmap (dict, optional): Maps POSIX signals to their respective
# handlers.
# timer (bool, optional): Prints a timer showing the elapsed time.
#
# Returns:
# core.Yaspin: instance of the Yaspin class.
#
# Raises:
# ValueError: If unsupported ``color`` is specified.
# ValueError: If unsupported ``on_color`` is specified.
# ValueError: If unsupported color attribute in ``attrs``
# is specified.
# ValueError: If trying to register handler for SIGKILL signal.
# ValueError: If unsupported ``side`` is specified.
#
# Available text colors:
# red, green, yellow, blue, magenta, cyan, white.
#
# Available text highlights:
# on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan,
# on_white, on_grey.
#
# Available attributes:
# bold, dark, underline, blink, reverse, concealed.
#
# Example::
#
# # Use as a context manager
# with yaspin():
# some_operations()
#
# # Context manager with text
# with yaspin(text="Processing..."):
# some_operations()
#
# # Context manager with custom sequence
# with yaspin(Spinner('-\\|/', 150)):
# some_operations()
#
# # As decorator
# @yaspin(text="Loading...")
# def foo():
# time.sleep(5)
#
# foo()
#
# """
# return Yaspin(*args, **kwargs)
which might include code, classes, or functions. Output only the next line. | with yaspin(text=TimedText("time passed:")): |
Predict the next line after this snippet: <|code_start|>"""
examples.right_spinner
~~~~~~~~~~~~~~~~~~~~~~
Left and Right spinner position.
"""
def main():
<|code_end|>
using the current file's imports:
import time
from yaspin import yaspin
and any relevant context from other files:
# Path: yaspin/api.py
# def yaspin(*args, **kwargs):
# """Display spinner in stdout.
#
# Can be used as a context manager or as a function decorator.
#
# Arguments:
# spinner (base_spinner.Spinner, optional): Spinner object to use.
# text (str, optional): Text to show along with spinner.
# color (str, optional): Spinner color.
# on_color (str, optional): Color highlight for the spinner.
# attrs (list, optional): Color attributes for the spinner.
# reversal (bool, optional): Reverse spin direction.
# side (str, optional): Place spinner to the right or left end
# of the text string.
# sigmap (dict, optional): Maps POSIX signals to their respective
# handlers.
# timer (bool, optional): Prints a timer showing the elapsed time.
#
# Returns:
# core.Yaspin: instance of the Yaspin class.
#
# Raises:
# ValueError: If unsupported ``color`` is specified.
# ValueError: If unsupported ``on_color`` is specified.
# ValueError: If unsupported color attribute in ``attrs``
# is specified.
# ValueError: If trying to register handler for SIGKILL signal.
# ValueError: If unsupported ``side`` is specified.
#
# Available text colors:
# red, green, yellow, blue, magenta, cyan, white.
#
# Available text highlights:
# on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan,
# on_white, on_grey.
#
# Available attributes:
# bold, dark, underline, blink, reverse, concealed.
#
# Example::
#
# # Use as a context manager
# with yaspin():
# some_operations()
#
# # Context manager with text
# with yaspin(text="Processing..."):
# some_operations()
#
# # Context manager with custom sequence
# with yaspin(Spinner('-\\|/', 150)):
# some_operations()
#
# # As decorator
# @yaspin(text="Loading...")
# def foo():
# time.sleep(5)
#
# foo()
#
# """
# return Yaspin(*args, **kwargs)
. Output only the next line. | with yaspin(text="Right spinner", side="right", color="cyan") as sp: |
Continue the code snippet: <|code_start|> ("simpleDots", 1),
("star", 0.5),
("balloon", 0.7),
("noise", 0.5),
("arc", 0.5),
("arrow2", 0.5),
("bouncingBar", 1),
("bouncingBall", 1),
("smiley", 0.7),
("hearts", 0.5),
("clock", 0.7),
("earth", 0.7),
("moon", 0.7),
("runner", 0.5),
("pong", 1),
("shark", 1.5),
("christmas", 0.5),
]
random.shuffle(params)
# Setup printing
max_len = 45
msg = "[Any spinner you like]"
for name, period in params:
spinner = getattr(Spinners, name)
spaces_qty = max_len - len(name) - len(msg) - len(spinner.frames[0])
text = "{0}{1}{2}".format(name, " " * spaces_qty, msg)
<|code_end|>
. Use current file imports:
import random
import time
from yaspin import yaspin
from yaspin.constants import COLOR_MAP
from yaspin.spinners import Spinners
and context (classes, functions, or code) from other files:
# Path: yaspin/api.py
# def yaspin(*args, **kwargs):
# """Display spinner in stdout.
#
# Can be used as a context manager or as a function decorator.
#
# Arguments:
# spinner (base_spinner.Spinner, optional): Spinner object to use.
# text (str, optional): Text to show along with spinner.
# color (str, optional): Spinner color.
# on_color (str, optional): Color highlight for the spinner.
# attrs (list, optional): Color attributes for the spinner.
# reversal (bool, optional): Reverse spin direction.
# side (str, optional): Place spinner to the right or left end
# of the text string.
# sigmap (dict, optional): Maps POSIX signals to their respective
# handlers.
# timer (bool, optional): Prints a timer showing the elapsed time.
#
# Returns:
# core.Yaspin: instance of the Yaspin class.
#
# Raises:
# ValueError: If unsupported ``color`` is specified.
# ValueError: If unsupported ``on_color`` is specified.
# ValueError: If unsupported color attribute in ``attrs``
# is specified.
# ValueError: If trying to register handler for SIGKILL signal.
# ValueError: If unsupported ``side`` is specified.
#
# Available text colors:
# red, green, yellow, blue, magenta, cyan, white.
#
# Available text highlights:
# on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan,
# on_white, on_grey.
#
# Available attributes:
# bold, dark, underline, blink, reverse, concealed.
#
# Example::
#
# # Use as a context manager
# with yaspin():
# some_operations()
#
# # Context manager with text
# with yaspin(text="Processing..."):
# some_operations()
#
# # Context manager with custom sequence
# with yaspin(Spinner('-\\|/', 150)):
# some_operations()
#
# # As decorator
# @yaspin(text="Loading...")
# def foo():
# time.sleep(5)
#
# foo()
#
# """
# return Yaspin(*args, **kwargs)
#
# Path: yaspin/constants.py
# COLOR_MAP = {
# # name: type
# "blink": "attrs",
# "bold": "attrs",
# "concealed": "attrs",
# "dark": "attrs",
# "reverse": "attrs",
# "underline": "attrs",
# "blue": "color",
# "cyan": "color",
# "green": "color",
# "magenta": "color",
# "red": "color",
# "white": "color",
# "yellow": "color",
# "on_blue": "on_color",
# "on_cyan": "on_color",
# "on_green": "on_color",
# "on_grey": "on_color",
# "on_magenta": "on_color",
# "on_red": "on_color",
# "on_white": "on_color",
# "on_yellow": "on_color",
# }
#
# Path: yaspin/spinners.py
# SPINNERS_DATA = pkgutil.get_data(__name__, "data/spinners.json").decode("utf-8")
# def _hook(dct):
. Output only the next line. | with yaspin(spinner, text=text, color="cyan"): |
Predict the next line after this snippet: <|code_start|>"""
examples.demo
~~~~~~~~~~~~~
Yaspin features demonstration.
"""
<|code_end|>
using the current file's imports:
import random
import time
from yaspin import yaspin
from yaspin.constants import COLOR_MAP
from yaspin.spinners import Spinners
and any relevant context from other files:
# Path: yaspin/api.py
# def yaspin(*args, **kwargs):
# """Display spinner in stdout.
#
# Can be used as a context manager or as a function decorator.
#
# Arguments:
# spinner (base_spinner.Spinner, optional): Spinner object to use.
# text (str, optional): Text to show along with spinner.
# color (str, optional): Spinner color.
# on_color (str, optional): Color highlight for the spinner.
# attrs (list, optional): Color attributes for the spinner.
# reversal (bool, optional): Reverse spin direction.
# side (str, optional): Place spinner to the right or left end
# of the text string.
# sigmap (dict, optional): Maps POSIX signals to their respective
# handlers.
# timer (bool, optional): Prints a timer showing the elapsed time.
#
# Returns:
# core.Yaspin: instance of the Yaspin class.
#
# Raises:
# ValueError: If unsupported ``color`` is specified.
# ValueError: If unsupported ``on_color`` is specified.
# ValueError: If unsupported color attribute in ``attrs``
# is specified.
# ValueError: If trying to register handler for SIGKILL signal.
# ValueError: If unsupported ``side`` is specified.
#
# Available text colors:
# red, green, yellow, blue, magenta, cyan, white.
#
# Available text highlights:
# on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan,
# on_white, on_grey.
#
# Available attributes:
# bold, dark, underline, blink, reverse, concealed.
#
# Example::
#
# # Use as a context manager
# with yaspin():
# some_operations()
#
# # Context manager with text
# with yaspin(text="Processing..."):
# some_operations()
#
# # Context manager with custom sequence
# with yaspin(Spinner('-\\|/', 150)):
# some_operations()
#
# # As decorator
# @yaspin(text="Loading...")
# def foo():
# time.sleep(5)
#
# foo()
#
# """
# return Yaspin(*args, **kwargs)
#
# Path: yaspin/constants.py
# COLOR_MAP = {
# # name: type
# "blink": "attrs",
# "bold": "attrs",
# "concealed": "attrs",
# "dark": "attrs",
# "reverse": "attrs",
# "underline": "attrs",
# "blue": "color",
# "cyan": "color",
# "green": "color",
# "magenta": "color",
# "red": "color",
# "white": "color",
# "yellow": "color",
# "on_blue": "on_color",
# "on_cyan": "on_color",
# "on_green": "on_color",
# "on_grey": "on_color",
# "on_magenta": "on_color",
# "on_red": "on_color",
# "on_white": "on_color",
# "on_yellow": "on_color",
# }
#
# Path: yaspin/spinners.py
# SPINNERS_DATA = pkgutil.get_data(__name__, "data/spinners.json").decode("utf-8")
# def _hook(dct):
. Output only the next line. | COLORS = (k for k, v in COLOR_MAP.items() if v == "color") |
Here is a snippet: <|code_start|>def any_spinner_you_like():
params = [
("line", 0.8),
("dots10", 0.8),
("dots11", 0.8),
("simpleDots", 1),
("star", 0.5),
("balloon", 0.7),
("noise", 0.5),
("arc", 0.5),
("arrow2", 0.5),
("bouncingBar", 1),
("bouncingBall", 1),
("smiley", 0.7),
("hearts", 0.5),
("clock", 0.7),
("earth", 0.7),
("moon", 0.7),
("runner", 0.5),
("pong", 1),
("shark", 1.5),
("christmas", 0.5),
]
random.shuffle(params)
# Setup printing
max_len = 45
msg = "[Any spinner you like]"
for name, period in params:
<|code_end|>
. Write the next line using the current file imports:
import random
import time
from yaspin import yaspin
from yaspin.constants import COLOR_MAP
from yaspin.spinners import Spinners
and context from other files:
# Path: yaspin/api.py
# def yaspin(*args, **kwargs):
# """Display spinner in stdout.
#
# Can be used as a context manager or as a function decorator.
#
# Arguments:
# spinner (base_spinner.Spinner, optional): Spinner object to use.
# text (str, optional): Text to show along with spinner.
# color (str, optional): Spinner color.
# on_color (str, optional): Color highlight for the spinner.
# attrs (list, optional): Color attributes for the spinner.
# reversal (bool, optional): Reverse spin direction.
# side (str, optional): Place spinner to the right or left end
# of the text string.
# sigmap (dict, optional): Maps POSIX signals to their respective
# handlers.
# timer (bool, optional): Prints a timer showing the elapsed time.
#
# Returns:
# core.Yaspin: instance of the Yaspin class.
#
# Raises:
# ValueError: If unsupported ``color`` is specified.
# ValueError: If unsupported ``on_color`` is specified.
# ValueError: If unsupported color attribute in ``attrs``
# is specified.
# ValueError: If trying to register handler for SIGKILL signal.
# ValueError: If unsupported ``side`` is specified.
#
# Available text colors:
# red, green, yellow, blue, magenta, cyan, white.
#
# Available text highlights:
# on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan,
# on_white, on_grey.
#
# Available attributes:
# bold, dark, underline, blink, reverse, concealed.
#
# Example::
#
# # Use as a context manager
# with yaspin():
# some_operations()
#
# # Context manager with text
# with yaspin(text="Processing..."):
# some_operations()
#
# # Context manager with custom sequence
# with yaspin(Spinner('-\\|/', 150)):
# some_operations()
#
# # As decorator
# @yaspin(text="Loading...")
# def foo():
# time.sleep(5)
#
# foo()
#
# """
# return Yaspin(*args, **kwargs)
#
# Path: yaspin/constants.py
# COLOR_MAP = {
# # name: type
# "blink": "attrs",
# "bold": "attrs",
# "concealed": "attrs",
# "dark": "attrs",
# "reverse": "attrs",
# "underline": "attrs",
# "blue": "color",
# "cyan": "color",
# "green": "color",
# "magenta": "color",
# "red": "color",
# "white": "color",
# "yellow": "color",
# "on_blue": "on_color",
# "on_cyan": "on_color",
# "on_green": "on_color",
# "on_grey": "on_color",
# "on_magenta": "on_color",
# "on_red": "on_color",
# "on_white": "on_color",
# "on_yellow": "on_color",
# }
#
# Path: yaspin/spinners.py
# SPINNERS_DATA = pkgutil.get_data(__name__, "data/spinners.json").decode("utf-8")
# def _hook(dct):
, which may include functions, classes, or code. Output only the next line. | spinner = getattr(Spinners, name) |
Based on the snippet: <|code_start|>"""
examples.cli_spinners
~~~~~~~~~~~~~~~~~~~~~
Run all spinners from cli-spinners library:
https://github.com/sindresorhus/cli-spinners
Spinners are sorted alphabetically.
"""
def main():
for name in SPINNER_ATTRS:
spinner = getattr(Spinners, name)
<|code_end|>
, predict the immediate next line with the help of imports:
import time
from yaspin import yaspin
from yaspin.constants import SPINNER_ATTRS
from yaspin.spinners import Spinners
and context (classes, functions, sometimes code) from other files:
# Path: yaspin/api.py
# def yaspin(*args, **kwargs):
# """Display spinner in stdout.
#
# Can be used as a context manager or as a function decorator.
#
# Arguments:
# spinner (base_spinner.Spinner, optional): Spinner object to use.
# text (str, optional): Text to show along with spinner.
# color (str, optional): Spinner color.
# on_color (str, optional): Color highlight for the spinner.
# attrs (list, optional): Color attributes for the spinner.
# reversal (bool, optional): Reverse spin direction.
# side (str, optional): Place spinner to the right or left end
# of the text string.
# sigmap (dict, optional): Maps POSIX signals to their respective
# handlers.
# timer (bool, optional): Prints a timer showing the elapsed time.
#
# Returns:
# core.Yaspin: instance of the Yaspin class.
#
# Raises:
# ValueError: If unsupported ``color`` is specified.
# ValueError: If unsupported ``on_color`` is specified.
# ValueError: If unsupported color attribute in ``attrs``
# is specified.
# ValueError: If trying to register handler for SIGKILL signal.
# ValueError: If unsupported ``side`` is specified.
#
# Available text colors:
# red, green, yellow, blue, magenta, cyan, white.
#
# Available text highlights:
# on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan,
# on_white, on_grey.
#
# Available attributes:
# bold, dark, underline, blink, reverse, concealed.
#
# Example::
#
# # Use as a context manager
# with yaspin():
# some_operations()
#
# # Context manager with text
# with yaspin(text="Processing..."):
# some_operations()
#
# # Context manager with custom sequence
# with yaspin(Spinner('-\\|/', 150)):
# some_operations()
#
# # As decorator
# @yaspin(text="Loading...")
# def foo():
# time.sleep(5)
#
# foo()
#
# """
# return Yaspin(*args, **kwargs)
#
# Path: yaspin/constants.py
# SPINNER_ATTRS = [
# "aesthetic",
# "arc",
# "arrow",
# "arrow2",
# "arrow3",
# "balloon",
# "balloon2",
# "betaWave",
# "bluePulse",
# "bounce",
# "bouncingBall",
# "bouncingBar",
# "boxBounce",
# "boxBounce2",
# "christmas",
# "circle",
# "circleHalves",
# "circleQuarters",
# "clock",
# "dots",
# "dots10",
# "dots11",
# "dots12",
# "dots2",
# "dots3",
# "dots4",
# "dots5",
# "dots6",
# "dots7",
# "dots8",
# "dots8Bit",
# "dots9",
# "dqpb",
# "earth",
# "fingerDance",
# "fistBump",
# "flip",
# "grenade",
# "growHorizontal",
# "growVertical",
# "hamburger",
# "hearts",
# "layer",
# "line",
# "line2",
# "material",
# "mindblown",
# "monkey",
# "moon",
# "noise",
# "orangeBluePulse",
# "orangePulse",
# "pipe",
# "point",
# "pong",
# "runner",
# "shark",
# "simpleDots",
# "simpleDotsScrolling",
# "smiley",
# "soccerHeader",
# "speaker",
# "squareCorners",
# "squish",
# "star",
# "star2",
# "timeTravel",
# "toggle",
# "toggle10",
# "toggle11",
# "toggle12",
# "toggle13",
# "toggle2",
# "toggle3",
# "toggle4",
# "toggle5",
# "toggle6",
# "toggle7",
# "toggle8",
# "toggle9",
# "triangle",
# "weather",
# ]
#
# Path: yaspin/spinners.py
# SPINNERS_DATA = pkgutil.get_data(__name__, "data/spinners.json").decode("utf-8")
# def _hook(dct):
. Output only the next line. | with yaspin(spinner, text=name): |
Predict the next line for this snippet: <|code_start|>"""
examples.cli_spinners
~~~~~~~~~~~~~~~~~~~~~
Run all spinners from cli-spinners library:
https://github.com/sindresorhus/cli-spinners
Spinners are sorted alphabetically.
"""
def main():
<|code_end|>
with the help of current file imports:
import time
from yaspin import yaspin
from yaspin.constants import SPINNER_ATTRS
from yaspin.spinners import Spinners
and context from other files:
# Path: yaspin/api.py
# def yaspin(*args, **kwargs):
# """Display spinner in stdout.
#
# Can be used as a context manager or as a function decorator.
#
# Arguments:
# spinner (base_spinner.Spinner, optional): Spinner object to use.
# text (str, optional): Text to show along with spinner.
# color (str, optional): Spinner color.
# on_color (str, optional): Color highlight for the spinner.
# attrs (list, optional): Color attributes for the spinner.
# reversal (bool, optional): Reverse spin direction.
# side (str, optional): Place spinner to the right or left end
# of the text string.
# sigmap (dict, optional): Maps POSIX signals to their respective
# handlers.
# timer (bool, optional): Prints a timer showing the elapsed time.
#
# Returns:
# core.Yaspin: instance of the Yaspin class.
#
# Raises:
# ValueError: If unsupported ``color`` is specified.
# ValueError: If unsupported ``on_color`` is specified.
# ValueError: If unsupported color attribute in ``attrs``
# is specified.
# ValueError: If trying to register handler for SIGKILL signal.
# ValueError: If unsupported ``side`` is specified.
#
# Available text colors:
# red, green, yellow, blue, magenta, cyan, white.
#
# Available text highlights:
# on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan,
# on_white, on_grey.
#
# Available attributes:
# bold, dark, underline, blink, reverse, concealed.
#
# Example::
#
# # Use as a context manager
# with yaspin():
# some_operations()
#
# # Context manager with text
# with yaspin(text="Processing..."):
# some_operations()
#
# # Context manager with custom sequence
# with yaspin(Spinner('-\\|/', 150)):
# some_operations()
#
# # As decorator
# @yaspin(text="Loading...")
# def foo():
# time.sleep(5)
#
# foo()
#
# """
# return Yaspin(*args, **kwargs)
#
# Path: yaspin/constants.py
# SPINNER_ATTRS = [
# "aesthetic",
# "arc",
# "arrow",
# "arrow2",
# "arrow3",
# "balloon",
# "balloon2",
# "betaWave",
# "bluePulse",
# "bounce",
# "bouncingBall",
# "bouncingBar",
# "boxBounce",
# "boxBounce2",
# "christmas",
# "circle",
# "circleHalves",
# "circleQuarters",
# "clock",
# "dots",
# "dots10",
# "dots11",
# "dots12",
# "dots2",
# "dots3",
# "dots4",
# "dots5",
# "dots6",
# "dots7",
# "dots8",
# "dots8Bit",
# "dots9",
# "dqpb",
# "earth",
# "fingerDance",
# "fistBump",
# "flip",
# "grenade",
# "growHorizontal",
# "growVertical",
# "hamburger",
# "hearts",
# "layer",
# "line",
# "line2",
# "material",
# "mindblown",
# "monkey",
# "moon",
# "noise",
# "orangeBluePulse",
# "orangePulse",
# "pipe",
# "point",
# "pong",
# "runner",
# "shark",
# "simpleDots",
# "simpleDotsScrolling",
# "smiley",
# "soccerHeader",
# "speaker",
# "squareCorners",
# "squish",
# "star",
# "star2",
# "timeTravel",
# "toggle",
# "toggle10",
# "toggle11",
# "toggle12",
# "toggle13",
# "toggle2",
# "toggle3",
# "toggle4",
# "toggle5",
# "toggle6",
# "toggle7",
# "toggle8",
# "toggle9",
# "triangle",
# "weather",
# ]
#
# Path: yaspin/spinners.py
# SPINNERS_DATA = pkgutil.get_data(__name__, "data/spinners.json").decode("utf-8")
# def _hook(dct):
, which may contain function names, class names, or code. Output only the next line. | for name in SPINNER_ATTRS: |
Given snippet: <|code_start|>"""
examples.cli_spinners
~~~~~~~~~~~~~~~~~~~~~
Run all spinners from cli-spinners library:
https://github.com/sindresorhus/cli-spinners
Spinners are sorted alphabetically.
"""
def main():
for name in SPINNER_ATTRS:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import time
from yaspin import yaspin
from yaspin.constants import SPINNER_ATTRS
from yaspin.spinners import Spinners
and context:
# Path: yaspin/api.py
# def yaspin(*args, **kwargs):
# """Display spinner in stdout.
#
# Can be used as a context manager or as a function decorator.
#
# Arguments:
# spinner (base_spinner.Spinner, optional): Spinner object to use.
# text (str, optional): Text to show along with spinner.
# color (str, optional): Spinner color.
# on_color (str, optional): Color highlight for the spinner.
# attrs (list, optional): Color attributes for the spinner.
# reversal (bool, optional): Reverse spin direction.
# side (str, optional): Place spinner to the right or left end
# of the text string.
# sigmap (dict, optional): Maps POSIX signals to their respective
# handlers.
# timer (bool, optional): Prints a timer showing the elapsed time.
#
# Returns:
# core.Yaspin: instance of the Yaspin class.
#
# Raises:
# ValueError: If unsupported ``color`` is specified.
# ValueError: If unsupported ``on_color`` is specified.
# ValueError: If unsupported color attribute in ``attrs``
# is specified.
# ValueError: If trying to register handler for SIGKILL signal.
# ValueError: If unsupported ``side`` is specified.
#
# Available text colors:
# red, green, yellow, blue, magenta, cyan, white.
#
# Available text highlights:
# on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan,
# on_white, on_grey.
#
# Available attributes:
# bold, dark, underline, blink, reverse, concealed.
#
# Example::
#
# # Use as a context manager
# with yaspin():
# some_operations()
#
# # Context manager with text
# with yaspin(text="Processing..."):
# some_operations()
#
# # Context manager with custom sequence
# with yaspin(Spinner('-\\|/', 150)):
# some_operations()
#
# # As decorator
# @yaspin(text="Loading...")
# def foo():
# time.sleep(5)
#
# foo()
#
# """
# return Yaspin(*args, **kwargs)
#
# Path: yaspin/constants.py
# SPINNER_ATTRS = [
# "aesthetic",
# "arc",
# "arrow",
# "arrow2",
# "arrow3",
# "balloon",
# "balloon2",
# "betaWave",
# "bluePulse",
# "bounce",
# "bouncingBall",
# "bouncingBar",
# "boxBounce",
# "boxBounce2",
# "christmas",
# "circle",
# "circleHalves",
# "circleQuarters",
# "clock",
# "dots",
# "dots10",
# "dots11",
# "dots12",
# "dots2",
# "dots3",
# "dots4",
# "dots5",
# "dots6",
# "dots7",
# "dots8",
# "dots8Bit",
# "dots9",
# "dqpb",
# "earth",
# "fingerDance",
# "fistBump",
# "flip",
# "grenade",
# "growHorizontal",
# "growVertical",
# "hamburger",
# "hearts",
# "layer",
# "line",
# "line2",
# "material",
# "mindblown",
# "monkey",
# "moon",
# "noise",
# "orangeBluePulse",
# "orangePulse",
# "pipe",
# "point",
# "pong",
# "runner",
# "shark",
# "simpleDots",
# "simpleDotsScrolling",
# "smiley",
# "soccerHeader",
# "speaker",
# "squareCorners",
# "squish",
# "star",
# "star2",
# "timeTravel",
# "toggle",
# "toggle10",
# "toggle11",
# "toggle12",
# "toggle13",
# "toggle2",
# "toggle3",
# "toggle4",
# "toggle5",
# "toggle6",
# "toggle7",
# "toggle8",
# "toggle9",
# "triangle",
# "weather",
# ]
#
# Path: yaspin/spinners.py
# SPINNERS_DATA = pkgutil.get_data(__name__, "data/spinners.json").decode("utf-8")
# def _hook(dct):
which might include code, classes, or functions. Output only the next line. | spinner = getattr(Spinners, name) |
Given snippet: <|code_start|> # SIG_DFL and SIG_IGN cases
assert sig_handler == handler
finally:
sp.stop()
def test_raise_exception_for_sigkill():
sp = yaspin(sigmap={signal.SIGKILL: signal.SIG_IGN})
try:
with pytest.raises(ValueError):
sp.start()
finally:
sp.stop()
def test_default_handlers_are_set_at_cleanup_stage(sigmap_test_cases):
sigmap = sigmap_test_cases
if not sigmap:
pytest.skip("{0!r} - unsupported case".format(sigmap))
sp = yaspin(sigmap=sigmap)
sp.start()
sp.stop()
for sig in sigmap.keys():
handler = signal.getsignal(sig)
assert handler == sp._dfl_sigmap[sig]
def test_kbi_safe_yaspin():
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import functools
import signal
import pytest
from yaspin import kbi_safe_yaspin, yaspin
and context:
# Path: yaspin/api.py
# def kbi_safe_yaspin(*args, **kwargs):
# kwargs["sigmap"] = {signal.SIGINT: default_handler}
# return Yaspin(*args, **kwargs)
#
# def yaspin(*args, **kwargs):
# """Display spinner in stdout.
#
# Can be used as a context manager or as a function decorator.
#
# Arguments:
# spinner (base_spinner.Spinner, optional): Spinner object to use.
# text (str, optional): Text to show along with spinner.
# color (str, optional): Spinner color.
# on_color (str, optional): Color highlight for the spinner.
# attrs (list, optional): Color attributes for the spinner.
# reversal (bool, optional): Reverse spin direction.
# side (str, optional): Place spinner to the right or left end
# of the text string.
# sigmap (dict, optional): Maps POSIX signals to their respective
# handlers.
# timer (bool, optional): Prints a timer showing the elapsed time.
#
# Returns:
# core.Yaspin: instance of the Yaspin class.
#
# Raises:
# ValueError: If unsupported ``color`` is specified.
# ValueError: If unsupported ``on_color`` is specified.
# ValueError: If unsupported color attribute in ``attrs``
# is specified.
# ValueError: If trying to register handler for SIGKILL signal.
# ValueError: If unsupported ``side`` is specified.
#
# Available text colors:
# red, green, yellow, blue, magenta, cyan, white.
#
# Available text highlights:
# on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan,
# on_white, on_grey.
#
# Available attributes:
# bold, dark, underline, blink, reverse, concealed.
#
# Example::
#
# # Use as a context manager
# with yaspin():
# some_operations()
#
# # Context manager with text
# with yaspin(text="Processing..."):
# some_operations()
#
# # Context manager with custom sequence
# with yaspin(Spinner('-\\|/', 150)):
# some_operations()
#
# # As decorator
# @yaspin(text="Loading...")
# def foo():
# time.sleep(5)
#
# foo()
#
# """
# return Yaspin(*args, **kwargs)
which might include code, classes, or functions. Output only the next line. | sp = kbi_safe_yaspin() |
Here is a snippet: <|code_start|>"""
tests.test_signals
~~~~~~~~~~~~~~~~~~
Test Yaspin signals handling.
"""
def test_sigmap_setting(sigmap_test_cases):
sigmap = sigmap_test_cases
<|code_end|>
. Write the next line using the current file imports:
import functools
import signal
import pytest
from yaspin import kbi_safe_yaspin, yaspin
and context from other files:
# Path: yaspin/api.py
# def kbi_safe_yaspin(*args, **kwargs):
# kwargs["sigmap"] = {signal.SIGINT: default_handler}
# return Yaspin(*args, **kwargs)
#
# def yaspin(*args, **kwargs):
# """Display spinner in stdout.
#
# Can be used as a context manager or as a function decorator.
#
# Arguments:
# spinner (base_spinner.Spinner, optional): Spinner object to use.
# text (str, optional): Text to show along with spinner.
# color (str, optional): Spinner color.
# on_color (str, optional): Color highlight for the spinner.
# attrs (list, optional): Color attributes for the spinner.
# reversal (bool, optional): Reverse spin direction.
# side (str, optional): Place spinner to the right or left end
# of the text string.
# sigmap (dict, optional): Maps POSIX signals to their respective
# handlers.
# timer (bool, optional): Prints a timer showing the elapsed time.
#
# Returns:
# core.Yaspin: instance of the Yaspin class.
#
# Raises:
# ValueError: If unsupported ``color`` is specified.
# ValueError: If unsupported ``on_color`` is specified.
# ValueError: If unsupported color attribute in ``attrs``
# is specified.
# ValueError: If trying to register handler for SIGKILL signal.
# ValueError: If unsupported ``side`` is specified.
#
# Available text colors:
# red, green, yellow, blue, magenta, cyan, white.
#
# Available text highlights:
# on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan,
# on_white, on_grey.
#
# Available attributes:
# bold, dark, underline, blink, reverse, concealed.
#
# Example::
#
# # Use as a context manager
# with yaspin():
# some_operations()
#
# # Context manager with text
# with yaspin(text="Processing..."):
# some_operations()
#
# # Context manager with custom sequence
# with yaspin(Spinner('-\\|/', 150)):
# some_operations()
#
# # As decorator
# @yaspin(text="Loading...")
# def foo():
# time.sleep(5)
#
# foo()
#
# """
# return Yaspin(*args, **kwargs)
, which may include functions, classes, or code. Output only the next line. | sp = yaspin(sigmap=sigmap) |
Given the following code snippet before the placeholder: <|code_start|> assert req.meta['depth'] == 1 and copy_req.meta['depth'] == 0
def test_replace_http_request():
req = HttpRequest('http://example.com/', 'POST', body=b'body1')
new_req = req.replace(url='https://example.com/', body=b'body2')
assert new_req.url == 'https://example.com/'
assert new_req.body == b'body2'
assert new_req.method == 'POST'
def test_http_request_to_dict():
headers = HttpHeaders()
headers.add('Set-Cookie', 'a=b')
headers.add('Set-Cookie', 'c=d')
req = HttpRequest('http://example.com/', 'POST', body=b'body', headers=headers)
d = req.to_dict()
assert d['url'] == 'http://example.com/'
assert d['method'] == 'POST'
assert d['body'] == b'body'
assert d['headers'] == headers
req2 = HttpRequest.from_dict(d)
assert req.url == req2.url
assert req.method == req2.method
assert req.body == req2.body
assert req.headers == req2.headers
def test_copy_http_response():
<|code_end|>
, predict the next line using imports from the current file:
from xpaw.http import HttpRequest, HttpResponse, HttpHeaders
from xpaw.utils import get_params_in_url
and context including class names, function names, and sometimes code from other files:
# Path: xpaw/http.py
# class HttpRequest:
# class HttpResponse:
# def __init__(self, url, method="GET", body=None, params=None, headers=None, proxy=None,
# timeout=20, verify_ssl=False, allow_redirects=True, auth=None, proxy_auth=None,
# priority=None, dont_filter=False, callback=None, errback=None, meta=None,
# render=None):
# def __str__(self):
# def meta(self):
# def copy(self):
# def replace(self, **kwargs):
# def to_dict(self):
# def from_dict(cls, d):
# def __init__(self, url, status, body=None, headers=None,
# request=None, encoding=None):
# def __str__(self):
# def encoding(self):
# def encoding(self, value):
# def text(self):
# def meta(self):
# def copy(self):
# def replace(self, **kwargs):
#
# Path: xpaw/utils.py
# def get_params_in_url(url):
# return parse_qs(urlsplit(url).query)
. Output only the next line. | resp = HttpResponse('http://example.com/', 200, body=b'body') |
Given the following code snippet before the placeholder: <|code_start|># coding=utf-8
def test_copy_http_request():
req = HttpRequest('http://example.com/', params={'key': 'value'}, meta={'depth': 0})
copy_req = req.copy()
assert copy_req.url == req.url
params = get_params_in_url(copy_req.url)
assert 'key' in params and params['key'] == ['value']
assert 'depth' in copy_req.meta and copy_req.meta['depth'] == 0
req.meta['depth'] = 1
assert req.meta['depth'] == 1 and copy_req.meta['depth'] == 0
def test_replace_http_request():
req = HttpRequest('http://example.com/', 'POST', body=b'body1')
new_req = req.replace(url='https://example.com/', body=b'body2')
assert new_req.url == 'https://example.com/'
assert new_req.body == b'body2'
assert new_req.method == 'POST'
def test_http_request_to_dict():
<|code_end|>
, predict the next line using imports from the current file:
from xpaw.http import HttpRequest, HttpResponse, HttpHeaders
from xpaw.utils import get_params_in_url
and context including class names, function names, and sometimes code from other files:
# Path: xpaw/http.py
# class HttpRequest:
# class HttpResponse:
# def __init__(self, url, method="GET", body=None, params=None, headers=None, proxy=None,
# timeout=20, verify_ssl=False, allow_redirects=True, auth=None, proxy_auth=None,
# priority=None, dont_filter=False, callback=None, errback=None, meta=None,
# render=None):
# def __str__(self):
# def meta(self):
# def copy(self):
# def replace(self, **kwargs):
# def to_dict(self):
# def from_dict(cls, d):
# def __init__(self, url, status, body=None, headers=None,
# request=None, encoding=None):
# def __str__(self):
# def encoding(self):
# def encoding(self, value):
# def text(self):
# def meta(self):
# def copy(self):
# def replace(self, **kwargs):
#
# Path: xpaw/utils.py
# def get_params_in_url(url):
# return parse_qs(urlsplit(url).query)
. Output only the next line. | headers = HttpHeaders() |
Next line prediction: <|code_start|># coding=utf-8
def test_copy_http_request():
req = HttpRequest('http://example.com/', params={'key': 'value'}, meta={'depth': 0})
copy_req = req.copy()
assert copy_req.url == req.url
<|code_end|>
. Use current file imports:
(from xpaw.http import HttpRequest, HttpResponse, HttpHeaders
from xpaw.utils import get_params_in_url)
and context including class names, function names, or small code snippets from other files:
# Path: xpaw/http.py
# class HttpRequest:
# class HttpResponse:
# def __init__(self, url, method="GET", body=None, params=None, headers=None, proxy=None,
# timeout=20, verify_ssl=False, allow_redirects=True, auth=None, proxy_auth=None,
# priority=None, dont_filter=False, callback=None, errback=None, meta=None,
# render=None):
# def __str__(self):
# def meta(self):
# def copy(self):
# def replace(self, **kwargs):
# def to_dict(self):
# def from_dict(cls, d):
# def __init__(self, url, status, body=None, headers=None,
# request=None, encoding=None):
# def __str__(self):
# def encoding(self):
# def encoding(self, value):
# def text(self):
# def meta(self):
# def copy(self):
# def replace(self, **kwargs):
#
# Path: xpaw/utils.py
# def get_params_in_url(url):
# return parse_qs(urlsplit(url).query)
. Output only the next line. | params = get_params_in_url(copy_req.url) |
Next line prediction: <|code_start|># coding=utf-8
log = logging.getLogger(__name__)
__all__ = ['DefaultHeadersMiddleware']
class DefaultHeadersMiddleware:
def __init__(self, default_headers=None):
self._headers = default_headers or {}
def __repr__(self):
cls_name = self.__class__.__name__
return '{}(default_headers={})'.format(cls_name, repr(self._headers))
@classmethod
def from_crawler(cls, crawler):
default_headers = crawler.config.get("default_headers")
if default_headers is None:
<|code_end|>
. Use current file imports:
(import logging
from xpaw.errors import NotEnabled)
and context including class names, function names, or small code snippets from other files:
# Path: xpaw/errors.py
# class NotEnabled(Exception):
# """
# Not enabled.
# """
. Output only the next line. | raise NotEnabled |
Predict the next line after this snippet: <|code_start|> """
method
"""
@staticmethod
def staticmethod():
"""
static method
"""
def method1(self):
self.count1 += 1
@pytest.mark.asyncio
async def method2(self):
self.count2 += 1
def method_set_value(self, value):
self.value = value
def method_raise_error(self):
raise RuntimeError('not an error actually')
def test_raise_value_error():
def func():
"""
function
"""
<|code_end|>
using the current file's imports:
import pytest
from xpaw.eventbus import EventBus
and any relevant context from other files:
# Path: xpaw/eventbus.py
# class EventBus:
# def __init__(self):
# self._refs = {}
#
# def subscribe(self, receiver, event):
# if event not in self._refs:
# self._refs[event] = {}
# if not hasattr(receiver, '__func__') or not hasattr(receiver, '__self__'):
# raise ValueError("Failed to subscribe, {} has no attribute '__func__' or '__self__'".format(receiver))
# i = self._calc_id(receiver)
# if i in self._refs[event]:
# f = self._refs[event][i]()
# if f is not None:
# return
# self._refs[event][i] = weakref.WeakMethod(receiver)
#
# def unsubscribe(self, receiver, event):
# if event in self._refs:
# i = self._calc_id(receiver)
# if i in self._refs[event]:
# del self._refs[event][i]
#
# async def send(self, event, **kwargs):
# if event not in self._refs:
# return
# del_list = []
# for i in self._refs[event]:
# f = self._refs[event][i]()
# if f is None:
# del_list.append(i)
# else:
# try:
# res = f(**kwargs)
# if inspect.iscoroutine(res):
# await res
# except CancelledError:
# raise
# except Exception:
# log.warning("Failed to send the event", exc_info=True)
# for i in del_list:
# del self._refs[event][i]
# del del_list
#
# def _calc_id(self, receiver):
# return hash((id(receiver.__func__), id(receiver.__self__)))
. Output only the next line. | eventbus = EventBus() |
Continue the code snippet: <|code_start|># coding=utf-8
class TestXPathSelector:
def test_selector_list(self):
html = """<li>a</li><div><ul><li>b</li><li>c</li></ul></div><ul><li>d</li></ul>"""
<|code_end|>
. Use current file imports:
import pytest
from xpaw.selector import Selector
from lxml.etree import XMLSyntaxError
and context (classes, functions, or code) from other files:
# Path: xpaw/selector.py
# class Selector:
# def __init__(self, text=None, root=None, text_type='html'):
# self.type = _get_text_type(text_type)
# c = _text_type_config[self.type]
# self._parser_cls = c['parser_cls']
# self._tostring_method = c['tostring_method']
# self._css_translator = c['css_translator']
# if text is not None:
# if not isinstance(text, str):
# raise TypeError("'text' argument must be str")
# root = create_root_node(text, parser_cls=self._parser_cls)
# if root is None:
# raise ValueError("Needs either text or root argument")
# self.root = root
#
# def xpath(self, xpath, **kwargs):
# kwargs.setdefault('smart_strings', False)
# res = self.root.xpath(xpath, **kwargs)
# if not isinstance(res, list):
# res = [res]
# return SelectorList([self.__class__(root=i) for i in res])
#
# def css(self, css, **kwargs):
# xpath = self._css_translator.css_to_xpath(css)
# return self.xpath(xpath, **kwargs)
#
# @property
# def string(self):
# try:
# return etree.tostring(self.root, encoding="unicode", method=self._tostring_method, with_tail=False)
# except TypeError:
# return str(self.root)
#
# @property
# def text(self):
# try:
# return etree.tostring(self.root, encoding="unicode", method="text", with_tail=False)
# except TypeError:
# return str(self.root)
#
# def attr(self, name):
# res = self.xpath('@' + name)
# if len(res) > 0:
# return res[0].text
. Output only the next line. | s = Selector(html) |
Continue the code snippet: <|code_start|>
@classmethod
def from_dict(cls, d):
return cls(**d)
class HttpResponse:
def __init__(self, url, status, body=None, headers=None,
request=None, encoding=None):
"""
Construct an HTTP response.
"""
self.url = url
self.status = status
self.body = body
self.headers = headers
self.request = request
self._encoding = encoding
def __str__(self):
return '<{}, {}>'.format(self.status, self.url)
__repr__ = __str__
@property
def encoding(self):
if self._encoding:
return self._encoding
encoding = get_encoding_from_content_type(self.headers.get("Content-Type"))
if not encoding and self.body:
<|code_end|>
. Use current file imports:
import inspect
from tornado.httputil import HTTPHeaders as _HttpHeaders
from .utils import get_encoding_from_content, get_encoding_from_content_type, make_url
and context (classes, functions, or code) from other files:
# Path: xpaw/utils.py
# def get_encoding_from_content(content):
# if isinstance(content, bytes):
# content = content.decode("ascii", errors="ignore")
# elif not isinstance(content, str):
# raise ValueError("content should be bytes or str")
# s = _charset_flag.search(content)
# if s:
# return s.group(1).strip()
# s = _pragma_flag.search(content)
# if s:
# return s.group(1).strip()
# s = _xml_flag.search(content)
# if s:
# return s.group(1).strip()
#
# def get_encoding_from_content_type(content_type):
# if content_type:
# content_type, params = cgi.parse_header(content_type)
# if "charset" in params:
# return params["charset"]
#
# def make_url(url, params=None):
# args = []
# if isinstance(params, dict):
# for k, v in params.items():
# if isinstance(v, (tuple, list)):
# for i in v:
# args.append((k, i))
# else:
# args.append((k, v))
# elif isinstance(params, (tuple, list)):
# for k, v in params:
# args.append((k, v))
# return url_concat(url, args)
. Output only the next line. | encoding = get_encoding_from_content(self.body) |
Given the following code snippet before the placeholder: <|code_start|> }
return d
@classmethod
def from_dict(cls, d):
return cls(**d)
class HttpResponse:
def __init__(self, url, status, body=None, headers=None,
request=None, encoding=None):
"""
Construct an HTTP response.
"""
self.url = url
self.status = status
self.body = body
self.headers = headers
self.request = request
self._encoding = encoding
def __str__(self):
return '<{}, {}>'.format(self.status, self.url)
__repr__ = __str__
@property
def encoding(self):
if self._encoding:
return self._encoding
<|code_end|>
, predict the next line using imports from the current file:
import inspect
from tornado.httputil import HTTPHeaders as _HttpHeaders
from .utils import get_encoding_from_content, get_encoding_from_content_type, make_url
and context including class names, function names, and sometimes code from other files:
# Path: xpaw/utils.py
# def get_encoding_from_content(content):
# if isinstance(content, bytes):
# content = content.decode("ascii", errors="ignore")
# elif not isinstance(content, str):
# raise ValueError("content should be bytes or str")
# s = _charset_flag.search(content)
# if s:
# return s.group(1).strip()
# s = _pragma_flag.search(content)
# if s:
# return s.group(1).strip()
# s = _xml_flag.search(content)
# if s:
# return s.group(1).strip()
#
# def get_encoding_from_content_type(content_type):
# if content_type:
# content_type, params = cgi.parse_header(content_type)
# if "charset" in params:
# return params["charset"]
#
# def make_url(url, params=None):
# args = []
# if isinstance(params, dict):
# for k, v in params.items():
# if isinstance(v, (tuple, list)):
# for i in v:
# args.append((k, i))
# else:
# args.append((k, v))
# elif isinstance(params, (tuple, list)):
# for k, v in params:
# args.append((k, v))
# return url_concat(url, args)
. Output only the next line. | encoding = get_encoding_from_content_type(self.headers.get("Content-Type")) |
Given the code snippet: <|code_start|># coding=utf-8
HttpHeaders = _HttpHeaders
class HttpRequest:
def __init__(self, url, method="GET", body=None, params=None, headers=None, proxy=None,
timeout=20, verify_ssl=False, allow_redirects=True, auth=None, proxy_auth=None,
priority=None, dont_filter=False, callback=None, errback=None, meta=None,
render=None):
"""
Construct an HTTP request.
"""
<|code_end|>
, generate the next line using the imports in this file:
import inspect
from tornado.httputil import HTTPHeaders as _HttpHeaders
from .utils import get_encoding_from_content, get_encoding_from_content_type, make_url
and context (functions, classes, or occasionally code) from other files:
# Path: xpaw/utils.py
# def get_encoding_from_content(content):
# if isinstance(content, bytes):
# content = content.decode("ascii", errors="ignore")
# elif not isinstance(content, str):
# raise ValueError("content should be bytes or str")
# s = _charset_flag.search(content)
# if s:
# return s.group(1).strip()
# s = _pragma_flag.search(content)
# if s:
# return s.group(1).strip()
# s = _xml_flag.search(content)
# if s:
# return s.group(1).strip()
#
# def get_encoding_from_content_type(content_type):
# if content_type:
# content_type, params = cgi.parse_header(content_type)
# if "charset" in params:
# return params["charset"]
#
# def make_url(url, params=None):
# args = []
# if isinstance(params, dict):
# for k, v in params.items():
# if isinstance(v, (tuple, list)):
# for i in v:
# args.append((k, i))
# else:
# args.append((k, v))
# elif isinstance(params, (tuple, list)):
# for k, v in params:
# args.append((k, v))
# return url_concat(url, args)
. Output only the next line. | self.url = make_url(url, params) |
Predict the next line for this snippet: <|code_start|># coding=utf-8
log = logging.getLogger(__name__)
__all__ = ['SpeedLimitMiddleware']
class SpeedLimitMiddleware:
def __init__(self, rate=1, burst=1):
self._rate = rate
self._burst = burst
if self._rate <= 0:
raise ValueError("rate must be greater than 0")
if self._burst <= 0:
raise ValueError('burst must be greater than 0')
self._interval = 1.0 / self._rate
self._bucket = self._burst
self._semaphore = asyncio.Semaphore(self._burst)
self._update_future = None
def __repr__(self):
cls_name = self.__class__.__name__
return '{}(speed_limit_rate={}, speed_limit_burst={})'.format(cls_name, repr(self._rate), repr(self._burst))
@classmethod
def from_crawler(cls, crawler):
config = crawler.config
if config['speed_limit'] is None:
<|code_end|>
with the help of current file imports:
import logging
import asyncio
from xpaw.errors import NotEnabled
and context from other files:
# Path: xpaw/errors.py
# class NotEnabled(Exception):
# """
# Not enabled.
# """
, which may contain function names, class names, or code. Output only the next line. | raise NotEnabled |
Predict the next line for this snippet: <|code_start|># coding=utf-8
log = logging.getLogger(__name__)
__all__ = ['ProxyMiddleware']
class ProxyMiddleware:
def __init__(self, proxy):
self._proxies = {'http': None, 'https': None}
self._set_proxy(proxy)
def __repr__(self):
cls_name = self.__class__.__name__
return '{}(proxy={})'.format(cls_name, repr(self._proxies))
@classmethod
def from_crawler(cls, crawler):
proxy = crawler.config.get('proxy')
if not proxy:
<|code_end|>
with the help of current file imports:
import logging
from urllib.parse import urlsplit
from xpaw.errors import NotEnabled
and context from other files:
# Path: xpaw/errors.py
# class NotEnabled(Exception):
# """
# Not enabled.
# """
, which may contain function names, class names, or code. Output only the next line. | raise NotEnabled |
Continue the code snippet: <|code_start|># coding=utf-8
class TestConfig:
def test_get(self):
d = {'key': 'value'}
<|code_end|>
. Use current file imports:
from xpaw.config import Config
and context (classes, functions, or code) from other files:
# Path: xpaw/config.py
# class Config(MutableMapping):
# def __init__(self, __values=None, **kwargs):
# self.attrs = {}
# self.update(__values, **kwargs)
#
# def __getitem__(self, name):
# if name not in self:
# return None
# return self.attrs[name]
#
# def __contains__(self, name):
# return name in self.attrs
#
# def get(self, name, default=None):
# return self[name] if self[name] is not None else default
#
# def getbool(self, name, default=None):
# v = self.get(name, default)
# return getbool(v)
#
# def getint(self, name, default=None):
# v = self.get(name, default)
# return getint(v)
#
# def getfloat(self, name, default=None):
# v = self.get(name, default)
# return getfloat(v)
#
# def getlist(self, name, default=None):
# v = self.get(name, default)
# return getlist(v)
#
# def __setitem__(self, name, value):
# self.attrs[name] = value
#
# def set(self, name, value):
# self[name] = value
#
# def setdefault(self, k, default=None):
# if k not in self:
# self[k] = default
#
# def update(self, __values=None, **kwargs):
# if __values is not None:
# if isinstance(__values, Config):
# for name in __values:
# self[name] = __values[name]
# else:
# for name, value in __values.items():
# self[name] = value
# for k, v in kwargs.items():
# self[k] = v
#
# def delete(self, name):
# del self.attrs[name]
#
# def __delitem__(self, name):
# del self.attrs[name]
#
# def copy(self):
# return copy.deepcopy(self)
#
# def __iter__(self):
# return iter(self.attrs)
#
# def __len__(self):
# return len(self.attrs)
. Output only the next line. | config = Config(d) |
Predict the next line for this snippet: <|code_start|># coding=utf-8
log = logging.getLogger(__name__)
class HashDupeFilter:
def __init__(self):
self._hash = set()
def is_duplicated(self, request):
if request.dont_filter:
return False
<|code_end|>
with the help of current file imports:
import logging
from .utils import request_fingerprint
and context from other files:
# Path: xpaw/utils.py
# def request_fingerprint(request):
# sha1 = hashlib.sha1()
# sha1.update(to_bytes(request.method))
# res = urlsplit(request.url)
# queries = parse_qsl(res.query)
# queries.sort()
# final_query = urlencode(queries)
# sha1.update(to_bytes('{}://{}{}:{}?{}'.format(res.scheme,
# '' if res.hostname is None else res.hostname,
# res.path,
# 80 if res.port is None else res.port,
# final_query)))
# sha1.update(request.body or b'')
# return sha1.hexdigest()
, which may contain function names, class names, or code. Output only the next line. | h = request_fingerprint(request) |
Continue the code snippet: <|code_start|># coding=utf-8
class Crawler:
def __init__(self, **kwargs):
self.event_bus = EventBus()
<|code_end|>
. Use current file imports:
from xpaw.eventbus import EventBus
from xpaw.config import Config, DEFAULT_CONFIG
and context (classes, functions, or code) from other files:
# Path: xpaw/eventbus.py
# class EventBus:
# def __init__(self):
# self._refs = {}
#
# def subscribe(self, receiver, event):
# if event not in self._refs:
# self._refs[event] = {}
# if not hasattr(receiver, '__func__') or not hasattr(receiver, '__self__'):
# raise ValueError("Failed to subscribe, {} has no attribute '__func__' or '__self__'".format(receiver))
# i = self._calc_id(receiver)
# if i in self._refs[event]:
# f = self._refs[event][i]()
# if f is not None:
# return
# self._refs[event][i] = weakref.WeakMethod(receiver)
#
# def unsubscribe(self, receiver, event):
# if event in self._refs:
# i = self._calc_id(receiver)
# if i in self._refs[event]:
# del self._refs[event][i]
#
# async def send(self, event, **kwargs):
# if event not in self._refs:
# return
# del_list = []
# for i in self._refs[event]:
# f = self._refs[event][i]()
# if f is None:
# del_list.append(i)
# else:
# try:
# res = f(**kwargs)
# if inspect.iscoroutine(res):
# await res
# except CancelledError:
# raise
# except Exception:
# log.warning("Failed to send the event", exc_info=True)
# for i in del_list:
# del self._refs[event][i]
# del del_list
#
# def _calc_id(self, receiver):
# return hash((id(receiver.__func__), id(receiver.__self__)))
#
# Path: xpaw/config.py
# class Config(MutableMapping):
# def __init__(self, __values=None, **kwargs):
# self.attrs = {}
# self.update(__values, **kwargs)
#
# def __getitem__(self, name):
# if name not in self:
# return None
# return self.attrs[name]
#
# def __contains__(self, name):
# return name in self.attrs
#
# def get(self, name, default=None):
# return self[name] if self[name] is not None else default
#
# def getbool(self, name, default=None):
# v = self.get(name, default)
# return getbool(v)
#
# def getint(self, name, default=None):
# v = self.get(name, default)
# return getint(v)
#
# def getfloat(self, name, default=None):
# v = self.get(name, default)
# return getfloat(v)
#
# def getlist(self, name, default=None):
# v = self.get(name, default)
# return getlist(v)
#
# def __setitem__(self, name, value):
# self.attrs[name] = value
#
# def set(self, name, value):
# self[name] = value
#
# def setdefault(self, k, default=None):
# if k not in self:
# self[k] = default
#
# def update(self, __values=None, **kwargs):
# if __values is not None:
# if isinstance(__values, Config):
# for name in __values:
# self[name] = __values[name]
# else:
# for name, value in __values.items():
# self[name] = value
# for k, v in kwargs.items():
# self[k] = v
#
# def delete(self, name):
# del self.attrs[name]
#
# def __delitem__(self, name):
# del self.attrs[name]
#
# def copy(self):
# return copy.deepcopy(self)
#
# def __iter__(self):
# return iter(self.attrs)
#
# def __len__(self):
# return len(self.attrs)
#
# DEFAULT_CONFIG = {
# 'daemon': False,
# 'log_level': 'info',
# 'log_format': '%(asctime)s %(name)s [%(levelname)s] %(message)s',
# 'log_dateformat': '[%Y-%m-%d %H:%M:%S %z]',
# 'downloader': 'xpaw.downloader.Downloader',
# 'user_agent': ':desktop',
# 'random_user_agent': False,
# 'retry_enabled': True,
# 'stats_collector': 'xpaw.stats.StatsCollector',
# 'queue': 'xpaw.queue.PriorityQueue',
# 'dupe_filter': 'xpaw.dupefilter.HashDupeFilter',
# 'default_extensions': [
# 'xpaw.extensions.DefaultHeadersMiddleware',
# 'xpaw.extensions.UserAgentMiddleware',
# 'xpaw.extensions.RetryMiddleware',
# 'xpaw.extensions.ProxyMiddleware',
# 'xpaw.extensions.SpeedLimitMiddleware',
# 'xpaw.extensions.DepthMiddleware',
# ]
# }
. Output only the next line. | self.config = Config(DEFAULT_CONFIG, **kwargs) |
Given the following code snippet before the placeholder: <|code_start|># coding=utf-8
class Crawler:
def __init__(self, **kwargs):
self.event_bus = EventBus()
<|code_end|>
, predict the next line using imports from the current file:
from xpaw.eventbus import EventBus
from xpaw.config import Config, DEFAULT_CONFIG
and context including class names, function names, and sometimes code from other files:
# Path: xpaw/eventbus.py
# class EventBus:
# def __init__(self):
# self._refs = {}
#
# def subscribe(self, receiver, event):
# if event not in self._refs:
# self._refs[event] = {}
# if not hasattr(receiver, '__func__') or not hasattr(receiver, '__self__'):
# raise ValueError("Failed to subscribe, {} has no attribute '__func__' or '__self__'".format(receiver))
# i = self._calc_id(receiver)
# if i in self._refs[event]:
# f = self._refs[event][i]()
# if f is not None:
# return
# self._refs[event][i] = weakref.WeakMethod(receiver)
#
# def unsubscribe(self, receiver, event):
# if event in self._refs:
# i = self._calc_id(receiver)
# if i in self._refs[event]:
# del self._refs[event][i]
#
# async def send(self, event, **kwargs):
# if event not in self._refs:
# return
# del_list = []
# for i in self._refs[event]:
# f = self._refs[event][i]()
# if f is None:
# del_list.append(i)
# else:
# try:
# res = f(**kwargs)
# if inspect.iscoroutine(res):
# await res
# except CancelledError:
# raise
# except Exception:
# log.warning("Failed to send the event", exc_info=True)
# for i in del_list:
# del self._refs[event][i]
# del del_list
#
# def _calc_id(self, receiver):
# return hash((id(receiver.__func__), id(receiver.__self__)))
#
# Path: xpaw/config.py
# class Config(MutableMapping):
# def __init__(self, __values=None, **kwargs):
# self.attrs = {}
# self.update(__values, **kwargs)
#
# def __getitem__(self, name):
# if name not in self:
# return None
# return self.attrs[name]
#
# def __contains__(self, name):
# return name in self.attrs
#
# def get(self, name, default=None):
# return self[name] if self[name] is not None else default
#
# def getbool(self, name, default=None):
# v = self.get(name, default)
# return getbool(v)
#
# def getint(self, name, default=None):
# v = self.get(name, default)
# return getint(v)
#
# def getfloat(self, name, default=None):
# v = self.get(name, default)
# return getfloat(v)
#
# def getlist(self, name, default=None):
# v = self.get(name, default)
# return getlist(v)
#
# def __setitem__(self, name, value):
# self.attrs[name] = value
#
# def set(self, name, value):
# self[name] = value
#
# def setdefault(self, k, default=None):
# if k not in self:
# self[k] = default
#
# def update(self, __values=None, **kwargs):
# if __values is not None:
# if isinstance(__values, Config):
# for name in __values:
# self[name] = __values[name]
# else:
# for name, value in __values.items():
# self[name] = value
# for k, v in kwargs.items():
# self[k] = v
#
# def delete(self, name):
# del self.attrs[name]
#
# def __delitem__(self, name):
# del self.attrs[name]
#
# def copy(self):
# return copy.deepcopy(self)
#
# def __iter__(self):
# return iter(self.attrs)
#
# def __len__(self):
# return len(self.attrs)
#
# DEFAULT_CONFIG = {
# 'daemon': False,
# 'log_level': 'info',
# 'log_format': '%(asctime)s %(name)s [%(levelname)s] %(message)s',
# 'log_dateformat': '[%Y-%m-%d %H:%M:%S %z]',
# 'downloader': 'xpaw.downloader.Downloader',
# 'user_agent': ':desktop',
# 'random_user_agent': False,
# 'retry_enabled': True,
# 'stats_collector': 'xpaw.stats.StatsCollector',
# 'queue': 'xpaw.queue.PriorityQueue',
# 'dupe_filter': 'xpaw.dupefilter.HashDupeFilter',
# 'default_extensions': [
# 'xpaw.extensions.DefaultHeadersMiddleware',
# 'xpaw.extensions.UserAgentMiddleware',
# 'xpaw.extensions.RetryMiddleware',
# 'xpaw.extensions.ProxyMiddleware',
# 'xpaw.extensions.SpeedLimitMiddleware',
# 'xpaw.extensions.DepthMiddleware',
# ]
# }
. Output only the next line. | self.config = Config(DEFAULT_CONFIG, **kwargs) |
Predict the next line for this snippet: <|code_start|> assert stats.get('key2') == 1
stats.inc('key3', start=1)
assert stats.get('key3') == 2
stats.inc('key4', 2, start=3)
assert stats.get('key4') == 5
def test_clear_stats(self):
stats = StatsCollector()
stats.set('key1', 1)
stats.set('key2', 2)
assert stats.stats == {'key1': 1, 'key2': 2}
stats.clear()
assert stats.stats == {}
def test_set_stats(self):
stats = StatsCollector()
stats.set_stats({'key1': 1, 'key2': 2})
assert stats.stats == {'key1': 1, 'key2': 2}
def test_remove_key(self):
stats = StatsCollector()
stats.set('key', 'value')
assert stats.get('key') == 'value'
stats.remove('key')
assert stats.get('key') is None
assert stats.get('key', 'default') == 'default'
class TestDummyStatsCollector:
def test_set_value(self):
<|code_end|>
with the help of current file imports:
from xpaw.stats import StatsCollector, DummyStatsCollector
and context from other files:
# Path: xpaw/stats.py
# class StatsCollector:
# def __init__(self):
# self._stats = {}
#
# def get(self, key, default=None):
# return self._stats.get(key, default)
#
# def set(self, key, value):
# self._stats[key] = value
#
# def set_default(self, key, default=None):
# self._stats.setdefault(key, default)
#
# def set_min(self, key, value):
# self._stats[key] = min(self._stats.setdefault(key, value), value)
#
# def set_max(self, key, value):
# self._stats[key] = max(self._stats.setdefault(key, value), value)
#
# def inc(self, key, value=1, start=0):
# self._stats[key] = self._stats.setdefault(key, start) + value
#
# def clear(self):
# self._stats.clear()
#
# def remove(self, key):
# if key in self._stats:
# del self._stats[key]
#
# @property
# def stats(self):
# return self._stats
#
# def set_stats(self, stats):
# self._stats = stats
#
# class DummyStatsCollector(StatsCollector):
# def get(self, key, default=None):
# return default
#
# def set(self, key, value):
# pass
#
# def set_default(self, key, default=None):
# pass
#
# def set_min(self, key, value):
# pass
#
# def set_max(self, key, value):
# pass
#
# def inc(self, key, value=1, start=0):
# pass
#
# def set_stats(self, stats):
# pass
, which may contain function names, class names, or code. Output only the next line. | stats = DummyStatsCollector() |
Using the snippet: <|code_start|># coding=utf-8
log = logging.getLogger(__name__)
__all__ = ['DepthMiddleware']
class DepthMiddleware:
def __init__(self, max_depth=None):
self._max_depth = max_depth
def __repr__(self):
cls_name = self.__class__.__name__
return '{}(max_depth={})'.format(cls_name, repr(self._max_depth))
@classmethod
def from_crawler(cls, crawler):
config = crawler.config
max_depth = config.getint('max_depth')
return cls(max_depth=max_depth)
def handle_spider_output(self, response, result):
depth = response.meta.get('depth', 0) + 1
for r in result:
<|code_end|>
, determine the next line of code. You have imports:
import logging
from xpaw.http import HttpRequest
and context (class names, function names, or code) available:
# Path: xpaw/http.py
# class HttpRequest:
# def __init__(self, url, method="GET", body=None, params=None, headers=None, proxy=None,
# timeout=20, verify_ssl=False, allow_redirects=True, auth=None, proxy_auth=None,
# priority=None, dont_filter=False, callback=None, errback=None, meta=None,
# render=None):
# """
# Construct an HTTP request.
# """
# self.url = make_url(url, params)
# self.method = method
# self.body = body
# self.headers = headers
# self.proxy = proxy
# self.timeout = timeout
# self.verify_ssl = verify_ssl
# self.allow_redirects = allow_redirects
# self.auth = auth
# self.proxy_auth = proxy_auth
# self.priority = priority
# self.dont_filter = dont_filter
# self.callback = callback
# self.errback = errback
# self._meta = dict(meta) if meta else {}
# self.render = render
#
# def __str__(self):
# return '<{}, {}>'.format(self.method, self.url)
#
# __repr__ = __str__
#
# @property
# def meta(self):
# return self._meta
#
# def copy(self):
# return self.replace()
#
# def replace(self, **kwargs):
# for i in ["url", "method", "body", "headers", "proxy",
# "timeout", "verify_ssl", "allow_redirects", "auth", "proxy_auth",
# "priority", "dont_filter", "callback", "errback", "meta",
# "render"]:
# kwargs.setdefault(i, getattr(self, i))
# return type(self)(**kwargs)
#
# def to_dict(self):
# callback = self.callback
# if inspect.ismethod(callback):
# callback = callback.__name__
# errback = self.errback
# if inspect.ismethod(errback):
# errback = errback.__name__
# d = {
# 'url': self.url,
# 'method': self.method,
# 'body': self.body,
# 'headers': self.headers,
# 'proxy': self.proxy,
# 'timeout': self.timeout,
# 'verify_ssl': self.verify_ssl,
# 'allow_redirects': self.allow_redirects,
# 'auth': self.auth,
# 'proxy_auth': self.proxy_auth,
# 'priority': self.priority,
# 'dont_filter': self.dont_filter,
# 'callback': callback,
# 'errback': errback,
# 'meta': self.meta,
# 'render': self.render
# }
# return d
#
# @classmethod
# def from_dict(cls, d):
# return cls(**d)
. Output only the next line. | if isinstance(r, HttpRequest): |
Using the snippet: <|code_start|># coding=utf-8
class FooSpider(Spider):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.data = self.config['data']
def open(self):
super().open()
self.data['open'] = ''
def close(self):
super().close()
self.data['close'] = ''
@pytest.mark.asyncio
async def test_spider():
data = {}
crawler = Crawler(data=data)
spider = FooSpider.from_crawler(crawler)
<|code_end|>
, determine the next line of code. You have imports:
import pytest
from xpaw.spider import Spider
from xpaw import events
from .crawler import Crawler
and context (class names, function names, or code) available:
# Path: xpaw/spider.py
# class Spider:
#
# @classmethod
# def from_crawler(cls, crawler):
# cls.crawler = crawler
# cls.config = crawler.config
# spider = cls()
# crawler.event_bus.subscribe(spider.open, events.crawler_start)
# crawler.event_bus.subscribe(spider.close, events.crawler_shutdown)
# return spider
#
# @property
# def logger(self):
# return log
#
# def log(self, message, *args, level=logging.INFO, **kwargs):
# self.logger.log(level, message, *args, **kwargs)
#
# def parse(self, response):
# raise NotImplementedError
#
# def start_requests(self):
# raise NotImplementedError
#
# def open(self):
# pass
#
# def close(self):
# pass
#
# async def request_success(self, response):
# callback = response.request.callback
# if callback:
# res = self._get_mothod(callback)(response)
# else:
# res = self.parse(response)
# if inspect.iscoroutine(res):
# res = await res
# return res
#
# async def request_error(self, request, error):
# try:
# if request and request.errback:
# r = self._get_mothod(request.errback)(request, error)
# if inspect.iscoroutine(r):
# await r
# except CancelledError:
# raise
# except Exception:
# log.warning("Error occurred in the error callback of spider", exc_info=True)
#
# def _get_mothod(self, method):
# if isinstance(method, str):
# method = getattr(self, method)
# return method
#
# Path: xpaw/events.py
#
# Path: tests/crawler.py
# class Crawler:
# def __init__(self, **kwargs):
# self.event_bus = EventBus()
# self.config = Config(DEFAULT_CONFIG, **kwargs)
. Output only the next line. | await crawler.event_bus.send(events.crawler_start) |
Continue the code snippet: <|code_start|># coding=utf-8
class FooSpider(Spider):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.data = self.config['data']
def open(self):
super().open()
self.data['open'] = ''
def close(self):
super().close()
self.data['close'] = ''
@pytest.mark.asyncio
async def test_spider():
data = {}
<|code_end|>
. Use current file imports:
import pytest
from xpaw.spider import Spider
from xpaw import events
from .crawler import Crawler
and context (classes, functions, or code) from other files:
# Path: xpaw/spider.py
# class Spider:
#
# @classmethod
# def from_crawler(cls, crawler):
# cls.crawler = crawler
# cls.config = crawler.config
# spider = cls()
# crawler.event_bus.subscribe(spider.open, events.crawler_start)
# crawler.event_bus.subscribe(spider.close, events.crawler_shutdown)
# return spider
#
# @property
# def logger(self):
# return log
#
# def log(self, message, *args, level=logging.INFO, **kwargs):
# self.logger.log(level, message, *args, **kwargs)
#
# def parse(self, response):
# raise NotImplementedError
#
# def start_requests(self):
# raise NotImplementedError
#
# def open(self):
# pass
#
# def close(self):
# pass
#
# async def request_success(self, response):
# callback = response.request.callback
# if callback:
# res = self._get_mothod(callback)(response)
# else:
# res = self.parse(response)
# if inspect.iscoroutine(res):
# res = await res
# return res
#
# async def request_error(self, request, error):
# try:
# if request and request.errback:
# r = self._get_mothod(request.errback)(request, error)
# if inspect.iscoroutine(r):
# await r
# except CancelledError:
# raise
# except Exception:
# log.warning("Error occurred in the error callback of spider", exc_info=True)
#
# def _get_mothod(self, method):
# if isinstance(method, str):
# method = getattr(self, method)
# return method
#
# Path: xpaw/events.py
#
# Path: tests/crawler.py
# class Crawler:
# def __init__(self, **kwargs):
# self.event_bus = EventBus()
# self.config = Config(DEFAULT_CONFIG, **kwargs)
. Output only the next line. | crawler = Crawler(data=data) |
Using the snippet: <|code_start|> default_arguments = ['--headless', '--incognito', '--ignore-certificate-errors', '--ignore-ssl-errors',
'--disable-gpu', '--no-sandbox']
default_prefs = {'profile.managed_default_content_settings.images': 2}
def __init__(self, options=None):
self.options = {'default': self.make_chrome_options()}
if options:
for k, v in options.items():
self.options[k] = self.make_chrome_options(arguments=v.get('arguments'),
experimental_options=v.get('experimental_options'))
self.available_drivers = {}
for name in self.options.keys():
self.available_drivers[name] = deque()
async def fetch(self, request):
lock = asyncio.Future()
t = Thread(target=self._run_fetch_thread, args=(asyncio.get_event_loop(), lock, request))
t.start()
await lock
result = lock.result()
if isinstance(result, Exception):
raise result
return result
def _run_fetch_thread(self, loop, lock, request):
driver_instance = None
try:
driver_instance = self.get_driver_instance(request)
driver = driver_instance.driver
driver.get(request.url)
<|code_end|>
, determine the next line of code. You have imports:
import asyncio
import logging
from threading import Thread
from collections import deque
from selenium.webdriver import Chrome, ChromeOptions
from .http import HttpResponse, HttpHeaders
and context (class names, function names, or code) available:
# Path: xpaw/http.py
# class HttpRequest:
# class HttpResponse:
# def __init__(self, url, method="GET", body=None, params=None, headers=None, proxy=None,
# timeout=20, verify_ssl=False, allow_redirects=True, auth=None, proxy_auth=None,
# priority=None, dont_filter=False, callback=None, errback=None, meta=None,
# render=None):
# def __str__(self):
# def meta(self):
# def copy(self):
# def replace(self, **kwargs):
# def to_dict(self):
# def from_dict(cls, d):
# def __init__(self, url, status, body=None, headers=None,
# request=None, encoding=None):
# def __str__(self):
# def encoding(self):
# def encoding(self, value):
# def text(self):
# def meta(self):
# def copy(self):
# def replace(self, **kwargs):
. Output only the next line. | response = HttpResponse(driver.current_url, 200, body=driver.page_source.encode('utf-8'), |
Predict the next line after this snippet: <|code_start|> '--disable-gpu', '--no-sandbox']
default_prefs = {'profile.managed_default_content_settings.images': 2}
def __init__(self, options=None):
self.options = {'default': self.make_chrome_options()}
if options:
for k, v in options.items():
self.options[k] = self.make_chrome_options(arguments=v.get('arguments'),
experimental_options=v.get('experimental_options'))
self.available_drivers = {}
for name in self.options.keys():
self.available_drivers[name] = deque()
async def fetch(self, request):
lock = asyncio.Future()
t = Thread(target=self._run_fetch_thread, args=(asyncio.get_event_loop(), lock, request))
t.start()
await lock
result = lock.result()
if isinstance(result, Exception):
raise result
return result
def _run_fetch_thread(self, loop, lock, request):
driver_instance = None
try:
driver_instance = self.get_driver_instance(request)
driver = driver_instance.driver
driver.get(request.url)
response = HttpResponse(driver.current_url, 200, body=driver.page_source.encode('utf-8'),
<|code_end|>
using the current file's imports:
import asyncio
import logging
from threading import Thread
from collections import deque
from selenium.webdriver import Chrome, ChromeOptions
from .http import HttpResponse, HttpHeaders
and any relevant context from other files:
# Path: xpaw/http.py
# class HttpRequest:
# class HttpResponse:
# def __init__(self, url, method="GET", body=None, params=None, headers=None, proxy=None,
# timeout=20, verify_ssl=False, allow_redirects=True, auth=None, proxy_auth=None,
# priority=None, dont_filter=False, callback=None, errback=None, meta=None,
# render=None):
# def __str__(self):
# def meta(self):
# def copy(self):
# def replace(self, **kwargs):
# def to_dict(self):
# def from_dict(cls, d):
# def __init__(self, url, status, body=None, headers=None,
# request=None, encoding=None):
# def __str__(self):
# def encoding(self):
# def encoding(self, value):
# def text(self):
# def meta(self):
# def copy(self):
# def replace(self, **kwargs):
. Output only the next line. | headers=HttpHeaders(), request=request) |
Here is a snippet: <|code_start|> chrome_options.add_argument('--ignore-certificate-errors')
chrome_options.add_argument('--ignore-ssl-errors')
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('--no-sandbox')
prefs = {'profile.managed_default_content_settings.images': 2}
chrome_options.add_experimental_option('prefs', prefs)
return chrome_options
def create_chrome_driver():
driver = Chrome(options=make_chrome_options())
driver.set_page_load_timeout(10)
driver.set_script_timeout(10)
driver.implicitly_wait(10)
return driver
def reopen_chrome_thread(sem):
driver = None
try:
driver = create_chrome_driver()
driver.get(TEST_URL)
except Exception as e:
print(e)
finally:
if driver:
driver.quit()
sem.release()
<|code_end|>
. Write the next line using the current file imports:
from threading import Thread, Semaphore
from collections import deque
from selenium.webdriver import Chrome, ChromeOptions
from benchmarks.utils import log_time
and context from other files:
# Path: benchmarks/utils.py
# def log_time(name):
# def wrapper(func):
# def run(*args, **kwargs):
# start = time.time()
# res = func(*args, **kwargs)
# print('The execution time of {}: {}'.format(name, time.time() - start))
# return res
#
# return run
#
# return wrapper
, which may include functions, classes, or code. Output only the next line. | @log_time('reopen chrome') |
Predict the next line for this snippet: <|code_start|># coding=utf-8
@pytest.mark.asyncio
async def test_fifo_queue():
q = FifoQueue()
with pytest.raises(asyncio.TimeoutError):
with async_timeout.timeout(0.1):
await q.pop()
obj_list = [HttpRequest('1'), HttpRequest('2'), HttpRequest('3')]
for o in obj_list:
await q.push(o)
for i in range(len(obj_list)):
assert await q.pop() == obj_list[i]
with pytest.raises(asyncio.TimeoutError):
with async_timeout.timeout(0.1):
await q.pop()
@pytest.mark.asyncio
async def test_lifo_queue():
<|code_end|>
with the help of current file imports:
import asyncio
import pytest
import async_timeout
from xpaw.queue import FifoQueue, LifoQueue, PriorityQueue
from xpaw.http import HttpRequest
and context from other files:
# Path: xpaw/queue.py
# class FifoQueue:
# def __init__(self):
# self._queue = deque()
# self._semaphore = Semaphore(0)
#
# def __len__(self):
# return len(self._queue)
#
# async def push(self, request):
# self._queue.append(request)
# self._semaphore.release()
#
# async def pop(self):
# await self._semaphore.acquire()
# return self._queue.popleft()
#
# class LifoQueue(FifoQueue):
# async def pop(self):
# await self._semaphore.acquire()
# return self._queue.pop()
#
# class PriorityQueue:
# def __init__(self):
# self._queue = []
# self._semaphore = Semaphore(0)
#
# def __len__(self):
# return len(self._queue)
#
# async def push(self, request):
# heappush(self._queue, _PriorityQueueItem(request))
# self._semaphore.release()
#
# async def pop(self):
# await self._semaphore.acquire()
# item = heappop(self._queue)
# return item.request
#
# Path: xpaw/http.py
# class HttpRequest:
# def __init__(self, url, method="GET", body=None, params=None, headers=None, proxy=None,
# timeout=20, verify_ssl=False, allow_redirects=True, auth=None, proxy_auth=None,
# priority=None, dont_filter=False, callback=None, errback=None, meta=None,
# render=None):
# """
# Construct an HTTP request.
# """
# self.url = make_url(url, params)
# self.method = method
# self.body = body
# self.headers = headers
# self.proxy = proxy
# self.timeout = timeout
# self.verify_ssl = verify_ssl
# self.allow_redirects = allow_redirects
# self.auth = auth
# self.proxy_auth = proxy_auth
# self.priority = priority
# self.dont_filter = dont_filter
# self.callback = callback
# self.errback = errback
# self._meta = dict(meta) if meta else {}
# self.render = render
#
# def __str__(self):
# return '<{}, {}>'.format(self.method, self.url)
#
# __repr__ = __str__
#
# @property
# def meta(self):
# return self._meta
#
# def copy(self):
# return self.replace()
#
# def replace(self, **kwargs):
# for i in ["url", "method", "body", "headers", "proxy",
# "timeout", "verify_ssl", "allow_redirects", "auth", "proxy_auth",
# "priority", "dont_filter", "callback", "errback", "meta",
# "render"]:
# kwargs.setdefault(i, getattr(self, i))
# return type(self)(**kwargs)
#
# def to_dict(self):
# callback = self.callback
# if inspect.ismethod(callback):
# callback = callback.__name__
# errback = self.errback
# if inspect.ismethod(errback):
# errback = errback.__name__
# d = {
# 'url': self.url,
# 'method': self.method,
# 'body': self.body,
# 'headers': self.headers,
# 'proxy': self.proxy,
# 'timeout': self.timeout,
# 'verify_ssl': self.verify_ssl,
# 'allow_redirects': self.allow_redirects,
# 'auth': self.auth,
# 'proxy_auth': self.proxy_auth,
# 'priority': self.priority,
# 'dont_filter': self.dont_filter,
# 'callback': callback,
# 'errback': errback,
# 'meta': self.meta,
# 'render': self.render
# }
# return d
#
# @classmethod
# def from_dict(cls, d):
# return cls(**d)
, which may contain function names, class names, or code. Output only the next line. | q = LifoQueue() |
Continue the code snippet: <|code_start|> assert await q.pop() == obj_list[i]
with pytest.raises(asyncio.TimeoutError):
with async_timeout.timeout(0.1):
await q.pop()
@pytest.mark.asyncio
async def test_lifo_queue():
q = LifoQueue()
with pytest.raises(asyncio.TimeoutError):
with async_timeout.timeout(0.1):
await q.pop()
obj_list = [HttpRequest('1'), HttpRequest('2'), HttpRequest('3')]
for o in obj_list:
await q.push(o)
for i in range(len(obj_list)):
assert await q.pop() == obj_list[len(obj_list) - i - 1]
with pytest.raises(asyncio.TimeoutError):
with async_timeout.timeout(0.1):
await q.pop()
@pytest.mark.asyncio
async def test_priority_queue():
item1_1 = HttpRequest('1_1', priority=1)
item1_2 = HttpRequest('1_2', priority=1)
item2_1 = HttpRequest('2_1', priority=2)
item2_2 = HttpRequest('2_2', priority=2)
item3_1 = HttpRequest('3_1', priority=3)
item3_2 = HttpRequest('3_2', priority=3)
<|code_end|>
. Use current file imports:
import asyncio
import pytest
import async_timeout
from xpaw.queue import FifoQueue, LifoQueue, PriorityQueue
from xpaw.http import HttpRequest
and context (classes, functions, or code) from other files:
# Path: xpaw/queue.py
# class FifoQueue:
# def __init__(self):
# self._queue = deque()
# self._semaphore = Semaphore(0)
#
# def __len__(self):
# return len(self._queue)
#
# async def push(self, request):
# self._queue.append(request)
# self._semaphore.release()
#
# async def pop(self):
# await self._semaphore.acquire()
# return self._queue.popleft()
#
# class LifoQueue(FifoQueue):
# async def pop(self):
# await self._semaphore.acquire()
# return self._queue.pop()
#
# class PriorityQueue:
# def __init__(self):
# self._queue = []
# self._semaphore = Semaphore(0)
#
# def __len__(self):
# return len(self._queue)
#
# async def push(self, request):
# heappush(self._queue, _PriorityQueueItem(request))
# self._semaphore.release()
#
# async def pop(self):
# await self._semaphore.acquire()
# item = heappop(self._queue)
# return item.request
#
# Path: xpaw/http.py
# class HttpRequest:
# def __init__(self, url, method="GET", body=None, params=None, headers=None, proxy=None,
# timeout=20, verify_ssl=False, allow_redirects=True, auth=None, proxy_auth=None,
# priority=None, dont_filter=False, callback=None, errback=None, meta=None,
# render=None):
# """
# Construct an HTTP request.
# """
# self.url = make_url(url, params)
# self.method = method
# self.body = body
# self.headers = headers
# self.proxy = proxy
# self.timeout = timeout
# self.verify_ssl = verify_ssl
# self.allow_redirects = allow_redirects
# self.auth = auth
# self.proxy_auth = proxy_auth
# self.priority = priority
# self.dont_filter = dont_filter
# self.callback = callback
# self.errback = errback
# self._meta = dict(meta) if meta else {}
# self.render = render
#
# def __str__(self):
# return '<{}, {}>'.format(self.method, self.url)
#
# __repr__ = __str__
#
# @property
# def meta(self):
# return self._meta
#
# def copy(self):
# return self.replace()
#
# def replace(self, **kwargs):
# for i in ["url", "method", "body", "headers", "proxy",
# "timeout", "verify_ssl", "allow_redirects", "auth", "proxy_auth",
# "priority", "dont_filter", "callback", "errback", "meta",
# "render"]:
# kwargs.setdefault(i, getattr(self, i))
# return type(self)(**kwargs)
#
# def to_dict(self):
# callback = self.callback
# if inspect.ismethod(callback):
# callback = callback.__name__
# errback = self.errback
# if inspect.ismethod(errback):
# errback = errback.__name__
# d = {
# 'url': self.url,
# 'method': self.method,
# 'body': self.body,
# 'headers': self.headers,
# 'proxy': self.proxy,
# 'timeout': self.timeout,
# 'verify_ssl': self.verify_ssl,
# 'allow_redirects': self.allow_redirects,
# 'auth': self.auth,
# 'proxy_auth': self.proxy_auth,
# 'priority': self.priority,
# 'dont_filter': self.dont_filter,
# 'callback': callback,
# 'errback': errback,
# 'meta': self.meta,
# 'render': self.render
# }
# return d
#
# @classmethod
# def from_dict(cls, d):
# return cls(**d)
. Output only the next line. | q = PriorityQueue() |
Given the following code snippet before the placeholder: <|code_start|># coding=utf-8
@pytest.mark.asyncio
async def test_fifo_queue():
q = FifoQueue()
with pytest.raises(asyncio.TimeoutError):
with async_timeout.timeout(0.1):
await q.pop()
<|code_end|>
, predict the next line using imports from the current file:
import asyncio
import pytest
import async_timeout
from xpaw.queue import FifoQueue, LifoQueue, PriorityQueue
from xpaw.http import HttpRequest
and context including class names, function names, and sometimes code from other files:
# Path: xpaw/queue.py
# class FifoQueue:
# def __init__(self):
# self._queue = deque()
# self._semaphore = Semaphore(0)
#
# def __len__(self):
# return len(self._queue)
#
# async def push(self, request):
# self._queue.append(request)
# self._semaphore.release()
#
# async def pop(self):
# await self._semaphore.acquire()
# return self._queue.popleft()
#
# class LifoQueue(FifoQueue):
# async def pop(self):
# await self._semaphore.acquire()
# return self._queue.pop()
#
# class PriorityQueue:
# def __init__(self):
# self._queue = []
# self._semaphore = Semaphore(0)
#
# def __len__(self):
# return len(self._queue)
#
# async def push(self, request):
# heappush(self._queue, _PriorityQueueItem(request))
# self._semaphore.release()
#
# async def pop(self):
# await self._semaphore.acquire()
# item = heappop(self._queue)
# return item.request
#
# Path: xpaw/http.py
# class HttpRequest:
# def __init__(self, url, method="GET", body=None, params=None, headers=None, proxy=None,
# timeout=20, verify_ssl=False, allow_redirects=True, auth=None, proxy_auth=None,
# priority=None, dont_filter=False, callback=None, errback=None, meta=None,
# render=None):
# """
# Construct an HTTP request.
# """
# self.url = make_url(url, params)
# self.method = method
# self.body = body
# self.headers = headers
# self.proxy = proxy
# self.timeout = timeout
# self.verify_ssl = verify_ssl
# self.allow_redirects = allow_redirects
# self.auth = auth
# self.proxy_auth = proxy_auth
# self.priority = priority
# self.dont_filter = dont_filter
# self.callback = callback
# self.errback = errback
# self._meta = dict(meta) if meta else {}
# self.render = render
#
# def __str__(self):
# return '<{}, {}>'.format(self.method, self.url)
#
# __repr__ = __str__
#
# @property
# def meta(self):
# return self._meta
#
# def copy(self):
# return self.replace()
#
# def replace(self, **kwargs):
# for i in ["url", "method", "body", "headers", "proxy",
# "timeout", "verify_ssl", "allow_redirects", "auth", "proxy_auth",
# "priority", "dont_filter", "callback", "errback", "meta",
# "render"]:
# kwargs.setdefault(i, getattr(self, i))
# return type(self)(**kwargs)
#
# def to_dict(self):
# callback = self.callback
# if inspect.ismethod(callback):
# callback = callback.__name__
# errback = self.errback
# if inspect.ismethod(errback):
# errback = errback.__name__
# d = {
# 'url': self.url,
# 'method': self.method,
# 'body': self.body,
# 'headers': self.headers,
# 'proxy': self.proxy,
# 'timeout': self.timeout,
# 'verify_ssl': self.verify_ssl,
# 'allow_redirects': self.allow_redirects,
# 'auth': self.auth,
# 'proxy_auth': self.proxy_auth,
# 'priority': self.priority,
# 'dont_filter': self.dont_filter,
# 'callback': callback,
# 'errback': errback,
# 'meta': self.meta,
# 'render': self.render
# }
# return d
#
# @classmethod
# def from_dict(cls, d):
# return cls(**d)
. Output only the next line. | obj_list = [HttpRequest('1'), HttpRequest('2'), HttpRequest('3')] |
Next line prediction: <|code_start|> async def pop(self):
await self._semaphore.acquire()
return self._queue.pop()
class PriorityQueue:
def __init__(self):
self._queue = []
self._semaphore = Semaphore(0)
def __len__(self):
return len(self._queue)
async def push(self, request):
heappush(self._queue, _PriorityQueueItem(request))
self._semaphore.release()
async def pop(self):
await self._semaphore.acquire()
item = heappop(self._queue)
return item.request
class _PriorityQueueItem:
def __init__(self, request):
self.request = request
self.priority = self.request.priority or 0
self.now = time.time()
def __cmp__(self, other):
<|code_end|>
. Use current file imports:
(import time
import logging
from asyncio import Semaphore
from collections import deque
from heapq import heappush, heappop
from .utils import cmp)
and context including class names, function names, or small code snippets from other files:
# Path: xpaw/utils.py
# def cmp(a, b):
# return (a > b) - (a < b)
. Output only the next line. | return cmp((-self.priority, self.now), (-other.priority, other.now)) |
Continue the code snippet: <|code_start|> r_get_dont_filter = HttpRequest("http://example.com", dont_filter=True)
r_get_dir = HttpRequest("http://example.com/")
r_get_post = HttpRequest("http://example.com/post")
r_post = HttpRequest("http://example.com/post", "POST")
r_post_dir = HttpRequest("http://example.com/post/", "POST")
r_post_data = HttpRequest("http://example.com/post", "POST", body=b'data')
r_get_param = HttpRequest(make_url("http://example.com/get", params={'k1': 'v1'}))
r_get_query = HttpRequest("http://example.com/get?k1=v1")
r_get_param_2 = HttpRequest(make_url("http://example.com/get", params={'k1': 'v1', 'k2': 'v2'}))
r_get_query_2 = HttpRequest("http://example.com/get?k2=v2&k1=v1")
r_get_query_param = HttpRequest(make_url("http://example.com/get?k1=v1", params={'k2': 'v2'}))
assert f.is_duplicated(r_get) is False
assert f.is_duplicated(r_get_port_80) is True
assert f.is_duplicated(r_get_port_81) is False
assert f.is_duplicated(r_get) is True
assert f.is_duplicated(r_get_dont_filter) is False
assert f.is_duplicated(r_get_dir) is False
assert f.is_duplicated(r_get_post) is False
assert f.is_duplicated(r_post) is False
assert f.is_duplicated(r_post_dir) is False
assert f.is_duplicated(r_post_data) is False
assert f.is_duplicated(r_get_param) is False
assert f.is_duplicated(r_get_query) is True
assert f.is_duplicated(r_get_param_2) is False
assert f.is_duplicated(r_get_query_2) is True
assert f.is_duplicated(r_get_query_param) is True
class TestHashDupeFilter:
def test_is_duplicated(self):
<|code_end|>
. Use current file imports:
from xpaw.http import HttpRequest
from xpaw.dupefilter import HashDupeFilter
from xpaw.utils import make_url
and context (classes, functions, or code) from other files:
# Path: xpaw/http.py
# class HttpRequest:
# def __init__(self, url, method="GET", body=None, params=None, headers=None, proxy=None,
# timeout=20, verify_ssl=False, allow_redirects=True, auth=None, proxy_auth=None,
# priority=None, dont_filter=False, callback=None, errback=None, meta=None,
# render=None):
# """
# Construct an HTTP request.
# """
# self.url = make_url(url, params)
# self.method = method
# self.body = body
# self.headers = headers
# self.proxy = proxy
# self.timeout = timeout
# self.verify_ssl = verify_ssl
# self.allow_redirects = allow_redirects
# self.auth = auth
# self.proxy_auth = proxy_auth
# self.priority = priority
# self.dont_filter = dont_filter
# self.callback = callback
# self.errback = errback
# self._meta = dict(meta) if meta else {}
# self.render = render
#
# def __str__(self):
# return '<{}, {}>'.format(self.method, self.url)
#
# __repr__ = __str__
#
# @property
# def meta(self):
# return self._meta
#
# def copy(self):
# return self.replace()
#
# def replace(self, **kwargs):
# for i in ["url", "method", "body", "headers", "proxy",
# "timeout", "verify_ssl", "allow_redirects", "auth", "proxy_auth",
# "priority", "dont_filter", "callback", "errback", "meta",
# "render"]:
# kwargs.setdefault(i, getattr(self, i))
# return type(self)(**kwargs)
#
# def to_dict(self):
# callback = self.callback
# if inspect.ismethod(callback):
# callback = callback.__name__
# errback = self.errback
# if inspect.ismethod(errback):
# errback = errback.__name__
# d = {
# 'url': self.url,
# 'method': self.method,
# 'body': self.body,
# 'headers': self.headers,
# 'proxy': self.proxy,
# 'timeout': self.timeout,
# 'verify_ssl': self.verify_ssl,
# 'allow_redirects': self.allow_redirects,
# 'auth': self.auth,
# 'proxy_auth': self.proxy_auth,
# 'priority': self.priority,
# 'dont_filter': self.dont_filter,
# 'callback': callback,
# 'errback': errback,
# 'meta': self.meta,
# 'render': self.render
# }
# return d
#
# @classmethod
# def from_dict(cls, d):
# return cls(**d)
#
# Path: xpaw/dupefilter.py
# class HashDupeFilter:
# def __init__(self):
# self._hash = set()
#
# def is_duplicated(self, request):
# if request.dont_filter:
# return False
# h = request_fingerprint(request)
# if h in self._hash:
# log.debug("%s is duplicated", request)
# return True
# self._hash.add(h)
# return False
#
# def clear(self):
# self._hash.clear()
#
# Path: xpaw/utils.py
# def make_url(url, params=None):
# args = []
# if isinstance(params, dict):
# for k, v in params.items():
# if isinstance(v, (tuple, list)):
# for i in v:
# args.append((k, i))
# else:
# args.append((k, v))
# elif isinstance(params, (tuple, list)):
# for k, v in params:
# args.append((k, v))
# return url_concat(url, args)
. Output only the next line. | run_any_dupe_filter(HashDupeFilter()) |
Using the snippet: <|code_start|># coding=utf-8
def run_any_dupe_filter(f):
r_get = HttpRequest("http://example.com")
r_get_port_80 = HttpRequest("http://example.com:80")
r_get_port_81 = HttpRequest("http://example.com:81")
r_get_dont_filter = HttpRequest("http://example.com", dont_filter=True)
r_get_dir = HttpRequest("http://example.com/")
r_get_post = HttpRequest("http://example.com/post")
r_post = HttpRequest("http://example.com/post", "POST")
r_post_dir = HttpRequest("http://example.com/post/", "POST")
r_post_data = HttpRequest("http://example.com/post", "POST", body=b'data')
<|code_end|>
, determine the next line of code. You have imports:
from xpaw.http import HttpRequest
from xpaw.dupefilter import HashDupeFilter
from xpaw.utils import make_url
and context (class names, function names, or code) available:
# Path: xpaw/http.py
# class HttpRequest:
# def __init__(self, url, method="GET", body=None, params=None, headers=None, proxy=None,
# timeout=20, verify_ssl=False, allow_redirects=True, auth=None, proxy_auth=None,
# priority=None, dont_filter=False, callback=None, errback=None, meta=None,
# render=None):
# """
# Construct an HTTP request.
# """
# self.url = make_url(url, params)
# self.method = method
# self.body = body
# self.headers = headers
# self.proxy = proxy
# self.timeout = timeout
# self.verify_ssl = verify_ssl
# self.allow_redirects = allow_redirects
# self.auth = auth
# self.proxy_auth = proxy_auth
# self.priority = priority
# self.dont_filter = dont_filter
# self.callback = callback
# self.errback = errback
# self._meta = dict(meta) if meta else {}
# self.render = render
#
# def __str__(self):
# return '<{}, {}>'.format(self.method, self.url)
#
# __repr__ = __str__
#
# @property
# def meta(self):
# return self._meta
#
# def copy(self):
# return self.replace()
#
# def replace(self, **kwargs):
# for i in ["url", "method", "body", "headers", "proxy",
# "timeout", "verify_ssl", "allow_redirects", "auth", "proxy_auth",
# "priority", "dont_filter", "callback", "errback", "meta",
# "render"]:
# kwargs.setdefault(i, getattr(self, i))
# return type(self)(**kwargs)
#
# def to_dict(self):
# callback = self.callback
# if inspect.ismethod(callback):
# callback = callback.__name__
# errback = self.errback
# if inspect.ismethod(errback):
# errback = errback.__name__
# d = {
# 'url': self.url,
# 'method': self.method,
# 'body': self.body,
# 'headers': self.headers,
# 'proxy': self.proxy,
# 'timeout': self.timeout,
# 'verify_ssl': self.verify_ssl,
# 'allow_redirects': self.allow_redirects,
# 'auth': self.auth,
# 'proxy_auth': self.proxy_auth,
# 'priority': self.priority,
# 'dont_filter': self.dont_filter,
# 'callback': callback,
# 'errback': errback,
# 'meta': self.meta,
# 'render': self.render
# }
# return d
#
# @classmethod
# def from_dict(cls, d):
# return cls(**d)
#
# Path: xpaw/dupefilter.py
# class HashDupeFilter:
# def __init__(self):
# self._hash = set()
#
# def is_duplicated(self, request):
# if request.dont_filter:
# return False
# h = request_fingerprint(request)
# if h in self._hash:
# log.debug("%s is duplicated", request)
# return True
# self._hash.add(h)
# return False
#
# def clear(self):
# self._hash.clear()
#
# Path: xpaw/utils.py
# def make_url(url, params=None):
# args = []
# if isinstance(params, dict):
# for k, v in params.items():
# if isinstance(v, (tuple, list)):
# for i in v:
# args.append((k, i))
# else:
# args.append((k, v))
# elif isinstance(params, (tuple, list)):
# for k, v in params:
# args.append((k, v))
# return url_concat(url, args)
. Output only the next line. | r_get_param = HttpRequest(make_url("http://example.com/get", params={'k1': 'v1'})) |
Next line prediction: <|code_start|># coding=utf-8
log = logging.getLogger(__name__)
__all__ = ['RetryMiddleware']
class RetryMiddleware:
<|code_end|>
. Use current file imports:
(import logging
from xpaw.errors import ClientError, NotEnabled, HttpError
from xpaw.utils import with_not_none_params)
and context including class names, function names, or small code snippets from other files:
# Path: xpaw/errors.py
# class ClientError(Exception):
# """
# Downloader client error.
# """
#
# class NotEnabled(Exception):
# """
# Not enabled.
# """
#
# class HttpError(Exception):
# """
# HTTP status is not 2xx.
# """
#
# def __init__(self, *args, response=None, **kwargs):
# self.response = response
# super().__init__(*args, **kwargs)
#
# Path: xpaw/utils.py
# def with_not_none_params(**kwargs):
# params = {}
# for k, v in kwargs.items():
# if v is not None:
# params[k] = v
# return params
. Output only the next line. | RETRY_ERRORS = (ClientError,) |
Predict the next line after this snippet: <|code_start|># coding=utf-8
log = logging.getLogger(__name__)
__all__ = ['RetryMiddleware']
class RetryMiddleware:
RETRY_ERRORS = (ClientError,)
RETRY_HTTP_STATUS = (500, 502, 503, 504, 408, 429)
def __init__(self, max_retry_times=3, retry_http_status=None):
self._max_retry_times = max_retry_times
self._retry_http_status = retry_http_status or self.RETRY_HTTP_STATUS
def __repr__(self):
cls_name = self.__class__.__name__
return '{}(max_retry_times={}, retry_http_status={})' \
.format(cls_name, repr(self._max_retry_times), repr(self._retry_http_status))
@classmethod
def from_crawler(cls, crawler):
config = crawler.config
if not config.getbool('retry_enabled'):
<|code_end|>
using the current file's imports:
import logging
from xpaw.errors import ClientError, NotEnabled, HttpError
from xpaw.utils import with_not_none_params
and any relevant context from other files:
# Path: xpaw/errors.py
# class ClientError(Exception):
# """
# Downloader client error.
# """
#
# class NotEnabled(Exception):
# """
# Not enabled.
# """
#
# class HttpError(Exception):
# """
# HTTP status is not 2xx.
# """
#
# def __init__(self, *args, response=None, **kwargs):
# self.response = response
# super().__init__(*args, **kwargs)
#
# Path: xpaw/utils.py
# def with_not_none_params(**kwargs):
# params = {}
# for k, v in kwargs.items():
# if v is not None:
# params[k] = v
# return params
. Output only the next line. | raise NotEnabled |
Given the following code snippet before the placeholder: <|code_start|> def handle_response(self, request, response):
for p in self._retry_http_status:
if self.match_status(p, response.status):
return self.retry(request, "HTTP status={}".format(response.status))
@staticmethod
def match_status(pattern, status):
if isinstance(pattern, int):
return pattern == status
verse = False
if pattern.startswith("!") or pattern.startswith("~"):
verse = True
pattern = pattern[1:]
s = str(status)
n = len(s)
match = True
if len(pattern) != n:
match = False
else:
for i in range(n):
if pattern[i] != "x" and pattern[i] != "X" and pattern[i] != s[i]:
match = False
break
if verse:
match = not match
return match
def handle_error(self, request, error):
if isinstance(error, self.RETRY_ERRORS):
return self.retry(request, error)
<|code_end|>
, predict the next line using imports from the current file:
import logging
from xpaw.errors import ClientError, NotEnabled, HttpError
from xpaw.utils import with_not_none_params
and context including class names, function names, and sometimes code from other files:
# Path: xpaw/errors.py
# class ClientError(Exception):
# """
# Downloader client error.
# """
#
# class NotEnabled(Exception):
# """
# Not enabled.
# """
#
# class HttpError(Exception):
# """
# HTTP status is not 2xx.
# """
#
# def __init__(self, *args, response=None, **kwargs):
# self.response = response
# super().__init__(*args, **kwargs)
#
# Path: xpaw/utils.py
# def with_not_none_params(**kwargs):
# params = {}
# for k, v in kwargs.items():
# if v is not None:
# params[k] = v
# return params
. Output only the next line. | if isinstance(error, HttpError): |
Here is a snippet: <|code_start|># coding=utf-8
log = logging.getLogger(__name__)
__all__ = ['RetryMiddleware']
class RetryMiddleware:
RETRY_ERRORS = (ClientError,)
RETRY_HTTP_STATUS = (500, 502, 503, 504, 408, 429)
def __init__(self, max_retry_times=3, retry_http_status=None):
self._max_retry_times = max_retry_times
self._retry_http_status = retry_http_status or self.RETRY_HTTP_STATUS
def __repr__(self):
cls_name = self.__class__.__name__
return '{}(max_retry_times={}, retry_http_status={})' \
.format(cls_name, repr(self._max_retry_times), repr(self._retry_http_status))
@classmethod
def from_crawler(cls, crawler):
config = crawler.config
if not config.getbool('retry_enabled'):
raise NotEnabled
<|code_end|>
. Write the next line using the current file imports:
import logging
from xpaw.errors import ClientError, NotEnabled, HttpError
from xpaw.utils import with_not_none_params
and context from other files:
# Path: xpaw/errors.py
# class ClientError(Exception):
# """
# Downloader client error.
# """
#
# class NotEnabled(Exception):
# """
# Not enabled.
# """
#
# class HttpError(Exception):
# """
# HTTP status is not 2xx.
# """
#
# def __init__(self, *args, response=None, **kwargs):
# self.response = response
# super().__init__(*args, **kwargs)
#
# Path: xpaw/utils.py
# def with_not_none_params(**kwargs):
# params = {}
# for k, v in kwargs.items():
# if v is not None:
# params[k] = v
# return params
, which may include functions, classes, or code. Output only the next line. | return cls(**with_not_none_params(max_retry_times=config.getint('max_retry_times'), |
Next line prediction: <|code_start|># coding=utf-8
class ListHeapPriorityQueue:
def __init__(self):
self.q = []
def push(self, item):
heappush(self.q, item)
def pop(self):
return heappop(self.q)
<|code_end|>
. Use current file imports:
(import random
from queue import PriorityQueue
from heapq import heappush, heappop
from benchmarks.utils import log_time)
and context including class names, function names, or small code snippets from other files:
# Path: benchmarks/utils.py
# def log_time(name):
# def wrapper(func):
# def run(*args, **kwargs):
# start = time.time()
# res = func(*args, **kwargs)
# print('The execution time of {}: {}'.format(name, time.time() - start))
# return res
#
# return run
#
# return wrapper
. Output only the next line. | @log_time('prepare benchmark data') |
Using the snippet: <|code_start|> 'values',
'cpt'
*V* : a dict
Notes
-----
"""
if file is not None:
bn = ior.read_bn(file)
self.V = bn.V
self.E = bn.E
self.F = bn.F
else:
if E is not None:
#assert (value_dict is not None), 'Must set values if E is set.'
self.set_structure(E, value_dict)
else:
self.V = []
self.E = {}
self.F = {}
def __eq__(self, y):
"""
Tests whether two Bayesian Networks are
equivalent - i.e. they contain the same
node/edge structure, and equality of
conditional probabilities.
"""
<|code_end|>
, determine the next line of code. You have imports:
from copy import copy, deepcopy
from pyBN.utils.class_equivalence import are_class_equivalent
from pyBN.utils.graph import topsort
import numpy as np
import pyBN.io.read as ior
and context (class names, function names, or code) available:
# Path: pyBN/utils/class_equivalence.py
# def are_class_equivalent(x,y):
# """
# Check whether two Bayesian networks belong
# to the same equivalence class.
# """
# are_equivalent = True
#
# if set(list(x.nodes())) != set(list(y.nodes())):
# are_equivalent = False
# else:
# for rv in x.nodes():
# rv_x_neighbors = set(x.parents(rv)) + set(y.children(rv))
# rv_y_neighbors = set(y.parents(rv)) + set(y.children(rv))
# if rv_x_neighbors != rv_y_neighbors:
# are_equivalent = False
# break
# return are_equivalent
#
# Path: pyBN/utils/graph.py
# def topsort(edge_dict, root=None):
# """
# List of nodes in topological sort order from edge dict
# where key = rv and value = list of rv's children
# """
# queue = []
# if root is not None:
# queue = [root]
# else:
# for rv in edge_dict.keys():
# prior=True
# for p in edge_dict.keys():
# if rv in edge_dict[p]:
# prior=False
# if prior==True:
# queue.append(rv)
#
# visited = []
# while queue:
# vertex = queue.pop(0)
# if vertex not in visited:
# visited.append(vertex)
# for nbr in edge_dict[vertex]:
# queue.append(nbr)
# #queue.extend(edge_dict[vertex]) # add all vertex's children
# return visited
. Output only the next line. | return are_class_equivalent(self, y)
|
Using the snippet: <|code_start|> skeleton after structure learning algorithms.
See "structure_learn" folder & algorithms
Arguments
---------
*edge_dict* : a dictionary,
where key = rv,
value = list of rv's children
NOTE: THIS MUST BE DIRECTED ALREADY!
*value_dict* : a dictionary,
where key = rv,
value = list of rv's possible values
Returns
-------
None
Effects
-------
- sets self.V in topsort order from edge_dict
- sets self.E
- creates self.F structure and sets the parents
Notes
-----
"""
<|code_end|>
, determine the next line of code. You have imports:
from copy import copy, deepcopy
from pyBN.utils.class_equivalence import are_class_equivalent
from pyBN.utils.graph import topsort
import numpy as np
import pyBN.io.read as ior
and context (class names, function names, or code) available:
# Path: pyBN/utils/class_equivalence.py
# def are_class_equivalent(x,y):
# """
# Check whether two Bayesian networks belong
# to the same equivalence class.
# """
# are_equivalent = True
#
# if set(list(x.nodes())) != set(list(y.nodes())):
# are_equivalent = False
# else:
# for rv in x.nodes():
# rv_x_neighbors = set(x.parents(rv)) + set(y.children(rv))
# rv_y_neighbors = set(y.parents(rv)) + set(y.children(rv))
# if rv_x_neighbors != rv_y_neighbors:
# are_equivalent = False
# break
# return are_equivalent
#
# Path: pyBN/utils/graph.py
# def topsort(edge_dict, root=None):
# """
# List of nodes in topological sort order from edge dict
# where key = rv and value = list of rv's children
# """
# queue = []
# if root is not None:
# queue = [root]
# else:
# for rv in edge_dict.keys():
# prior=True
# for p in edge_dict.keys():
# if rv in edge_dict[p]:
# prior=False
# if prior==True:
# queue.append(rv)
#
# visited = []
# while queue:
# vertex = queue.pop(0)
# if vertex not in visited:
# visited.append(vertex)
# for nbr in edge_dict[vertex]:
# queue.append(nbr)
# #queue.extend(edge_dict[vertex]) # add all vertex's children
# return visited
. Output only the next line. | self.V = topsort(edge_dict)
|
Predict the next line after this snippet: <|code_start|>"""
******************************
Conditional Independence Tests
for Constraint-based Learning
******************************
Implemented Constraint-based Tests
----------------------------------
- mutual information
- Pearson's X^2
I may consider putting this code into its own class structure. The
main benefit I could see from doing this would be the ability to
cache joint/marginal/conditional probabilities for expedited tests.
"""
__author__ = """Nicholas Cullen <ncullen.th@dartmouth.edu>"""
def are_independent(data, alpha=0.05, method='mi_test'):
pval = mi_test(data)
if pval < alpha:
return True
else:
return False
def mutual_information(data, conditional=False):
#bins = np.amax(data, axis=0)+1 # read levels for each variable
<|code_end|>
using the current file's imports:
import numpy as np
from scipy import stats
from pyBN.utils.data import unique_bins
and any relevant context from other files:
# Path: pyBN/utils/data.py
# def unique_bins(data):
# """
# Get the unique values for each column in a dataset.
# """
# bins = np.empty(len(data.T), dtype=np.int32)
# i = 0
# for col in data.T:
# bins[i] = len(np.unique(col))
# i+=1
# return bins
. Output only the next line. | bins = unique_bins(data) |
Continue the code snippet: <|code_start|>"""
********
UnitTest
Misc
********
"""
__author__ = """Nicholas Cullen <ncullen.th@dartmouth.edu>"""
class RandomSampleTestCase(unittest.TestCase):
def setUp(self):
self.dpath = os.path.join(dirname(dirname(dirname(dirname(__file__)))),'data')
self.bn = read_bn(os.path.join(self.dpath,'cancer.bif'))
def tearDown(self):
pass
def test_random_sample(self):
np.random.seed(3636)
<|code_end|>
. Use current file imports:
import unittest
import os
import numpy as np
from os.path import dirname
from pyBN.utils.random_sample import random_sample
from pyBN.readwrite.read import read_bn
and context (classes, functions, or code) from other files:
# Path: pyBN/utils/random_sample.py
# def random_sample(bn, n=1000):
# """
# Take a random sample of "n" observations from a
# BayesNet object. This is essentially just the
# forward sample algorithm that returns the samples.
#
# Parameters
# ----------
# *bn* : a BayesNet object from which to sample
#
# *n* : an integer
# The number of observations to take
#
# *evidence* : a dictionary, key=rv & value=instantiation
# Evidence to pass in
#
# Returns
# -------
# *sample_dict* : a list of samples, where each sample
# is a list of values in bn.nodes() (topsort) order
#
# Notes
# -----
#
# """
# sample = np.empty((n,bn.num_nodes()),dtype=np.int)
#
# rv_map = dict([(rv,idx) for idx,rv in enumerate(bn.nodes())])
# factor_map = dict([(rv,Factor(bn,rv)) for rv in bn.nodes()])
#
# for i in range(n):
# for rv in bn.nodes():
# f = deepcopy(factor_map[rv])
# # reduce_factor by parent samples
# for p in bn.parents(rv):
# f.reduce_factor(p,bn.values(p)[sample[i][rv_map[p]]])
# choice_vals = bn.values(rv)
# choice_probs = f.cpt
# chosen_val = np.random.choice(choice_vals, p=choice_probs)
# sample[i][rv_map[rv]] = bn.values(rv).index(chosen_val)
#
# return sample
. Output only the next line. | sample = random_sample(self.bn,5) |
Given the code snippet: <|code_start|> _T = range(n_rv)
else:
assert (not isinstance(feature_selection, list)), 'feature_selection must be only one value'
_T = [feature_selection]
# LEARN MARKOV BLANKET
for T in _T:
V = set(range(n_rv)) - {T}
Mb_change=True
# GROWING PHASE
while Mb_change:
Mb_change = False
cols = tuple({T}) + tuple(Mb[T])
H_tmb = entropy(data[:,cols])
# find X1_min in V-Mb[T]-{T} that minimizes
# entropy of T|X1_inMb[T]
# i.e. min of entropy(data[:,(T,X,Mb[T])])
min_val1, min_val2 = 1e7,1e7
min_x1, min_x2 = None, None
for X in V - Mb[T] - {T}:
cols = (T,X)+tuple(Mb[T])
ent_val = entropy(data[:,cols])
if ent_val < min_val:
min_val2, min_val1 = min_val1, ent_val
min_x2,min_x1 = min_x1, X
# if min_x1 is dependent on T given Mb[T]...
cols = (min_x1,T) + tuple(Mb[T])
<|code_end|>
, generate the next line using the imports in this file:
import numpy as np
from pyBN.utils.independence_tests import are_independent, entropy
and context (functions, classes, or occasionally code) from other files:
# Path: pyBN/utils/independence_tests.py
# def are_independent(data, alpha=0.05, method='mi_test'):
# pval = mi_test(data)
# if pval < alpha:
# return True
# else:
# return False
#
# def entropy(data):
# """
# In the context of structure learning, and more specifically
# in constraint-based algorithms which rely on the mutual information
# test for conditional independence, it has been proven that the variable
# X in a set which MAXIMIZES mutual information is also the variable which
# MINIMIZES entropy. This fact can be used to reduce the computational
# requirements of tests based on the following relationship:
#
# Entropy is related to marginal mutual information as follows:
# MI(X;Y) = H(X) - H(X|Y)
#
# Entropy is related to conditional mutual information as follows:
# MI(X;Y|Z) = H(X|Z) - H(X|Y,Z)
#
# For one varibale, H(X) is equal to the following:
# -1 * sum of p(x) * log(p(x))
#
# For two variables H(X|Y) is equal to the following:
# sum over x,y of p(x,y)*log(p(y)/p(x,y))
#
# For three variables, H(X|Y,Z) is equal to the following:
# -1 * sum of p(x,y,z) * log(p(x|y,z)),
# where p(x|y,z) = p(x,y,z)/p(y)*p(z)
# Arguments
# ----------
# *data* : a nested numpy array
# The data from which to learn - must have at least three
# variables. All conditioned variables (i.e. Z) are compressed
# into one variable.
#
# Returns
# -------
# *H* : entropy value
#
# """
# try:
# cols = data.shape[1]
# except IndexError:
# cols = 1
#
# #bins = np.amax(data,axis=0)
# bins = unique_bins(data)
#
# if cols == 1:
# hist,_ = np.histogramdd(data, bins=(bins)) # frequency counts
# Px = hist/hist.sum()
# H = -1 * np.sum( Px * np.log( Px ) )
#
# elif cols == 2: # two variables -> assume X then Y
# hist,_ = np.histogramdd(data, bins=bins[0:2]) # frequency counts
#
# Pxy = hist / hist.sum()# joint probability distribution over X,Y,Z
# Py = np.sum(Pxy, axis = 0) # P(Y)
# Py += 1e-7
# Pxy += 1e-7
# H = np.sum( Pxy * np.log( Py / Pxy ) )
#
# else:
# # CHECK FOR > 3 COLUMNS -> concatenate Z into one column
# if cols > 3:
# data = data.astype('str')
# ncols = len(bins)
# for i in range(len(data)):
# data[i,2] = ''.join(data[i,2:ncols])
# data = data.astype('int')[:,0:3]
#
# bins = np.amax(data,axis=0)
# hist,_ = np.histogramdd(data, bins=bins) # frequency counts
#
# Pxyz = hist / hist.sum()# joint probability distribution over X,Y,Z
# Pyz = np.sum(Pxyz, axis=0)
#
# Pxyz += 1e-7 # for log -inf
# Pyz += 1e-7
# H = -1 * np.sum( Pxyz * np.log( Pxyz ) ) + np.sum( Pyz * np.log( Pyz ) )
#
# return round(H,4)
. Output only the next line. | if are_independent(data[:,cols]): |
Based on the snippet: <|code_start|> Returns
-------
*bn* : a BayesNet object
Effects
-------
None
Notes
-----
"""
n_rv = data.shape[1]
Mb = dict([(rv,{}) for rv in range(n_rv)])
if feature_selection is None:
_T = range(n_rv)
else:
assert (not isinstance(feature_selection, list)), 'feature_selection must be only one value'
_T = [feature_selection]
# LEARN MARKOV BLANKET
for T in _T:
V = set(range(n_rv)) - {T}
Mb_change=True
# GROWING PHASE
while Mb_change:
Mb_change = False
cols = tuple({T}) + tuple(Mb[T])
<|code_end|>
, predict the immediate next line with the help of imports:
import numpy as np
from pyBN.utils.independence_tests import are_independent, entropy
and context (classes, functions, sometimes code) from other files:
# Path: pyBN/utils/independence_tests.py
# def are_independent(data, alpha=0.05, method='mi_test'):
# pval = mi_test(data)
# if pval < alpha:
# return True
# else:
# return False
#
# def entropy(data):
# """
# In the context of structure learning, and more specifically
# in constraint-based algorithms which rely on the mutual information
# test for conditional independence, it has been proven that the variable
# X in a set which MAXIMIZES mutual information is also the variable which
# MINIMIZES entropy. This fact can be used to reduce the computational
# requirements of tests based on the following relationship:
#
# Entropy is related to marginal mutual information as follows:
# MI(X;Y) = H(X) - H(X|Y)
#
# Entropy is related to conditional mutual information as follows:
# MI(X;Y|Z) = H(X|Z) - H(X|Y,Z)
#
# For one varibale, H(X) is equal to the following:
# -1 * sum of p(x) * log(p(x))
#
# For two variables H(X|Y) is equal to the following:
# sum over x,y of p(x,y)*log(p(y)/p(x,y))
#
# For three variables, H(X|Y,Z) is equal to the following:
# -1 * sum of p(x,y,z) * log(p(x|y,z)),
# where p(x|y,z) = p(x,y,z)/p(y)*p(z)
# Arguments
# ----------
# *data* : a nested numpy array
# The data from which to learn - must have at least three
# variables. All conditioned variables (i.e. Z) are compressed
# into one variable.
#
# Returns
# -------
# *H* : entropy value
#
# """
# try:
# cols = data.shape[1]
# except IndexError:
# cols = 1
#
# #bins = np.amax(data,axis=0)
# bins = unique_bins(data)
#
# if cols == 1:
# hist,_ = np.histogramdd(data, bins=(bins)) # frequency counts
# Px = hist/hist.sum()
# H = -1 * np.sum( Px * np.log( Px ) )
#
# elif cols == 2: # two variables -> assume X then Y
# hist,_ = np.histogramdd(data, bins=bins[0:2]) # frequency counts
#
# Pxy = hist / hist.sum()# joint probability distribution over X,Y,Z
# Py = np.sum(Pxy, axis = 0) # P(Y)
# Py += 1e-7
# Pxy += 1e-7
# H = np.sum( Pxy * np.log( Py / Pxy ) )
#
# else:
# # CHECK FOR > 3 COLUMNS -> concatenate Z into one column
# if cols > 3:
# data = data.astype('str')
# ncols = len(bins)
# for i in range(len(data)):
# data[i,2] = ''.join(data[i,2:ncols])
# data = data.astype('int')[:,0:3]
#
# bins = np.amax(data,axis=0)
# hist,_ = np.histogramdd(data, bins=bins) # frequency counts
#
# Pxyz = hist / hist.sum()# joint probability distribution over X,Y,Z
# Pyz = np.sum(Pxyz, axis=0)
#
# Pxyz += 1e-7 # for log -inf
# Pyz += 1e-7
# H = -1 * np.sum( Pxyz * np.log( Pxyz ) ) + np.sum( Pyz * np.log( Pyz ) )
#
# return round(H,4)
. Output only the next line. | H_tmb = entropy(data[:,cols]) |
Continue the code snippet: <|code_start|>#!/usr/bin/env python3
'''ARM multisample discarding extension for EGL.
This extension allows the multisample buffer of pixmap surface to be
marked as discardable. This is aimed at GPU hardware that does all
multisampled rendering internally and only writes downsampled data to
external memory, thus making the EGL multisample buffer redundant.
'''
# Copyright © 2014 Tim Pederick.
#
# This file is part of Pegl.
#
# Pegl is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Pegl is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
# License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Pegl. If not, see <http://www.gnu.org/licenses/>.
# Local imports.
# New surface attribute.
<|code_end|>
. Use current file imports:
from ..attribs.surface import SurfaceAttribs
from ..surface import PixmapSurface
and context (classes, functions, or code) from other files:
# Path: src/pegl/attribs/surface.py
# class SurfaceAttribs(Attribs):
# # For creating window surfaces.
# RENDER_BUFFER = ContextAttribs.RENDER_BUFFER
# # For creating Pbuffer surfaces.
# WIDTH, HEIGHT, LARGEST_PBUFFER = 0x3057, 0x3056, 0x3058
# TEXTURE_FORMAT, TEXTURE_TARGET, MIPMAP_TEXTURE = 0x3080, 0x3081, 0x3082
# # For creating all surfaces.
# VG_COLORSPACE, VG_ALPHA_FORMAT = 0x3087, 0x3088
# # For setting attributes of a surface.
# MIPMAP_LEVEL, MULTISAMPLE_RESOLVE, SWAP_BEHAVIOR = 0x3083, 0x3099, 0x3093
# # For querying attributes of a surface.
# CONFIG_ID = ConfigAttribs.CONFIG_ID
# HORIZONTAL_RESOLUTION, VERTICAL_RESOLUTION, PIXEL_ASPECT_RATIO = (0x3090,
# 0x3091,
# 0x3092)
# details = {RENDER_BUFFER: Details('Which buffer type this surface renders '
# 'into', RenderBufferTypes,
# RenderBufferTypes.BACK),
# WIDTH: Details('Width in pixels of the pbuffer', c_int, 0),
# HEIGHT: Details('Height in pixels of the pbuffer', c_int, 0),
# LARGEST_PBUFFER: Details('Whether or not to get the largest '
# 'available pbuffer if the requested '
# 'size is unavailable', bool, False),
# TEXTURE_FORMAT: Details('Format of the texture that the pbuffer '
# 'is bound to', TextureFormats,
# TextureFormats.NONE),
# TEXTURE_TARGET: Details('Target of the texture that the pbuffer '
# 'is bound to', TextureTargets,
# TextureTargets.NONE),
# MIPMAP_TEXTURE: Details('Whether or not mipmap space is '
# 'allocated', bool, False),
# VG_COLORSPACE: Details('The color space to be used by OpenVG',
# VGColorSpaces, VGColorSpaces.SRGB),
# VG_ALPHA_FORMAT: Details('Whether or not alpha values are '
# 'premultiplied by OpenVG',
# VGAlphaFormats, VGAlphaFormats.NONPRE),
# MIPMAP_LEVEL: Details('The level of the mipmap texture to '
# 'render', c_int, 0),
# MULTISAMPLE_RESOLVE: Details('The filter to use when resolving '
# 'the multisample buffer',
# MultisampleResolve,
# MultisampleResolve.DEFAULT),
# SWAP_BEHAVIOR: Details('Effect on color buffer upon a buffer '
# 'swap', SwapBehaviors,
# # The actual default is implementation-
# # defined, but since "preserved" behavior
# # needs its own bit flag in the config to
# # indicate support, "destroyed" seems
# # like a reasonable default to put here.
# SwapBehaviors.DESTROYED),
# CONFIG_ID: Details('The unique identifier of the configuration '
# 'used to create this surface', c_int, 0),
# HORIZONTAL_RESOLUTION: Details('Horizontal resolution of the '
# 'display, in pixels per metre',
# scaled, UNKNOWN_VALUE),
# VERTICAL_RESOLUTION: Details('Vertical resolution of the '
# 'display, in pixels per metre',
# scaled, UNKNOWN_VALUE),
# PIXEL_ASPECT_RATIO: Details('Ratio of physical pixel width to '
# 'height', scaled,
# UNKNOWN_VALUE)}
#
# Path: src/pegl/surface.py
# class PixmapSurface(Surface):
# '''Represents a surface that renders to a native pixmap.
#
# Instance attributes:
# shandle, display, config, attribs -- Inherited from Surface.
#
# '''
# def __init__(self, display, config, attribs, pixmap):
# '''Create the pixmap surface.
#
# Only the following attributes from SurfaceAttribs are accepted
# when creating a pixmap surface:
# * VG_COLORSPACE and VG_ALPHA_FORMAT (only used by OpenVG)
#
# Keyword arguments:
# display, config, attribs -- As the instance attributes.
# pixmap -- The native pixmap to render to.
#
# '''
# super().__init__(display, config, attribs)
# self.shandle = native.eglCreatePixmapSurface(self.display, self.config,
# pixmap, self.attribs)
. Output only the next line. | SurfaceAttribs.extend('DISCARD_SAMPLES', 0x3286, bool, False) |
Given the code snippet: <|code_start|>multisampled rendering internally and only writes downsampled data to
external memory, thus making the EGL multisample buffer redundant.
'''
# Copyright © 2014 Tim Pederick.
#
# This file is part of Pegl.
#
# Pegl is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Pegl is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
# License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Pegl. If not, see <http://www.gnu.org/licenses/>.
# Local imports.
# New surface attribute.
SurfaceAttribs.extend('DISCARD_SAMPLES', 0x3286, bool, False)
# Allow querying the new attribute on pixmap surfaces.
def samples_discardable(self):
'''Determine whether the multisample buffer is discardable.'''
return self._attr(SurfaceAttribs.DISCARD_SAMPLES)
<|code_end|>
, generate the next line using the imports in this file:
from ..attribs.surface import SurfaceAttribs
from ..surface import PixmapSurface
and context (functions, classes, or occasionally code) from other files:
# Path: src/pegl/attribs/surface.py
# class SurfaceAttribs(Attribs):
# # For creating window surfaces.
# RENDER_BUFFER = ContextAttribs.RENDER_BUFFER
# # For creating Pbuffer surfaces.
# WIDTH, HEIGHT, LARGEST_PBUFFER = 0x3057, 0x3056, 0x3058
# TEXTURE_FORMAT, TEXTURE_TARGET, MIPMAP_TEXTURE = 0x3080, 0x3081, 0x3082
# # For creating all surfaces.
# VG_COLORSPACE, VG_ALPHA_FORMAT = 0x3087, 0x3088
# # For setting attributes of a surface.
# MIPMAP_LEVEL, MULTISAMPLE_RESOLVE, SWAP_BEHAVIOR = 0x3083, 0x3099, 0x3093
# # For querying attributes of a surface.
# CONFIG_ID = ConfigAttribs.CONFIG_ID
# HORIZONTAL_RESOLUTION, VERTICAL_RESOLUTION, PIXEL_ASPECT_RATIO = (0x3090,
# 0x3091,
# 0x3092)
# details = {RENDER_BUFFER: Details('Which buffer type this surface renders '
# 'into', RenderBufferTypes,
# RenderBufferTypes.BACK),
# WIDTH: Details('Width in pixels of the pbuffer', c_int, 0),
# HEIGHT: Details('Height in pixels of the pbuffer', c_int, 0),
# LARGEST_PBUFFER: Details('Whether or not to get the largest '
# 'available pbuffer if the requested '
# 'size is unavailable', bool, False),
# TEXTURE_FORMAT: Details('Format of the texture that the pbuffer '
# 'is bound to', TextureFormats,
# TextureFormats.NONE),
# TEXTURE_TARGET: Details('Target of the texture that the pbuffer '
# 'is bound to', TextureTargets,
# TextureTargets.NONE),
# MIPMAP_TEXTURE: Details('Whether or not mipmap space is '
# 'allocated', bool, False),
# VG_COLORSPACE: Details('The color space to be used by OpenVG',
# VGColorSpaces, VGColorSpaces.SRGB),
# VG_ALPHA_FORMAT: Details('Whether or not alpha values are '
# 'premultiplied by OpenVG',
# VGAlphaFormats, VGAlphaFormats.NONPRE),
# MIPMAP_LEVEL: Details('The level of the mipmap texture to '
# 'render', c_int, 0),
# MULTISAMPLE_RESOLVE: Details('The filter to use when resolving '
# 'the multisample buffer',
# MultisampleResolve,
# MultisampleResolve.DEFAULT),
# SWAP_BEHAVIOR: Details('Effect on color buffer upon a buffer '
# 'swap', SwapBehaviors,
# # The actual default is implementation-
# # defined, but since "preserved" behavior
# # needs its own bit flag in the config to
# # indicate support, "destroyed" seems
# # like a reasonable default to put here.
# SwapBehaviors.DESTROYED),
# CONFIG_ID: Details('The unique identifier of the configuration '
# 'used to create this surface', c_int, 0),
# HORIZONTAL_RESOLUTION: Details('Horizontal resolution of the '
# 'display, in pixels per metre',
# scaled, UNKNOWN_VALUE),
# VERTICAL_RESOLUTION: Details('Vertical resolution of the '
# 'display, in pixels per metre',
# scaled, UNKNOWN_VALUE),
# PIXEL_ASPECT_RATIO: Details('Ratio of physical pixel width to '
# 'height', scaled,
# UNKNOWN_VALUE)}
#
# Path: src/pegl/surface.py
# class PixmapSurface(Surface):
# '''Represents a surface that renders to a native pixmap.
#
# Instance attributes:
# shandle, display, config, attribs -- Inherited from Surface.
#
# '''
# def __init__(self, display, config, attribs, pixmap):
# '''Create the pixmap surface.
#
# Only the following attributes from SurfaceAttribs are accepted
# when creating a pixmap surface:
# * VG_COLORSPACE and VG_ALPHA_FORMAT (only used by OpenVG)
#
# Keyword arguments:
# display, config, attribs -- As the instance attributes.
# pixmap -- The native pixmap to render to.
#
# '''
# super().__init__(display, config, attribs)
# self.shandle = native.eglCreatePixmapSurface(self.display, self.config,
# pixmap, self.attribs)
. Output only the next line. | PixmapSurface.samples_discardable = property(samples_discardable) |
Given snippet: <|code_start|>
# Subclass SyncAttribs to generate wider native values, and add the new sync
# attribute.
class WideSyncAttribs(SyncAttribs):
'''The set of attributes relevant to sync objects.
Unlike the superclass, SyncAttribs, this class uses a native type
that can fit any pointer, avoiding size issues on systems wider than
32 bits that fail to define their EGLint types as an appropriate
width.
Class attributes:
details -- As per the superclass, Attribs.
Additionally, symbolic constants for all the known attributes
are available as class attributes. Their names are the same as
in the extension specification, except without the EGL_ prefix
and _KHR suffix.
'''
_native_item = c_wideattr
_native_list = c_wideattr_list
WideSyncAttribs.extend('CL_EVENT_HANDLE', 0x309C, c_wideattr, None)
# New values for SyncTypes and SyncConditions.
# TODO: Replace the namedtuple instances with extensible enumerations.
SYNC_CL_EVENT = 0x30FE
SYNC_CL_EVENT_COMPLETE = 0x30FF
# New Sync subclass.
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from ctypes import c_int, c_int64, POINTER
from .khr_sync import FenceSync, SyncAttribs
and context:
# Path: src/pegl/ext/khr_sync.py
# class FenceSync(Sync):
# '''Represents the "fence" type of sync object.
#
# Class attributes:
# extension -- The name string of the fence sync extension.
# sync_type -- SyncTypes.FENCE.
#
# Instance attributes:
# synchandle, display, status, signaled, sync_type -- As per the
# superclass, Sync.
# attribs -- Always an empty AttribList.
# sync_condition -- The condition under which this sync object
# will be automatically set to signaled. A value from the
# SyncConditions tuple.
#
# '''
# extension = 'EGL_KHR_fence_sync'
# sync_type = SyncTypes.FENCE
#
# def __init__(self, display):
# '''Create the fence sync object.
#
# Keyword arguments:
# display -- As the instance attribute.
#
# '''
# # Fence sync objects have empty attribute lists.
# super().__init__(display, {})
#
# @property
# def sync_condition(self):
# '''Get the condition under which this sync object gets signaled.'''
# return self._attr(SyncAttribs.SYNC_CONDITION)
#
# class SyncAttribs(Attribs):
# '''The set of attributes relevant to sync objects.
#
# Class attributes:
# details -- As per the superclass, Attribs.
# Additionally, symbolic constants for all the known attributes
# are available as class attributes. Their names are the same as
# in the extension specification, except without the EGL_ prefix
# and _KHR suffix.
#
# '''
# # Only for querying; this is not set at creation, but can be toggled later.
# SYNC_STATUS = 0x30F1
# # Only for querying; at creation, this is passed as its own parameter.
# SYNC_TYPE = 0x30F7
# # As above, plus only valid for fence sync objects.
# SYNC_CONDITION = 0x30F8
#
# details = {SYNC_TYPE: Details('The type of this sync object', c_int, 0),
# SYNC_STATUS: Details('Which state this sync object is in',
# c_int, SyncStatus.UNSIGNALED),
# SYNC_CONDITION: Details('Under what condition this sync object '
# 'will be automatically signaled', c_int,
# SyncConditions.PRIOR_COMMANDS_COMPLETE)}
which might include code, classes, or functions. Output only the next line. | class OpenCLSync(FenceSync): |
Given the code snippet: <|code_start|># Pegl is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Pegl is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
# License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Pegl. If not, see <http://www.gnu.org/licenses/>.
# Standard library imports.
# Local imports.
# New native type. Note that the type EGLAttribKHR is actually defined to be an
# intptr_t, but as that's not supported in ctypes, a 64-bit integer will have
# to suffice. This might break on 128-bit systems(!).
c_wideattr = c_int64
c_wideattr_list = POINTER(c_int64)
# Get handle for the new extension function.
native_createsync = load_ext(b'eglCreateSync64KHR', c_sync,
(c_display, c_enum, c_wideattr_list),
fail_on=NO_SYNC)
# Subclass SyncAttribs to generate wider native values, and add the new sync
# attribute.
<|code_end|>
, generate the next line using the imports in this file:
from ctypes import c_int, c_int64, POINTER
from .khr_sync import FenceSync, SyncAttribs
and context (functions, classes, or occasionally code) from other files:
# Path: src/pegl/ext/khr_sync.py
# class FenceSync(Sync):
# '''Represents the "fence" type of sync object.
#
# Class attributes:
# extension -- The name string of the fence sync extension.
# sync_type -- SyncTypes.FENCE.
#
# Instance attributes:
# synchandle, display, status, signaled, sync_type -- As per the
# superclass, Sync.
# attribs -- Always an empty AttribList.
# sync_condition -- The condition under which this sync object
# will be automatically set to signaled. A value from the
# SyncConditions tuple.
#
# '''
# extension = 'EGL_KHR_fence_sync'
# sync_type = SyncTypes.FENCE
#
# def __init__(self, display):
# '''Create the fence sync object.
#
# Keyword arguments:
# display -- As the instance attribute.
#
# '''
# # Fence sync objects have empty attribute lists.
# super().__init__(display, {})
#
# @property
# def sync_condition(self):
# '''Get the condition under which this sync object gets signaled.'''
# return self._attr(SyncAttribs.SYNC_CONDITION)
#
# class SyncAttribs(Attribs):
# '''The set of attributes relevant to sync objects.
#
# Class attributes:
# details -- As per the superclass, Attribs.
# Additionally, symbolic constants for all the known attributes
# are available as class attributes. Their names are the same as
# in the extension specification, except without the EGL_ prefix
# and _KHR suffix.
#
# '''
# # Only for querying; this is not set at creation, but can be toggled later.
# SYNC_STATUS = 0x30F1
# # Only for querying; at creation, this is passed as its own parameter.
# SYNC_TYPE = 0x30F7
# # As above, plus only valid for fence sync objects.
# SYNC_CONDITION = 0x30F8
#
# details = {SYNC_TYPE: Details('The type of this sync object', c_int, 0),
# SYNC_STATUS: Details('Which state this sync object is in',
# c_int, SyncStatus.UNSIGNALED),
# SYNC_CONDITION: Details('Under what condition this sync object '
# 'will be automatically signaled', c_int,
# SyncConditions.PRIOR_COMMANDS_COMPLETE)}
. Output only the next line. | class WideSyncAttribs(SyncAttribs): |
Given the following code snippet before the placeholder: <|code_start|>#
# Pegl is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Pegl is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
# License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Pegl. If not, see <http://www.gnu.org/licenses/>.
# Standard library imports.
# Local imports.
# New symbolic constants.
NATIVE_FENCE = 0x3144
NATIVE_FENCE_SIGNALED = 0x3146
NO_NATIVE_FENCE_FD = -1
# TODO: Use a custom, extensible alternative to the namedtuple class, so that
# NATIVE_FENCE can be added to khr_sync.SyncTypes, and NATIVE_FENCE_SIGNALED
# to khr_sync.SyncConditions. Of course, I'm really only using those namedtuple
# instances as enumerations, and there's now a proper one of those in the
# standard library as of Python 3.3...
# Get handles of extension functions.
native_dupnativefence = load_ext(b'eglDupNativeFenceFDANDROID', c_int,
<|code_end|>
, predict the next line using imports from the current file:
from ctypes import c_int
from .khr_sync import c_sync, Sync, SyncAttribs
from ..native import c_display
and context including class names, function names, and sometimes code from other files:
# Path: src/pegl/ext/khr_sync.py
# NO_SYNC = c_void_p(0)
# FOREVER = 0xFFFFFFFFFFFFFFFF
# SYNC_STATUS = 0x30F1
# SYNC_TYPE = 0x30F7
# SYNC_CONDITION = 0x30F8
# TIMEOUT_EXPIRED, CONDITION_SATISFIED = 0x30F5, 0x30F6
# class WaitFlags(BitMask):
# class SyncAttribs(Attribs):
# class Sync:
# class ReusableSync(Sync):
# class FenceSync(Sync):
# def __init__(self, display, attribs):
# def _create_handle(self):
# def __del__(self):
# def _as_parameter_(self):
# def _attr(self, attr):
# def status(self):
# def sync_type(self):
# def signaled(self):
# def client_wait(self, timeout_ns=FOREVER, flush_commands=False):
# def __init__(self, display):
# def signal(self, signaled=True):
# def __init__(self, display):
# def sync_condition(self):
#
# Path: src/pegl/native.py
# def make_int_p(ival=0):
# def error_check(fn, fail_on=None, always_check=False, fallback_error=EGLError,
# fallback_msg=None, fail_on_null=False):
# def wrapped_fn(*args, **kwargs):
. Output only the next line. | (c_display, c_sync), fail_on=NO_NATIVE_FENCE_FD) |
Given the following code snippet before the placeholder: <|code_start|># Pegl is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
# License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Pegl. If not, see <http://www.gnu.org/licenses/>.
# Standard library imports.
# Local imports.
# New symbolic constants.
NATIVE_FENCE = 0x3144
NATIVE_FENCE_SIGNALED = 0x3146
NO_NATIVE_FENCE_FD = -1
# TODO: Use a custom, extensible alternative to the namedtuple class, so that
# NATIVE_FENCE can be added to khr_sync.SyncTypes, and NATIVE_FENCE_SIGNALED
# to khr_sync.SyncConditions. Of course, I'm really only using those namedtuple
# instances as enumerations, and there's now a proper one of those in the
# standard library as of Python 3.3...
# Get handles of extension functions.
native_dupnativefence = load_ext(b'eglDupNativeFenceFDANDROID', c_int,
(c_display, c_sync), fail_on=NO_NATIVE_FENCE_FD)
# New sync attribute.
SyncAttribs.extend('NATIVE_FENCE_FD', 0x3145, c_int, NO_NATIVE_FENCE_FD)
# New Sync subclass.
<|code_end|>
, predict the next line using imports from the current file:
from ctypes import c_int
from .khr_sync import c_sync, Sync, SyncAttribs
from ..native import c_display
and context including class names, function names, and sometimes code from other files:
# Path: src/pegl/ext/khr_sync.py
# NO_SYNC = c_void_p(0)
# FOREVER = 0xFFFFFFFFFFFFFFFF
# SYNC_STATUS = 0x30F1
# SYNC_TYPE = 0x30F7
# SYNC_CONDITION = 0x30F8
# TIMEOUT_EXPIRED, CONDITION_SATISFIED = 0x30F5, 0x30F6
# class WaitFlags(BitMask):
# class SyncAttribs(Attribs):
# class Sync:
# class ReusableSync(Sync):
# class FenceSync(Sync):
# def __init__(self, display, attribs):
# def _create_handle(self):
# def __del__(self):
# def _as_parameter_(self):
# def _attr(self, attr):
# def status(self):
# def sync_type(self):
# def signaled(self):
# def client_wait(self, timeout_ns=FOREVER, flush_commands=False):
# def __init__(self, display):
# def signal(self, signaled=True):
# def __init__(self, display):
# def sync_condition(self):
#
# Path: src/pegl/native.py
# def make_int_p(ival=0):
# def error_check(fn, fail_on=None, always_check=False, fallback_error=EGLError,
# fallback_msg=None, fail_on_null=False):
# def wrapped_fn(*args, **kwargs):
. Output only the next line. | class NativeFenceSync(Sync): |
Given the code snippet: <|code_start|># the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Pegl is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
# License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Pegl. If not, see <http://www.gnu.org/licenses/>.
# Standard library imports.
# Local imports.
# New symbolic constants.
NATIVE_FENCE = 0x3144
NATIVE_FENCE_SIGNALED = 0x3146
NO_NATIVE_FENCE_FD = -1
# TODO: Use a custom, extensible alternative to the namedtuple class, so that
# NATIVE_FENCE can be added to khr_sync.SyncTypes, and NATIVE_FENCE_SIGNALED
# to khr_sync.SyncConditions. Of course, I'm really only using those namedtuple
# instances as enumerations, and there's now a proper one of those in the
# standard library as of Python 3.3...
# Get handles of extension functions.
native_dupnativefence = load_ext(b'eglDupNativeFenceFDANDROID', c_int,
(c_display, c_sync), fail_on=NO_NATIVE_FENCE_FD)
# New sync attribute.
<|code_end|>
, generate the next line using the imports in this file:
from ctypes import c_int
from .khr_sync import c_sync, Sync, SyncAttribs
from ..native import c_display
and context (functions, classes, or occasionally code) from other files:
# Path: src/pegl/ext/khr_sync.py
# NO_SYNC = c_void_p(0)
# FOREVER = 0xFFFFFFFFFFFFFFFF
# SYNC_STATUS = 0x30F1
# SYNC_TYPE = 0x30F7
# SYNC_CONDITION = 0x30F8
# TIMEOUT_EXPIRED, CONDITION_SATISFIED = 0x30F5, 0x30F6
# class WaitFlags(BitMask):
# class SyncAttribs(Attribs):
# class Sync:
# class ReusableSync(Sync):
# class FenceSync(Sync):
# def __init__(self, display, attribs):
# def _create_handle(self):
# def __del__(self):
# def _as_parameter_(self):
# def _attr(self, attr):
# def status(self):
# def sync_type(self):
# def signaled(self):
# def client_wait(self, timeout_ns=FOREVER, flush_commands=False):
# def __init__(self, display):
# def signal(self, signaled=True):
# def __init__(self, display):
# def sync_condition(self):
#
# Path: src/pegl/native.py
# def make_int_p(ival=0):
# def error_check(fn, fail_on=None, always_check=False, fallback_error=EGLError,
# fallback_msg=None, fail_on_null=False):
# def wrapped_fn(*args, **kwargs):
. Output only the next line. | SyncAttribs.extend('NATIVE_FENCE_FD', 0x3145, c_int, NO_NATIVE_FENCE_FD) |
Continue the code snippet: <|code_start|>#
# Pegl is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Pegl is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
# License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Pegl. If not, see <http://www.gnu.org/licenses/>.
# Standard library imports.
# Local imports.
# New symbolic constants.
NATIVE_FENCE = 0x3144
NATIVE_FENCE_SIGNALED = 0x3146
NO_NATIVE_FENCE_FD = -1
# TODO: Use a custom, extensible alternative to the namedtuple class, so that
# NATIVE_FENCE can be added to khr_sync.SyncTypes, and NATIVE_FENCE_SIGNALED
# to khr_sync.SyncConditions. Of course, I'm really only using those namedtuple
# instances as enumerations, and there's now a proper one of those in the
# standard library as of Python 3.3...
# Get handles of extension functions.
native_dupnativefence = load_ext(b'eglDupNativeFenceFDANDROID', c_int,
<|code_end|>
. Use current file imports:
from ctypes import c_int
from .khr_sync import c_sync, Sync, SyncAttribs
from ..native import c_display
and context (classes, functions, or code) from other files:
# Path: src/pegl/ext/khr_sync.py
# NO_SYNC = c_void_p(0)
# FOREVER = 0xFFFFFFFFFFFFFFFF
# SYNC_STATUS = 0x30F1
# SYNC_TYPE = 0x30F7
# SYNC_CONDITION = 0x30F8
# TIMEOUT_EXPIRED, CONDITION_SATISFIED = 0x30F5, 0x30F6
# class WaitFlags(BitMask):
# class SyncAttribs(Attribs):
# class Sync:
# class ReusableSync(Sync):
# class FenceSync(Sync):
# def __init__(self, display, attribs):
# def _create_handle(self):
# def __del__(self):
# def _as_parameter_(self):
# def _attr(self, attr):
# def status(self):
# def sync_type(self):
# def signaled(self):
# def client_wait(self, timeout_ns=FOREVER, flush_commands=False):
# def __init__(self, display):
# def signal(self, signaled=True):
# def __init__(self, display):
# def sync_condition(self):
#
# Path: src/pegl/native.py
# def make_int_p(ival=0):
# def error_check(fn, fail_on=None, always_check=False, fallback_error=EGLError,
# fallback_msg=None, fail_on_null=False):
# def wrapped_fn(*args, **kwargs):
. Output only the next line. | (c_display, c_sync), fail_on=NO_NATIVE_FENCE_FD) |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python3
'''Cross-vendor Wayland platform support extension for EGL.
This extension adds the Wayland display server as an explicitly
supportable native platform.
http://www.khronos.org/registry/egl/extensions/EXT/EGL_EXT_platform_wayland.txt
'''
# Copyright © 2014 Tim Pederick.
#
# This file is part of Pegl.
#
# Pegl is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Pegl is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
# License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Pegl. If not, see <http://www.gnu.org/licenses/>.
# Local imports.
# New PlatformDisplay subclass.
<|code_end|>
with the help of current file imports:
from .ext_platform import PlatformDisplay
and context from other files:
# Path: src/pegl/ext/ext_platform.py
# class PlatformDisplay(Display):
# '''Superclass for all platform-specific displays.
#
# Class attributes:
# platform -- The numeric identifier for the native platform. All
# subclasses must define this; it is None in this class, and
# so this class cannot be instantiated.
#
# Instance attributes:
# dhandle, client_apis, extensions, swap_interval, vendor,
# version -- Inherited from Display.
# attribs -- The attributes with which this display was created.
# An instance of AttribList.
#
# '''
# platform = None
#
# def __init__(self, native_id, attribs, delay_init=False):
# '''Get a display for this platform.
#
# Keyword arguments:
# native_id -- As the superclass constructor, but not optional.
# attribs -- As the instance attribute.
# delay_init -- As the superclass constructor.
#
# '''
# # We're not trying to instantiate THIS class, are we?
# if self.__class__.platform is None:
# raise NotImplementedError("use a subclass of PlatformDisplay that "
# "defines class attribute 'platform'")
#
# self.attribs = (attribs if isinstance(attribs, AttribList) else
# AttribList(DisplayAttribs, attribs))
# dhandle = native_getdisplay(self.__class__.platform, native_id,
# attribs)
#
# # Call the parent class constructor.
# super().__init__(dhandle=dhandle, delay_init=delay_init)
, which may contain function names, class names, or code. Output only the next line. | class WaylandDisplay(PlatformDisplay): |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.