INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
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 | 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 rai... | 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.
.. warning::
The local pin factory uses a seconds-based monotonic value for
its ticks but you *must not* rely upon this behaviour. Ticks are
an opaque value that should only be compared with the associated
... | 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 bo... | 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]]])
Sets a default proxy which all further socksocket objects will use,
unless explicitly changed. All parameters are as for socket.set_proxy(). | 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
Like socket.create_connection(), but connects to proxy
before returning the socket object.
dest_pair - 2-tuple of (IP/hostname, port).
**proxy_args - Same args passed to socksocket.set_proxy() if present.
timeout - Optional ... | 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.
proxy_type - The type of the proxy to be used. Three types
are supported: PROXY_TYPE_SOCKS4 (including socks4a),
PROXY_TYPE_SOCKS5 and PROXY_TYPE_HTTP
... | 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... |
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.
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 None if domain has no private part. | 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
:param psl_file: path for the file to store the list. Default: PSLFILE | 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.
If all_units==True, then build queues of other units (such as Carriers
(Interceptors) or Oracles (Stasis Ward))... | 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... |
UnitTypeId found in sc2/ids/unit_typeid
Caches all type_ids of the same unit type | def type_id(self) -> UnitTypeId:
""" UnitTypeId found in sc2/ids/unit_typeid
Caches all type_ids of the same unit type"""
unit_type = self._proto.unit_type
if unit_type not in self._game_data.unit_types:
self._game_data.unit_types[unit_type] = UnitTypeId(unit_type)
re... |
Does not include upgrades | def ground_dps(self) -> Union[int, float]:
""" Does not include upgrades """
if self._weapons:
weapon = next(
(weapon for weapon in self._weapons if weapon.type in {TargetType.Ground.value, TargetType.Any.value}),
None,
)
if weapon:
... |
Does not include upgrades | def ground_range(self) -> Union[int, float]:
""" Does not include upgrades """
if self._weapons:
weapon = next(
(weapon for weapon in self._weapons if weapon.type in {TargetType.Ground.value, TargetType.Any.value}),
None,
)
if weapon:
... |
Does not include upgrades | def can_attack_air(self) -> bool:
""" Does not include upgrades """
if self._weapons:
weapon = next(
(weapon for weapon in self._weapons if weapon.type in {TargetType.Air.value, TargetType.Any.value}),
None,
)
return weapon is not None
... |
Does not include upgrades | def air_range(self) -> Union[int, float]:
""" Does not include upgrades """
if self._weapons:
weapon = next(
(weapon for weapon in self._weapons if weapon.type in {TargetType.Air.value, TargetType.Any.value}),
None,
)
if weapon:
... |
Does not include upgrades | def air_dps(self) -> Union[int, float]:
""" Does not include upgrades """
if self._weapons:
weapon = next(
(weapon for weapon in self._weapons if weapon.type in {TargetType.Air.value, TargetType.Any.value}),
None,
)
if weapon:
... |
Returns a tuple of form 'bonus damage, armor type' if unit does bonus damage against armor type
Light = 1; Armored = 2; Biological = 3; Mechanical = 4; Robotic = 5; Psionic = 6; Massive = 7;
Structure = 8; Hover = 9; Heroic = 10; Summoned = 11 | def bonus_damage(self):
""" Returns a tuple of form 'bonus damage, armor type' if unit does bonus damage against armor type
Light = 1; Armored = 2; Biological = 3; Mechanical = 4; Robotic = 5; Psionic = 6; Massive = 7;
Structure = 8; Hover = 9; Heroic = 10; Summoned = 11 """
# TODO Consi... |
Does not include shields | def health_percentage(self) -> Union[int, float]:
""" Does not include shields """
if self._proto.health_max == 0:
return 0
return self._proto.health / self._proto.health_max |
Using the 2d distance between self and p. To calculate the 3d distance,
use unit.position3d.distance_to(p) | def distance_to(self, p: Union["Unit", Point2, Point3], bot: "BotAI" = None) -> Union[int, float]:
""" Using the 2d distance between self and p. To calculate the 3d distance,
use unit.position3d.distance_to(p) """
if bot and isinstance(p, Unit):
index = bot.distances_tag_dict
... |
Returns some time (more than game loops) until the unit can fire again,
returns -1 for units that can't attack.
Usage:
if unit.weapon_cooldown == 0:
await self.do(unit.attack(target))
elif unit.weapon_cooldown < 0:
await self.do(unit.move(closest_allied_unit_becau... | def weapon_cooldown(self) -> Union[int, float]:
""" Returns some time (more than game loops) until the unit can fire again,
returns -1 for units that can't attack.
Usage:
if unit.weapon_cooldown == 0:
await self.do(unit.attack(target))
elif unit.weapon_cooldown < 0:
... |
Units inside a Bunker, CommandCenter, Nydus, Medivac, WarpPrism, Overlord | def passengers(self) -> Set["PassengerUnit"]:
""" Units inside a Bunker, CommandCenter, Nydus, Medivac, WarpPrism, Overlord """
return {PassengerUnit(unit, self._game_data) for unit in self._proto.passengers} |
Includes the target's radius when calculating distance to target | def target_in_range(self, target: "Unit", bonus_distance: Union[int, float] = 0) -> bool:
""" Includes the target's radius when calculating distance to target """
if self.can_attack_ground and not target.is_flying:
unit_attack_range = self.ground_range
elif self.can_attack_air and (t... |
Checks if a worker or MULE is carrying (gold-)minerals. | def is_carrying_minerals(self) -> bool:
""" Checks if a worker or MULE is carrying (gold-)minerals. """
return any(
buff.value in self._proto.buff_ids
for buff in {BuffId.CARRYMINERALFIELDMINERALS, BuffId.CARRYHIGHYIELDMINERALFIELDMINERALS}
) |
Checks if a worker is carrying vespene. | def is_carrying_vespene(self) -> bool:
""" Checks if a worker is carrying vespene. """
return any(
buff.value in self._proto.buff_ids
for buff in {
BuffId.CARRYHARVESTABLEVESPENEGEYSERGAS,
BuffId.CARRYHARVESTABLEVESPENEGEYSERGASPROTOSS,
... |
Checks if a unit is patrolling. | def is_patrolling(self) -> bool:
""" Checks if a unit is patrolling. """
return self.orders and self.orders[0].ability.id is AbilityId.PATROL |
Checks if a unit is on its way to a mineral field / vespene geyser to mine. | def is_gathering(self) -> bool:
""" Checks if a unit is on its way to a mineral field / vespene geyser to mine. """
return self.orders and self.orders[0].ability.id is AbilityId.HARVEST_GATHER |
Checks if a unit is returning from mineral field / vespene geyser to deliver resources to townhall. | def is_returning(self) -> bool:
""" Checks if a unit is returning from mineral field / vespene geyser to deliver resources to townhall. """
return self.orders and self.orders[0].ability.id is AbilityId.HARVEST_RETURN |
Combines the two properties above. | def is_collecting(self) -> bool:
""" Combines the two properties above. """
return self.orders and self.orders[0].ability.id in {AbilityId.HARVEST_GATHER, AbilityId.HARVEST_RETURN} |
Returns the target tag (if it is a Unit) or Point2 (if it is a Position)
from the first order, returns None if the unit is idle | def order_target(self) -> Optional[Union[int, Point2]]:
""" Returns the target tag (if it is a Unit) or Point2 (if it is a Position)
from the first order, returns None if the unit is idle """
if self.orders:
if isinstance(self.orders[0].target, int):
return self.order... |
Requires UpgradeId to be passed instead of AbilityId | def research(self, upgrade, *args, **kwargs):
""" Requires UpgradeId to be passed instead of AbilityId """
return self(self._game_data.upgrades[upgrade.value].research_ability.id, *args, **kwargs) |
Filters units that are in attack range of the unit in parameter | def in_attack_range_of(self, unit: Unit, bonus_distance: Union[int, float] = 0) -> "Units":
""" Filters units that are in attack range of the unit in parameter """
return self.filter(lambda x: unit.target_in_range(x, bonus_distance=bonus_distance)) |
Returns the distance between the closest unit from this group to the target unit | def closest_distance_to(self, position: Union[Unit, Point2, Point3]) -> Union[int, float]:
""" Returns the distance between the closest unit from this group to the target unit """
assert self.exists
if isinstance(position, Unit):
position = position.position
return position.d... |
Returns the distance between the furthest unit from this group to the target unit | def furthest_distance_to(self, position: Union[Unit, Point2, Point3]) -> Union[int, float]:
""" Returns the distance between the furthest unit from this group to the target unit """
assert self.exists
if isinstance(position, Unit):
position = position.position
return position... |
This function should be a bit faster than using units.sorted(keyfn=lambda u: u.distance_to(position)) | def sorted_by_distance_to(self, position: Union[Unit, Point2], reverse: bool = False) -> "Units":
""" This function should be a bit faster than using units.sorted(keyfn=lambda u: u.distance_to(position)) """
if len(self) in [0, 1]:
return self
position = position.position
ret... |
Filters all units that have their tags not in the 'other' set/list/dict | def tags_not_in(self, other: Union[Set[int], List[int], Dict[int, Any]]) -> "Units":
""" Filters all units that have their tags not in the 'other' set/list/dict """
# example: self.units(QUEEN).tags_not_in(self.queen_tags_assigned_to_do_injects)
if isinstance(other, list):
other = se... |
Filters all units that are of a specific type | def of_type(self, other: Union[UnitTypeId, Set[UnitTypeId], List[UnitTypeId], Dict[UnitTypeId, Any]]) -> "Units":
""" Filters all units that are of a specific type """
# example: self.units.of_type([ZERGLING, ROACH, HYDRALISK, BROODLORD])
if isinstance(other, UnitTypeId):
other = {ot... |
Usage:
'self.units.same_tech(UnitTypeId.COMMANDCENTER)' or 'self.units.same_tech(UnitTypeId.ORBITALCOMMAND)'
returns all CommandCenter, CommandCenterFlying, OrbitalCommand, OrbitalCommandFlying, PlanetaryFortress
This also works with a set/list/dict parameter, e.g. 'self.units.same_tech({UnitTyp... | def same_tech(self, other: Union[UnitTypeId, Set[UnitTypeId], List[UnitTypeId], Dict[UnitTypeId, Any]]) -> "Units":
""" Usage:
'self.units.same_tech(UnitTypeId.COMMANDCENTER)' or 'self.units.same_tech(UnitTypeId.ORBITALCOMMAND)'
returns all CommandCenter, CommandCenterFlying, OrbitalCommand, Orb... |
Usage:
'self.units.same_tech(UnitTypeId.COMMANDCENTER)'
returns CommandCenter and CommandCenterFlying,
'self.units.same_tech(UnitTypeId.ORBITALCOMMAND)'
returns OrbitalCommand and OrbitalCommandFlying
This also works with a set/list/dict parameter, e.g. 'self.units.same_tech({Uni... | def same_unit(self, other: Union[UnitTypeId, Set[UnitTypeId], List[UnitTypeId], Dict[UnitTypeId, Any]]) -> "Units":
""" Usage:
'self.units.same_tech(UnitTypeId.COMMANDCENTER)'
returns CommandCenter and CommandCenterFlying,
'self.units.same_tech(UnitTypeId.ORBITALCOMMAND)'
returns... |
Returns the central point of all units in this list | def center(self) -> Point2:
""" Returns the central point of all units in this list """
assert self
pos = Point2(
(
sum([unit.position.x for unit in self]) / self.amount,
sum([unit.position.y for unit in self]) / self.amount,
)
)
... |
- depots when low on remaining supply
- townhalls contains commandcenter and orbitalcommand
- self.units(TYPE).not_ready.amount selects all units of that type, filters incomplete units, and then counts the amount
- self.already_pending(TYPE) counts how many units are queued - but in this bot be... | async def on_step(self, iteration):
self.combinedActions = []
"""
- depots when low on remaining supply
- townhalls contains commandcenter and orbitalcommand
- self.units(TYPE).not_ready.amount selects all units of that type, filters incomplete units, and then counts the amount... |
You can use 'await self._client.leave()' to surrender midst game. | async def leave(self):
""" You can use 'await self._client.leave()' to surrender midst game. """
is_resign = self._game_result is None
if is_resign:
# For all clients that can leave, result of leaving the game either
# loss, or the client will ignore the result
... |
EXPERIMENTAL: Change self._client.game_step during the step function to increase or decrease steps per second | async def step(self):
""" EXPERIMENTAL: Change self._client.game_step during the step function to increase or decrease steps per second """
result = await self._execute(step=sc_pb.RequestStep(count=self.game_step))
return result |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.