partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
train
_Surface.blit_np_array
Fill this surface using the contents of a numpy array.
pysc2/lib/renderer_human.py
def blit_np_array(self, array): """Fill this surface using the contents of a numpy array.""" with sw("make_surface"): raw_surface = pygame.surfarray.make_surface(array.transpose([1, 0, 2])) with sw("draw"): pygame.transform.scale(raw_surface, self.surf.get_size(), self.surf)
def blit_np_array(self, array): """Fill this surface using the contents of a numpy array.""" with sw("make_surface"): raw_surface = pygame.surfarray.make_surface(array.transpose([1, 0, 2])) with sw("draw"): pygame.transform.scale(raw_surface, self.surf.get_size(), self.surf)
[ "Fill", "this", "surface", "using", "the", "contents", "of", "a", "numpy", "array", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/renderer_human.py#L165-L170
[ "def", "blit_np_array", "(", "self", ",", "array", ")", ":", "with", "sw", "(", "\"make_surface\"", ")", ":", "raw_surface", "=", "pygame", ".", "surfarray", ".", "make_surface", "(", "array", ".", "transpose", "(", "[", "1", ",", "0", ",", "2", "]", ...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
_Surface.write_screen
Write to the screen in font.size relative coordinates.
pysc2/lib/renderer_human.py
def write_screen(self, font, color, screen_pos, text, align="left", valign="top"): """Write to the screen in font.size relative coordinates.""" pos = point.Point(*screen_pos) * point.Point(0.75, 1) * font.get_linesize() text_surf = font.render(str(text), True, color) rect = text_surf....
def write_screen(self, font, color, screen_pos, text, align="left", valign="top"): """Write to the screen in font.size relative coordinates.""" pos = point.Point(*screen_pos) * point.Point(0.75, 1) * font.get_linesize() text_surf = font.render(str(text), True, color) rect = text_surf....
[ "Write", "to", "the", "screen", "in", "font", ".", "size", "relative", "coordinates", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/renderer_human.py#L172-L186
[ "def", "write_screen", "(", "self", ",", "font", ",", "color", ",", "screen_pos", ",", "text", ",", "align", "=", "\"left\"", ",", "valign", "=", "\"top\"", ")", ":", "pos", "=", "point", ".", "Point", "(", "*", "screen_pos", ")", "*", "point", ".", ...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
MousePos.action_spatial
Given an Action, return the right spatial action.
pysc2/lib/renderer_human.py
def action_spatial(self, action): """Given an Action, return the right spatial action.""" if self.surf.surf_type & SurfType.FEATURE: return action.action_feature_layer elif self.surf.surf_type & SurfType.RGB: return action.action_render else: assert self.surf.surf_type & (SurfType.RGB ...
def action_spatial(self, action): """Given an Action, return the right spatial action.""" if self.surf.surf_type & SurfType.FEATURE: return action.action_feature_layer elif self.surf.surf_type & SurfType.RGB: return action.action_render else: assert self.surf.surf_type & (SurfType.RGB ...
[ "Given", "an", "Action", "return", "the", "right", "spatial", "action", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/renderer_human.py#L201-L208
[ "def", "action_spatial", "(", "self", ",", "action", ")", ":", "if", "self", ".", "surf", ".", "surf_type", "&", "SurfType", ".", "FEATURE", ":", "return", "action", ".", "action_feature_layer", "elif", "self", ".", "surf", ".", "surf_type", "&", "SurfType...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
RendererHuman.init
Take the game info and the static data needed to set up the game. This must be called before render or get_actions for each game or restart. Args: game_info: A `sc_pb.ResponseGameInfo` object for this game. static_data: A `StaticData` object for this game. Raises: ValueError: if there i...
pysc2/lib/renderer_human.py
def init(self, game_info, static_data): """Take the game info and the static data needed to set up the game. This must be called before render or get_actions for each game or restart. Args: game_info: A `sc_pb.ResponseGameInfo` object for this game. static_data: A `StaticData` object for this ...
def init(self, game_info, static_data): """Take the game info and the static data needed to set up the game. This must be called before render or get_actions for each game or restart. Args: game_info: A `sc_pb.ResponseGameInfo` object for this game. static_data: A `StaticData` object for this ...
[ "Take", "the", "game", "info", "and", "the", "static", "data", "needed", "to", "set", "up", "the", "game", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/renderer_human.py#L323-L379
[ "def", "init", "(", "self", ",", "game_info", ",", "static_data", ")", ":", "self", ".", "_game_info", "=", "game_info", "self", ".", "_static_data", "=", "static_data", "if", "not", "game_info", ".", "HasField", "(", "\"start_raw\"", ")", ":", "raise", "V...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
RendererHuman.init_window
Initialize the pygame window and lay out the surfaces.
pysc2/lib/renderer_human.py
def init_window(self): """Initialize the pygame window and lay out the surfaces.""" if platform.system() == "Windows": # Enable DPI awareness on Windows to give the correct window size. ctypes.windll.user32.SetProcessDPIAware() # pytype: disable=module-attr pygame.init() if self._desktop_...
def init_window(self): """Initialize the pygame window and lay out the surfaces.""" if platform.system() == "Windows": # Enable DPI awareness on Windows to give the correct window size. ctypes.windll.user32.SetProcessDPIAware() # pytype: disable=module-attr pygame.init() if self._desktop_...
[ "Initialize", "the", "pygame", "window", "and", "lay", "out", "the", "surfaces", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/renderer_human.py#L383-L647
[ "def", "init_window", "(", "self", ")", ":", "if", "platform", ".", "system", "(", ")", "==", "\"Windows\"", ":", "# Enable DPI awareness on Windows to give the correct window size.", "ctypes", ".", "windll", ".", "user32", ".", "SetProcessDPIAware", "(", ")", "# py...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
RendererHuman._update_camera
Update the camera transform based on the new camera center.
pysc2/lib/renderer_human.py
def _update_camera(self, camera_center): """Update the camera transform based on the new camera center.""" self._world_tl_to_world_camera_rel.offset = ( -self._world_to_world_tl.fwd_pt(camera_center) * self._world_tl_to_world_camera_rel.scale) if self._feature_screen_px: camera_radius...
def _update_camera(self, camera_center): """Update the camera transform based on the new camera center.""" self._world_tl_to_world_camera_rel.offset = ( -self._world_to_world_tl.fwd_pt(camera_center) * self._world_tl_to_world_camera_rel.scale) if self._feature_screen_px: camera_radius...
[ "Update", "the", "camera", "transform", "based", "on", "the", "new", "camera", "center", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/renderer_human.py#L649-L662
[ "def", "_update_camera", "(", "self", ",", "camera_center", ")", ":", "self", ".", "_world_tl_to_world_camera_rel", ".", "offset", "=", "(", "-", "self", ".", "_world_to_world_tl", ".", "fwd_pt", "(", "camera_center", ")", "*", "self", ".", "_world_tl_to_world_c...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
RendererHuman.get_mouse_pos
Return a MousePos filled with the world position and surf it hit.
pysc2/lib/renderer_human.py
def get_mouse_pos(self, window_pos=None): """Return a MousePos filled with the world position and surf it hit.""" window_pos = window_pos or pygame.mouse.get_pos() # +0.5 to center the point on the middle of the pixel. window_pt = point.Point(*window_pos) + 0.5 for surf in reversed(self._surfaces): ...
def get_mouse_pos(self, window_pos=None): """Return a MousePos filled with the world position and surf it hit.""" window_pos = window_pos or pygame.mouse.get_pos() # +0.5 to center the point on the middle of the pixel. window_pt = point.Point(*window_pos) + 0.5 for surf in reversed(self._surfaces): ...
[ "Return", "a", "MousePos", "filled", "with", "the", "world", "position", "and", "surf", "it", "hit", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/renderer_human.py#L669-L679
[ "def", "get_mouse_pos", "(", "self", ",", "window_pos", "=", "None", ")", ":", "window_pos", "=", "window_pos", "or", "pygame", ".", "mouse", ".", "get_pos", "(", ")", "# +0.5 to center the point on the middle of the pixel.", "window_pt", "=", "point", ".", "Point...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
RendererHuman.get_actions
Get actions from the UI, apply to controller, and return an ActionCmd.
pysc2/lib/renderer_human.py
def get_actions(self, run_config, controller): """Get actions from the UI, apply to controller, and return an ActionCmd.""" if not self._initialized: return ActionCmd.STEP for event in pygame.event.get(): ctrl = pygame.key.get_mods() & pygame.KMOD_CTRL shift = pygame.key.get_mods() & pyga...
def get_actions(self, run_config, controller): """Get actions from the UI, apply to controller, and return an ActionCmd.""" if not self._initialized: return ActionCmd.STEP for event in pygame.event.get(): ctrl = pygame.key.get_mods() & pygame.KMOD_CTRL shift = pygame.key.get_mods() & pyga...
[ "Get", "actions", "from", "the", "UI", "apply", "to", "controller", "and", "return", "an", "ActionCmd", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/renderer_human.py#L693-L817
[ "def", "get_actions", "(", "self", ",", "run_config", ",", "controller", ")", ":", "if", "not", "self", ".", "_initialized", ":", "return", "ActionCmd", ".", "STEP", "for", "event", "in", "pygame", ".", "event", ".", "get", "(", ")", ":", "ctrl", "=", ...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
RendererHuman.camera_action
Return a `sc_pb.Action` with the camera movement filled.
pysc2/lib/renderer_human.py
def camera_action(self, mouse_pos): """Return a `sc_pb.Action` with the camera movement filled.""" action = sc_pb.Action() action_spatial = mouse_pos.action_spatial(action) mouse_pos.obs_pos.assign_to(action_spatial.camera_move.center_minimap) return action
def camera_action(self, mouse_pos): """Return a `sc_pb.Action` with the camera movement filled.""" action = sc_pb.Action() action_spatial = mouse_pos.action_spatial(action) mouse_pos.obs_pos.assign_to(action_spatial.camera_move.center_minimap) return action
[ "Return", "a", "sc_pb", ".", "Action", "with", "the", "camera", "movement", "filled", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/renderer_human.py#L819-L824
[ "def", "camera_action", "(", "self", ",", "mouse_pos", ")", ":", "action", "=", "sc_pb", ".", "Action", "(", ")", "action_spatial", "=", "mouse_pos", ".", "action_spatial", "(", "action", ")", "mouse_pos", ".", "obs_pos", ".", "assign_to", "(", "action_spati...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
RendererHuman.camera_action_raw
Return a `sc_pb.Action` with the camera movement filled.
pysc2/lib/renderer_human.py
def camera_action_raw(self, world_pos): """Return a `sc_pb.Action` with the camera movement filled.""" action = sc_pb.Action() world_pos.assign_to(action.action_raw.camera_move.center_world_space) return action
def camera_action_raw(self, world_pos): """Return a `sc_pb.Action` with the camera movement filled.""" action = sc_pb.Action() world_pos.assign_to(action.action_raw.camera_move.center_world_space) return action
[ "Return", "a", "sc_pb", ".", "Action", "with", "the", "camera", "movement", "filled", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/renderer_human.py#L826-L830
[ "def", "camera_action_raw", "(", "self", ",", "world_pos", ")", ":", "action", "=", "sc_pb", ".", "Action", "(", ")", "world_pos", ".", "assign_to", "(", "action", ".", "action_raw", ".", "camera_move", ".", "center_world_space", ")", "return", "action" ]
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
RendererHuman.select_action
Return a `sc_pb.Action` with the selection filled.
pysc2/lib/renderer_human.py
def select_action(self, pos1, pos2, ctrl, shift): """Return a `sc_pb.Action` with the selection filled.""" assert pos1.surf.surf_type == pos2.surf.surf_type assert pos1.surf.world_to_obs == pos2.surf.world_to_obs action = sc_pb.Action() action_spatial = pos1.action_spatial(action) if pos1.worl...
def select_action(self, pos1, pos2, ctrl, shift): """Return a `sc_pb.Action` with the selection filled.""" assert pos1.surf.surf_type == pos2.surf.surf_type assert pos1.surf.world_to_obs == pos2.surf.world_to_obs action = sc_pb.Action() action_spatial = pos1.action_spatial(action) if pos1.worl...
[ "Return", "a", "sc_pb", ".", "Action", "with", "the", "selection", "filled", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/renderer_human.py#L832-L861
[ "def", "select_action", "(", "self", ",", "pos1", ",", "pos2", ",", "ctrl", ",", "shift", ")", ":", "assert", "pos1", ".", "surf", ".", "surf_type", "==", "pos2", ".", "surf", ".", "surf_type", "assert", "pos1", ".", "surf", ".", "world_to_obs", "==", ...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
RendererHuman.select_idle_worker
Select an idle worker.
pysc2/lib/renderer_human.py
def select_idle_worker(self, ctrl, shift): """Select an idle worker.""" action = sc_pb.Action() mod = sc_ui.ActionSelectIdleWorker if ctrl: select_worker = mod.AddAll if shift else mod.All else: select_worker = mod.Add if shift else mod.Set action.action_ui.select_idle_worker.type = ...
def select_idle_worker(self, ctrl, shift): """Select an idle worker.""" action = sc_pb.Action() mod = sc_ui.ActionSelectIdleWorker if ctrl: select_worker = mod.AddAll if shift else mod.All else: select_worker = mod.Add if shift else mod.Set action.action_ui.select_idle_worker.type = ...
[ "Select", "an", "idle", "worker", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/renderer_human.py#L863-L872
[ "def", "select_idle_worker", "(", "self", ",", "ctrl", ",", "shift", ")", ":", "action", "=", "sc_pb", ".", "Action", "(", ")", "mod", "=", "sc_ui", ".", "ActionSelectIdleWorker", "if", "ctrl", ":", "select_worker", "=", "mod", ".", "AddAll", "if", "shif...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
RendererHuman.select_army
Select the entire army.
pysc2/lib/renderer_human.py
def select_army(self, shift): """Select the entire army.""" action = sc_pb.Action() action.action_ui.select_army.selection_add = shift return action
def select_army(self, shift): """Select the entire army.""" action = sc_pb.Action() action.action_ui.select_army.selection_add = shift return action
[ "Select", "the", "entire", "army", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/renderer_human.py#L874-L878
[ "def", "select_army", "(", "self", ",", "shift", ")", ":", "action", "=", "sc_pb", ".", "Action", "(", ")", "action", ".", "action_ui", ".", "select_army", ".", "selection_add", "=", "shift", "return", "action" ]
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
RendererHuman.select_warp_gates
Select all warp gates.
pysc2/lib/renderer_human.py
def select_warp_gates(self, shift): """Select all warp gates.""" action = sc_pb.Action() action.action_ui.select_warp_gates.selection_add = shift return action
def select_warp_gates(self, shift): """Select all warp gates.""" action = sc_pb.Action() action.action_ui.select_warp_gates.selection_add = shift return action
[ "Select", "all", "warp", "gates", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/renderer_human.py#L880-L884
[ "def", "select_warp_gates", "(", "self", ",", "shift", ")", ":", "action", "=", "sc_pb", ".", "Action", "(", ")", "action", ".", "action_ui", ".", "select_warp_gates", ".", "selection_add", "=", "shift", "return", "action" ]
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
RendererHuman.select_larva
Select all larva.
pysc2/lib/renderer_human.py
def select_larva(self): """Select all larva.""" action = sc_pb.Action() action.action_ui.select_larva.SetInParent() # Adds the empty proto field. return action
def select_larva(self): """Select all larva.""" action = sc_pb.Action() action.action_ui.select_larva.SetInParent() # Adds the empty proto field. return action
[ "Select", "all", "larva", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/renderer_human.py#L886-L890
[ "def", "select_larva", "(", "self", ")", ":", "action", "=", "sc_pb", ".", "Action", "(", ")", "action", ".", "action_ui", ".", "select_larva", ".", "SetInParent", "(", ")", "# Adds the empty proto field.", "return", "action" ]
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
RendererHuman.control_group
Act on a control group, selecting, setting, etc.
pysc2/lib/renderer_human.py
def control_group(self, control_group_id, ctrl, shift, alt): """Act on a control group, selecting, setting, etc.""" action = sc_pb.Action() select = action.action_ui.control_group mod = sc_ui.ActionControlGroup if not ctrl and not shift and not alt: select.action = mod.Recall elif ctrl an...
def control_group(self, control_group_id, ctrl, shift, alt): """Act on a control group, selecting, setting, etc.""" action = sc_pb.Action() select = action.action_ui.control_group mod = sc_ui.ActionControlGroup if not ctrl and not shift and not alt: select.action = mod.Recall elif ctrl an...
[ "Act", "on", "a", "control", "group", "selecting", "setting", "etc", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/renderer_human.py#L892-L911
[ "def", "control_group", "(", "self", ",", "control_group_id", ",", "ctrl", ",", "shift", ",", "alt", ")", ":", "action", "=", "sc_pb", ".", "Action", "(", ")", "select", "=", "action", ".", "action_ui", ".", "control_group", "mod", "=", "sc_ui", ".", "...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
RendererHuman.unit_action
Return a `sc_pb.Action` filled with the cmd and appropriate target.
pysc2/lib/renderer_human.py
def unit_action(self, cmd, pos, shift): """Return a `sc_pb.Action` filled with the cmd and appropriate target.""" action = sc_pb.Action() if pos: action_spatial = pos.action_spatial(action) unit_command = action_spatial.unit_command unit_command.ability_id = cmd.ability_id unit_comma...
def unit_action(self, cmd, pos, shift): """Return a `sc_pb.Action` filled with the cmd and appropriate target.""" action = sc_pb.Action() if pos: action_spatial = pos.action_spatial(action) unit_command = action_spatial.unit_command unit_command.ability_id = cmd.ability_id unit_comma...
[ "Return", "a", "sc_pb", ".", "Action", "filled", "with", "the", "cmd", "and", "appropriate", "target", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/renderer_human.py#L913-L932
[ "def", "unit_action", "(", "self", ",", "cmd", ",", "pos", ",", "shift", ")", ":", "action", "=", "sc_pb", ".", "Action", "(", ")", "if", "pos", ":", "action_spatial", "=", "pos", ".", "action_spatial", "(", "action", ")", "unit_command", "=", "action_...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
RendererHuman._abilities
Return the list of abilities filtered by `fn`.
pysc2/lib/renderer_human.py
def _abilities(self, fn=None): """Return the list of abilities filtered by `fn`.""" out = {} for cmd in self._obs.observation.abilities: ability = _Ability(cmd, self._static_data.abilities) if not fn or fn(ability): out[ability.ability_id] = ability return list(out.values())
def _abilities(self, fn=None): """Return the list of abilities filtered by `fn`.""" out = {} for cmd in self._obs.observation.abilities: ability = _Ability(cmd, self._static_data.abilities) if not fn or fn(ability): out[ability.ability_id] = ability return list(out.values())
[ "Return", "the", "list", "of", "abilities", "filtered", "by", "fn", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/renderer_human.py#L934-L941
[ "def", "_abilities", "(", "self", ",", "fn", "=", "None", ")", ":", "out", "=", "{", "}", "for", "cmd", "in", "self", ".", "_obs", ".", "observation", ".", "abilities", ":", "ability", "=", "_Ability", "(", "cmd", ",", "self", ".", "_static_data", ...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
RendererHuman._visible_units
A generator of visible units and their positions as `Point`s, sorted.
pysc2/lib/renderer_human.py
def _visible_units(self): """A generator of visible units and their positions as `Point`s, sorted.""" # Sort the units by elevation, then owned (eg refinery) above world (ie 16) # (eg geiser), small above big, and otherwise arbitrary but stable. for u in sorted(self._obs.observation.raw_data.units, ...
def _visible_units(self): """A generator of visible units and their positions as `Point`s, sorted.""" # Sort the units by elevation, then owned (eg refinery) above world (ie 16) # (eg geiser), small above big, and otherwise arbitrary but stable. for u in sorted(self._obs.observation.raw_data.units, ...
[ "A", "generator", "of", "visible", "units", "and", "their", "positions", "as", "Point", "s", "sorted", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/renderer_human.py#L943-L949
[ "def", "_visible_units", "(", "self", ")", ":", "# Sort the units by elevation, then owned (eg refinery) above world (ie 16)", "# (eg geiser), small above big, and otherwise arbitrary but stable.", "for", "u", "in", "sorted", "(", "self", ".", "_obs", ".", "observation", ".", "...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
RendererHuman._units_in_area
Return the list of units that intersect the rect.
pysc2/lib/renderer_human.py
def _units_in_area(self, rect): """Return the list of units that intersect the rect.""" player_id = self._obs.observation.player_common.player_id return [u for u, p in self._visible_units() if rect.intersects_circle(p, u.radius) and u.owner == player_id]
def _units_in_area(self, rect): """Return the list of units that intersect the rect.""" player_id = self._obs.observation.player_common.player_id return [u for u, p in self._visible_units() if rect.intersects_circle(p, u.radius) and u.owner == player_id]
[ "Return", "the", "list", "of", "units", "that", "intersect", "the", "rect", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/renderer_human.py#L951-L955
[ "def", "_units_in_area", "(", "self", ",", "rect", ")", ":", "player_id", "=", "self", ".", "_obs", ".", "observation", ".", "player_common", ".", "player_id", "return", "[", "u", "for", "u", ",", "p", "in", "self", ".", "_visible_units", "(", ")", "if...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
RendererHuman.get_unit_name
Get a length limited unit name for drawing units.
pysc2/lib/renderer_human.py
def get_unit_name(self, surf, name, radius): """Get a length limited unit name for drawing units.""" key = (name, radius) if key not in self._name_lengths: max_len = surf.world_to_surf.fwd_dist(radius * 1.6) for i in range(len(name)): if self._font_small.size(name[:i + 1])[0] > max_len: ...
def get_unit_name(self, surf, name, radius): """Get a length limited unit name for drawing units.""" key = (name, radius) if key not in self._name_lengths: max_len = surf.world_to_surf.fwd_dist(radius * 1.6) for i in range(len(name)): if self._font_small.size(name[:i + 1])[0] > max_len: ...
[ "Get", "a", "length", "limited", "unit", "name", "for", "drawing", "units", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/renderer_human.py#L957-L968
[ "def", "get_unit_name", "(", "self", ",", "surf", ",", "name", ",", "radius", ")", ":", "key", "=", "(", "name", ",", "radius", ")", "if", "key", "not", "in", "self", ".", "_name_lengths", ":", "max_len", "=", "surf", ".", "world_to_surf", ".", "fwd_...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
RendererHuman.draw_units
Draw the units and buildings.
pysc2/lib/renderer_human.py
def draw_units(self, surf): """Draw the units and buildings.""" for u, p in self._visible_units(): if self._camera.intersects_circle(p, u.radius): fraction_damage = clamp((u.health_max - u.health) / (u.health_max or 1), 0, 1) surf.draw_circle(colors.PLAYER_A...
def draw_units(self, surf): """Draw the units and buildings.""" for u, p in self._visible_units(): if self._camera.intersects_circle(p, u.radius): fraction_damage = clamp((u.health_max - u.health) / (u.health_max or 1), 0, 1) surf.draw_circle(colors.PLAYER_A...
[ "Draw", "the", "units", "and", "buildings", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/renderer_human.py#L971-L999
[ "def", "draw_units", "(", "self", ",", "surf", ")", ":", "for", "u", ",", "p", "in", "self", ".", "_visible_units", "(", ")", ":", "if", "self", ".", "_camera", ".", "intersects_circle", "(", "p", ",", "u", ".", "radius", ")", ":", "fraction_damage",...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
RendererHuman.draw_selection
Draw the selection rectange.
pysc2/lib/renderer_human.py
def draw_selection(self, surf): """Draw the selection rectange.""" select_start = self._select_start # Cache to avoid a race condition. if select_start: mouse_pos = self.get_mouse_pos() if (mouse_pos and mouse_pos.surf.surf_type & SurfType.SCREEN and mouse_pos.surf.surf_type == select...
def draw_selection(self, surf): """Draw the selection rectange.""" select_start = self._select_start # Cache to avoid a race condition. if select_start: mouse_pos = self.get_mouse_pos() if (mouse_pos and mouse_pos.surf.surf_type & SurfType.SCREEN and mouse_pos.surf.surf_type == select...
[ "Draw", "the", "selection", "rectange", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/renderer_human.py#L1002-L1010
[ "def", "draw_selection", "(", "self", ",", "surf", ")", ":", "select_start", "=", "self", ".", "_select_start", "# Cache to avoid a race condition.", "if", "select_start", ":", "mouse_pos", "=", "self", ".", "get_mouse_pos", "(", ")", "if", "(", "mouse_pos", "an...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
RendererHuman.draw_build_target
Draw the build target.
pysc2/lib/renderer_human.py
def draw_build_target(self, surf): """Draw the build target.""" round_half = lambda v, cond: round(v - 0.5) + 0.5 if cond else round(v) queued_action = self._queued_action if queued_action: radius = queued_action.footprint_radius if radius: pos = self.get_mouse_pos() if pos:...
def draw_build_target(self, surf): """Draw the build target.""" round_half = lambda v, cond: round(v - 0.5) + 0.5 if cond else round(v) queued_action = self._queued_action if queued_action: radius = queued_action.footprint_radius if radius: pos = self.get_mouse_pos() if pos:...
[ "Draw", "the", "build", "target", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/renderer_human.py#L1013-L1028
[ "def", "draw_build_target", "(", "self", ",", "surf", ")", ":", "round_half", "=", "lambda", "v", ",", "cond", ":", "round", "(", "v", "-", "0.5", ")", "+", "0.5", "if", "cond", "else", "round", "(", "v", ")", "queued_action", "=", "self", ".", "_q...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
RendererHuman.draw_overlay
Draw the overlay describing resources.
pysc2/lib/renderer_human.py
def draw_overlay(self, surf): """Draw the overlay describing resources.""" obs = self._obs.observation player = obs.player_common surf.write_screen( self._font_large, colors.green, (0.2, 0.2), "Minerals: %s, Vespene: %s, Food: %s / %s" % ( player.minerals, player.vespene, pla...
def draw_overlay(self, surf): """Draw the overlay describing resources.""" obs = self._obs.observation player = obs.player_common surf.write_screen( self._font_large, colors.green, (0.2, 0.2), "Minerals: %s, Vespene: %s, Food: %s / %s" % ( player.minerals, player.vespene, pla...
[ "Draw", "the", "overlay", "describing", "resources", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/renderer_human.py#L1031-L1059
[ "def", "draw_overlay", "(", "self", ",", "surf", ")", ":", "obs", "=", "self", ".", "_obs", ".", "observation", "player", "=", "obs", ".", "player_common", "surf", ".", "write_screen", "(", "self", ".", "_font_large", ",", "colors", ".", "green", ",", ...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
RendererHuman.draw_help
Draw the help dialog.
pysc2/lib/renderer_human.py
def draw_help(self, surf): """Draw the help dialog.""" if not self._help: return def write(loc, text): surf.write_screen(self._font_large, colors.black, loc, text) surf.surf.fill(colors.white * 0.8) write((1, 1), "Shortcuts:") max_len = max(len(s) for s, _ in self.shortcuts) f...
def draw_help(self, surf): """Draw the help dialog.""" if not self._help: return def write(loc, text): surf.write_screen(self._font_large, colors.black, loc, text) surf.surf.fill(colors.white * 0.8) write((1, 1), "Shortcuts:") max_len = max(len(s) for s, _ in self.shortcuts) f...
[ "Draw", "the", "help", "dialog", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/renderer_human.py#L1062-L1076
[ "def", "draw_help", "(", "self", ",", "surf", ")", ":", "if", "not", "self", ".", "_help", ":", "return", "def", "write", "(", "loc", ",", "text", ")", ":", "surf", ".", "write_screen", "(", "self", ".", "_font_large", ",", "colors", ".", "black", ...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
RendererHuman.draw_commands
Draw the list of available commands.
pysc2/lib/renderer_human.py
def draw_commands(self, surf): """Draw the list of available commands.""" past_abilities = {act.ability for act in self._past_actions if act.ability} for y, cmd in enumerate(sorted(self._abilities( lambda c: c.name != "Smart"), key=lambda c: c.name), start=2): if self._queued_action and cmd ==...
def draw_commands(self, surf): """Draw the list of available commands.""" past_abilities = {act.ability for act in self._past_actions if act.ability} for y, cmd in enumerate(sorted(self._abilities( lambda c: c.name != "Smart"), key=lambda c: c.name), start=2): if self._queued_action and cmd ==...
[ "Draw", "the", "list", "of", "available", "commands", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/renderer_human.py#L1079-L1094
[ "def", "draw_commands", "(", "self", ",", "surf", ")", ":", "past_abilities", "=", "{", "act", ".", "ability", "for", "act", "in", "self", ".", "_past_actions", "if", "act", ".", "ability", "}", "for", "y", ",", "cmd", "in", "enumerate", "(", "sorted",...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
RendererHuman.draw_panel
Draw the unit selection or build queue.
pysc2/lib/renderer_human.py
def draw_panel(self, surf): """Draw the unit selection or build queue.""" left = -12 # How far from the right border def unit_name(unit_type): return self._static_data.units.get(unit_type, "<unknown>") def write(loc, text, color=colors.yellow): surf.write_screen(self._font_large, color, ...
def draw_panel(self, surf): """Draw the unit selection or build queue.""" left = -12 # How far from the right border def unit_name(unit_type): return self._static_data.units.get(unit_type, "<unknown>") def write(loc, text, color=colors.yellow): surf.write_screen(self._font_large, color, ...
[ "Draw", "the", "unit", "selection", "or", "build", "queue", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/renderer_human.py#L1097-L1163
[ "def", "draw_panel", "(", "self", ",", "surf", ")", ":", "left", "=", "-", "12", "# How far from the right border", "def", "unit_name", "(", "unit_type", ")", ":", "return", "self", ".", "_static_data", ".", "units", ".", "get", "(", "unit_type", ",", "\"<...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
RendererHuman.draw_actions
Draw the actions so that they can be inspected for accuracy.
pysc2/lib/renderer_human.py
def draw_actions(self): """Draw the actions so that they can be inspected for accuracy.""" now = time.time() for act in self._past_actions: if act.pos and now < act.deadline: remain = (act.deadline - now) / (act.deadline - act.time) if isinstance(act.pos, point.Point): size =...
def draw_actions(self): """Draw the actions so that they can be inspected for accuracy.""" now = time.time() for act in self._past_actions: if act.pos and now < act.deadline: remain = (act.deadline - now) / (act.deadline - act.time) if isinstance(act.pos, point.Point): size =...
[ "Draw", "the", "actions", "so", "that", "they", "can", "be", "inspected", "for", "accuracy", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/renderer_human.py#L1166-L1177
[ "def", "draw_actions", "(", "self", ")", ":", "now", "=", "time", ".", "time", "(", ")", "for", "act", "in", "self", ".", "_past_actions", ":", "if", "act", ".", "pos", "and", "now", "<", "act", ".", "deadline", ":", "remain", "=", "(", "act", "....
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
RendererHuman.prepare_actions
Keep a list of the past actions so they can be drawn.
pysc2/lib/renderer_human.py
def prepare_actions(self, obs): """Keep a list of the past actions so they can be drawn.""" now = time.time() while self._past_actions and self._past_actions[0].deadline < now: self._past_actions.pop(0) def add_act(ability_id, color, pos, timeout=1): if ability_id: ability = self._s...
def prepare_actions(self, obs): """Keep a list of the past actions so they can be drawn.""" now = time.time() while self._past_actions and self._past_actions[0].deadline < now: self._past_actions.pop(0) def add_act(ability_id, color, pos, timeout=1): if ability_id: ability = self._s...
[ "Keep", "a", "list", "of", "the", "past", "actions", "so", "they", "can", "be", "drawn", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/renderer_human.py#L1180-L1252
[ "def", "prepare_actions", "(", "self", ",", "obs", ")", ":", "now", "=", "time", ".", "time", "(", ")", "while", "self", ".", "_past_actions", "and", "self", ".", "_past_actions", "[", "0", "]", ".", "deadline", "<", "now", ":", "self", ".", "_past_a...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
RendererHuman.draw_base_map
Draw the base map.
pysc2/lib/renderer_human.py
def draw_base_map(self, surf): """Draw the base map.""" hmap_feature = features.SCREEN_FEATURES.height_map hmap = hmap_feature.unpack(self._obs.observation) if not hmap.any(): hmap = hmap + 100 # pylint: disable=g-no-augmented-assignment hmap_color = hmap_feature.color(hmap) creep_featur...
def draw_base_map(self, surf): """Draw the base map.""" hmap_feature = features.SCREEN_FEATURES.height_map hmap = hmap_feature.unpack(self._obs.observation) if not hmap.any(): hmap = hmap + 100 # pylint: disable=g-no-augmented-assignment hmap_color = hmap_feature.color(hmap) creep_featur...
[ "Draw", "the", "base", "map", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/renderer_human.py#L1255-L1284
[ "def", "draw_base_map", "(", "self", ",", "surf", ")", ":", "hmap_feature", "=", "features", ".", "SCREEN_FEATURES", ".", "height_map", "hmap", "=", "hmap_feature", ".", "unpack", "(", "self", ".", "_obs", ".", "observation", ")", "if", "not", "hmap", ".",...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
RendererHuman.draw_mini_map
Draw the minimap.
pysc2/lib/renderer_human.py
def draw_mini_map(self, surf): """Draw the minimap.""" if (self._render_rgb and self._obs.observation.HasField("render_data") and self._obs.observation.render_data.HasField("minimap")): # Draw the rendered version. surf.blit_np_array(features.Feature.unpack_rgb_image( self._obs.obs...
def draw_mini_map(self, surf): """Draw the minimap.""" if (self._render_rgb and self._obs.observation.HasField("render_data") and self._obs.observation.render_data.HasField("minimap")): # Draw the rendered version. surf.blit_np_array(features.Feature.unpack_rgb_image( self._obs.obs...
[ "Draw", "the", "minimap", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/renderer_human.py#L1287-L1334
[ "def", "draw_mini_map", "(", "self", ",", "surf", ")", ":", "if", "(", "self", ".", "_render_rgb", "and", "self", ".", "_obs", ".", "observation", ".", "HasField", "(", "\"render_data\"", ")", "and", "self", ".", "_obs", ".", "observation", ".", "render_...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
RendererHuman.draw_rendered_map
Draw the rendered pixels.
pysc2/lib/renderer_human.py
def draw_rendered_map(self, surf): """Draw the rendered pixels.""" surf.blit_np_array(features.Feature.unpack_rgb_image( self._obs.observation.render_data.map))
def draw_rendered_map(self, surf): """Draw the rendered pixels.""" surf.blit_np_array(features.Feature.unpack_rgb_image( self._obs.observation.render_data.map))
[ "Draw", "the", "rendered", "pixels", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/renderer_human.py#L1346-L1349
[ "def", "draw_rendered_map", "(", "self", ",", "surf", ")", ":", "surf", ".", "blit_np_array", "(", "features", ".", "Feature", ".", "unpack_rgb_image", "(", "self", ".", "_obs", ".", "observation", ".", "render_data", ".", "map", ")", ")" ]
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
RendererHuman.draw_screen
Draw the screen area.
pysc2/lib/renderer_human.py
def draw_screen(self, surf): """Draw the screen area.""" # surf.fill(colors.black) if (self._render_rgb and self._obs.observation.HasField("render_data") and self._obs.observation.render_data.HasField("map")): self.draw_rendered_map(surf) else: self.draw_base_map(surf) self.dra...
def draw_screen(self, surf): """Draw the screen area.""" # surf.fill(colors.black) if (self._render_rgb and self._obs.observation.HasField("render_data") and self._obs.observation.render_data.HasField("map")): self.draw_rendered_map(surf) else: self.draw_base_map(surf) self.dra...
[ "Draw", "the", "screen", "area", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/renderer_human.py#L1351-L1364
[ "def", "draw_screen", "(", "self", ",", "surf", ")", ":", "# surf.fill(colors.black)", "if", "(", "self", ".", "_render_rgb", "and", "self", ".", "_obs", ".", "observation", ".", "HasField", "(", "\"render_data\"", ")", "and", "self", ".", "_obs", ".", "ob...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
RendererHuman.draw_feature_layer
Draw a feature layer.
pysc2/lib/renderer_human.py
def draw_feature_layer(self, surf, feature): """Draw a feature layer.""" layer = feature.unpack(self._obs.observation) if layer is not None: surf.blit_np_array(feature.color(layer)) else: # Ignore layers that aren't in this version of SC2. surf.surf.fill(colors.black)
def draw_feature_layer(self, surf, feature): """Draw a feature layer.""" layer = feature.unpack(self._obs.observation) if layer is not None: surf.blit_np_array(feature.color(layer)) else: # Ignore layers that aren't in this version of SC2. surf.surf.fill(colors.black)
[ "Draw", "a", "feature", "layer", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/renderer_human.py#L1367-L1373
[ "def", "draw_feature_layer", "(", "self", ",", "surf", ",", "feature", ")", ":", "layer", "=", "feature", ".", "unpack", "(", "self", ".", "_obs", ".", "observation", ")", "if", "layer", "is", "not", "None", ":", "surf", ".", "blit_np_array", "(", "fea...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
RendererHuman.render
Push an observation onto the queue to be rendered.
pysc2/lib/renderer_human.py
def render(self, obs): """Push an observation onto the queue to be rendered.""" if not self._initialized: return now = time.time() self._game_times.append( (now - self._last_time, max(1, obs.observation.game_loop - self._obs.observation.game_loop))) self._last_time = now s...
def render(self, obs): """Push an observation onto the queue to be rendered.""" if not self._initialized: return now = time.time() self._game_times.append( (now - self._last_time, max(1, obs.observation.game_loop - self._obs.observation.game_loop))) self._last_time = now s...
[ "Push", "an", "observation", "onto", "the", "queue", "to", "be", "rendered", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/renderer_human.py#L1381-L1393
[ "def", "render", "(", "self", ",", "obs", ")", ":", "if", "not", "self", ".", "_initialized", ":", "return", "now", "=", "time", ".", "time", "(", ")", "self", ".", "_game_times", ".", "append", "(", "(", "now", "-", "self", ".", "_last_time", ",",...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
RendererHuman.render_thread
A render loop that pulls observations off the queue to render.
pysc2/lib/renderer_human.py
def render_thread(self): """A render loop that pulls observations off the queue to render.""" obs = True while obs: # Send something falsy through the queue to shut down. obs = self._obs_queue.get() if obs: for alert in obs.observation.alerts: self._alerts[sc_pb.Alert.Name(ale...
def render_thread(self): """A render loop that pulls observations off the queue to render.""" obs = True while obs: # Send something falsy through the queue to shut down. obs = self._obs_queue.get() if obs: for alert in obs.observation.alerts: self._alerts[sc_pb.Alert.Name(ale...
[ "A", "render", "loop", "that", "pulls", "observations", "off", "the", "queue", "to", "render", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/renderer_human.py#L1395-L1413
[ "def", "render_thread", "(", "self", ")", ":", "obs", "=", "True", "while", "obs", ":", "# Send something falsy through the queue to shut down.", "obs", "=", "self", ".", "_obs_queue", ".", "get", "(", ")", "if", "obs", ":", "for", "alert", "in", "obs", ".",...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
RendererHuman.render_obs
Render a frame given an observation.
pysc2/lib/renderer_human.py
def render_obs(self, obs): """Render a frame given an observation.""" start_time = time.time() self._obs = obs self.check_valid_queued_action() self._update_camera(point.Point.build( self._obs.observation.raw_data.player.camera)) for surf in self._surfaces: # Render that surface. ...
def render_obs(self, obs): """Render a frame given an observation.""" start_time = time.time() self._obs = obs self.check_valid_queued_action() self._update_camera(point.Point.build( self._obs.observation.raw_data.player.camera)) for surf in self._surfaces: # Render that surface. ...
[ "Render", "a", "frame", "given", "an", "observation", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/renderer_human.py#L1417-L1440
[ "def", "render_obs", "(", "self", ",", "obs", ")", ":", "start_time", "=", "time", ".", "time", "(", ")", "self", ".", "_obs", "=", "obs", "self", ".", "check_valid_queued_action", "(", ")", "self", ".", "_update_camera", "(", "point", ".", "Point", "....
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
RendererHuman.run
Run loop that gets observations, renders them, and sends back actions.
pysc2/lib/renderer_human.py
def run(self, run_config, controller, max_game_steps=0, max_episodes=0, game_steps_per_episode=0, save_replay=False): """Run loop that gets observations, renders them, and sends back actions.""" is_replay = (controller.status == remote_controller.Status.in_replay) total_game_steps = 0 start_ti...
def run(self, run_config, controller, max_game_steps=0, max_episodes=0, game_steps_per_episode=0, save_replay=False): """Run loop that gets observations, renders them, and sends back actions.""" is_replay = (controller.status == remote_controller.Status.in_replay) total_game_steps = 0 start_ti...
[ "Run", "loop", "that", "gets", "observations", "renders", "them", "and", "sends", "back", "actions", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/renderer_human.py#L1442-L1510
[ "def", "run", "(", "self", ",", "run_config", ",", "controller", ",", "max_game_steps", "=", "0", ",", "max_episodes", "=", "0", ",", "game_steps_per_episode", "=", "0", ",", "save_replay", "=", "False", ")", ":", "is_replay", "=", "(", "controller", ".", ...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
catch_websocket_connection_errors
A context manager that translates websocket errors into ConnectionError.
pysc2/lib/protocol.py
def catch_websocket_connection_errors(): """A context manager that translates websocket errors into ConnectionError.""" try: yield except websocket.WebSocketConnectionClosedException: raise ConnectionError("Connection already closed. SC2 probably crashed. " "Check the error log."...
def catch_websocket_connection_errors(): """A context manager that translates websocket errors into ConnectionError.""" try: yield except websocket.WebSocketConnectionClosedException: raise ConnectionError("Connection already closed. SC2 probably crashed. " "Check the error log."...
[ "A", "context", "manager", "that", "translates", "websocket", "errors", "into", "ConnectionError", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/protocol.py#L59-L69
[ "def", "catch_websocket_connection_errors", "(", ")", ":", "try", ":", "yield", "except", "websocket", ".", "WebSocketConnectionClosedException", ":", "raise", "ConnectionError", "(", "\"Connection already closed. SC2 probably crashed. \"", "\"Check the error log.\"", ")", "exc...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
StarcraftProtocol.read
Read a Response, do some validation, and return it.
pysc2/lib/protocol.py
def read(self): """Read a Response, do some validation, and return it.""" if FLAGS.sc2_verbose_protocol: self._log(" Reading response ".center(60, "-")) start = time.time() response = self._read() if FLAGS.sc2_verbose_protocol: self._log(" %0.1f msec\n" % (1000 * (time.time() - start))...
def read(self): """Read a Response, do some validation, and return it.""" if FLAGS.sc2_verbose_protocol: self._log(" Reading response ".center(60, "-")) start = time.time() response = self._read() if FLAGS.sc2_verbose_protocol: self._log(" %0.1f msec\n" % (1000 * (time.time() - start))...
[ "Read", "a", "Response", "do", "some", "validation", "and", "return", "it", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/protocol.py#L90-L109
[ "def", "read", "(", "self", ")", ":", "if", "FLAGS", ".", "sc2_verbose_protocol", ":", "self", ".", "_log", "(", "\" Reading response \"", ".", "center", "(", "60", ",", "\"-\"", ")", ")", "start", "=", "time", ".", "time", "(", ")", "response", "=", ...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
StarcraftProtocol.write
Write a Request.
pysc2/lib/protocol.py
def write(self, request): """Write a Request.""" if FLAGS.sc2_verbose_protocol: self._log(" Writing request ".center(60, "-") + "\n") self._log_packet(request) self._write(request)
def write(self, request): """Write a Request.""" if FLAGS.sc2_verbose_protocol: self._log(" Writing request ".center(60, "-") + "\n") self._log_packet(request) self._write(request)
[ "Write", "a", "Request", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/protocol.py#L112-L117
[ "def", "write", "(", "self", ",", "request", ")", ":", "if", "FLAGS", ".", "sc2_verbose_protocol", ":", "self", ".", "_log", "(", "\" Writing request \"", ".", "center", "(", "60", ",", "\"-\"", ")", "+", "\"\\n\"", ")", "self", ".", "_log_packet", "(", ...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
StarcraftProtocol.send
Create and send a specific request, and return the response. For example: send(ping=sc_pb.RequestPing()) => sc_pb.ResponsePing Args: **kwargs: A single kwarg with the name and value to fill in to Request. Returns: The Response corresponding to your request.
pysc2/lib/protocol.py
def send(self, **kwargs): """Create and send a specific request, and return the response. For example: send(ping=sc_pb.RequestPing()) => sc_pb.ResponsePing Args: **kwargs: A single kwarg with the name and value to fill in to Request. Returns: The Response corresponding to your request. ...
def send(self, **kwargs): """Create and send a specific request, and return the response. For example: send(ping=sc_pb.RequestPing()) => sc_pb.ResponsePing Args: **kwargs: A single kwarg with the name and value to fill in to Request. Returns: The Response corresponding to your request. ...
[ "Create", "and", "send", "a", "specific", "request", "and", "return", "the", "response", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/protocol.py#L124-L137
[ "def", "send", "(", "self", ",", "*", "*", "kwargs", ")", ":", "assert", "len", "(", "kwargs", ")", "==", "1", ",", "\"Must make a single request.\"", "res", "=", "self", ".", "send_req", "(", "sc_pb", ".", "Request", "(", "*", "*", "kwargs", ")", ")...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
StarcraftProtocol._log
r"""Log a string. It flushes but doesn't append \n, so do that yourself.
pysc2/lib/protocol.py
def _log(self, s): r"""Log a string. It flushes but doesn't append \n, so do that yourself.""" # TODO(tewalds): Should this be using logging.info instead? How to see them # outside of google infrastructure? sys.stderr.write(s) sys.stderr.flush()
def _log(self, s): r"""Log a string. It flushes but doesn't append \n, so do that yourself.""" # TODO(tewalds): Should this be using logging.info instead? How to see them # outside of google infrastructure? sys.stderr.write(s) sys.stderr.flush()
[ "r", "Log", "a", "string", ".", "It", "flushes", "but", "doesn", "t", "append", "\\", "n", "so", "do", "that", "yourself", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/protocol.py#L150-L155
[ "def", "_log", "(", "self", ",", "s", ")", ":", "# TODO(tewalds): Should this be using logging.info instead? How to see them", "# outside of google infrastructure?", "sys", ".", "stderr", ".", "write", "(", "s", ")", "sys", ".", "stderr", ".", "flush", "(", ")" ]
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
StarcraftProtocol._read
Actually read the response and parse it, returning a Response.
pysc2/lib/protocol.py
def _read(self): """Actually read the response and parse it, returning a Response.""" with sw("read_response"): with catch_websocket_connection_errors(): response_str = self._sock.recv() if not response_str: raise ProtocolError("Got an empty response from SC2.") response = sc_pb.Resp...
def _read(self): """Actually read the response and parse it, returning a Response.""" with sw("read_response"): with catch_websocket_connection_errors(): response_str = self._sock.recv() if not response_str: raise ProtocolError("Got an empty response from SC2.") response = sc_pb.Resp...
[ "Actually", "read", "the", "response", "and", "parse", "it", "returning", "a", "Response", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/protocol.py#L157-L167
[ "def", "_read", "(", "self", ")", ":", "with", "sw", "(", "\"read_response\"", ")", ":", "with", "catch_websocket_connection_errors", "(", ")", ":", "response_str", "=", "self", ".", "_sock", ".", "recv", "(", ")", "if", "not", "response_str", ":", "raise"...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
StarcraftProtocol._write
Actually serialize and write the request.
pysc2/lib/protocol.py
def _write(self, request): """Actually serialize and write the request.""" with sw("serialize_request"): request_str = request.SerializeToString() with sw("write_request"): with catch_websocket_connection_errors(): self._sock.send(request_str)
def _write(self, request): """Actually serialize and write the request.""" with sw("serialize_request"): request_str = request.SerializeToString() with sw("write_request"): with catch_websocket_connection_errors(): self._sock.send(request_str)
[ "Actually", "serialize", "and", "write", "the", "request", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/protocol.py#L169-L175
[ "def", "_write", "(", "self", ",", "request", ")", ":", "with", "sw", "(", "\"serialize_request\"", ")", ":", "request_str", "=", "request", ".", "SerializeToString", "(", ")", "with", "sw", "(", "\"write_request\"", ")", ":", "with", "catch_websocket_connecti...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
get_maps
Get the full dict of maps {map_name: map_class}.
pysc2/maps/lib.py
def get_maps(): """Get the full dict of maps {map_name: map_class}.""" maps = {} for mp in Map.all_subclasses(): if mp.filename: map_name = mp.__name__ if map_name in maps: raise DuplicateMapException("Duplicate map found: " + map_name) maps[map_name] = mp return maps
def get_maps(): """Get the full dict of maps {map_name: map_class}.""" maps = {} for mp in Map.all_subclasses(): if mp.filename: map_name = mp.__name__ if map_name in maps: raise DuplicateMapException("Duplicate map found: " + map_name) maps[map_name] = mp return maps
[ "Get", "the", "full", "dict", "of", "maps", "{", "map_name", ":", "map_class", "}", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/maps/lib.py#L113-L122
[ "def", "get_maps", "(", ")", ":", "maps", "=", "{", "}", "for", "mp", "in", "Map", ".", "all_subclasses", "(", ")", ":", "if", "mp", ".", "filename", ":", "map_name", "=", "mp", ".", "__name__", "if", "map_name", "in", "maps", ":", "raise", "Duplic...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
get
Get an instance of a map by name. Errors if the map doesn't exist.
pysc2/maps/lib.py
def get(map_name): """Get an instance of a map by name. Errors if the map doesn't exist.""" if isinstance(map_name, Map): return map_name # Get the list of maps. This isn't at module scope to avoid problems of maps # being defined after this module is imported. maps = get_maps() map_class = maps.get(ma...
def get(map_name): """Get an instance of a map by name. Errors if the map doesn't exist.""" if isinstance(map_name, Map): return map_name # Get the list of maps. This isn't at module scope to avoid problems of maps # being defined after this module is imported. maps = get_maps() map_class = maps.get(ma...
[ "Get", "an", "instance", "of", "a", "map", "by", "name", ".", "Errors", "if", "the", "map", "doesn", "t", "exist", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/maps/lib.py#L125-L136
[ "def", "get", "(", "map_name", ")", ":", "if", "isinstance", "(", "map_name", ",", "Map", ")", ":", "return", "map_name", "# Get the list of maps. This isn't at module scope to avoid problems of maps", "# being defined after this module is imported.", "maps", "=", "get_maps",...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
Map.path
The full path to the map file: directory, filename and file ending.
pysc2/maps/lib.py
def path(self): """The full path to the map file: directory, filename and file ending.""" if self.filename: map_path = os.path.join(self.directory, self.filename) if not map_path.endswith(".SC2Map"): map_path += ".SC2Map" return map_path
def path(self): """The full path to the map file: directory, filename and file ending.""" if self.filename: map_path = os.path.join(self.directory, self.filename) if not map_path.endswith(".SC2Map"): map_path += ".SC2Map" return map_path
[ "The", "full", "path", "to", "the", "map", "file", ":", "directory", "filename", "and", "file", "ending", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/maps/lib.py#L72-L78
[ "def", "path", "(", "self", ")", ":", "if", "self", ".", "filename", ":", "map_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "directory", ",", "self", ".", "filename", ")", "if", "not", "map_path", ".", "endswith", "(", "\".SC2Map\"",...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
Map.data
Return the map data.
pysc2/maps/lib.py
def data(self, run_config): """Return the map data.""" try: return run_config.map_data(self.path) except (IOError, OSError) as e: # Catch both for python 2/3 compatibility. if self.download and hasattr(e, "filename"): logging.error("Error reading map '%s' from: %s", self.name, e.filenam...
def data(self, run_config): """Return the map data.""" try: return run_config.map_data(self.path) except (IOError, OSError) as e: # Catch both for python 2/3 compatibility. if self.download and hasattr(e, "filename"): logging.error("Error reading map '%s' from: %s", self.name, e.filenam...
[ "Return", "the", "map", "data", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/maps/lib.py#L80-L88
[ "def", "data", "(", "self", ",", "run_config", ")", ":", "try", ":", "return", "run_config", ".", "map_data", "(", "self", ".", "path", ")", "except", "(", "IOError", ",", "OSError", ")", "as", "e", ":", "# Catch both for python 2/3 compatibility.", "if", ...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
_to_point
Convert (width, height) or size -> point.Point.
pysc2/lib/features.py
def _to_point(dims): """Convert (width, height) or size -> point.Point.""" assert dims if isinstance(dims, (tuple, list)): if len(dims) != 2: raise ValueError( "A two element tuple or list is expected here, got {}.".format(dims)) else: width = int(dims[0]) height = int(dims[1]...
def _to_point(dims): """Convert (width, height) or size -> point.Point.""" assert dims if isinstance(dims, (tuple, list)): if len(dims) != 2: raise ValueError( "A two element tuple or list is expected here, got {}.".format(dims)) else: width = int(dims[0]) height = int(dims[1]...
[ "Convert", "(", "width", "height", ")", "or", "size", "-", ">", "point", ".", "Point", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/features.py#L342-L363
[ "def", "_to_point", "(", "dims", ")", ":", "assert", "dims", "if", "isinstance", "(", "dims", ",", "(", "tuple", ",", "list", ")", ")", ":", "if", "len", "(", "dims", ")", "!=", "2", ":", "raise", "ValueError", "(", "\"A two element tuple or list is expe...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
parse_agent_interface_format
Creates an AgentInterfaceFormat object from keyword args. Convenient when using dictionaries or command-line arguments for config. Note that the feature_* and rgb_* properties define the respective spatial observation dimensions and accept: * None or 0 to disable that spatial observation. * A single...
pysc2/lib/features.py
def parse_agent_interface_format( feature_screen=None, feature_minimap=None, rgb_screen=None, rgb_minimap=None, action_space=None, camera_width_world_units=None, use_feature_units=False, use_raw_units=False, use_unit_counts=False, use_camera_position=False): """Creates an Agent...
def parse_agent_interface_format( feature_screen=None, feature_minimap=None, rgb_screen=None, rgb_minimap=None, action_space=None, camera_width_world_units=None, use_feature_units=False, use_raw_units=False, use_unit_counts=False, use_camera_position=False): """Creates an Agent...
[ "Creates", "an", "AgentInterfaceFormat", "object", "from", "keyword", "args", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/features.py#L536-L598
[ "def", "parse_agent_interface_format", "(", "feature_screen", "=", "None", ",", "feature_minimap", "=", "None", ",", "rgb_screen", "=", "None", ",", "rgb_minimap", "=", "None", ",", "action_space", "=", "None", ",", "camera_width_world_units", "=", "None", ",", ...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
features_from_game_info
Construct a Features object using data extracted from game info. Args: game_info: A `sc_pb.ResponseGameInfo` from the game. use_feature_units: Whether to include the feature unit observation. use_raw_units: Whether to include raw unit data in observations. This differs from feature_units because ...
pysc2/lib/features.py
def features_from_game_info( game_info, use_feature_units=False, use_raw_units=False, action_space=None, hide_specific_actions=True, use_unit_counts=False, use_camera_position=False): """Construct a Features object using data extracted from game info. Args: game_info: A `sc_pb.Respo...
def features_from_game_info( game_info, use_feature_units=False, use_raw_units=False, action_space=None, hide_specific_actions=True, use_unit_counts=False, use_camera_position=False): """Construct a Features object using data extracted from game info. Args: game_info: A `sc_pb.Respo...
[ "Construct", "a", "Features", "object", "using", "data", "extracted", "from", "game", "info", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/features.py#L601-L670
[ "def", "features_from_game_info", "(", "game_info", ",", "use_feature_units", "=", "False", ",", "use_raw_units", "=", "False", ",", "action_space", "=", "None", ",", "hide_specific_actions", "=", "True", ",", "use_unit_counts", "=", "False", ",", "use_camera_positi...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
_init_valid_functions
Initialize ValidFunctions and set up the callbacks.
pysc2/lib/features.py
def _init_valid_functions(action_dimensions): """Initialize ValidFunctions and set up the callbacks.""" sizes = { "screen": tuple(int(i) for i in action_dimensions.screen), "screen2": tuple(int(i) for i in action_dimensions.screen), "minimap": tuple(int(i) for i in action_dimensions.minimap), } ...
def _init_valid_functions(action_dimensions): """Initialize ValidFunctions and set up the callbacks.""" sizes = { "screen": tuple(int(i) for i in action_dimensions.screen), "screen2": tuple(int(i) for i in action_dimensions.screen), "minimap": tuple(int(i) for i in action_dimensions.minimap), } ...
[ "Initialize", "ValidFunctions", "and", "set", "up", "the", "callbacks", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/features.py#L673-L689
[ "def", "_init_valid_functions", "(", "action_dimensions", ")", ":", "sizes", "=", "{", "\"screen\"", ":", "tuple", "(", "int", "(", "i", ")", "for", "i", "in", "action_dimensions", ".", "screen", ")", ",", "\"screen2\"", ":", "tuple", "(", "int", "(", "i...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
Feature.unpack
Return a correctly shaped numpy array for this feature.
pysc2/lib/features.py
def unpack(self, obs): """Return a correctly shaped numpy array for this feature.""" planes = getattr(obs.feature_layer_data, self.layer_set) plane = getattr(planes, self.name) return self.unpack_layer(plane)
def unpack(self, obs): """Return a correctly shaped numpy array for this feature.""" planes = getattr(obs.feature_layer_data, self.layer_set) plane = getattr(planes, self.name) return self.unpack_layer(plane)
[ "Return", "a", "correctly", "shaped", "numpy", "array", "for", "this", "feature", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/features.py#L222-L226
[ "def", "unpack", "(", "self", ",", "obs", ")", ":", "planes", "=", "getattr", "(", "obs", ".", "feature_layer_data", ",", "self", ".", "layer_set", ")", "plane", "=", "getattr", "(", "planes", ",", "self", ".", "name", ")", "return", "self", ".", "un...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
Feature.unpack_layer
Return a correctly shaped numpy array given the feature layer bytes.
pysc2/lib/features.py
def unpack_layer(plane): """Return a correctly shaped numpy array given the feature layer bytes.""" size = point.Point.build(plane.size) if size == (0, 0): # New layer that isn't implemented in this SC2 version. return None data = np.frombuffer(plane.data, dtype=Feature.dtypes[plane.bits_per...
def unpack_layer(plane): """Return a correctly shaped numpy array given the feature layer bytes.""" size = point.Point.build(plane.size) if size == (0, 0): # New layer that isn't implemented in this SC2 version. return None data = np.frombuffer(plane.data, dtype=Feature.dtypes[plane.bits_per...
[ "Return", "a", "correctly", "shaped", "numpy", "array", "given", "the", "feature", "layer", "bytes", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/features.py#L230-L244
[ "def", "unpack_layer", "(", "plane", ")", ":", "size", "=", "point", ".", "Point", ".", "build", "(", "plane", ".", "size", ")", "if", "size", "==", "(", "0", ",", "0", ")", ":", "# New layer that isn't implemented in this SC2 version.", "return", "None", ...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
Feature.unpack_rgb_image
Return a correctly shaped numpy array given the image bytes.
pysc2/lib/features.py
def unpack_rgb_image(plane): """Return a correctly shaped numpy array given the image bytes.""" assert plane.bits_per_pixel == 24, "{} != 24".format(plane.bits_per_pixel) size = point.Point.build(plane.size) data = np.frombuffer(plane.data, dtype=np.uint8) return data.reshape(size.y, size.x, 3)
def unpack_rgb_image(plane): """Return a correctly shaped numpy array given the image bytes.""" assert plane.bits_per_pixel == 24, "{} != 24".format(plane.bits_per_pixel) size = point.Point.build(plane.size) data = np.frombuffer(plane.data, dtype=np.uint8) return data.reshape(size.y, size.x, 3)
[ "Return", "a", "correctly", "shaped", "numpy", "array", "given", "the", "image", "bytes", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/features.py#L248-L253
[ "def", "unpack_rgb_image", "(", "plane", ")", ":", "assert", "plane", ".", "bits_per_pixel", "==", "24", ",", "\"{} != 24\"", ".", "format", "(", "plane", ".", "bits_per_pixel", ")", "size", "=", "point", ".", "Point", ".", "build", "(", "plane", ".", "s...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
Features.init_camera
Initialize the camera (especially for feature_units). This is called in the constructor and may be called repeatedly after `Features` is constructed, since it deals with rescaling coordinates and not changing environment/action specs. Args: feature_dimensions: See the documentation in `AgentInte...
pysc2/lib/features.py
def init_camera( self, feature_dimensions, map_size, camera_width_world_units): """Initialize the camera (especially for feature_units). This is called in the constructor and may be called repeatedly after `Features` is constructed, since it deals with rescaling coordinates and not changing envir...
def init_camera( self, feature_dimensions, map_size, camera_width_world_units): """Initialize the camera (especially for feature_units). This is called in the constructor and may be called repeatedly after `Features` is constructed, since it deals with rescaling coordinates and not changing envir...
[ "Initialize", "the", "camera", "(", "especially", "for", "feature_units", ")", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/features.py#L733-L766
[ "def", "init_camera", "(", "self", ",", "feature_dimensions", ",", "map_size", ",", "camera_width_world_units", ")", ":", "if", "not", "map_size", "or", "not", "camera_width_world_units", ":", "raise", "ValueError", "(", "\"Either pass the game_info with raw enabled, or m...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
Features._update_camera
Update the camera transform based on the new camera center.
pysc2/lib/features.py
def _update_camera(self, camera_center): """Update the camera transform based on the new camera center.""" self._world_tl_to_world_camera_rel.offset = ( -self._world_to_world_tl.fwd_pt(camera_center) * self._world_tl_to_world_camera_rel.scale)
def _update_camera(self, camera_center): """Update the camera transform based on the new camera center.""" self._world_tl_to_world_camera_rel.offset = ( -self._world_to_world_tl.fwd_pt(camera_center) * self._world_tl_to_world_camera_rel.scale)
[ "Update", "the", "camera", "transform", "based", "on", "the", "new", "camera", "center", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/features.py#L768-L772
[ "def", "_update_camera", "(", "self", ",", "camera_center", ")", ":", "self", ".", "_world_tl_to_world_camera_rel", ".", "offset", "=", "(", "-", "self", ".", "_world_to_world_tl", ".", "fwd_pt", "(", "camera_center", ")", "*", "self", ".", "_world_tl_to_world_c...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
Features.observation_spec
The observation spec for the SC2 environment. It's worth noting that the image-like observations are in y,x/row,column order which is different than the actions which are in x,y order. This is due to conflicting conventions, and to facilitate printing of the images. Returns: The dict of observat...
pysc2/lib/features.py
def observation_spec(self): """The observation spec for the SC2 environment. It's worth noting that the image-like observations are in y,x/row,column order which is different than the actions which are in x,y order. This is due to conflicting conventions, and to facilitate printing of the images. ...
def observation_spec(self): """The observation spec for the SC2 environment. It's worth noting that the image-like observations are in y,x/row,column order which is different than the actions which are in x,y order. This is due to conflicting conventions, and to facilitate printing of the images. ...
[ "The", "observation", "spec", "for", "the", "SC2", "environment", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/features.py#L774-L832
[ "def", "observation_spec", "(", "self", ")", ":", "obs_spec", "=", "named_array", ".", "NamedDict", "(", "{", "\"action_result\"", ":", "(", "0", ",", ")", ",", "# See error.proto: ActionResult.", "\"alerts\"", ":", "(", "0", ",", ")", ",", "# See sc2api.proto...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
Features.transform_obs
Render some SC2 observations into something an agent can handle.
pysc2/lib/features.py
def transform_obs(self, obs): """Render some SC2 observations into something an agent can handle.""" empty = np.array([], dtype=np.int32).reshape((0, 7)) out = named_array.NamedDict({ # Fill out some that are sometimes empty. "single_select": empty, "multi_select": empty, "build_que...
def transform_obs(self, obs): """Render some SC2 observations into something an agent can handle.""" empty = np.array([], dtype=np.int32).reshape((0, 7)) out = named_array.NamedDict({ # Fill out some that are sometimes empty. "single_select": empty, "multi_select": empty, "build_que...
[ "Render", "some", "SC2", "observations", "into", "something", "an", "agent", "can", "handle", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/features.py#L839-L1054
[ "def", "transform_obs", "(", "self", ",", "obs", ")", ":", "empty", "=", "np", ".", "array", "(", "[", "]", ",", "dtype", "=", "np", ".", "int32", ")", ".", "reshape", "(", "(", "0", ",", "7", ")", ")", "out", "=", "named_array", ".", "NamedDic...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
Features.available_actions
Return the list of available action ids.
pysc2/lib/features.py
def available_actions(self, obs): """Return the list of available action ids.""" available_actions = set() hide_specific_actions = self._agent_interface_format.hide_specific_actions for i, func in six.iteritems(actions.FUNCTIONS_AVAILABLE): if func.avail_fn(obs): available_actions.add(i) ...
def available_actions(self, obs): """Return the list of available action ids.""" available_actions = set() hide_specific_actions = self._agent_interface_format.hide_specific_actions for i, func in six.iteritems(actions.FUNCTIONS_AVAILABLE): if func.avail_fn(obs): available_actions.add(i) ...
[ "Return", "the", "list", "of", "available", "action", "ids", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/features.py#L1057-L1079
[ "def", "available_actions", "(", "self", ",", "obs", ")", ":", "available_actions", "=", "set", "(", ")", "hide_specific_actions", "=", "self", ".", "_agent_interface_format", ".", "hide_specific_actions", "for", "i", ",", "func", "in", "six", ".", "iteritems", ...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
Features.transform_action
Tranform an agent-style action to one that SC2 can consume. Args: obs: a `sc_pb.Observation` from the previous frame. func_call: a `FunctionCall` to be turned into a `sc_pb.Action`. skip_available: If True, assume the action is available. This should only be used for testing or if you e...
pysc2/lib/features.py
def transform_action(self, obs, func_call, skip_available=False): """Tranform an agent-style action to one that SC2 can consume. Args: obs: a `sc_pb.Observation` from the previous frame. func_call: a `FunctionCall` to be turned into a `sc_pb.Action`. skip_available: If True, assume the action...
def transform_action(self, obs, func_call, skip_available=False): """Tranform an agent-style action to one that SC2 can consume. Args: obs: a `sc_pb.Observation` from the previous frame. func_call: a `FunctionCall` to be turned into a `sc_pb.Action`. skip_available: If True, assume the action...
[ "Tranform", "an", "agent", "-", "style", "action", "to", "one", "that", "SC2", "can", "consume", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/features.py#L1082-L1146
[ "def", "transform_action", "(", "self", ",", "obs", ",", "func_call", ",", "skip_available", "=", "False", ")", ":", "func_id", "=", "func_call", ".", "function", "try", ":", "func", "=", "actions", ".", "FUNCTIONS", "[", "func_id", "]", "except", "KeyErro...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
Features.reverse_action
Transform an SC2-style action into an agent-style action. This should be the inverse of `transform_action`. Args: action: a `sc_pb.Action` to be transformed. Returns: A corresponding `actions.FunctionCall`. Raises: ValueError: if it doesn't know how to transform this action.
pysc2/lib/features.py
def reverse_action(self, action): """Transform an SC2-style action into an agent-style action. This should be the inverse of `transform_action`. Args: action: a `sc_pb.Action` to be transformed. Returns: A corresponding `actions.FunctionCall`. Raises: ValueError: if it doesn't ...
def reverse_action(self, action): """Transform an SC2-style action into an agent-style action. This should be the inverse of `transform_action`. Args: action: a `sc_pb.Action` to be transformed. Returns: A corresponding `actions.FunctionCall`. Raises: ValueError: if it doesn't ...
[ "Transform", "an", "SC2", "-", "style", "action", "into", "an", "agent", "-", "style", "action", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/features.py#L1149-L1247
[ "def", "reverse_action", "(", "self", ",", "action", ")", ":", "FUNCTIONS", "=", "actions", ".", "FUNCTIONS", "# pylint: disable=invalid-name", "aif", "=", "self", ".", "_agent_interface_format", "def", "func_call_ability", "(", "ability_id", ",", "cmd_type", ",", ...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
_xy_locs
Mask should be a set of bools from comparison with a feature layer.
pysc2/agents/scripted_agent.py
def _xy_locs(mask): """Mask should be a set of bools from comparison with a feature layer.""" y, x = mask.nonzero() return list(zip(x, y))
def _xy_locs(mask): """Mask should be a set of bools from comparison with a feature layer.""" y, x = mask.nonzero() return list(zip(x, y))
[ "Mask", "should", "be", "a", "set", "of", "bools", "from", "comparison", "with", "a", "feature", "layer", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/agents/scripted_agent.py#L33-L36
[ "def", "_xy_locs", "(", "mask", ")", ":", "y", ",", "x", "=", "mask", ".", "nonzero", "(", ")", "return", "list", "(", "zip", "(", "x", ",", "y", ")", ")" ]
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
main
Run SC2 to play a game or a replay.
pysc2/bin/play.py
def main(unused_argv): """Run SC2 to play a game or a replay.""" stopwatch.sw.enabled = FLAGS.profile or FLAGS.trace stopwatch.sw.trace = FLAGS.trace if (FLAGS.map and FLAGS.replay) or (not FLAGS.map and not FLAGS.replay): sys.exit("Must supply either a map or replay.") if FLAGS.replay and not FLAGS.rep...
def main(unused_argv): """Run SC2 to play a game or a replay.""" stopwatch.sw.enabled = FLAGS.profile or FLAGS.trace stopwatch.sw.trace = FLAGS.trace if (FLAGS.map and FLAGS.replay) or (not FLAGS.map and not FLAGS.replay): sys.exit("Must supply either a map or replay.") if FLAGS.replay and not FLAGS.rep...
[ "Run", "SC2", "to", "play", "a", "game", "or", "a", "replay", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/bin/play.py#L84-L197
[ "def", "main", "(", "unused_argv", ")", ":", "stopwatch", ".", "sw", ".", "enabled", "=", "FLAGS", ".", "profile", "or", "FLAGS", ".", "trace", "stopwatch", ".", "sw", ".", "trace", "=", "FLAGS", ".", "trace", "if", "(", "FLAGS", ".", "map", "and", ...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
_shutdown_proc
Wait for a proc to shut down, then terminate or kill it after `timeout`.
pysc2/lib/sc_process.py
def _shutdown_proc(p, timeout): """Wait for a proc to shut down, then terminate or kill it after `timeout`.""" freq = 10 # how often to check per second for _ in range(1 + timeout * freq): ret = p.poll() if ret is not None: logging.info("Shutdown gracefully.") return ret time.sleep(1 / fr...
def _shutdown_proc(p, timeout): """Wait for a proc to shut down, then terminate or kill it after `timeout`.""" freq = 10 # how often to check per second for _ in range(1 + timeout * freq): ret = p.poll() if ret is not None: logging.info("Shutdown gracefully.") return ret time.sleep(1 / fr...
[ "Wait", "for", "a", "proc", "to", "shut", "down", "then", "terminate", "or", "kill", "it", "after", "timeout", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/sc_process.py#L195-L206
[ "def", "_shutdown_proc", "(", "p", ",", "timeout", ")", ":", "freq", "=", "10", "# how often to check per second", "for", "_", "in", "range", "(", "1", "+", "timeout", "*", "freq", ")", ":", "ret", "=", "p", ".", "poll", "(", ")", "if", "ret", "is", ...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
StarcraftProcess.close
Shut down the game and clean up.
pysc2/lib/sc_process.py
def close(self): """Shut down the game and clean up.""" if hasattr(self, "_controller") and self._controller: self._controller.quit() self._controller.close() self._controller = None self._shutdown() if hasattr(self, "_port") and self._port: portpicker.return_port(self._port) ...
def close(self): """Shut down the game and clean up.""" if hasattr(self, "_controller") and self._controller: self._controller.quit() self._controller.close() self._controller = None self._shutdown() if hasattr(self, "_port") and self._port: portpicker.return_port(self._port) ...
[ "Shut", "down", "the", "game", "and", "clean", "up", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/sc_process.py#L122-L133
[ "def", "close", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "\"_controller\"", ")", "and", "self", ".", "_controller", ":", "self", ".", "_controller", ".", "quit", "(", ")", "self", ".", "_controller", ".", "close", "(", ")", "self", "...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
StarcraftProcess._launch
Launch the process and return the process object.
pysc2/lib/sc_process.py
def _launch(self, run_config, args, **kwargs): """Launch the process and return the process object.""" del kwargs try: with sw("popen"): return subprocess.Popen(args, cwd=run_config.cwd, env=run_config.env) except OSError: logging.exception("Failed to launch") raise SC2LaunchEr...
def _launch(self, run_config, args, **kwargs): """Launch the process and return the process object.""" del kwargs try: with sw("popen"): return subprocess.Popen(args, cwd=run_config.cwd, env=run_config.env) except OSError: logging.exception("Failed to launch") raise SC2LaunchEr...
[ "Launch", "the", "process", "and", "return", "the", "process", "object", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/sc_process.py#L168-L176
[ "def", "_launch", "(", "self", ",", "run_config", ",", "args", ",", "*", "*", "kwargs", ")", ":", "del", "kwargs", "try", ":", "with", "sw", "(", "\"popen\"", ")", ":", "return", "subprocess", ".", "Popen", "(", "args", ",", "cwd", "=", "run_config",...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
StarcraftProcess._shutdown
Terminate the sub-process.
pysc2/lib/sc_process.py
def _shutdown(self): """Terminate the sub-process.""" if self._proc: ret = _shutdown_proc(self._proc, 3) logging.info("Shutdown with return code: %s", ret) self._proc = None
def _shutdown(self): """Terminate the sub-process.""" if self._proc: ret = _shutdown_proc(self._proc, 3) logging.info("Shutdown with return code: %s", ret) self._proc = None
[ "Terminate", "the", "sub", "-", "process", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/sc_process.py#L178-L183
[ "def", "_shutdown", "(", "self", ")", ":", "if", "self", ".", "_proc", ":", "ret", "=", "_shutdown_proc", "(", "self", ".", "_proc", ",", "3", ")", "logging", ".", "info", "(", "\"Shutdown with return code: %s\"", ",", "ret", ")", "self", ".", "_proc", ...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
get_data
Retrieve static data from the game.
pysc2/bin/gen_actions.py
def get_data(): """Retrieve static data from the game.""" run_config = run_configs.get() with run_config.start(want_rgb=False) as controller: m = maps.get("Sequencer") # Arbitrary ladder map. create = sc_pb.RequestCreateGame(local_map=sc_pb.LocalMap( map_path=m.path, map_data=m.data(run_config))...
def get_data(): """Retrieve static data from the game.""" run_config = run_configs.get() with run_config.start(want_rgb=False) as controller: m = maps.get("Sequencer") # Arbitrary ladder map. create = sc_pb.RequestCreateGame(local_map=sc_pb.LocalMap( map_path=m.path, map_data=m.data(run_config))...
[ "Retrieve", "static", "data", "from", "the", "game", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/bin/gen_actions.py#L39-L55
[ "def", "get_data", "(", ")", ":", "run_config", "=", "run_configs", ".", "get", "(", ")", "with", "run_config", ".", "start", "(", "want_rgb", "=", "False", ")", "as", "controller", ":", "m", "=", "maps", ".", "get", "(", "\"Sequencer\"", ")", "# Arbit...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
generate_csv
Generate a CSV of the abilities for easy commenting.
pysc2/bin/gen_actions.py
def generate_csv(data): """Generate a CSV of the abilities for easy commenting.""" print(",".join([ "ability_id", "link_name", "link_index", "button_name", "hotkey", "friendly_name", "remap_to", "mismatch", ])) for ability in sorted(six.itervalues(data.abilities),...
def generate_csv(data): """Generate a CSV of the abilities for easy commenting.""" print(",".join([ "ability_id", "link_name", "link_index", "button_name", "hotkey", "friendly_name", "remap_to", "mismatch", ])) for ability in sorted(six.itervalues(data.abilities),...
[ "Generate", "a", "CSV", "of", "the", "abilities", "for", "easy", "commenting", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/bin/gen_actions.py#L72-L124
[ "def", "generate_csv", "(", "data", ")", ":", "print", "(", "\",\"", ".", "join", "(", "[", "\"ability_id\"", ",", "\"link_name\"", ",", "\"link_index\"", ",", "\"button_name\"", ",", "\"hotkey\"", ",", "\"friendly_name\"", ",", "\"remap_to\"", ",", "\"mismatch\...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
generate_py_abilities
Generate the list of functions in actions.py.
pysc2/bin/gen_actions.py
def generate_py_abilities(data): """Generate the list of functions in actions.py.""" def print_action(func_id, name, func, ab_id, general_id): args = [func_id, '"%s"' % name, func, ab_id] if general_id: args.append(general_id) print(" Function.ability(%s)," % ", ".join(str(v) for v in args)) ...
def generate_py_abilities(data): """Generate the list of functions in actions.py.""" def print_action(func_id, name, func, ab_id, general_id): args = [func_id, '"%s"' % name, func, ab_id] if general_id: args.append(general_id) print(" Function.ability(%s)," % ", ".join(str(v) for v in args)) ...
[ "Generate", "the", "list", "of", "functions", "in", "actions", ".", "py", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/bin/gen_actions.py#L127-L157
[ "def", "generate_py_abilities", "(", "data", ")", ":", "def", "print_action", "(", "func_id", ",", "name", ",", "func", ",", "ab_id", ",", "general_id", ")", ":", "args", "=", "[", "func_id", ",", "'\"%s\"'", "%", "name", ",", "func", ",", "ab_id", "]"...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
agent
Run the agent, connecting to a (remote) host started independently.
pysc2/bin/agent_remote.py
def agent(): """Run the agent, connecting to a (remote) host started independently.""" agent_module, agent_name = FLAGS.agent.rsplit(".", 1) agent_cls = getattr(importlib.import_module(agent_module), agent_name) logging.info("Starting agent:") with remote_sc2_env.RemoteSC2Env( map_name=FLAGS.map, ...
def agent(): """Run the agent, connecting to a (remote) host started independently.""" agent_module, agent_name = FLAGS.agent.rsplit(".", 1) agent_cls = getattr(importlib.import_module(agent_module), agent_name) logging.info("Starting agent:") with remote_sc2_env.RemoteSC2Env( map_name=FLAGS.map, ...
[ "Run", "the", "agent", "connecting", "to", "a", "(", "remote", ")", "host", "started", "independently", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/bin/agent_remote.py#L124-L152
[ "def", "agent", "(", ")", ":", "agent_module", ",", "agent_name", "=", "FLAGS", ".", "agent", ".", "rsplit", "(", "\".\"", ",", "1", ")", "agent_cls", "=", "getattr", "(", "importlib", ".", "import_module", "(", "agent_module", ")", ",", "agent_name", ")...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
human
Run a host which expects one player to connect remotely.
pysc2/bin/agent_remote.py
def human(): """Run a host which expects one player to connect remotely.""" run_config = run_configs.get() map_inst = maps.get(FLAGS.map) if not FLAGS.rgb_screen_size or not FLAGS.rgb_minimap_size: logging.info("Use --rgb_screen_size and --rgb_minimap_size if you want rgb " "observations....
def human(): """Run a host which expects one player to connect remotely.""" run_config = run_configs.get() map_inst = maps.get(FLAGS.map) if not FLAGS.rgb_screen_size or not FLAGS.rgb_minimap_size: logging.info("Use --rgb_screen_size and --rgb_minimap_size if you want rgb " "observations....
[ "Run", "a", "host", "which", "expects", "one", "player", "to", "connect", "remotely", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/bin/agent_remote.py#L155-L229
[ "def", "human", "(", ")", ":", "run_config", "=", "run_configs", ".", "get", "(", ")", "map_inst", "=", "maps", ".", "get", "(", "FLAGS", ".", "map", ")", "if", "not", "FLAGS", ".", "rgb_screen_size", "or", "not", "FLAGS", ".", "rgb_minimap_size", ":",...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
Stat.dev
Standard deviation.
pysc2/lib/stopwatch.py
def dev(self): """Standard deviation.""" if self.num == 0: return 0 return math.sqrt(max(0, self.sum_sq / self.num - (self.sum / self.num)**2))
def dev(self): """Standard deviation.""" if self.num == 0: return 0 return math.sqrt(max(0, self.sum_sq / self.num - (self.sum / self.num)**2))
[ "Standard", "deviation", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/stopwatch.py#L60-L64
[ "def", "dev", "(", "self", ")", ":", "if", "self", ".", "num", "==", "0", ":", "return", "0", "return", "math", ".", "sqrt", "(", "max", "(", "0", ",", "self", ".", "sum_sq", "/", "self", ".", "num", "-", "(", "self", ".", "sum", "/", "self",...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
StopWatch.decorate
Decorate a function/method to check its timings. To use the function's name: @sw.decorate def func(): pass To name it explicitly: @sw.decorate("name") def random_func_name(): pass Args: name_or_func: the name or the function to decorate. Returns: I...
pysc2/lib/stopwatch.py
def decorate(self, name_or_func): """Decorate a function/method to check its timings. To use the function's name: @sw.decorate def func(): pass To name it explicitly: @sw.decorate("name") def random_func_name(): pass Args: name_or_func: the name or the fu...
def decorate(self, name_or_func): """Decorate a function/method to check its timings. To use the function's name: @sw.decorate def func(): pass To name it explicitly: @sw.decorate("name") def random_func_name(): pass Args: name_or_func: the name or the fu...
[ "Decorate", "a", "function", "/", "method", "to", "check", "its", "timings", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/stopwatch.py#L174-L206
[ "def", "decorate", "(", "self", ",", "name_or_func", ")", ":", "if", "os", ".", "environ", ".", "get", "(", "\"SC2_NO_STOPWATCH\"", ")", ":", "return", "name_or_func", "if", "callable", "(", "name_or_func", ")", "else", "lambda", "func", ":", "func", "def"...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
StopWatch.parse
Parse the output below to create a new StopWatch.
pysc2/lib/stopwatch.py
def parse(s): """Parse the output below to create a new StopWatch.""" stopwatch = StopWatch() for line in s.splitlines(): if line.strip(): parts = line.split(None) name = parts[0] if name != "%": # ie not the header line rest = (float(v) for v in parts[2:]) ...
def parse(s): """Parse the output below to create a new StopWatch.""" stopwatch = StopWatch() for line in s.splitlines(): if line.strip(): parts = line.split(None) name = parts[0] if name != "%": # ie not the header line rest = (float(v) for v in parts[2:]) ...
[ "Parse", "the", "output", "below", "to", "create", "a", "new", "StopWatch", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/stopwatch.py#L242-L252
[ "def", "parse", "(", "s", ")", ":", "stopwatch", "=", "StopWatch", "(", ")", "for", "line", "in", "s", ".", "splitlines", "(", ")", ":", "if", "line", ".", "strip", "(", ")", ":", "parts", "=", "line", ".", "split", "(", "None", ")", "name", "=...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
StopWatch.str
Return a string representation of the timings.
pysc2/lib/stopwatch.py
def str(self, threshold=0.1): """Return a string representation of the timings.""" if not self._times: return "" total = sum(s.sum for k, s in six.iteritems(self._times) if "." not in k) table = [["", "% total", "sum", "avg", "dev", "min", "max", "num"]] for k, v in sorted(self._times.items())...
def str(self, threshold=0.1): """Return a string representation of the timings.""" if not self._times: return "" total = sum(s.sum for k, s in six.iteritems(self._times) if "." not in k) table = [["", "% total", "sum", "avg", "dev", "min", "max", "num"]] for k, v in sorted(self._times.items())...
[ "Return", "a", "string", "representation", "of", "the", "timings", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/stopwatch.py#L254-L282
[ "def", "str", "(", "self", ",", "threshold", "=", "0.1", ")", ":", "if", "not", "self", ".", "_times", ":", "return", "\"\"", "total", "=", "sum", "(", "s", ".", "sum", "for", "k", ",", "s", "in", "six", ".", "iteritems", "(", "self", ".", "_ti...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
generate_py_units
Generate the list of units in units.py.
pysc2/bin/gen_units.py
def generate_py_units(data): """Generate the list of units in units.py.""" units = collections.defaultdict(list) for unit in sorted(data.units, key=lambda a: a.name): if unit.unit_id in static_data.UNIT_TYPES: units[unit.race].append(unit) def print_race(name, race): print("class %s(enum.IntEnum)...
def generate_py_units(data): """Generate the list of units in units.py.""" units = collections.defaultdict(list) for unit in sorted(data.units, key=lambda a: a.name): if unit.unit_id in static_data.UNIT_TYPES: units[unit.race].append(unit) def print_race(name, race): print("class %s(enum.IntEnum)...
[ "Generate", "the", "list", "of", "units", "in", "units", ".", "py", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/bin/gen_units.py#L51-L68
[ "def", "generate_py_units", "(", "data", ")", ":", "units", "=", "collections", ".", "defaultdict", "(", "list", ")", "for", "unit", "in", "sorted", "(", "data", ".", "units", ",", "key", "=", "lambda", "a", ":", "a", ".", "name", ")", ":", "if", "...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
RunParallel.run
Run a set of functions in parallel, returning their results. Make sure any function you pass exits with a reasonable timeout. If it doesn't return within the timeout or the result is ignored due an exception in a separate thread it will continue to stick around until it finishes, including blocking pro...
pysc2/lib/run_parallel.py
def run(self, funcs): """Run a set of functions in parallel, returning their results. Make sure any function you pass exits with a reasonable timeout. If it doesn't return within the timeout or the result is ignored due an exception in a separate thread it will continue to stick around until it finishe...
def run(self, funcs): """Run a set of functions in parallel, returning their results. Make sure any function you pass exits with a reasonable timeout. If it doesn't return within the timeout or the result is ignored due an exception in a separate thread it will continue to stick around until it finishe...
[ "Run", "a", "set", "of", "functions", "in", "parallel", "returning", "their", "results", "." ]
deepmind/pysc2
python
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/run_parallel.py#L37-L75
[ "def", "run", "(", "self", ",", "funcs", ")", ":", "funcs", "=", "[", "f", "if", "callable", "(", "f", ")", "else", "functools", ".", "partial", "(", "*", "f", ")", "for", "f", "in", "funcs", "]", "if", "len", "(", "funcs", ")", "==", "1", ":...
df4cc4b00f07a2242be9ba153d4a7f4ad2017897
train
dict_to_json
Converts a list of dicts from datamodel query results to google chart json data. :param xcol: The name of a string column to be used has X axis on chart :param ycols: A list with the names of series cols, that can be used as numeric :param labels: A d...
flask_appbuilder/charts/jsontools.py
def dict_to_json(xcol, ycols, labels, value_columns): """ Converts a list of dicts from datamodel query results to google chart json data. :param xcol: The name of a string column to be used has X axis on chart :param ycols: A list with the names of series co...
def dict_to_json(xcol, ycols, labels, value_columns): """ Converts a list of dicts from datamodel query results to google chart json data. :param xcol: The name of a string column to be used has X axis on chart :param ycols: A list with the names of series co...
[ "Converts", "a", "list", "of", "dicts", "from", "datamodel", "query", "results", "to", "google", "chart", "json", "data", "." ]
dpgaspar/Flask-AppBuilder
python
https://github.com/dpgaspar/Flask-AppBuilder/blob/c293734c1b86e176a3ba57ee2deab6676d125576/flask_appbuilder/charts/jsontools.py#L6-L42
[ "def", "dict_to_json", "(", "xcol", ",", "ycols", ",", "labels", ",", "value_columns", ")", ":", "json_data", "=", "dict", "(", ")", "json_data", "[", "'cols'", "]", "=", "[", "{", "'id'", ":", "xcol", ",", "'label'", ":", "as_unicode", "(", "labels", ...
c293734c1b86e176a3ba57ee2deab6676d125576
train
OpenApi.get
Endpoint that renders an OpenApi spec for all views that belong to a certain version --- get: parameters: - in: path schema: type: string name: version responses: 200: description: Item from Model ...
flask_appbuilder/api/manager.py
def get(self, version): """ Endpoint that renders an OpenApi spec for all views that belong to a certain version --- get: parameters: - in: path schema: type: string name: version responses: 200: ...
def get(self, version): """ Endpoint that renders an OpenApi spec for all views that belong to a certain version --- get: parameters: - in: path schema: type: string name: version responses: 200: ...
[ "Endpoint", "that", "renders", "an", "OpenApi", "spec", "for", "all", "views", "that", "belong", "to", "a", "certain", "version", "---", "get", ":", "parameters", ":", "-", "in", ":", "path", "schema", ":", "type", ":", "string", "name", ":", "version", ...
dpgaspar/Flask-AppBuilder
python
https://github.com/dpgaspar/Flask-AppBuilder/blob/c293734c1b86e176a3ba57ee2deab6676d125576/flask_appbuilder/api/manager.py#L18-L49
[ "def", "get", "(", "self", ",", "version", ")", ":", "version_found", "=", "False", "api_spec", "=", "self", ".", "_create_api_spec", "(", "version", ")", "for", "base_api", "in", "current_app", ".", "appbuilder", ".", "baseviews", ":", "if", "isinstance", ...
c293734c1b86e176a3ba57ee2deab6676d125576
train
get_field_setup_query
Help function for SQLA filters, checks for dot notation on column names. If it exists, will join the query with the model from the first part of the field name. example: Contact.created_by: if created_by is a User model, it will be joined to the query.
flask_appbuilder/models/sqla/filters.py
def get_field_setup_query(query, model, column_name): """ Help function for SQLA filters, checks for dot notation on column names. If it exists, will join the query with the model from the first part of the field name. example: Contact.created_by: if created_by is a User...
def get_field_setup_query(query, model, column_name): """ Help function for SQLA filters, checks for dot notation on column names. If it exists, will join the query with the model from the first part of the field name. example: Contact.created_by: if created_by is a User...
[ "Help", "function", "for", "SQLA", "filters", "checks", "for", "dot", "notation", "on", "column", "names", ".", "If", "it", "exists", "will", "join", "the", "query", "with", "the", "model", "from", "the", "first", "part", "of", "the", "field", "name", "....
dpgaspar/Flask-AppBuilder
python
https://github.com/dpgaspar/Flask-AppBuilder/blob/c293734c1b86e176a3ba57ee2deab6676d125576/flask_appbuilder/models/sqla/filters.py#L30-L46
[ "def", "get_field_setup_query", "(", "query", ",", "model", ",", "column_name", ")", ":", "if", "not", "hasattr", "(", "model", ",", "column_name", ")", ":", "# it's an inner obj attr", "rel_model", "=", "getattr", "(", "model", ",", "column_name", ".", "split...
c293734c1b86e176a3ba57ee2deab6676d125576
train
SecurityManager.add_permission
Adds a permission to the backend, model permission :param name: name of the permission: 'can_add','can_edit' etc...
flask_appbuilder/security/mongoengine/manager.py
def add_permission(self, name): """ Adds a permission to the backend, model permission :param name: name of the permission: 'can_add','can_edit' etc... """ perm = self.find_permission(name) if perm is None: try: perm = ...
def add_permission(self, name): """ Adds a permission to the backend, model permission :param name: name of the permission: 'can_add','can_edit' etc... """ perm = self.find_permission(name) if perm is None: try: perm = ...
[ "Adds", "a", "permission", "to", "the", "backend", "model", "permission" ]
dpgaspar/Flask-AppBuilder
python
https://github.com/dpgaspar/Flask-AppBuilder/blob/c293734c1b86e176a3ba57ee2deab6676d125576/flask_appbuilder/security/mongoengine/manager.py#L187-L202
[ "def", "add_permission", "(", "self", ",", "name", ")", ":", "perm", "=", "self", ".", "find_permission", "(", "name", ")", "if", "perm", "is", "None", ":", "try", ":", "perm", "=", "self", ".", "permission_model", "(", "name", "=", "name", ")", "per...
c293734c1b86e176a3ba57ee2deab6676d125576
train
SecurityManager.add_view_menu
Adds a view or menu to the backend, model view_menu param name: name of the view menu to add
flask_appbuilder/security/mongoengine/manager.py
def add_view_menu(self, name): """ Adds a view or menu to the backend, model view_menu param name: name of the view menu to add """ view_menu = self.find_view_menu(name) if view_menu is None: try: view_menu = self.viewme...
def add_view_menu(self, name): """ Adds a view or menu to the backend, model view_menu param name: name of the view menu to add """ view_menu = self.find_view_menu(name) if view_menu is None: try: view_menu = self.viewme...
[ "Adds", "a", "view", "or", "menu", "to", "the", "backend", "model", "view_menu", "param", "name", ":", "name", "of", "the", "view", "menu", "to", "add" ]
dpgaspar/Flask-AppBuilder
python
https://github.com/dpgaspar/Flask-AppBuilder/blob/c293734c1b86e176a3ba57ee2deab6676d125576/flask_appbuilder/security/mongoengine/manager.py#L233-L247
[ "def", "add_view_menu", "(", "self", ",", "name", ")", ":", "view_menu", "=", "self", ".", "find_view_menu", "(", "name", ")", "if", "view_menu", "is", "None", ":", "try", ":", "view_menu", "=", "self", ".", "viewmenu_model", "(", "name", "=", "name", ...
c293734c1b86e176a3ba57ee2deab6676d125576
train
SecurityManager.del_view_menu
Deletes a ViewMenu from the backend :param name: name of the ViewMenu
flask_appbuilder/security/mongoengine/manager.py
def del_view_menu(self, name): """ Deletes a ViewMenu from the backend :param name: name of the ViewMenu """ obj = self.find_view_menu(name) if obj: try: obj.delete() except Exception as e: l...
def del_view_menu(self, name): """ Deletes a ViewMenu from the backend :param name: name of the ViewMenu """ obj = self.find_view_menu(name) if obj: try: obj.delete() except Exception as e: l...
[ "Deletes", "a", "ViewMenu", "from", "the", "backend" ]
dpgaspar/Flask-AppBuilder
python
https://github.com/dpgaspar/Flask-AppBuilder/blob/c293734c1b86e176a3ba57ee2deab6676d125576/flask_appbuilder/security/mongoengine/manager.py#L249-L261
[ "def", "del_view_menu", "(", "self", ",", "name", ")", ":", "obj", "=", "self", ".", "find_view_menu", "(", "name", ")", "if", "obj", ":", "try", ":", "obj", ".", "delete", "(", ")", "except", "Exception", "as", "e", ":", "log", ".", "error", "(", ...
c293734c1b86e176a3ba57ee2deab6676d125576
train
SecurityManager.find_permission_view_menu
Finds and returns a PermissionView by names
flask_appbuilder/security/mongoengine/manager.py
def find_permission_view_menu(self, permission_name, view_menu_name): """ Finds and returns a PermissionView by names """ permission = self.find_permission(permission_name) view_menu = self.find_view_menu(view_menu_name) if permission and view_menu: return...
def find_permission_view_menu(self, permission_name, view_menu_name): """ Finds and returns a PermissionView by names """ permission = self.find_permission(permission_name) view_menu = self.find_view_menu(view_menu_name) if permission and view_menu: return...
[ "Finds", "and", "returns", "a", "PermissionView", "by", "names" ]
dpgaspar/Flask-AppBuilder
python
https://github.com/dpgaspar/Flask-AppBuilder/blob/c293734c1b86e176a3ba57ee2deab6676d125576/flask_appbuilder/security/mongoengine/manager.py#L269-L278
[ "def", "find_permission_view_menu", "(", "self", ",", "permission_name", ",", "view_menu_name", ")", ":", "permission", "=", "self", ".", "find_permission", "(", "permission_name", ")", "view_menu", "=", "self", ".", "find_view_menu", "(", "view_menu_name", ")", "...
c293734c1b86e176a3ba57ee2deab6676d125576
train
SecurityManager.add_permission_view_menu
Adds a permission on a view or menu to the backend :param permission_name: name of the permission to add: 'can_add','can_edit' etc... :param view_menu_name: name of the view menu to add
flask_appbuilder/security/mongoengine/manager.py
def add_permission_view_menu(self, permission_name, view_menu_name): """ Adds a permission on a view or menu to the backend :param permission_name: name of the permission to add: 'can_add','can_edit' etc... :param view_menu_name: name of the v...
def add_permission_view_menu(self, permission_name, view_menu_name): """ Adds a permission on a view or menu to the backend :param permission_name: name of the permission to add: 'can_add','can_edit' etc... :param view_menu_name: name of the v...
[ "Adds", "a", "permission", "on", "a", "view", "or", "menu", "to", "the", "backend" ]
dpgaspar/Flask-AppBuilder
python
https://github.com/dpgaspar/Flask-AppBuilder/blob/c293734c1b86e176a3ba57ee2deab6676d125576/flask_appbuilder/security/mongoengine/manager.py#L289-L315
[ "def", "add_permission_view_menu", "(", "self", ",", "permission_name", ",", "view_menu_name", ")", ":", "if", "not", "(", "permission_name", "and", "view_menu_name", ")", ":", "return", "None", "pv", "=", "self", ".", "find_permission_view_menu", "(", "permission...
c293734c1b86e176a3ba57ee2deab6676d125576
train
SecurityManager.add_permission_role
Add permission-ViewMenu object to Role :param role: The role object :param perm_view: The PermissionViewMenu object
flask_appbuilder/security/mongoengine/manager.py
def add_permission_role(self, role, perm_view): """ Add permission-ViewMenu object to Role :param role: The role object :param perm_view: The PermissionViewMenu object """ if perm_view not in role.permissions: try: ...
def add_permission_role(self, role, perm_view): """ Add permission-ViewMenu object to Role :param role: The role object :param perm_view: The PermissionViewMenu object """ if perm_view not in role.permissions: try: ...
[ "Add", "permission", "-", "ViewMenu", "object", "to", "Role" ]
dpgaspar/Flask-AppBuilder
python
https://github.com/dpgaspar/Flask-AppBuilder/blob/c293734c1b86e176a3ba57ee2deab6676d125576/flask_appbuilder/security/mongoengine/manager.py#L344-L361
[ "def", "add_permission_role", "(", "self", ",", "role", ",", "perm_view", ")", ":", "if", "perm_view", "not", "in", "role", ".", "permissions", ":", "try", ":", "role", ".", "permissions", ".", "append", "(", "perm_view", ")", "role", ".", "save", "(", ...
c293734c1b86e176a3ba57ee2deab6676d125576
train
SecurityManager.del_permission_role
Remove permission-ViewMenu object to Role :param role: The role object :param perm_view: The PermissionViewMenu object
flask_appbuilder/security/mongoengine/manager.py
def del_permission_role(self, role, perm_view): """ Remove permission-ViewMenu object to Role :param role: The role object :param perm_view: The PermissionViewMenu object """ if perm_view in role.permissions: try: ...
def del_permission_role(self, role, perm_view): """ Remove permission-ViewMenu object to Role :param role: The role object :param perm_view: The PermissionViewMenu object """ if perm_view in role.permissions: try: ...
[ "Remove", "permission", "-", "ViewMenu", "object", "to", "Role" ]
dpgaspar/Flask-AppBuilder
python
https://github.com/dpgaspar/Flask-AppBuilder/blob/c293734c1b86e176a3ba57ee2deab6676d125576/flask_appbuilder/security/mongoengine/manager.py#L363-L380
[ "def", "del_permission_role", "(", "self", ",", "role", ",", "perm_view", ")", ":", "if", "perm_view", "in", "role", ".", "permissions", ":", "try", ":", "role", ".", "permissions", ".", "remove", "(", "perm_view", ")", "role", ".", "save", "(", ")", "...
c293734c1b86e176a3ba57ee2deab6676d125576
train
MongoEngineInterface.get_columns_list
modified: removing the '_cls' column added by Mongoengine to support mongodb document inheritance cf. http://docs.mongoengine.org/apireference.html#documents: "A Document subclass may be itself subclassed, to create a specialised version of the document that will be stored in the...
flask_appbuilder/models/mongoengine/interface.py
def get_columns_list(self): """ modified: removing the '_cls' column added by Mongoengine to support mongodb document inheritance cf. http://docs.mongoengine.org/apireference.html#documents: "A Document subclass may be itself subclassed, to create a specialised version of...
def get_columns_list(self): """ modified: removing the '_cls' column added by Mongoengine to support mongodb document inheritance cf. http://docs.mongoengine.org/apireference.html#documents: "A Document subclass may be itself subclassed, to create a specialised version of...
[ "modified", ":", "removing", "the", "_cls", "column", "added", "by", "Mongoengine", "to", "support", "mongodb", "document", "inheritance", "cf", ".", "http", ":", "//", "docs", ".", "mongoengine", ".", "org", "/", "apireference", ".", "html#documents", ":", ...
dpgaspar/Flask-AppBuilder
python
https://github.com/dpgaspar/Flask-AppBuilder/blob/c293734c1b86e176a3ba57ee2deab6676d125576/flask_appbuilder/models/mongoengine/interface.py#L238-L254
[ "def", "get_columns_list", "(", "self", ")", ":", "columns", "=", "list", "(", "self", ".", "obj", ".", "_fields", ".", "keys", "(", ")", ")", "if", "\"_cls\"", "in", "columns", ":", "columns", ".", "remove", "(", "\"_cls\"", ")", "return", "columns" ]
c293734c1b86e176a3ba57ee2deab6676d125576
train
MongoEngineInterface.get_order_columns_list
Returns the columns that can be ordered :param list_columns: optional list of columns name, if provided will use this list only.
flask_appbuilder/models/mongoengine/interface.py
def get_order_columns_list(self, list_columns=None): """ Returns the columns that can be ordered :param list_columns: optional list of columns name, if provided will use this list only. """ ret_lst = list() list_columns = list_columns or self.get_...
def get_order_columns_list(self, list_columns=None): """ Returns the columns that can be ordered :param list_columns: optional list of columns name, if provided will use this list only. """ ret_lst = list() list_columns = list_columns or self.get_...
[ "Returns", "the", "columns", "that", "can", "be", "ordered" ]
dpgaspar/Flask-AppBuilder
python
https://github.com/dpgaspar/Flask-AppBuilder/blob/c293734c1b86e176a3ba57ee2deab6676d125576/flask_appbuilder/models/mongoengine/interface.py#L274-L289
[ "def", "get_order_columns_list", "(", "self", ",", "list_columns", "=", "None", ")", ":", "ret_lst", "=", "list", "(", ")", "list_columns", "=", "list_columns", "or", "self", ".", "get_columns_list", "(", ")", "for", "col_name", "in", "list_columns", ":", "i...
c293734c1b86e176a3ba57ee2deab6676d125576
train
MongoEngineInterface.get_keys
return a list of pk values from object list
flask_appbuilder/models/mongoengine/interface.py
def get_keys(self, lst): """ return a list of pk values from object list """ pk_name = self.get_pk_name() return [getattr(item, pk_name) for item in lst]
def get_keys(self, lst): """ return a list of pk values from object list """ pk_name = self.get_pk_name() return [getattr(item, pk_name) for item in lst]
[ "return", "a", "list", "of", "pk", "values", "from", "object", "list" ]
dpgaspar/Flask-AppBuilder
python
https://github.com/dpgaspar/Flask-AppBuilder/blob/c293734c1b86e176a3ba57ee2deab6676d125576/flask_appbuilder/models/mongoengine/interface.py#L305-L310
[ "def", "get_keys", "(", "self", ",", "lst", ")", ":", "pk_name", "=", "self", ".", "get_pk_name", "(", ")", "return", "[", "getattr", "(", "item", ",", "pk_name", ")", "for", "item", "in", "lst", "]" ]
c293734c1b86e176a3ba57ee2deab6676d125576
train
renders
Use this decorator to map your custom Model properties to actual Model db properties. As an example:: class MyModel(Model): id = Column(Integer, primary_key=True) name = Column(String(50), unique = True, nullable=False) custom = Column(Integer(20)) ...
flask_appbuilder/models/decorators.py
def renders(col_name): """ Use this decorator to map your custom Model properties to actual Model db properties. As an example:: class MyModel(Model): id = Column(Integer, primary_key=True) name = Column(String(50), unique = True, nullable=False) ...
def renders(col_name): """ Use this decorator to map your custom Model properties to actual Model db properties. As an example:: class MyModel(Model): id = Column(Integer, primary_key=True) name = Column(String(50), unique = True, nullable=False) ...
[ "Use", "this", "decorator", "to", "map", "your", "custom", "Model", "properties", "to", "actual", "Model", "db", "properties", ".", "As", "an", "example", "::" ]
dpgaspar/Flask-AppBuilder
python
https://github.com/dpgaspar/Flask-AppBuilder/blob/c293734c1b86e176a3ba57ee2deab6676d125576/flask_appbuilder/models/decorators.py#L1-L27
[ "def", "renders", "(", "col_name", ")", ":", "def", "wrap", "(", "f", ")", ":", "if", "not", "hasattr", "(", "f", ",", "'_col_name'", ")", ":", "f", ".", "_col_name", "=", "col_name", "return", "f", "return", "wrap" ]
c293734c1b86e176a3ba57ee2deab6676d125576
train
BaseInterface._get_values
Get Values: formats values for list template. returns [{'col_name':'col_value',....},{'col_name':'col_value',....}] :param lst: The list of item objects from query :param list_columns: The list of columns to include
flask_appbuilder/models/base.py
def _get_values(self, lst, list_columns): """ Get Values: formats values for list template. returns [{'col_name':'col_value',....},{'col_name':'col_value',....}] :param lst: The list of item objects from query :param list_columns: ...
def _get_values(self, lst, list_columns): """ Get Values: formats values for list template. returns [{'col_name':'col_value',....},{'col_name':'col_value',....}] :param lst: The list of item objects from query :param list_columns: ...
[ "Get", "Values", ":", "formats", "values", "for", "list", "template", ".", "returns", "[", "{", "col_name", ":", "col_value", "....", "}", "{", "col_name", ":", "col_value", "....", "}", "]" ]
dpgaspar/Flask-AppBuilder
python
https://github.com/dpgaspar/Flask-AppBuilder/blob/c293734c1b86e176a3ba57ee2deab6676d125576/flask_appbuilder/models/base.py#L93-L109
[ "def", "_get_values", "(", "self", ",", "lst", ",", "list_columns", ")", ":", "retlst", "=", "[", "]", "for", "item", "in", "lst", ":", "retdict", "=", "{", "}", "for", "col", "in", "list_columns", ":", "retdict", "[", "col", "]", "=", "self", ".",...
c293734c1b86e176a3ba57ee2deab6676d125576
train
BaseInterface.get_values
Get Values: formats values for list template. returns [{'col_name':'col_value',....},{'col_name':'col_value',....}] :param lst: The list of item objects from query :param list_columns: The list of columns to include
flask_appbuilder/models/base.py
def get_values(self, lst, list_columns): """ Get Values: formats values for list template. returns [{'col_name':'col_value',....},{'col_name':'col_value',....}] :param lst: The list of item objects from query :param list_columns: T...
def get_values(self, lst, list_columns): """ Get Values: formats values for list template. returns [{'col_name':'col_value',....},{'col_name':'col_value',....}] :param lst: The list of item objects from query :param list_columns: T...
[ "Get", "Values", ":", "formats", "values", "for", "list", "template", ".", "returns", "[", "{", "col_name", ":", "col_value", "....", "}", "{", "col_name", ":", "col_value", "....", "}", "]" ]
dpgaspar/Flask-AppBuilder
python
https://github.com/dpgaspar/Flask-AppBuilder/blob/c293734c1b86e176a3ba57ee2deab6676d125576/flask_appbuilder/models/base.py#L111-L125
[ "def", "get_values", "(", "self", ",", "lst", ",", "list_columns", ")", ":", "for", "item", "in", "lst", ":", "retdict", "=", "{", "}", "for", "col", "in", "list_columns", ":", "retdict", "[", "col", "]", "=", "self", ".", "_get_attr_value", "(", "it...
c293734c1b86e176a3ba57ee2deab6676d125576
train
BaseInterface.get_values_json
Converts list of objects from query to JSON
flask_appbuilder/models/base.py
def get_values_json(self, lst, list_columns): """ Converts list of objects from query to JSON """ result = [] for item in self.get_values(lst, list_columns): for key, value in list(item.items()): if isinstance(value, datetime.datetime) or isinstanc...
def get_values_json(self, lst, list_columns): """ Converts list of objects from query to JSON """ result = [] for item in self.get_values(lst, list_columns): for key, value in list(item.items()): if isinstance(value, datetime.datetime) or isinstanc...
[ "Converts", "list", "of", "objects", "from", "query", "to", "JSON" ]
dpgaspar/Flask-AppBuilder
python
https://github.com/dpgaspar/Flask-AppBuilder/blob/c293734c1b86e176a3ba57ee2deab6676d125576/flask_appbuilder/models/base.py#L127-L142
[ "def", "get_values_json", "(", "self", ",", "lst", ",", "list_columns", ")", ":", "result", "=", "[", "]", "for", "item", "in", "self", ".", "get_values", "(", "lst", ",", "list_columns", ")", ":", "for", "key", ",", "value", "in", "list", "(", "item...
c293734c1b86e176a3ba57ee2deab6676d125576
train
BaseInterface.get_keys
return a list of pk values from object list
flask_appbuilder/models/base.py
def get_keys(self, lst): """ return a list of pk values from object list """ pk_name = self.get_pk_name() if self.is_pk_composite(): return [[getattr(item, pk) for pk in pk_name] for item in lst] else: return [getattr(item, pk_name) for item in...
def get_keys(self, lst): """ return a list of pk values from object list """ pk_name = self.get_pk_name() if self.is_pk_composite(): return [[getattr(item, pk) for pk in pk_name] for item in lst] else: return [getattr(item, pk_name) for item in...
[ "return", "a", "list", "of", "pk", "values", "from", "object", "list" ]
dpgaspar/Flask-AppBuilder
python
https://github.com/dpgaspar/Flask-AppBuilder/blob/c293734c1b86e176a3ba57ee2deab6676d125576/flask_appbuilder/models/base.py#L275-L283
[ "def", "get_keys", "(", "self", ",", "lst", ")", ":", "pk_name", "=", "self", ".", "get_pk_name", "(", ")", "if", "self", ".", "is_pk_composite", "(", ")", ":", "return", "[", "[", "getattr", "(", "item", ",", "pk", ")", "for", "pk", "in", "pk_name...
c293734c1b86e176a3ba57ee2deab6676d125576
train
BaseRegisterUser.send_email
Method for sending the registration Email to the user
flask_appbuilder/security/registerviews.py
def send_email(self, register_user): """ Method for sending the registration Email to the user """ try: from flask_mail import Mail, Message except Exception: log.error("Install Flask-Mail to use User registration") return False mai...
def send_email(self, register_user): """ Method for sending the registration Email to the user """ try: from flask_mail import Mail, Message except Exception: log.error("Install Flask-Mail to use User registration") return False mai...
[ "Method", "for", "sending", "the", "registration", "Email", "to", "the", "user" ]
dpgaspar/Flask-AppBuilder
python
https://github.com/dpgaspar/Flask-AppBuilder/blob/c293734c1b86e176a3ba57ee2deab6676d125576/flask_appbuilder/security/registerviews.py#L72-L102
[ "def", "send_email", "(", "self", ",", "register_user", ")", ":", "try", ":", "from", "flask_mail", "import", "Mail", ",", "Message", "except", "Exception", ":", "log", ".", "error", "(", "\"Install Flask-Mail to use User registration\"", ")", "return", "False", ...
c293734c1b86e176a3ba57ee2deab6676d125576