INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Returns * values * quantized to * steps * increments. All items in * values * are assumed to be between * input_min * and * input_max * ( which default to 0 and 1 respectively ) and the output will be in the same range. | def quantized(values, steps, input_min=0, input_max=1):
"""
Returns *values* quantized to *steps* increments. All items in *values* are
assumed to be between *input_min* and *input_max* (which default to 0 and
1 respectively), and the output will be in the same range.
For example, to quantize value... |
Returns True for each item in * values * between * min_value * and * max_value * and False otherwise. * hysteresis * can optionally be used to add hysteresis _ which prevents the output value rapidly flipping when the input value is fluctuating near the * min_value * or * max_value * thresholds. For example to light an... | def booleanized(values, min_value, max_value, hysteresis=0):
"""
Returns True for each item in *values* between *min_value* and
*max_value*, and False otherwise. *hysteresis* can optionally be used to
add `hysteresis`_ which prevents the output value rapidly flipping when
the input value is fluctuat... |
Returns the logical conjunction _ of all supplied values ( the result is only: data: True if and only if all input values are simultaneously: data: True ). One or more * values * can be specified. For example to light an: class: ~gpiozero. LED only when * both * buttons are pressed:: | def all_values(*values):
"""
Returns the `logical conjunction`_ of all supplied values (the result is
only :data:`True` if and only if all input values are simultaneously
:data:`True`). One or more *values* can be specified. For example, to light
an :class:`~gpiozero.LED` only when *both* buttons ar... |
Returns the logical disjunction _ of all supplied values ( the result is: data: True if any of the input values are currently: data: True ). One or more * values * can be specified. For example to light an: class: ~gpiozero. LED when * any * button is pressed:: | def any_values(*values):
"""
Returns the `logical disjunction`_ of all supplied values (the result is
:data:`True` if any of the input values are currently :data:`True`). One or
more *values* can be specified. For example, to light an
:class:`~gpiozero.LED` when *any* button is pressed::
fr... |
Returns the mean of all supplied values. One or more * values * can be specified. For example to light a: class: ~gpiozero. PWMLED as the average of several potentiometers connected to an: class: ~gpiozero. MCP3008 ADC:: | def averaged(*values):
"""
Returns the mean of all supplied values. One or more *values* can be
specified. For example, to light a :class:`~gpiozero.PWMLED` as the average
of several potentiometers connected to an :class:`~gpiozero.MCP3008` ADC::
from gpiozero import MCP3008, PWMLED
fro... |
Returns the sum of all supplied values. One or more * values * can be specified. For example to light a: class: ~gpiozero. PWMLED as the ( scaled ) sum of several potentiometers connected to an: class: ~gpiozero. MCP3008 ADC:: | def summed(*values):
"""
Returns the sum of all supplied values. One or more *values* can be
specified. For example, to light a :class:`~gpiozero.PWMLED` as the
(scaled) sum of several potentiometers connected to an
:class:`~gpiozero.MCP3008` ADC::
from gpiozero import MCP3008, PWMLED
... |
Returns the product of all supplied values. One or more * values * can be specified. For example to light a: class: ~gpiozero. PWMLED as the product ( i. e. multiplication ) of several potentiometers connected to an: class: ~gpiozero. MCP3008 ADC:: | def multiplied(*values):
"""
Returns the product of all supplied values. One or more *values* can be
specified. For example, to light a :class:`~gpiozero.PWMLED` as the product
(i.e. multiplication) of several potentiometers connected to an
:class:`~gpiozero.MCP3008`
ADC::
from gpiozero... |
Queues up readings from * values * ( the number of readings queued is determined by * qsize * ) and begins yielding values only when the queue is full. For example to cascade values along a sequence of LEDs:: | def queued(values, qsize):
"""
Queues up readings from *values* (the number of readings queued is
determined by *qsize*) and begins yielding values only when the queue is
full. For example, to "cascade" values along a sequence of LEDs::
from gpiozero import LEDBoard, Button
from gpiozer... |
Queues up readings from * values * ( the number of readings queued is determined by * qsize * ) and begins yielding the * average * of the last * qsize * values when the queue is full. The larger the * qsize * the more the values are smoothed. For example to smooth the analog values read from an ADC:: | def smoothed(values, qsize, average=mean):
"""
Queues up readings from *values* (the number of readings queued is
determined by *qsize*) and begins yielding the *average* of the last
*qsize* values when the queue is full. The larger the *qsize*, the more the
values are smoothed. For example, to smoo... |
Waits for * delay * seconds before returning each item from * values *. | def pre_delayed(values, delay):
"""
Waits for *delay* seconds before returning each item from *values*.
"""
values = _normalize(values)
if delay < 0:
raise ValueError("delay must be 0 or larger")
for v in values:
sleep(delay)
yield v |
Waits for * delay * seconds after returning each item from * values *. | def post_delayed(values, delay):
"""
Waits for *delay* seconds after returning each item from *values*.
"""
values = _normalize(values)
if delay < 0:
raise ValueError("delay must be 0 or larger")
for v in values:
yield v
sleep(delay) |
Blocks the first * block * items from * values * repeating the block after every * repeat_after * items if * repeat_after * is non - zero. For example to discard the first 50 values read from an ADC:: | def pre_periodic_filtered(values, block, repeat_after):
"""
Blocks the first *block* items from *values*, repeating the block after
every *repeat_after* items, if *repeat_after* is non-zero. For example, to
discard the first 50 values read from an ADC::
from gpiozero import MCP3008
from... |
After every * repeat_after * items blocks the next * block * items from * values *. Note that unlike: func: pre_periodic_filtered * repeat_after * can t be 0. For example to block every tenth item read from an ADC:: | def post_periodic_filtered(values, repeat_after, block):
"""
After every *repeat_after* items, blocks the next *block* items from
*values*. Note that unlike :func:`pre_periodic_filtered`, *repeat_after*
can't be 0. For example, to block every tenth item read from an ADC::
from gpiozero import M... |
Provides an infinite source of values representing a sine wave ( from - 1 to + 1 ) which repeats every * period * values. For example to produce a siren effect with a couple of LEDs that repeats once a second:: | def sin_values(period=360):
"""
Provides an infinite source of values representing a sine wave (from -1 to
+1) which repeats every *period* values. For example, to produce a "siren"
effect with a couple of LEDs that repeats once a second::
from gpiozero import PWMLED
from gpiozero.tools... |
Provides an infinite source of values representing a cosine wave ( from - 1 to + 1 ) which repeats every * period * values. For example to produce a siren effect with a couple of LEDs that repeats once a second:: | def cos_values(period=360):
"""
Provides an infinite source of values representing a cosine wave (from -1
to +1) which repeats every *period* values. For example, to produce a
"siren" effect with a couple of LEDs that repeats once a second::
from gpiozero import PWMLED
from gpiozero.too... |
Provides an infinite source of values representing a triangle wave ( from 0 to 1 and back again ) which repeats every * period * values. For example to pulse an LED once a second:: | def ramping_values(period=360):
"""
Provides an infinite source of values representing a triangle wave (from 0
to 1 and back again) which repeats every *period* values. For example, to
pulse an LED once a second::
from gpiozero import PWMLED
from gpiozero.tools import ramping_values
... |
Reverse the state of the device. If it s on turn it off ; if it s off turn it on. | def toggle(self):
"""
Reverse the state of the device. If it's on, turn it off; if it's off,
turn it on.
"""
with self._lock:
if self.is_active:
self.off()
else:
self.on() |
Make the device turn on and off repeatedly. | def blink(
self, on_time=1, off_time=1, fade_in_time=0, fade_out_time=0,
n=None, background=True):
"""
Make the device turn on and off repeatedly.
:param float on_time:
Number of seconds on. Defaults to 1 second.
:param float off_time:
Nu... |
Play the given * tone *. This can either be an instance of: class: ~gpiozero. tones. Tone or can be anything that could be used to construct an instance of: class: ~gpiozero. tones. Tone. | def play(self, tone):
"""
Play the given *tone*. This can either be an instance of
:class:`~gpiozero.tones.Tone` or can be anything that could be used to
construct an instance of :class:`~gpiozero.tones.Tone`.
For example::
>>> from gpiozero import TonalBuzzer
... |
Returns the: class: ~gpiozero. tones. Tone that the buzzer is currently playing or: data: None if the buzzer is silent. This property can also be set to play the specified tone. | def tone(self):
"""
Returns the :class:`~gpiozero.tones.Tone` that the buzzer is currently
playing, or :data:`None` if the buzzer is silent. This property can
also be set to play the specified tone.
"""
if self.pwm_device.pin.frequency is None:
return None
... |
Represents the state of the buzzer as a value between - 1 ( representing the minimum tone ) and 1 ( representing the maximum tone ). This can also be the special value: data: None indicating that the buzzer is currently silent. | def value(self):
"""
Represents the state of the buzzer as a value between -1 (representing
the minimum tone) and 1 (representing the maximum tone). This can also
be the special value :data:`None` indicating that the buzzer is
currently silent.
"""
if self.pwm_dev... |
Toggle the state of the device. If the device is currently off (: attr: value is ( 0 0 0 ) ) this changes it to fully on (: attr: value is ( 1 1 1 ) ). If the device has a specific color this method inverts the color. | def toggle(self):
"""
Toggle the state of the device. If the device is currently off
(:attr:`value` is ``(0, 0, 0)``), this changes it to "fully" on
(:attr:`value` is ``(1, 1, 1)``). If the device has a specific color,
this method inverts the color.
"""
r, g, b =... |
Make the device turn on and off repeatedly. | def blink(
self, on_time=1, off_time=1, fade_in_time=0, fade_out_time=0,
on_color=(1, 1, 1), off_color=(0, 0, 0), n=None, background=True):
"""
Make the device turn on and off repeatedly.
:param float on_time:
Number of seconds on. Defaults to 1 second.
... |
Drive the motor forwards. | def forward(self, speed=1):
"""
Drive the motor forwards.
:param float speed:
The speed at which the motor should turn. Can be any value between
0 (stopped) and the default 1 (maximum speed) if *pwm* was
:data:`True` when the class was constructed (and only 0... |
Represents the speed of the motor as a floating point value between - 1 ( full speed backward ) and 1 ( full speed forward ). | def value(self):
"""
Represents the speed of the motor as a floating point value between -1
(full speed backward) and 1 (full speed forward).
"""
return (
-self.enable_device.value
if self.phase_device.is_active else
self.enable_device.value
... |
Drive the motor forwards. | def forward(self, speed=1):
"""
Drive the motor forwards.
:param float speed:
The speed at which the motor should turn. Can be any value between
0 (stopped) and the default 1 (maximum speed).
"""
if isinstance(self.enable_device, DigitalOutputDevice):
... |
Drive the motor backwards. | def backward(self, speed=1):
"""
Drive the motor backwards.
:param float speed:
The speed at which the motor should turn. Can be any value between
0 (stopped) and the default 1 (maximum speed).
"""
if isinstance(self.enable_device, DigitalOutputDevice):
... |
Returns the current pulse width controlling the servo. | def pulse_width(self):
"""
Returns the current pulse width controlling the servo.
"""
if self.pwm_device.pin.frequency is None:
return None
else:
return self.pwm_device.pin.state * self.frame_width |
The position of the servo as an angle measured in degrees. This will only be accurate if: attr: min_angle and: attr: max_angle have been set appropriately in the constructor. | def angle(self):
"""
The position of the servo as an angle measured in degrees. This will
only be accurate if :attr:`min_angle` and :attr:`max_angle` have been
set appropriately in the constructor.
This can also be the special value :data:`None` indicating that the
servo... |
Construct a: class: Tone from a MIDI note which must be an integer in the range 0 to 127. For reference A4 ( concert A _ typically used for tuning ) is MIDI note #69. | def from_midi(cls, midi_note):
"""
Construct a :class:`Tone` from a MIDI note, which must be an integer
in the range 0 to 127. For reference, A4 (`concert A`_ typically used
for tuning) is MIDI note #69.
.. _concert A: https://en.wikipedia.org/wiki/Concert_pitch
"""
... |
Construct a: class: Tone from a musical note which must consist of a capital letter A through G followed by an optional semi - tone modifier ( b for flat # for sharp or their Unicode equivalents ) followed by an octave number ( 0 through 9 ). | def from_note(cls, note):
"""
Construct a :class:`Tone` from a musical note which must consist of
a capital letter A through G, followed by an optional semi-tone
modifier ("b" for flat, "#" for sharp, or their Unicode equivalents),
followed by an octave number (0 through 9).
... |
Construct a: class: Tone from a frequency specified in Hz _ which must be a positive floating - point value in the range 0 < freq < = 20000. | def from_frequency(cls, freq):
"""
Construct a :class:`Tone` from a frequency specified in `Hz`_ which
must be a positive floating-point value in the range 0 < freq <= 20000.
.. _Hz: https://en.wikipedia.org/wiki/Hertz
"""
if 0 < freq <= 20000:
return super(T... |
Return the ( nearest ) MIDI note to the tone s frequency. This will be an integer number in the range 0 to 127. If the frequency is outside the range represented by MIDI notes ( which is approximately 8Hz to 12. 5KHz ): exc: ValueError exception will be raised. | def midi(self):
"""
Return the (nearest) MIDI note to the tone's frequency. This will be an
integer number in the range 0 to 127. If the frequency is outside the
range represented by MIDI notes (which is approximately 8Hz to 12.5KHz)
:exc:`ValueError` exception will be raised.
... |
Return the ( nearest ) note to the tone s frequency. This will be a string in the form accepted by: meth: from_note. If the frequency is outside the range represented by this format ( A0 is approximately 27. 5Hz and G9 is approximately 12. 5Khz ) a: exc: ValueError exception will be raised. | def note(self):
"""
Return the (nearest) note to the tone's frequency. This will be a
string in the form accepted by :meth:`from_note`. If the frequency is
outside the range represented by this format ("A0" is approximately
27.5Hz, and "G9" is approximately 12.5Khz) a :exc:`Value... |
The length of time ( in seconds ) that the device has been active for. When the device is inactive this is: data: None. | def active_time(self):
"""
The length of time (in seconds) that the device has been active for.
When the device is inactive, this is :data:`None`.
"""
if self._active_event.is_set():
return self.pin_factory.ticks_diff(self.pin_factory.ticks(),
... |
The length of time ( in seconds ) that the device has been inactive for. When the device is active this is: data: None. | def inactive_time(self):
"""
The length of time (in seconds) that the device has been inactive for.
When the device is active, this is :data:`None`.
"""
if self._inactive_event.is_set():
return self.pin_factory.ticks_diff(self.pin_factory.ticks(),
... |
The length of time ( in seconds ) that the device has been held for. This is counted from the first execution of the: attr: when_held event rather than when the device activated in contrast to: attr: ~EventsMixin. active_time. If the device is not currently held this is: data: None. | def held_time(self):
"""
The length of time (in seconds) that the device has been held for.
This is counted from the first execution of the :attr:`when_held` event
rather than when the device activated, in contrast to
:attr:`~EventsMixin.active_time`. If the device is not current... |
Overridden to provide default ticks from the local Pi factory. | def _call_when_changed(self, ticks=None, state=None):
"""
Overridden to provide default ticks from the local Pi factory.
.. warning::
The local pin factory uses a seconds-based monotonic value for
its ticks but you *must not* rely upon this behaviour. Ticks are
... |
Instantiates the VGGFace architectures. Optionally loads weights pre - trained on VGGFace datasets. Note that when using TensorFlow for best performance you should set image_data_format = channels_last in your Keras config at ~/. keras/ keras. json. The model and the weights are compatible with both TensorFlow and Thea... | def VGGFace(include_top=True, model='vgg16', weights='vggface',
input_tensor=None, input_shape=None,
pooling=None,
classes=None):
"""Instantiates the VGGFace architectures.
Optionally loads weights pre-trained
on VGGFace datasets. Note that when using TensorFlow,
for ... |
set_default_proxy ( proxy_type addr [ port [ rdns [ username password ]]] ) | def set_default_proxy(proxy_type=None, addr=None, port=None, rdns=True, username=None, password=None):
"""
set_default_proxy(proxy_type, addr[, port[, rdns[, username, password]]])
Sets a default proxy which all further socksocket objects will use,
unless explicitly changed. All parameters are as for s... |
create_connection ( dest_pair * [ timeout ] ** proxy_args ) - > socket object | def create_connection(dest_pair, proxy_type=None, proxy_addr=None,
proxy_port=None, proxy_rdns=True,
proxy_username=None, proxy_password=None,
timeout=None, source_address=None,
socket_options=None):
"""create_connection(dest_pa... |
Receive EXACTLY the number of bytes requested from the file object. Blocks until the required number of bytes have been received. | def _readall(self, file, count):
"""
Receive EXACTLY the number of bytes requested from the file object.
Blocks until the required number of bytes have been received.
"""
data = b""
while len(data) < count:
d = file.read(count - len(data))
if not d... |
set_proxy ( proxy_type addr [ port [ rdns [ username [ password ]]]] ) Sets the proxy to be used. | def set_proxy(self, proxy_type=None, addr=None, port=None, rdns=True, username=None, password=None):
"""set_proxy(proxy_type, addr[, port[, rdns[, username[, password]]]])
Sets the proxy to be used.
proxy_type - The type of the proxy to be used. Three types
are suppor... |
Implements proxy connection for UDP sockets which happens during the bind () phase. | def bind(self, *pos, **kw):
"""
Implements proxy connection for UDP sockets,
which happens during the bind() phase.
"""
proxy_type, proxy_addr, proxy_port, rdns, username, password = self.proxy
if not proxy_type or self.type != socket.SOCK_DGRAM:
return _orig_... |
Negotiates a stream connection through a SOCKS5 server. | def _negotiate_SOCKS5(self, *dest_addr):
"""
Negotiates a stream connection through a SOCKS5 server.
"""
CONNECT = b"\x01"
self.proxy_peername, self.proxy_sockname = self._SOCKS5_request(self,
CONNECT, dest_addr) |
Send SOCKS5 request with given command ( CMD field ) and address ( DST field ). Returns resolved DST address that was used. | def _SOCKS5_request(self, conn, cmd, dst):
"""
Send SOCKS5 request with given command (CMD field) and
address (DST field). Returns resolved DST address that was used.
"""
proxy_type, addr, port, rdns, username, password = self.proxy
writer = conn.makefile("wb")
r... |
Return the host and port packed for the SOCKS5 protocol and the resolved address as a tuple object. | def _write_SOCKS5_address(self, addr, file):
"""
Return the host and port packed for the SOCKS5 protocol,
and the resolved address as a tuple object.
"""
host, port = addr
proxy_type, _, _, rdns, username, password = self.proxy
family_to_byte = {socket.AF_INET: b"... |
Negotiates a connection through a SOCKS4 server. | def _negotiate_SOCKS4(self, dest_addr, dest_port):
"""
Negotiates a connection through a SOCKS4 server.
"""
proxy_type, addr, port, rdns, username, password = self.proxy
writer = self.makefile("wb")
reader = self.makefile("rb", 0) # buffering=0 renamed in Python 3
... |
Negotiates a connection through an HTTP server. NOTE: This currently only supports HTTP CONNECT - style proxies. | def _negotiate_HTTP(self, dest_addr, dest_port):
"""
Negotiates a connection through an HTTP server.
NOTE: This currently only supports HTTP CONNECT-style proxies.
"""
proxy_type, addr, port, rdns, username, password = self.proxy
# If we need to resolve locally, we do th... |
Connects to the specified destination through a proxy. Uses the same API as socket s connect (). To select the proxy server use set_proxy (). | def connect(self, dest_pair):
"""
Connects to the specified destination through a proxy.
Uses the same API as socket's connect().
To select the proxy server, use set_proxy().
dest_pair - 2-tuple of (IP/hostname, port).
"""
if len(dest_pair) != 2 or dest_pair[0].s... |
Return proxy address to connect to as tuple object | def _proxy_addr(self):
"""
Return proxy address to connect to as tuple object
"""
proxy_type, proxy_addr, proxy_port, rdns, username, password = self.proxy
proxy_port = proxy_port or DEFAULT_PORTS.get(proxy_type)
if not proxy_port:
raise GeneralProxyError("Inv... |
PSL parser core | def _parse(self, source, accept_encoded_idn, only_icann=False):
""" PSL parser core """
publicsuffix = set()
maxlabel = 0
section_is_icann = None
if isinstance(source, decodablestr):
source = source.splitlines()
ln = 0
for line in source:
... |
Return shortest suffix assigned for an individual. | def privatesuffix(self, domain, accept_unknown=None):
""" Return shortest suffix assigned for an individual.
domain: str or unicode to parse. (Required)
accept_unknown: bool, assume unknown TLDs to be public suffix. (Default: object default)
Return None if domain has invalid format.
... |
Return tuple of labels and the private suffix. | def privateparts(self, domain):
""" Return tuple of labels and the private suffix. """
s = self.privatesuffix(domain)
if s is None:
return None
else:
# I know the domain is valid and ends with private suffix
pre = domain[0:-(len(s)+1)]
if p... |
Return so - called subdomain of specified depth in the private suffix. | def subdomain(self, domain, depth):
""" Return so-called subdomain of specified depth in the private suffix. """
p = self.privateparts(domain)
if p is None or depth > len(p) - 1:
return None
else:
return ".".join(p[-(depth+1):]) |
Updates a local copy of PSL file | def updatePSL(psl_file=PSLFILE):
""" Updates a local copy of PSL file
:param psl_file: path for the file to store the list. Default: PSLFILE
"""
if requests is None:
raise Exception("Please install python-requests http(s) library. $ sudo pip install requests")
r = requests.get(PSLURL)
... |
an updated version of pygments. formatter. format_unencoded | def get_marked_up_list(self, tokensource):
"""an updated version of pygments.formatter.format_unencoded"""
# import ipdb; ipdb.set_trace()
source = self._format_lines(tokensource)
if self.hl_lines:
source = self._highlight_lines(source)
if not self.nowrap:
... |
Get ssl context from private key and certificate paths. The return value is used when calling Flask. i. e. app. run ( ssl_context = get_ssl_context ( )) | def get_ssl_context(private_key, certificate):
"""Get ssl context from private key and certificate paths.
The return value is used when calling Flask.
i.e. app.run(ssl_context=get_ssl_context(,,,))
"""
if (
certificate
and os.path.isfile(certificate)
and private_key
a... |
Configures the specified Flask app to enforce SSL. | def init_app(self, app):
"""Configures the specified Flask app to enforce SSL."""
app.config.setdefault("SSLIFY_SUBDOMAINS", False)
app.config.setdefault("SSLIFY_PERMANENT", False)
app.config.setdefault("SSLIFY_SKIPS", None)
self.hsts_include_subdomains = (
self.hsts... |
Adds HSTS header to each response. | def set_hsts_header(self, response):
"""Adds HSTS header to each response."""
# Should we add STS header?
if request.is_secure and not self.skip:
response.headers.setdefault("Strict-Transport-Security", self.hsts_header)
return response |
returns None upon success | def csrf_protect_all_post_and_cross_origin_requests():
"""returns None upon success"""
success = None
if is_cross_origin(request):
logger.warning("Received cross origin request. Aborting")
abort(403)
if request.method in ["POST", "PUT"]:
token = session.get("csrf_token")
... |
Compare headers HOST and ORIGIN. Remove protocol prefix from ORIGIN then compare. Return true if they are not equal example HTTP_HOST: 127. 0. 0. 1: 5000 example HTTP_ORIGIN: http:// 127. 0. 0. 1: 5000 | def is_cross_origin(request):
"""Compare headers HOST and ORIGIN. Remove protocol prefix from ORIGIN, then
compare. Return true if they are not equal
example HTTP_HOST: '127.0.0.1:5000'
example HTTP_ORIGIN: 'http://127.0.0.1:5000'
"""
origin = request.environ.get("HTTP_ORIGIN")
host = reques... |
A decorator to add csrf protection by validing the X_CSRFTOKEN field in request header | def csrf_protect(f):
"""A decorator to add csrf protection by validing the X_CSRFTOKEN
field in request header"""
@wraps(f)
def wrapper(*args, **kwargs):
token = session.get("csrf_token", None)
if token is None or token != request.environ.get("HTTP_X_CSRFTOKEN"):
logger.warn... |
Run the server of the gdb gui | def setup_backend(
serve=True,
host=DEFAULT_HOST,
port=DEFAULT_PORT,
debug=False,
open_browser=True,
browsername=None,
testing=False,
private_key=None,
certificate=None,
LLDB=False,
):
"""Run the server of the gdb gui"""
app.config["LLDB"] = LLDB
kwargs = {}
ssl_... |
print only if app. debug is truthy | def dbprint(*args):
"""print only if app.debug is truthy"""
if app and app.debug:
if USING_WINDOWS:
print("DEBUG: " + " ".join(args))
else:
CYELLOW2 = "\33[93m"
NORMAL = "\033[0m"
print(CYELLOW2 + "DEBUG: " + " ".join(args) + NORMAL) |
Endpoint for a websocket route. Runs a gdb command. Responds only if an error occurs when trying to write the command to gdb | def run_gdb_command(message):
"""
Endpoint for a websocket route.
Runs a gdb command.
Responds only if an error occurs when trying to write the command to
gdb
"""
controller = _state.get_controller_from_client_id(request.sid)
if controller is not None:
try:
# the comm... |
Send message to all clients | def send_msg_to_clients(client_ids, msg, error=False):
"""Send message to all clients"""
if error:
stream = "stderr"
else:
stream = "stdout"
response = [{"message": None, "type": "console", "payload": msg, "stream": stream}]
for client_id in client_ids:
logger.info("emiting... |
A task that runs on a different thread and emits websocket messages of gdb responses | def read_and_forward_gdb_output():
"""A task that runs on a different thread, and emits websocket messages
of gdb responses"""
while True:
socketio.sleep(0.05)
controllers_to_remove = []
controller_items = _state.controller_to_client_ids.items()
for controller, client_ids in... |
returns a list of files that should be watched by the Flask server when in debug mode to trigger a reload of the server | def get_extra_files():
"""returns a list of files that should be watched by the Flask server
when in debug mode to trigger a reload of the server
"""
FILES_TO_SKIP = ["src/gdbgui.js"]
THIS_DIR = os.path.dirname(os.path.abspath(__file__))
extra_dirs = [THIS_DIR]
extra_files = []
for extra... |
Render the main gdbgui interface | def gdbgui():
"""Render the main gdbgui interface"""
interpreter = "lldb" if app.config["LLDB"] else "gdb"
gdbpid = request.args.get("gdbpid", 0)
initial_gdb_user_command = request.args.get("initial_gdb_user_command", "")
add_csrf_token_to_session()
THEMES = ["monokai", "light"]
# fmt: off... |
Get last modified unix time for a given file | def get_last_modified_unix_sec():
"""Get last modified unix time for a given file"""
path = request.args.get("path")
if path and os.path.isfile(path):
try:
last_modified = os.path.getmtime(path)
return jsonify({"path": path, "last_modified_unix_sec": last_modified})
... |
Read a file and return its contents as an array | def read_file():
"""Read a file and return its contents as an array"""
path = request.args.get("path")
start_line = int(request.args.get("start_line"))
end_line = int(request.args.get("end_line"))
start_line = max(1, start_line) # make sure it's not negative
try:
highlight = json.load... |
Entry point from command line | def main():
"""Entry point from command line"""
parser = get_parser()
args = parser.parse_args()
if args.debug:
logger.setLevel(logging.NOTSET)
initialize_preferences()
if args.version:
print(__version__)
return
cmd = args.cmd or args.args
if args.no_browser ... |
return True if user may need to turn shell off if mac OS version is 16 ( sierra ) or higher may need to set shell off due to os s security requirements http:// stackoverflow. com/ questions/ 39702871/ gdb - kind - of - doesnt - work - on - macos - sierra | def warn_startup_with_shell_off(platform, gdb_args):
"""return True if user may need to turn shell off
if mac OS version is 16 (sierra) or higher, may need to set shell off due
to os's security requirements
http://stackoverflow.com/questions/39702871/gdb-kind-of-doesnt-work-on-macos-sierra
"""
d... |
Returns the Ramp instance of the closest main - ramp to start location. Look in game_info. py for more information | def main_base_ramp(self) -> "Ramp":
""" Returns the Ramp instance of the closest main-ramp to start location. Look in game_info.py for more information """
if hasattr(self, "cached_main_base_ramp"):
return self.cached_main_base_ramp
self.cached_main_base_ramp = min(
{ramp... |
List of possible expansion locations. | def expansion_locations(self) -> Dict[Point2, Units]:
"""List of possible expansion locations."""
# RESOURCE_SPREAD_THRESHOLD = 144
RESOURCE_SPREAD_THRESHOLD = 225
geysers = self.state.vespene_geyser
all_resources = self.state.resources
# Group nearby minerals together t... |
Returns available abilities of one or more units. | async def get_available_abilities(self, units: Union[List[Unit], Units], ignore_resource_requirements=False) -> List[List[AbilityId]]:
""" Returns available abilities of one or more units. """
# right know only checks cooldown, energy cost, and whether the ability has been researched
return awai... |
Takes new expansion. | async def expand_now(self, building: UnitTypeId=None, max_distance: Union[int, float]=10, location: Optional[Point2]=None):
"""Takes new expansion."""
if not building:
# self.race is never Race.Random
start_townhall_type = {Race.Protoss: UnitTypeId.NEXUS, Race.Terran: UnitTypeId... |
Find next expansion location. | async def get_next_expansion(self) -> Optional[Point2]:
"""Find next expansion location."""
closest = None
distance = math.inf
for el in self.expansion_locations:
def is_near_to_expansion(t):
return t.position.distance_to(el) < self.EXPANSION_GAP_THRESHOLD
... |
Distributes workers across all the bases taken. WARNING: This is quite slow when there are lots of workers or multiple bases. | async def distribute_workers(self):
"""
Distributes workers across all the bases taken.
WARNING: This is quite slow when there are lots of workers or multiple bases.
"""
# TODO:
# OPTIMIZE: Assign idle workers smarter
# OPTIMIZE: Never use same worker mutltiple t... |
List of expansions owned by the player. | def owned_expansions(self):
"""List of expansions owned by the player."""
owned = {}
for el in self.expansion_locations:
def is_near_to_expansion(t):
return t.position.distance_to(el) < self.EXPANSION_GAP_THRESHOLD
th = next((x for x in self.townhalls if... |
Checks if you have enough free supply to build the unit | def can_feed(self, unit_type: UnitTypeId) -> bool:
""" Checks if you have enough free supply to build the unit """
required = self._game_data.units[unit_type.value]._proto.food_required
return required == 0 or self.supply_left >= required |
Tests if the player has enough resources to build a unit or cast an ability. | def can_afford(self, item_id: Union[UnitTypeId, UpgradeId, AbilityId], check_supply_cost: bool=True) -> "CanAffordWrapper":
"""Tests if the player has enough resources to build a unit or cast an ability."""
enough_supply = True
if isinstance(item_id, UnitTypeId):
unit = self._game_da... |
Tests if a unit has an ability available and enough energy to cast it. See data_pb2. py ( line 161 ) for the numbers 1 - 5 to make sense | async def can_cast(self, unit: Unit, ability_id: AbilityId, target: Optional[Union[Unit, Point2, Point3]]=None, only_check_energy_and_cooldown: bool=False, cached_abilities_of_unit: List[AbilityId]=None) -> bool:
"""Tests if a unit has an ability available and enough energy to cast it.
See data_pb2.py (... |
Select a worker to build a bulding with. | def select_build_worker(self, pos: Union[Unit, Point2, Point3], force: bool=False) -> Optional[Unit]:
"""Select a worker to build a bulding with."""
workers = self.workers.closer_than(20, pos) or self.workers
for worker in workers.prefer_close_to(pos).prefer_idle:
if not worker.orde... |
Tests if a building can be placed in the given location. | async def can_place(self, building: Union[AbilityData, AbilityId, UnitTypeId], position: Point2) -> bool:
"""Tests if a building can be placed in the given location."""
assert isinstance(building, (AbilityData, AbilityId, UnitTypeId))
if isinstance(building, UnitTypeId):
building =... |
Finds a placement location for building. | async def find_placement(self, building: UnitTypeId, near: Union[Unit, Point2, Point3], max_distance: int=20, random_alternative: bool=True, placement_step: int=2) -> Optional[Point2]:
"""Finds a placement location for building."""
assert isinstance(building, (AbilityId, UnitTypeId))
assert isi... |
Check if an upgrade is being researched Return values: 0: not started 0 < x < 1: researching 1: finished | def already_pending_upgrade(self, upgrade_type: UpgradeId) -> Union[int, float]:
""" Check if an upgrade is being researched
Return values:
0: not started
0 < x < 1: researching
1: finished
"""
assert isinstance(upgrade_type, UpgradeId)
if upgrade_type in ... |
Returns a number of buildings or units already in progress or if a worker is en route to build it. This also includes queued orders for workers and build queues of buildings. | def already_pending(self, unit_type: Union[UpgradeId, UnitTypeId], all_units: bool=False) -> int:
"""
Returns a number of buildings or units already in progress, or if a
worker is en route to build it. This also includes queued orders for
workers and build queues of buildings.
I... |
Build a building. | async def build(self, building: UnitTypeId, near: Union[Point2, Point3], max_distance: int=20, unit: Optional[Unit]=None, random_alternative: bool=True, placement_step: int=2):
"""Build a building."""
if isinstance(near, Unit):
near = near.position.to2
elif near is not None:
... |
Send a chat message. | async def chat_send(self, message: str):
"""Send a chat message."""
assert isinstance(message, str)
await self._client.chat_send(message, False) |
Returns terrain height at a position. Caution: terrain height is not anywhere near a unit s z - coordinate. | def get_terrain_height(self, pos: Union[Point2, Point3, Unit]) -> int:
""" Returns terrain height at a position. Caution: terrain height is not anywhere near a unit's z-coordinate. """
assert isinstance(pos, (Point2, Point3, Unit))
pos = pos.position.to2.rounded
return self._game_info.te... |
Returns True if you can place something at a position. Remember buildings usually use 2x2 3x3 or 5x5 of these grid points. Caution: some x and y offset might be required see ramp code: https:// github. com/ Dentosal/ python - sc2/ blob/ master/ sc2/ game_info. py#L17 - L18 | def in_placement_grid(self, pos: Union[Point2, Point3, Unit]) -> bool:
""" Returns True if you can place something at a position. Remember, buildings usually use 2x2, 3x3 or 5x5 of these grid points.
Caution: some x and y offset might be required, see ramp code:
https://github.com/Dentosal/pytho... |
Returns True if a unit can pass through a grid point. | def in_pathing_grid(self, pos: Union[Point2, Point3, Unit]) -> bool:
""" Returns True if a unit can pass through a grid point. """
assert isinstance(pos, (Point2, Point3, Unit))
pos = pos.position.to2.rounded
return self._game_info.pathing_grid[pos] == 0 |
Returns True if you have vision on a grid point. | def is_visible(self, pos: Union[Point2, Point3, Unit]) -> bool:
""" Returns True if you have vision on a grid point. """
# more info: https://github.com/Blizzard/s2client-proto/blob/9906df71d6909511907d8419b33acc1a3bd51ec0/s2clientprotocol/spatial.proto#L19
assert isinstance(pos, (Point2, Point3... |
Returns True if there is creep on the grid point. | def has_creep(self, pos: Union[Point2, Point3, Unit]) -> bool:
""" Returns True if there is creep on the grid point. """
assert isinstance(pos, (Point2, Point3, Unit))
pos = pos.position.to2.rounded
return self.state.creep[pos] != 0 |
Ran until game start to set game and player data. | def _prepare_start(self, client, player_id, game_info, game_data):
"""Ran until game start to set game and player data."""
self._client: "Client" = client
self._game_info: "GameInfo" = game_info
self._game_data: GameData = game_data
self.player_id: int = player_id
self.r... |
First step extra preparations. Must not be called before _prepare_step. | def _prepare_first_step(self):
"""First step extra preparations. Must not be called before _prepare_step."""
if self.townhalls:
self._game_info.player_start_location = self.townhalls.first.position
self._game_info.map_ramps = self._game_info._find_ramps() |
Set attributes from new state before on_step. | def _prepare_step(self, state):
"""Set attributes from new state before on_step."""
self.state: GameState = state
# Required for events
self._units_previous_map.clear()
for unit in self.units:
self._units_previous_map[unit.tag] = unit
self.units: Units = stat... |
This function will be automatically run from main. py and triggers the following functions: - on_unit_created - on_unit_destroyed - on_building_construction_complete | async def issue_events(self):
""" This function will be automatically run from main.py and triggers the following functions:
- on_unit_created
- on_unit_destroyed
- on_building_construction_complete
"""
await self._issue_unit_dead_events()
await self._issue_unit_a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.