text_prompt
stringlengths 157
13.1k
| code_prompt
stringlengths 7
19.8k
⌀ |
---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_context_file_name(pid_file):
"""When the daemon is started write out the information which port it was using."""
|
root = os.path.dirname(pid_file)
port_file = os.path.join(root, "context.json")
return port_file
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_context(pid_file, context_info):
"""Set context of running notebook. :param context_info: dict of extra context parameters, see comm.py comments """
|
assert type(context_info) == dict
port_file = get_context_file_name(pid_file)
with open(port_file, "wt") as f:
f.write(json.dumps(context_info))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_context(pid_file, daemon=False):
"""Get context of running notebook. A context file is created when notebook starts. :param daemon: Are we trying to fetch the context inside the daemon. Otherwise do the death check. :return: dict or None if the process is dead/not launcherd """
|
port_file = get_context_file_name(pid_file)
if not os.path.exists(port_file):
return None
with open(port_file, "rt") as f:
json_data = f.read()
try:
data = json.loads(json_data)
except ValueError as e:
logger.error("Damaged context json data %s", json_data)
return None
if not daemon:
pid = data.get("pid")
if pid and not check_pid(int(pid)):
# The Notebook daemon has exited uncleanly, as the PID does not point to any valid process
return None
return data
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clear_context(pid_file):
"""Called at exit. Delete the context file to signal there is no active notebook. We don't delete the whole file, but leave it around for debugging purposes. Maybe later we want to pass some information back to the web site. """
|
return
raise RuntimeError("Should not happen")
fname = get_context_file_name(pid_file)
shutil.move(fname, fname.replace("context.json", "context.old.json"))
data = {}
data["terminated"] = str(datetime.datetime.now(datetime.timezone.utc))
set_context(pid_file, data)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delayed_burst_run(self, target_cycles_per_sec):
""" Run CPU not faster than given speedlimit """
|
old_cycles = self.cycles
start_time = time.time()
self.burst_run()
is_duration = time.time() - start_time
new_cycles = self.cycles - old_cycles
try:
is_cycles_per_sec = new_cycles / is_duration
except ZeroDivisionError:
pass
else:
should_burst_duration = is_cycles_per_sec / target_cycles_per_sec
target_duration = should_burst_duration * is_duration
delay = target_duration - is_duration
if delay > 0:
if delay > self.max_delay:
self.delay = self.max_delay
else:
self.delay = delay
time.sleep(self.delay)
self.call_sync_callbacks()
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_model_counts(tagged_models, tag):
""" This does a model count so the side bar looks nice. """
|
model_counts = []
for model in tagged_models:
model['count'] = model['query'](tag).count()
if model['count']:
model_counts.append(model)
return model_counts
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
|
def patch_ui_functions(wrapper):
'''Wrap all termui functions with a custom decorator.'''
NONE = object()
import click
saved = []
for name, info in sorted(_ui_functions.items()):
f = getattr(click, name, NONE)
if f is NONE:
continue
new_f = wrapper(_copy_fn(f), info)
argspec = getargspec(f)
signature = inspect.formatargspec(*argspec) \
.lstrip('(') \
.rstrip(')')
args = ', '.join(arg.split('=')[0].split(':')[0].strip()
for arg in signature.split(','))
stub_f = eval('lambda {s}: {n}._real_click_fn({a})'
.format(n=f.__name__, s=signature, a=args))
if PY2:
saved.append((f, f.func_code))
f.func_code = stub_f.func_code
else:
saved.append((f, f.__code__))
f.__code__ = stub_f.__code__
f._real_click_fn = new_f
try:
yield
finally:
for f, code in saved:
if PY2:
f.func_code = code
else:
f.__code__ = code
del f._real_click_fn
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compute_region_border(start, end):
""" given the buffer start and end indices of a range, compute the border edges that should be drawn to enclose the range. this function currently assumes 0x10 length rows. the result is a dictionary from buffer index to Cell instance. the Cell instance has boolean properties "top", "bottom", "left", and "right" that describe if a border should be drawn on that side of the cell view. :rtype: Mapping[int, CellT] """
|
cells = defaultdict(Cell)
start_row = row_number(start)
end_row = row_number(end)
if end % 0x10 == 0:
end_row -= 1
## topmost cells
if start_row == end_row:
for i in range(start, end):
cells[i].top = True
else:
for i in range(start, row_end_index(start) + 1):
cells[i].top = True
# cells on second row, top left
if start_row != end_row:
next_row_start = row_start_index(start) + 0x10
for i in range(next_row_start, next_row_start + column_number(start)):
cells[i].top = True
## bottommost cells
if start_row == end_row:
for i in range(start, end):
cells[i].bottom = True
else:
for i in range(row_start_index(end), end):
cells[i].bottom = True
# cells on second-to-last row, bottom right
if start_row != end_row:
prev_row_end = row_end_index(end) - 0x10
for i in range(prev_row_end - (0x10 - column_number(end) - 1), prev_row_end + 1):
cells[i].bottom = True
## leftmost cells
if start_row == end_row:
cells[start].left = True
else:
second_row_start = row_start_index(start) + 0x10
for i in range(second_row_start, row_start_index(end) + 0x10, 0x10):
cells[i].left = True
# cells in first row, top left
if start_row != end_row:
cells[start].left = True
## rightmost cells
if start_row == end_row:
cells[end - 1].right = True
else:
penultimate_row_end = row_end_index(end) - 0x10
for i in range(row_end_index(start), penultimate_row_end + 0x10, 0x10):
cells[i].right = True
# cells in last row, bottom right
if start_row != end_row:
cells[end - 1].right = True
# convert back to standard dict
# trick from: http://stackoverflow.com/a/20428703/87207
cells.default_factory = None
return cells
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def swf2png(swf_path, png_path, swfrender_path="swfrender"):
"""Convert SWF slides into a PNG image Raises: OSError is raised if swfrender is not available. ConversionError is raised if image cannot be created. """
|
# Currently rely on swftools
#
# Would be great to have a native python dependency to convert swf into png or jpg.
# However it seems that pyswf isn't flawless. Some graphical elements (like the text!) are lost during
# the export.
try:
cmd = [swfrender_path, swf_path, '-o', png_path]
subprocess.check_output(cmd, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
raise ConversionError("Failed to convert SWF file %s.\n"
"\tCommand: %s\n"
"\tExit status: %s.\n"
"\tOutput:\n%s"
% (swf_path, " ".join(cmd), e.returncode, e.output))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_presentation(self):
""" Create the presentation. The audio track is mixed with the slides. The resulting file is saved as self.output DownloadError is raised if some resources cannot be fetched. ConversionError is raised if the final video cannot be created. """
|
# Avoid wasting time and bandwidth if we known that conversion will fail.
if not self.overwrite and os.path.exists(self.output):
raise ConversionError("File %s already exist and --overwrite not specified" % self.output)
video = self.download_video()
raw_slides = self.download_slides()
# ffmpeg does not support SWF
png_slides = self._convert_slides(raw_slides)
# Create one frame per second using the time code information
frame_pattern = self._prepare_frames(png_slides)
return self._assemble(video, frame_pattern)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download_slides(self):
""" Download all SWF slides. The location of the slides files are returned. A DownloadError is raised if at least one of the slides cannot be download.. """
|
return self.presentation.client.download_all(self.presentation.metadata['slides'], self.tmp_dir)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch_no_cache(self, url):
""" Fetch the resource specified and return its content. DownloadError is raised if the resource cannot be fetched. """
|
try:
with contextlib.closing(self.opener.open(url)) as response:
# InfoQ does not send a 404 but a 302 redirecting to a valid URL...
if response.code != 200 or response.url == INFOQ_404_URL:
raise DownloadError("%s not found" % url)
return response.read()
except urllib.error.URLError as e:
raise DownloadError("Failed to get %s: %s" % (url, e))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download(self, url, dir_path, filename=None):
""" Download the resources specified by url into dir_path. The resulting file path is returned. DownloadError is raised the resources cannot be downloaded. """
|
if not filename:
filename = url.rsplit('/', 1)[1]
path = os.path.join(dir_path, filename)
content = self.fetch(url)
with open(path, "wb") as f:
f.write(content)
return path
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download_all(self, urls, dir_path):
""" Download all the resources specified by urls into dir_path. The resulting file paths is returned. DownloadError is raised if at least one of the resources cannot be downloaded. In the case already downloaded resources are erased. """
|
# TODO: Implement parallel download
filenames = []
try:
for url in urls:
filenames.append(self.download(url, dir_path))
except DownloadError as e:
for filename in filenames:
os.remove(filename)
raise e
return filenames
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def push_byte(self, stack_pointer, byte):
""" pushed a byte onto stack """
|
# FIXME: self.system_stack_pointer -= 1
stack_pointer.decrement(1)
addr = stack_pointer.value
# log.info(
# log.error(
# "%x|\tpush $%x to %s stack at $%x\t|%s",
# self.last_op_address, byte, stack_pointer.name, addr,
# self.cfg.mem_info.get_shortest(self.last_op_address)
# )
self.memory.write_byte(addr, byte)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pull_byte(self, stack_pointer):
""" pulled a byte from stack """
|
addr = stack_pointer.value
byte = self.memory.read_byte(addr)
# log.info(
# log.error(
# "%x|\tpull $%x from %s stack at $%x\t|%s",
# self.last_op_address, byte, stack_pointer.name, addr,
# self.cfg.mem_info.get_shortest(self.last_op_address)
# )
# FIXME: self.system_stack_pointer += 1
stack_pointer.increment(1)
return byte
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def proxy_it(request, port):
"""Proxy HTTP request to upstream IPython Notebook Tornado server."""
|
# Check if we have websocket proxy configured
websocket_proxy = request.registry.settings.get("pyramid_notebook.websocket_proxy", "")
if websocket_proxy.strip():
r = DottedNameResolver()
websocket_proxy = r.maybe_resolve(websocket_proxy)
if "upgrade" in request.headers.get("connection", "").lower():
if websocket_proxy:
return websocket_proxy(request, port)
else:
# If we run on localhost on pserve, we should never hit here as requests go directly to IPython Notebook kernel, not us
raise RuntimeError("Websocket proxy support is not configured.")
proxy_app = WSGIProxyApplication(port)
return request.get_response(proxy_app)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prepare_notebook_context(request, notebook_context):
"""Fill in notebook context with default values."""
|
if not notebook_context:
notebook_context = {}
# Override notebook Jinja templates
if "extra_template_paths" not in notebook_context:
notebook_context["extra_template_paths"] = [os.path.join(os.path.dirname(__file__), "server", "templates")]
# Furious invalid state follows if we let this slip through
assert type(notebook_context["extra_template_paths"]) == list, "Got bad extra_template_paths {}".format(notebook_context["extra_template_paths"])
# Jinja variables
notebook_context["jinja_environment_options"] = notebook_context.get("jinja_environment_options", {})
assert type(notebook_context["jinja_environment_options"]) == dict
# XXX: Following passing of global variables to Jinja templates requires Jinja 2.8.0dev+ version and is not yet supported
# http://jinja.pocoo.org/docs/dev/api/#jinja2.Environment.globals
# notebook_context["jinja_environment_options"]["globals"] = notebook_context["jinja_environment_options"].get("globals", {})
# globals_ = notebook_context["jinja_environment_options"]["globals"]
#
# assert type(globals_) == dict
#
# if not "home_url" in globals_:
# globals_["home_url"] = request.host_url
#
# if not "home_title" in globals_:
# globals_["home_title"] = "Back to site"
# Tell notebook to correctly address WebSockets allow origin policy
notebook_context["allow_origin"] = route_to_alt_domain(request, request.host_url)
notebook_context["notebook_path"] = request.route_path("notebook_proxy", remainder="")
# Record the hash of the current parameters, so we know if this user accesses the notebook in this or different context
if "context_hash" not in notebook_context:
notebook_context["context_hash"] = make_dict_hash(notebook_context)
print(notebook_context)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def launch_on_demand(request, username, notebook_context):
"""See if we have notebook already running this context and if not then launch new one."""
|
security_check(request, username)
settings = request.registry.settings
notebook_folder = settings.get("pyramid_notebook.notebook_folder", None)
if not notebook_folder:
raise RuntimeError("Setting missing: pyramid_notebook.notebook_folder")
kill_timeout = settings.get("pyramid_notebook.kill_timeout", None)
if not kill_timeout:
raise RuntimeError("Setting missing: pyramid_notebook.kill_timeout")
kill_timeout = int(kill_timeout)
if not notebook_context:
notebook_context = {}
# Override notebook Jinja templates
if "extra_template_paths" not in notebook_context:
notebook_context["extra_template_paths"] = [os.path.join(os.path.dirname(__file__), "server", "templates")]
# Furious invalid state follows if we let this slip through
assert type(notebook_context["extra_template_paths"]) == list, "Got bad extra_template_paths {}".format(notebook_context["extra_template_paths"])
notebook_folder = settings.get("pyramid_notebook.notebook_folder", None)
if not notebook_folder:
raise RuntimeError("Setting missing: pyramid_notebook.notebook_folder")
kill_timeout = settings.get("pyramid_notebook.kill_timeout", None)
if not kill_timeout:
raise RuntimeError("Setting missing: pyramid_notebook.kill_timeout")
kill_timeout = int(kill_timeout)
prepare_notebook_context(request, notebook_context)
# Configure websockets
# websocket_url = settings.get("pyramid_notebook.websocket_url")
# assert websocket_url, "pyramid_notebook.websocket_url setting missing"
# assert websocket_url.startswith("ws:/") or websocket_url.startswith("wss:/")
if request.registry.settings.get("pyramid_notebook.websocket_proxy", ""):
websocket_url = route_to_alt_domain(request, request.host_url)
websocket_url = websocket_url.replace("http://", "ws://").replace("https://", "wss://")
notebook_context["websocket_url"] = websocket_url
else:
# Connect websockets directly to localhost notebook server, do not try to proxy them
websocket_url = "ws://localhost:{port}/notebook/"
# Record the hash of the current parameters, so we know if this user accesses the notebook in this or different context
if "context_hash" not in notebook_context:
notebook_context["context_hash"] = make_dict_hash(notebook_context)
manager = NotebookManager(notebook_folder, kill_timeout=kill_timeout)
notebook_info, creates = manager.start_notebook_on_demand(username, notebook_context)
return notebook_info
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def shutdown_notebook(request, username):
"""Stop any running notebook for a user."""
|
manager = get_notebook_manager(request)
if manager.is_running(username):
manager.stop_notebook(username)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def route_to_alt_domain(request, url):
"""Route URL to a different subdomain. Used to rewrite URLs to point to websocket serving domain. """
|
# Do we need to route IPython Notebook request from a different location
alternative_domain = request.registry.settings.get("pyramid_notebook.alternative_domain", "").strip()
if alternative_domain:
url = url.replace(request.host_url, alternative_domain)
return url
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _bselect(self, selection, start_bindex, end_bindex):
""" add the given buffer indices to the given QItemSelection, both byte and char panes """
|
selection.select(self._model.index2qindexb(start_bindex), self._model.index2qindexb(end_bindex))
selection.select(self._model.index2qindexc(start_bindex), self._model.index2qindexc(end_bindex))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _do_select(self, start_bindex, end_bindex):
""" select the given range by buffer indices selects items like this: xxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxx *not* like this: """
|
self.select(QItemSelection(), QItemSelectionModel.Clear)
if start_bindex > end_bindex:
start_bindex, end_bindex = end_bindex, start_bindex
selection = QItemSelection()
if row_number(end_bindex) - row_number(start_bindex) == 0:
# all on one line
self._bselect(selection, start_bindex, end_bindex)
elif row_number(end_bindex) - row_number(start_bindex) == 1:
# two lines
self._bselect(selection, start_bindex, row_end_index(start_bindex))
self._bselect(selection, row_start_index(end_bindex), end_bindex)
else:
# many lines
self._bselect(selection, start_bindex, row_end_index(start_bindex))
self._bselect(selection, row_start_index(start_bindex) + 0x10, row_end_index(end_bindex) - 0x10)
self._bselect(selection, row_start_index(end_bindex), end_bindex)
self.select(selection, QItemSelectionModel.SelectCurrent)
self.start = start_bindex
self.end = end_bindex
self.selectionRangeChanged.emit(end_bindex)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _update_selection(self, qindex1, qindex2):
""" select the given range by qmodel indices """
|
m = self.model()
self._do_select(m.qindex2index(qindex1), m.qindex2index(qindex2))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_context_menu(self, qpoint):
""" override this method to customize the context menu """
|
menu = QMenu(self)
index = self.view.indexAt(qpoint)
def add_action(menu, text, handler, icon=None):
a = None
if icon is None:
a = QAction(text, self)
else:
a = QAction(icon, text, self)
a.triggered.connect(handler)
menu.addAction(a)
add_action(menu, "Color selection", self._handle_color_selection)
# duplication here with vstructui
color_menu = menu.addMenu("Color selection...")
# need to escape the closure capture on the color loop variable below
# hint from: http://stackoverflow.com/a/6035865/87207
def make_color_selection_handler(color):
return lambda: self._handle_color_selection(color=color)
for color in QT_COLORS:
add_action(color_menu, "{:s}".format(color.name),
make_color_selection_handler(color.qcolor), make_color_icon(color.qcolor))
start = self._hsm.start
end = self._hsm.end
cm = self.getColorModel()
if (start == end and cm.is_index_colored(start)) or cm.is_region_colored(start, end):
def make_remove_color_handler(r):
return lambda: self._handle_remove_color_range(r)
remove_color_menu = menu.addMenu("Remove color...")
for cr in cm.get_region_colors(start, end):
pixmap = QPixmap(10, 10)
pixmap.fill(cr.color)
icon = QIcon(pixmap)
add_action(remove_color_menu,
"Remove color [{:s}, {:s}], len: {:s}".format(h(cr.begin), h(cr.end), h(cr.end - cr.begin)),
make_remove_color_handler(cr), make_color_icon(cr.color))
menu.addSeparator() # -----------------------------------------------------------------
add_action(menu, "Copy selection (binary)", self._handle_copy_binary)
copy_menu = menu.addMenu("Copy...")
add_action(copy_menu, "Copy selection (binary)", self._handle_copy_binary)
add_action(copy_menu, "Copy selection (text)", self._handle_copy_text)
add_action(copy_menu, "Copy selection (hex)", self._handle_copy_hex)
add_action(copy_menu, "Copy selection (hexdump)", self._handle_copy_hexdump)
add_action(copy_menu, "Copy selection (base64)", self._handle_copy_base64)
menu.addSeparator() # -----------------------------------------------------------------
add_action(menu, "Add origin", lambda: self._handle_add_origin(index))
return menu
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_sync_callback(self, callback_cycles, callback):
""" Add a CPU cycle triggered callback """
|
self.sync_callbacks_cyles[callback] = 0
self.sync_callbacks.append([callback_cycles, callback])
if self.quickest_sync_callback_cycles is None or \
self.quickest_sync_callback_cycles > callback_cycles:
self.quickest_sync_callback_cycles = callback_cycles
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def call_sync_callbacks(self):
""" Call every sync callback with CPU cycles trigger """
|
current_cycles = self.cycles
for callback_cycles, callback in self.sync_callbacks:
# get the CPU cycles count of the last call
last_call_cycles = self.sync_callbacks_cyles[callback]
if current_cycles - last_call_cycles > callback_cycles:
# this callback should be called
# Save the current cycles, to trigger the next call
self.sync_callbacks_cyles[callback] = self.cycles
# Call the callback function
callback(current_cycles - last_call_cycles)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def burst_run(self):
|
# https://wiki.python.org/moin/PythonSpeed/PerformanceTips#Avoiding_dots...
get_and_call_next_op = self.get_and_call_next_op
for __ in range(self.outer_burst_op_count):
for __ in range(self.inner_burst_op_count):
get_and_call_next_op()
self.call_sync_callbacks()
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def instruction_PAGE(self, opcode):
""" call op from page 2 or 3 """
|
op_address, opcode2 = self.read_pc_byte()
paged_opcode = opcode * 256 + opcode2
# log.debug("$%x *** call paged opcode $%x" % (
# self.program_counter, paged_opcode
# ))
self.call_instruction_func(op_address - 1, paged_opcode)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def instruction_ADD16(self, opcode, m, register):
""" Adds the 16-bit memory value into the 16-bit accumulator source code forms: ADDD P CC bits "HNZVC": -aaaa """
|
assert register.WIDTH == 16
old = register.value
r = old + m
register.set(r)
# log.debug("$%x %02x %02x ADD16 %s: $%02x + $%02x = $%02x" % (
# self.program_counter, opcode, m,
# register.name,
# old, m, r
# ))
self.clear_NZVC()
self.update_NZVC_16(old, m, r)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def instruction_ADD8(self, opcode, m, register):
""" Adds the memory byte into an 8-bit accumulator. source code forms: ADDA P; ADDB P CC bits "HNZVC": aaaaa """
|
assert register.WIDTH == 8
old = register.value
r = old + m
register.set(r)
# log.debug("$%x %02x %02x ADD8 %s: $%02x + $%02x = $%02x" % (
# self.program_counter, opcode, m,
# register.name,
# old, m, r
# ))
self.clear_HNZVC()
self.update_HNZVC_8(old, m, r)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def DEC(self, a):
""" Subtract one from the register. The carry bit is not affected, thus allowing this instruction to be used as a loop counter in multiple- precision computations. When operating on unsigned values, only BEQ and BNE branches can be expected to behave consistently. When operating on twos complement values, all signed branches are available. source code forms: DEC Q; DECA; DECB CC bits "HNZVC": -aaa- """
|
r = a - 1
self.clear_NZV()
self.update_NZ_8(r)
if r == 0x7f:
self.V = 1
return r
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def instruction_DEC_memory(self, opcode, ea, m):
""" Decrement memory location """
|
r = self.DEC(m)
# log.debug("$%x DEC memory value $%x -1 = $%x and write it to $%x \t| %s" % (
# self.program_counter,
# m, r, ea,
# self.cfg.mem_info.get_shortest(ea)
# ))
return ea, r & 0xff
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def instruction_SEX(self, opcode):
""" This instruction transforms a twos complement 8-bit value in accumulator B into a twos complement 16-bit value in the D accumulator. source code forms: SEX CC bits "HNZVC": -aa0- // 0x1d SEX inherent case 0x1d: WREG_A = (RREG_B & 0x80) ? 0xff : 0; CLR_NZ; SET_NZ16(REG_D); peek_byte(cpu, REG_PC); #define SIGNED(b) ((Word)(b&0x80?b|0xff00:b)) case 0x1D: /* SEX */ tw=SIGNED(ibreg); SETNZ16(tw) SETDREG(tw) break; """
|
b = self.accu_b.value
if b & 0x80 == 0:
self.accu_a.set(0x00)
d = self.accu_d.value
# log.debug("SEX: b=$%x ; $%x&0x80=$%x ; d=$%x", b, b, (b & 0x80), d)
self.clear_NZ()
self.update_NZ_16(d)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _str(obj):
"""Show nicely the generic object received."""
|
values = []
for name in obj._attribs:
val = getattr(obj, name)
if isinstance(val, str):
val = repr(val)
val = str(val) if len(str(val)) < 10 else "(...)"
values.append((name, val))
values = ", ".join("{}={}".format(k, v) for k, v in values)
return "{}({})".format(obj.__class__.__name__, values)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _repr(obj):
"""Show the received object as precise as possible."""
|
vals = ", ".join("{}={!r}".format(
name, getattr(obj, name)) for name in obj._attribs)
if vals:
t = "{}(name={}, {})".format(obj.__class__.__name__, obj.name, vals)
else:
t = "{}(name={})".format(obj.__class__.__name__, obj.name)
return t
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _make_object(name):
"""Create a generic object for the tags."""
|
klass = type(name, (SWFObject,),
{'__str__': _str, '__repr__': _repr, 'name': name})
return klass()
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parsefile(filename, read_twips=True):
"""Parse a SWF. If you have a file object already, just use SWFParser directly. read_twips: True - return values as read from the SWF False - return values in pixels (at 100% zoom) """
|
with open(filename, 'rb') as fh:
return SWFParser(fh, read_twips)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_header(self):
"""Parse the SWF header."""
|
fh = self._src
obj = _make_object("Header")
# first part of the header
obj.Signature = sign = "".join(chr(unpack_ui8(fh)) for _ in range(3))
obj.Version = self._version = unpack_ui8(fh)
obj.FileLength = file_length = unpack_ui32(fh)
# deal with compressed content
if sign[0] == 'C':
uncompressed = zlib.decompress(fh.read())
if len(uncompressed) + 8 != file_length:
raise ValueError("Problems dealing with compressed content")
fh = self._src = io.BytesIO(uncompressed)
# second part of the header
obj.FrameSize = self._get_struct_rect()
obj.FrameRate = unpack_ui16(fh)
obj.FrameCount = unpack_ui16(fh)
return obj
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _process_tags(self):
"""Get a sequence of tags."""
|
tags = []
while True:
tag_bf = unpack_ui16(self._src)
tag_type = tag_bf >> 6 # upper 10 bits
if tag_type == 0:
# the end
break
tag_len = tag_bf & 0x3f # last 6 bits
if tag_len == 0x3f:
# the length is the next four bytes!
tag_len = unpack_ui32(self._src)
try:
tag_name = TAG_NAMES[tag_type]
except KeyError:
# malformed SWF, create and unknown object with malformed tag
tag_payload = self._src.read(tag_len)
_dict = {
'__str__': _repr,
'__repr__': _repr,
'name': 'UnspecifiedObject(tag={!r})'.format(tag_type),
}
tag = type("UnknownObject", (SWFObject,), _dict)()
tag.raw_payload = tag_payload
tags.append(tag)
continue
try:
tag_meth = getattr(self, "_handle_tag_" + tag_name.lower())
except AttributeError:
if self.unknown_alert:
raise ValueError("Unknown tag: " + repr(tag_name))
tag_payload = self._src.read(tag_len)
_dict = {'__str__': _repr, '__repr__': _repr, 'name': tag_name}
tag = type("UnknownObject", (SWFObject,), _dict)()
tag.raw_payload = tag_payload
tags.append(tag)
continue
# we know the tag type, and have the handler, let's process it
prev_pos = self._src.tell()
self._src.guard = tag_len
try:
with ReadQuantityController(self._src, tag_len):
tag = tag_meth()
assert tag is not None, tag_name
except ValueError:
# an attempt to read too much happened; create a failing
# object with the raw payload
self._src.guard = None
self._src.seek(prev_pos)
tag_payload = self._src.read(tag_len)
_dict = {'__str__': _repr, '__repr__': _repr, 'name': tag_name}
tag = type("FailingObject", (SWFObject,), _dict)()
tag.raw_payload = tag_payload
tags.append(tag)
return tags
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _generic_definetext_parser(self, obj, rgb_struct):
"""Generic parser for the DefineTextN tags."""
|
obj.CharacterID = unpack_ui16(self._src)
obj.TextBounds = self._get_struct_rect()
obj.TextMatrix = self._get_struct_matrix()
obj.GlyphBits = glyph_bits = unpack_ui8(self._src)
obj.AdvanceBits = advance_bits = unpack_ui8(self._src)
# textrecords
obj.TextRecords = records = []
while True:
endofrecords_flag = unpack_ui8(self._src)
if endofrecords_flag == 0:
# all done
obj.EndOfRecordsFlag = 0
break
# we have a TEXTRECORD, let's go back the 8 bits and set the obj
self._src.seek(-1, io.SEEK_CUR)
record = _make_object("TextRecord")
records.append(record)
bc = BitConsumer(self._src)
record.TextRecordType = bc.u_get(1)
record.StyleFlagsReserved = bc.u_get(3)
record.StyleFlagsHasFont = bc.u_get(1)
record.StyleFlagsHasColor = bc.u_get(1)
record.StyleFlagsHasYOffset = bc.u_get(1)
record.StyleFlagsHasXOffset = bc.u_get(1)
if record.StyleFlagsHasFont:
record.FontID = unpack_ui16(self._src)
if record.StyleFlagsHasColor:
record.TextColor = rgb_struct()
if record.StyleFlagsHasXOffset:
record.XOffset = unpack_si16(self._src)
if record.StyleFlagsHasYOffset:
record.YOffset = unpack_si16(self._src)
if record.StyleFlagsHasFont:
record.TextHeight = unpack_ui16(self._src)
record.GlyphCount = unpack_ui8(self._src)
bc = BitConsumer(self._src)
record.GlyphEntries = glyphs = []
for _ in range(record.GlyphCount):
glyph = _make_object("GlyphEntry")
glyphs.append(glyph)
glyph.GlyphIndex = bc.u_get(glyph_bits)
glyph.GlyphAdvance = bc.u_get(advance_bits)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _handle_tag_definetext(self):
"""Handle the DefineText tag."""
|
obj = _make_object("DefineText")
self._generic_definetext_parser(obj, self._get_struct_rgb)
return obj
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _handle_tag_definetext2(self):
"""Handle the DefineText2 tag."""
|
obj = _make_object("DefineText2")
self._generic_definetext_parser(obj, self._get_struct_rgba)
return obj
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _handle_tag_defineedittext(self):
"""Handle the DefineEditText tag."""
|
obj = _make_object("DefineEditText")
obj.CharacterID = unpack_ui16(self._src)
obj.Bounds = self._get_struct_rect()
bc = BitConsumer(self._src)
obj.HasText = bc.u_get(1)
obj.WordWrap = bc.u_get(1)
obj.Multiline = bc.u_get(1)
obj.Password = bc.u_get(1)
obj.ReadOnly = bc.u_get(1)
obj.HasTextColor = bc.u_get(1)
obj.HasMaxLength = bc.u_get(1)
obj.HasFont = bc.u_get(1)
obj.HasFontClass = bc.u_get(1)
obj.AutoSize = bc.u_get(1)
obj.HasLayout = bc.u_get(1)
obj.NoSelect = bc.u_get(1)
obj.Border = bc.u_get(1)
obj.WasStatic = bc.u_get(1)
obj.HTML = bc.u_get(1)
obj.UseOutlines = bc.u_get(1)
if obj.HasFont:
obj.FontID = unpack_ui16(self._src)
if obj.HasFontClass:
obj.FontClass = self._get_struct_string()
if obj.HasFont:
obj.FontHeight = unpack_ui16(self._src)
if obj.HasTextColor:
obj.TextColor = self._get_struct_rgba()
if obj.HasMaxLength:
obj.MaxLength = unpack_ui16(self._src)
if obj.HasLayout:
obj.Align = unpack_ui8(self._src)
obj.LeftMargin = unpack_ui16(self._src)
obj.RightMargin = unpack_ui16(self._src)
obj.Indent = unpack_ui16(self._src)
obj.Leading = unpack_ui16(self._src)
obj.VariableName = self._get_struct_string()
if obj.HasText:
obj.InitialText = self._get_struct_string()
return obj
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _generic_placeobject_parser(self, obj, version):
"""A generic parser for several PlaceObjectX."""
|
bc = BitConsumer(self._src)
obj.PlaceFlagHasClipActions = bc.u_get(1)
obj.PlaceFlagHasClipDepth = bc.u_get(1)
obj.PlaceFlagHasName = bc.u_get(1)
obj.PlaceFlagHasRatio = bc.u_get(1)
obj.PlaceFlagHasColorTransform = bc.u_get(1)
obj.PlaceFlagHasMatrix = bc.u_get(1)
obj.PlaceFlagHasCharacter = bc.u_get(1)
obj.PlaceFlagMove = bc.u_get(1)
if version == 3:
obj.Reserved = bc.u_get(1)
obj.PlaceFlagOpaqueBackground = bc.u_get(1)
obj.PlaceFlagHasVisible = bc.u_get(1)
obj.PlaceFlagHasImage = bc.u_get(1)
obj.PlaceFlagHasClassName = bc.u_get(1)
obj.PlaceFlagHasCacheAsBitmap = bc.u_get(1)
obj.PlaceFlagHasBlendMode = bc.u_get(1)
obj.PlaceFlagHasFilterList = bc.u_get(1)
obj.Depth = unpack_ui16(self._src)
if version == 3:
if obj.PlaceFlagHasClassName or (
obj.PlaceFlagHasImage and obj.PlaceFlagHasCharacter):
obj.ClassName = self._get_struct_string()
if obj.PlaceFlagHasCharacter:
obj.CharacterId = unpack_ui16(self._src)
if obj.PlaceFlagHasMatrix:
obj.Matrix = self._get_struct_matrix()
if obj.PlaceFlagHasColorTransform:
obj.ColorTransform = self._get_struct_cxformwithalpha()
if obj.PlaceFlagHasRatio:
obj.Ratio = unpack_ui16(self._src)
if obj.PlaceFlagHasName:
obj.Name = self._get_struct_string()
if obj.PlaceFlagHasClipDepth:
obj.ClipDepth = unpack_ui16(self._src)
if version == 3:
if obj.PlaceFlagHasFilterList:
obj.SurfaceFilterList = self._get_struct_filterlist()
if obj.PlaceFlagHasBlendMode:
obj.BlendMode = unpack_ui8(self._src)
if obj.PlaceFlagHasCacheAsBitmap:
obj.BitmapCache = unpack_ui8(self._src)
if obj.PlaceFlagHasVisible:
obj.Visible = unpack_ui8(self._src)
obj.BackgroundColor = self._get_struct_rgba()
if obj.PlaceFlagHasClipActions:
obj.ClipActions = self._get_struct_clipactions()
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _handle_tag_definesprite(self):
"""Handle the DefineSprite tag."""
|
obj = _make_object("DefineSprite")
obj.CharacterID = unpack_ui16(self._src)
obj.FrameCount = unpack_ui16(self._src)
tags = self._process_tags()
obj.ControlTags = tags
return obj
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _generic_action_parser(self):
"""Generic parser for Actions."""
|
actions = []
while True:
action_code = unpack_ui8(self._src)
if action_code == 0:
break
action_name = ACTION_NAMES[action_code]
if action_code > 128:
# have a payload!
action_len = unpack_ui16(self._src)
try:
action_meth = getattr(
self, "_handle_" + action_name.lower())
except AttributeError:
if self.unknown_alert:
raise ValueError(
"Unknown action: " + repr(action_name))
action_payload = self._src.read(action_len)
_dict = {'__str__': _repr, '__repr__': _repr,
'name': action_name}
action = type("UnknownAction", (SWFObject,), _dict)()
action.raw_payload = action_payload
actions.append(action)
else:
prev_pos = self._src.tell()
for action in action_meth(action_len):
assert action is not None, action_name
actions.append(action)
quant_read = self._src.tell() - prev_pos
if quant_read != action_len:
raise RuntimeError(
"Bad bytes consumption by action {!r} handler "
"(did {}, should {})".format(
action_name, quant_read, action_len))
else:
action = _make_object(action_name)
actions.append(action)
return actions
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _handle_tag_fileattributes(self):
"""Handle the FileAttributes tag."""
|
obj = _make_object("FileAttributes")
bc = BitConsumer(self._src)
bc.u_get(1) # reserved
obj.UseDirectBlit = bc.u_get(1)
obj.UseGPU = bc.u_get(1)
obj.HasMetadata = bc.u_get(1)
obj.ActionScript3 = bc.u_get(1)
bc.u_get(2) # reserved
obj.UseNetwork = bc.u_get(1)
bc.u_get(24) # reserved
return obj
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _handle_tag_definesceneandframelabeldata(self):
"""Handle the DefineSceneAndFrameLabelData tag."""
|
obj = _make_object("DefineSceneAndFrameLabelData")
obj.SceneCount = self._get_struct_encodedu32()
for i in range(1, obj.SceneCount + 1):
setattr(obj, 'Offset{}'.format(i), self._get_struct_encodedu32())
setattr(obj, 'Name{}'.format(i), self._get_struct_string())
obj.FrameLabelCount = self._get_struct_encodedu32()
for i in range(1, obj.FrameLabelCount + 1):
setattr(obj, 'FrameNum{}'.format(i), self._get_struct_encodedu32())
setattr(obj, 'FrameLabel{}'.format(i), self._get_struct_string())
return obj
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _handle_tag_defineshape4(self):
"""Handle the DefineShape4 tag."""
|
obj = _make_object("DefineShape4")
obj.ShapeId = unpack_ui16(self._src)
obj.ShapeBounds = self._get_struct_rect()
obj.EdgeBounds = self._get_struct_rect()
bc = BitConsumer(self._src)
bc.u_get(5) # reserved
obj.UsesFillWindingRule = bc.u_get(1)
obj.UsesNonScalingStrokes = bc.u_get(1)
obj.UsesScalingStrokes = bc.u_get(1)
obj.Shapes = self._get_struct_shapewithstyle(4)
return obj
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _handle_tag_definemorphshape2(self):
"""Handle the DefineMorphShape2 tag."""
|
obj = _make_object("DefineMorphShape2")
obj.CharacterId = unpack_ui16(self._src)
obj.StartBounds = self._get_struct_rect()
obj.EndBounds = self._get_struct_rect()
obj.StartEdgeBounds = self._get_struct_rect()
obj.EndEdgeBounds = self._get_struct_rect()
bc = BitConsumer(self._src)
bc.u_get(6) # reserved
obj.UsesNonScalingStrokes = bc.u_get(1)
obj.UsesScalingStrokes = bc.u_get(1)
obj.Offset = unpack_ui32(self._src)
# FIXME: this tag needs more work; I'm skipping some attributes here
self._src.read(obj.Offset)
obj.EndEdges = self._get_struct_shape()
return obj
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _handle_tag_removeobject(self):
"""Handle the RemoveObject tag."""
|
obj = _make_object("RemoveObject")
obj.CharacterId = unpack_ui16(self._src)
obj.Depth = unpack_ui16(self._src)
return obj
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _handle_tag_removeobject2(self):
"""Handle the RemoveObject2 tag."""
|
obj = _make_object("RemoveObject2")
obj.Depth = unpack_ui16(self._src)
return obj
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _handle_tag_defineshape(self):
"""Handle the DefineShape tag."""
|
obj = _make_object("DefineShape")
obj.ShapeId = unpack_ui16(self._src)
obj.ShapeBounds = self._get_struct_rect()
obj.Shapes = self._get_struct_shapewithstyle(1)
return obj
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _generic_definefont_parser(self, obj):
"""A generic parser for several DefineFontX."""
|
obj.FontID = unpack_ui16(self._src)
bc = BitConsumer(self._src)
obj.FontFlagsHasLayout = bc.u_get(1)
obj.FontFlagsShiftJIS = bc.u_get(1)
obj.FontFlagsSmallText = bc.u_get(1)
obj.FontFlagsANSI = bc.u_get(1)
obj.FontFlagsWideOffsets = bc.u_get(1)
obj.FontFlagsWideCodes = bc.u_get(1)
obj.FontFlagsItalic = bc.u_get(1)
obj.FontFlagsBold = bc.u_get(1)
obj.LanguageCode = self._get_struct_langcode()
obj.FontNameLen = unpack_ui8(self._src)
obj.FontName = "".join(chr(unpack_ui8(self._src))
for i in range(obj.FontNameLen))
if obj.FontName[-1] == '\x00': # most probably ends in null, clean it
obj.FontName = obj.FontName[:-1]
obj.NumGlyphs = num_glyphs = unpack_ui16(self._src)
self._last_defined_glyphs_quantity = num_glyphs
getter_wide = unpack_ui32 if obj.FontFlagsWideOffsets else unpack_ui16
obj.OffsetTable = [getter_wide(self._src) for _ in range(num_glyphs)]
obj.CodeTableOffset = getter_wide(self._src)
obj.GlyphShapeTable = [self._get_struct_shape()
for _ in range(num_glyphs)]
obj.CodeTable = [unpack_ui16(self._src) for _ in range(num_glyphs)]
if obj.FontFlagsHasLayout:
obj.FontAscent = unpack_ui16(self._src)
obj.FontDecent = unpack_ui16(self._src)
obj.FontLeading = unpack_ui16(self._src)
obj.FontAdvanceTable = [unpack_si16(self._src)
for _ in range(num_glyphs)]
obj.FontBoundsTable = [self._get_struct_rect()
for _ in range(num_glyphs)]
obj.KerningCount = unpack_ui16(self._src)
obj.FontKerningTable = [
self._get_struct_kerningrecord(obj.FontFlagsWideCodes)
for _ in range(obj.KerningCount)]
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _handle_tag_definebutton2(self):
"""Handle the DefineButton2 tag."""
|
obj = _make_object("DefineButton2")
obj.ButtonId = unpack_ui16(self._src)
bc = BitConsumer(self._src)
bc.ReservedFlags = bc.u_get(7)
bc.TrackAsMenu = bc.u_get(1)
obj.ActionOffset = unpack_ui16(self._src)
# characters
obj.Characters = characters = []
while True:
end_flag = unpack_ui8(self._src)
if end_flag == 0:
# all done
obj.CharacterEndFlag = 0
break
# we have a BUTTONRECORD, let's go back the 8 bits and set the obj
self._src.seek(-1, io.SEEK_CUR)
character = _make_object("ButtonRecord")
characters.append(character)
bc = BitConsumer(self._src)
character.ButtonReserved = bc.u_get(2)
character.ButtonHasBlendMode = bc.u_get(1)
character.ButtonHasFilterList = bc.u_get(1)
character.ButtonStateHitTest = bc.u_get(1)
character.ButtonStateDown = bc.u_get(1)
character.ButtonStateOver = bc.u_get(1)
character.ButtonStateUp = bc.u_get(1)
character.CharacterId = unpack_ui16(self._src)
character.PlaceDepth = unpack_ui16(self._src)
character.PlaceMatrix = self._get_struct_matrix()
character.ColorTransform = self._get_struct_cxformwithalpha()
if character.ButtonHasFilterList:
character.FilterList = self._get_struct_filterlist()
if character.ButtonHasBlendMode:
character.BlendMode = unpack_ui8(self._src)
obj.Actions = actions = []
still_have_actions = True
while still_have_actions:
end_flag = unpack_ui16(self._src)
if end_flag == 0:
# this is the last action, parse it and then exit
still_have_actions = False
bca = _make_object("ButtonCondAction")
actions.append(bca)
bca.CondActionSize = end_flag
bc = BitConsumer(self._src)
bca.CondIdleToOverDown = bc.u_get(1)
bca.CondOutDownToIdle = bc.u_get(1)
bca.CondOutDownToOverDown = bc.u_get(1)
bca.CondOverDownToOutDown = bc.u_get(1)
bca.CondOverDownToOverUp = bc.u_get(1)
bca.CondOverUpToOverDown = bc.u_get(1)
bca.CondOverUpToIdle = bc.u_get(1)
bca.CondIdleToOverUp = bc.u_get(1)
bca.CondKeyPress = bc.u_get(7)
bca.CondOverDownToIdle = bc.u_get(1)
bca.Actions = self._generic_action_parser()
return obj
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _handle_tag_enabledebugger2(self):
"""Handle the EnableDebugger2 tag."""
|
obj = _make_object("EnableDebugger2")
obj.Reserved = unpack_ui16(self._src)
obj.Password = self._get_struct_string()
return obj
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _handle_tag_scriptlimits(self):
"""Handle the ScriptLimits tag."""
|
obj = _make_object("ScriptLimits")
obj.MaxRecursionDepth = unpack_ui16(self._src)
obj.ScriptTimeoutSeconds = unpack_ui16(self._src)
return obj
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _handle_tag_jpegtables(self):
"""Handle the JPEGTables tag."""
|
obj = _make_object("JPEGTables")
assert self._src.read(2) == b'\xFF\xD8' # SOI marker
eoimark1 = eoimark2 = None
allbytes = [b'\xFF\xD8']
while not (eoimark1 == b'\xFF' and eoimark2 == b'\xD9'):
newbyte = self._src.read(1)
allbytes.append(newbyte)
eoimark1 = eoimark2
eoimark2 = newbyte
# concatenate everything, removing the end mark
obj.JPEGData = b"".join(allbytes[:-2])
return obj
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _handle_tag_definefontalignzones(self):
"""Handle the DefineFontAlignZones tag."""
|
obj = _make_object("DefineFontAlignZones")
obj.FontId = unpack_ui16(self._src)
bc = BitConsumer(self._src)
obj.CSMTableHint = bc.u_get(2)
obj.Reserved = bc.u_get(6)
obj.ZoneTable = zone_records = []
glyph_count = self._last_defined_glyphs_quantity
self._last_defined_glyphs_quantity = None
for _ in range(glyph_count):
zone_record = _make_object("ZoneRecord")
zone_records.append(zone_record)
zone_record.NumZoneData = unpack_ui8(self._src)
zone_record.ZoneData = zone_data = []
for _ in range(zone_record.NumZoneData):
zone_datum = _make_object("ZoneData")
zone_data.append(zone_datum)
zone_datum.AlignmentCoordinate = unpack_float16(self._src)
zone_datum.Range = unpack_float16(self._src)
bc = BitConsumer(self._src)
zone_record.Reserved = bc.u_get(6)
zone_record.ZoneMaskY = bc.u_get(1)
zone_record.ZoneMaskX = bc.u_get(1)
return obj
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _handle_tag_definefontname(self):
"""Handle the DefineFontName tag."""
|
obj = _make_object("DefineFontName")
obj.FontId = unpack_ui16(self._src)
obj.FontName = self._get_struct_string()
obj.FontCopyright = self._get_struct_string()
return obj
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _handle_tag_csmtextsettings(self):
"""Handle the CSMTextSettings tag."""
|
obj = _make_object("CSMTextSettings")
obj.TextId = unpack_ui16(self._src)
bc = BitConsumer(self._src)
obj.UseFlashType = bc.u_get(2)
obj.GridFit = bc.u_get(3)
obj.Reserved1 = bc.u_get(3)
obj.Thickness = unpack_float(self._src)
obj.Sharpness = unpack_float(self._src)
obj.Reserved2 = unpack_ui8(self._src)
return obj
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_struct_rect(self):
"""Get the RECT structure."""
|
bc = BitConsumer(self._src)
nbits = bc.u_get(5)
if self._read_twips:
return tuple(bc.s_get(nbits) for _ in range(4))
else:
return tuple(bc.s_get(nbits) / 20.0 for _ in range(4))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_struct_kerningrecord(self, font_flags_wide_codes):
"""Get the KERNINGRECORD structure."""
|
getter = unpack_ui16 if font_flags_wide_codes else unpack_ui8
data = {}
data['FontKerningCode1'] = getter(self._src)
data['FontKerningCode2'] = getter(self._src)
data['FontKerningAdjustment'] = unpack_si16(self._src)
return data
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_struct_clipactions(self):
"""Get the several CLIPACTIONRECORDs."""
|
obj = _make_object("ClipActions")
# In SWF 5 and earlier, these are 2 bytes wide; in SWF 6
# and later 4 bytes
clipeventflags_size = 2 if self._version <= 5 else 4
clipactionend_size = 2 if self._version <= 5 else 4
all_zero = b"\x00" * clipactionend_size
assert unpack_ui16(self._src) == 0 # reserved
obj.AllEventFlags = self._src.read(clipeventflags_size)
obj.ClipActionRecords = records = []
while True:
next_bytes = self._src.read(clipactionend_size)
if next_bytes == all_zero:
# was the ClipActionEndFlag
return
record = _make_object("ClipActionRecord")
records.append(record)
# as event flags and end flag has same size, we can do this trick
record.EventFlags = next_bytes
record.ActionRecordSize = unpack_ui32(self._src)
record.TheRestTODO = self._src.read(record.ActionRecordSize)
# FIXME: this struct needs more work; the EventFlags should be
# expanded and each ActionRecord(s) should be detailed more
return obj
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_struct_string(self):
"""Get the STRING structure."""
|
data = []
while True:
t = self._src.read(1)
if t == b'\x00':
break
data.append(t)
val = b''.join(data)
return val.decode("utf8")
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_struct_matrix(self):
"""Get the values for the MATRIX record."""
|
obj = _make_object("Matrix")
bc = BitConsumer(self._src)
# scale
obj.HasScale = bc.u_get(1)
if obj.HasScale:
obj.NScaleBits = n_scale_bits = bc.u_get(5)
obj.ScaleX = bc.fb_get(n_scale_bits)
obj.ScaleY = bc.fb_get(n_scale_bits)
# rotate
obj.HasRotate = bc.u_get(1)
if obj.HasRotate:
obj.NRotateBits = n_rotate_bits = bc.u_get(5)
obj.RotateSkew0 = bc.fb_get(n_rotate_bits)
obj.RotateSkew1 = bc.fb_get(n_rotate_bits)
# translate
obj.NTranslateBits = n_translate_bits = bc.u_get(5)
obj.TranslateX = bc.s_get(n_translate_bits)
obj.TranslateY = bc.s_get(n_translate_bits)
if not self._read_twips:
obj.TranslateX /= 20.0
obj.TranslateY /= 20.0
return obj
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_struct_cxformwithalpha(self):
"""Get the values for the CXFORMWITHALPHA record."""
|
obj = _make_object("CXformWithAlpha")
bc = BitConsumer(self._src)
obj.HasAddTerms = bc.u_get(1)
obj.HasMultTerms = bc.u_get(1)
obj.NBits = nbits = bc.u_get(4)
if obj.HasMultTerms:
obj.RedMultTerm = bc.s_get(nbits)
obj.GreenMultTerm = bc.s_get(nbits)
obj.BlueMultTerm = bc.s_get(nbits)
obj.AlphaMultTerm = bc.s_get(nbits)
if obj.HasAddTerms:
obj.RedAddTerm = bc.s_get(nbits)
obj.GreenAddTerm = bc.s_get(nbits)
obj.BlueAddTerm = bc.s_get(nbits)
obj.AlphaAddTerm = bc.s_get(nbits)
return obj
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_shaperecords(self, num_fill_bits, num_line_bits, shape_number):
"""Return an array of SHAPERECORDS."""
|
shape_records = []
bc = BitConsumer(self._src)
while True:
type_flag = bc.u_get(1)
if type_flag:
# edge record
straight_flag = bc.u_get(1)
num_bits = bc.u_get(4)
if straight_flag:
record = _make_object('StraightEdgeRecord')
record.TypeFlag = 1
record.StraightFlag = 1
record.NumBits = num_bits
record.GeneralLineFlag = general_line_flag = bc.u_get(1)
if general_line_flag:
record.DeltaX = bc.s_get(num_bits + 2)
record.DeltaY = bc.s_get(num_bits + 2)
else:
record.VertLineFlag = vert_line_flag = bc.s_get(1)
if vert_line_flag:
record.DeltaY = bc.s_get(num_bits + 2)
else:
record.DeltaX = bc.s_get(num_bits + 2)
else:
record = _make_object('CurvedEdgeRecord')
record.TypeFlag = 1
record.StraightFlag = 0
record.NumBits = num_bits
record.ControlDeltaX = bc.s_get(num_bits + 2)
record.ControlDeltaY = bc.s_get(num_bits + 2)
record.AnchorDeltaX = bc.s_get(num_bits + 2)
record.AnchorDeltaY = bc.s_get(num_bits + 2)
else:
# non edge record
record = _make_object('StyleChangeRecord')
record.TypeFlag = 0
five_bits = [bc.u_get(1) for _ in range(5)]
if not any(five_bits):
# the five bits are zero, this is an EndShapeRecord
break
# we're not done, store the proper flags
(record.StateNewStyles, record.StateLineStyle,
record.StateFillStyle1, record.StateFillStyle0,
record.StateMoveTo) = five_bits
if record.StateMoveTo:
record.MoveBits = move_bits = bc.u_get(5)
record.MoveDeltaX = bc.s_get(move_bits)
record.MoveDeltaY = bc.s_get(move_bits)
if record.StateFillStyle0:
record.FillStyle0 = bc.u_get(num_fill_bits)
if record.StateFillStyle1:
record.FillStyle1 = bc.u_get(num_fill_bits)
if record.StateLineStyle:
record.LineStyle = bc.u_get(num_line_bits)
if record.StateNewStyles:
record.FillStyles = self._get_struct_fillstylearray(
shape_number)
record.LineStyles = self._get_struct_linestylearray(
shape_number)
# these two not only belong to the record, but also
# modifies the number of bits read in the future
# if shape number bigs enough (didn't find this in the
# spec, but works for now, maybe '2' is not the limit...)
if shape_number > 2:
record.NumFillBits = num_fill_bits = bc.u_get(4)
record.NumLineBits = num_line_bits = bc.u_get(4)
else:
record.NumFillBits = bc.u_get(4)
record.NumLineBits = bc.u_get(4)
# reset the BC here, as the structures just read work at
# byte level
bc = BitConsumer(self._src)
shape_records.append(record)
return shape_records
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_struct_shape(self):
"""Get the values for the SHAPE record."""
|
obj = _make_object("Shape")
bc = BitConsumer(self._src)
obj.NumFillBits = n_fill_bits = bc.u_get(4)
obj.NumLineBits = n_line_bits = bc.u_get(4)
obj.ShapeRecords = self._get_shaperecords(
n_fill_bits, n_line_bits, 0)
return obj
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_struct_fillstyle(self, shape_number):
"""Get the values for the FILLSTYLE record."""
|
obj = _make_object("FillStyle")
obj.FillStyleType = style_type = unpack_ui8(self._src)
if style_type == 0x00:
if shape_number <= 2:
obj.Color = self._get_struct_rgb()
else:
obj.Color = self._get_struct_rgba()
if style_type in (0x10, 0x12, 0x13):
obj.GradientMatrix = self._get_struct_matrix()
if style_type in (0x10, 0x12):
obj.Gradient = self._get_struct_gradient(shape_number)
if style_type == 0x13:
obj.Gradient = self._get_struct_focalgradient(shape_number)
if style_type in (0x40, 0x41, 0x42, 0x43):
obj.BitmapId = unpack_ui16(self._src)
obj.BitmapMatrix = self._get_struct_matrix()
return obj
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_struct_fillstylearray(self, shape_number):
"""Get the values for the FILLSTYLEARRAY record."""
|
obj = _make_object("FillStyleArray")
obj.FillStyleCount = count = unpack_ui8(self._src)
if count == 0xFF:
obj.FillStyleCountExtended = count = unpack_ui16(self._src)
obj.FillStyles = [self._get_struct_fillstyle(shape_number)
for _ in range(count)]
return obj
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_struct_linestylearray(self, shape_number):
"""Get the values for the LINESTYLEARRAY record."""
|
obj = _make_object("LineStyleArray")
obj.LineStyleCount = count = unpack_ui8(self._src)
if count == 0xFF:
obj.LineStyleCountExtended = count = unpack_ui16(self._src)
obj.LineStyles = line_styles = []
for _ in range(count):
if shape_number <= 3:
record = _make_object("LineStyle")
record.Width = unpack_ui16(self._src)
if shape_number <= 2:
record.Color = self._get_struct_rgb()
else:
record.Color = self._get_struct_rgba()
else:
record = _make_object("LineStyle2")
record.Width = unpack_ui16(self._src)
bc = BitConsumer(self._src)
record.StartCapStyle = bc.u_get(2)
record.JoinStyle = bc.u_get(2)
record.HasFillFlag = bc.u_get(1)
record.NoHScaleFlag = bc.u_get(1)
record.NoVScaleFlag = bc.u_get(1)
record.PixelHintingFlag = bc.u_get(1)
bc.u_get(5) # reserved
record.NoClose = bc.u_get(1)
record.EndCapStyle = bc.u_get(2)
if record.JoinStyle == 2:
record.MiterLimitFactor = unpack_ui16(self._src)
if record.HasFillFlag == 0:
record.Color = self._get_struct_rgba()
else:
record.Color = self._get_struct_fillstyle(shape_number)
line_styles.append(record)
return obj
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_struct_encodedu32(self):
"""Get a EncodedU32 number."""
|
useful = []
while True:
byte = ord(self._src.read(1))
useful.append(byte)
if byte < 127:
# got all the useful bytes
break
# transform into bits reordering the bytes
useful = ['00000000' + bin(b)[2:] for b in useful[::-1]]
# get the top 7 (*seven*, as the eight one is the flag) and convert
return int(''.join([b[-7:] for b in useful]), 2)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_struct_shapewithstyle(self, shape_number):
"""Get the values for the SHAPEWITHSTYLE record."""
|
obj = _make_object("ShapeWithStyle")
obj.FillStyles = self._get_struct_fillstylearray(shape_number)
obj.LineStyles = self._get_struct_linestylearray(shape_number)
bc = BitConsumer(self._src)
obj.NumFillBits = n_fill_bits = bc.u_get(4)
obj.NumlineBits = n_line_bits = bc.u_get(4)
obj.ShapeRecords = self._get_shaperecords(
n_fill_bits, n_line_bits, shape_number)
return obj
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_struct_gradient(self, shape_number):
"""Get the values for the GRADIENT record."""
|
obj = _make_object("Gradient")
bc = BitConsumer(self._src)
obj.SpreadMode = bc.u_get(2)
obj.InterpolationMode = bc.u_get(2)
obj.NumGradients = bc.u_get(4)
obj.GradientRecords = gradient_records = []
for _ in range(obj.NumGradients):
record = _make_object("GradRecord")
gradient_records.append(record)
record.Ratio = unpack_ui8(self._src)
if shape_number <= 2:
record.Color = self._get_struct_rgb()
else:
record.Color = self._get_struct_rgba()
return obj
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_struct_filterlist(self):
"""Get the values for the FILTERLIST record."""
|
obj = _make_object("FilterList")
obj.NumberOfFilters = unpack_ui8(self._src)
obj.Filter = filters = []
# how to decode each filter type (and name), according to the filter id
filter_type = [
("DropShadowFilter", self._get_struct_dropshadowfilter), # 0
("BlurFilter", self._get_struct_blurfilter), # 1
("GlowFilter", self._get_struct_glowfilter), # 2...
("BevelFilter", self._get_struct_bevelfilter),
("GradientGlowFilter", self._get_struct_gradientglowfilter),
("ConvolutionFilter", self._get_struct_convolutionfilter),
("ColorMatrixFilter", self._get_struct_colormatrixfilter),
("GradientBevelFilter", self._get_struct_gradientbevelfilter), # 7
]
for _ in range(obj.NumberOfFilters):
_filter = _make_object("Filter")
filters.append(_filter)
_filter.FilterId = unpack_ui8(self._src)
name, func = filter_type[_filter.FilterId]
setattr(_filter, name, func())
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_struct_dropshadowfilter(self):
"""Get the values for the DROPSHADOWFILTER record."""
|
obj = _make_object("DropShadowFilter")
obj.DropShadowColor = self._get_struct_rgba()
obj.BlurX = unpack_fixed16(self._src)
obj.BlurY = unpack_fixed16(self._src)
obj.Angle = unpack_fixed16(self._src)
obj.Distance = unpack_fixed16(self._src)
obj.Strength = unpack_fixed8(self._src)
bc = BitConsumer(self._src)
obj.InnerShadow = bc.u_get(1)
obj.Knockout = bc.u_get(1)
obj.CompositeSource = bc.u_get(1)
obj.Passes = bc.u_get(5)
return obj
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_struct_blurfilter(self):
"""Get the values for the BLURFILTER record."""
|
obj = _make_object("BlurFilter")
obj.BlurX = unpack_fixed16(self._src)
obj.BlurY = unpack_fixed16(self._src)
bc = BitConsumer(self._src)
obj.Passes = bc.u_get(5)
obj.Reserved = bc.u_get(3)
return obj
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_struct_glowfilter(self):
"""Get the values for the GLOWFILTER record."""
|
obj = _make_object("GlowFilter")
obj.GlowColor = self._get_struct_rgba()
obj.BlurX = unpack_fixed16(self._src)
obj.BlurY = unpack_fixed16(self._src)
obj.Strength = unpack_fixed8(self._src)
bc = BitConsumer(self._src)
obj.InnerGlow = bc.u_get(1)
obj.Knockout = bc.u_get(1)
obj.CompositeSource = bc.u_get(1)
obj.Passes = bc.u_get(5)
return obj
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_struct_bevelfilter(self):
"""Get the values for the BEVELFILTER record."""
|
obj = _make_object("BevelFilter")
obj.ShadowColor = self._get_struct_rgba()
obj.HighlightColor = self._get_struct_rgba()
obj.BlurX = unpack_fixed16(self._src)
obj.BlurY = unpack_fixed16(self._src)
obj.Angle = unpack_fixed16(self._src)
obj.Distance = unpack_fixed16(self._src)
obj.Strength = unpack_fixed8(self._src)
bc = BitConsumer(self._src)
obj.InnerShadow = bc.u_get(1)
obj.Knockout = bc.u_get(1)
obj.CompositeSource = bc.u_get(1)
obj.OnTop = bc.u_get(1)
obj.Passes = bc.u_get(4)
return obj
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_struct_convolutionfilter(self):
"""Get the values for the CONVOLUTIONFILTER record."""
|
obj = _make_object("ConvolutionFilter")
obj.MatrixX = unpack_ui8(self._src)
obj.MatrixY = unpack_ui8(self._src)
obj.Divisor = unpack_float(self._src)
obj.Bias = unpack_float(self._src)
_quant = obj.MatrixX * obj.MatrixY
obj.Matrix = [unpack_float(self._src) for _ in range(_quant)]
obj.DefaultColor = self._get_struct_rgba()
bc = BitConsumer(self._src)
obj.Reserved = bc.u_get(6)
obj.Clamp = bc.u_get(1)
obj.PreserveAlpha = bc.u_get(1)
return obj
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_struct_colormatrixfilter(self):
"""Get the values for the COLORMATRIXFILTER record."""
|
obj = _make_object("ColorMatrixFilter")
obj.Matrix = [unpack_float(self._src) for _ in range(20)]
return obj
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_struct_gradientbevelfilter(self):
"""Get the values for the GRADIENTBEVELFILTER record."""
|
obj = _make_object("GradientBevelFilter")
obj.NumColors = num_colors = unpack_ui8(self._src)
obj.GradientColors = [self._get_struct_rgba()
for _ in range(num_colors)]
obj.GradientRatio = [unpack_ui8(self._src)
for _ in range(num_colors)]
obj.BlurX = unpack_fixed16(self._src)
obj.BlurY = unpack_fixed16(self._src)
obj.Angle = unpack_fixed16(self._src)
obj.Distance = unpack_fixed16(self._src)
obj.Strength = unpack_fixed8(self._src)
bc = BitConsumer(self._src)
obj.InnerShadow = bc.u_get(1)
obj.Knockout = bc.u_get(1)
obj.CompositeSource = bc.u_get(1)
obj.OnTop = bc.u_get(1)
obj.Passes = bc.u_get(4)
return obj
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _handle_actionconstantpool(self, _):
"""Handle the ActionConstantPool action."""
|
obj = _make_object("ActionConstantPool")
obj.Count = count = unpack_ui16(self._src)
obj.ConstantPool = pool = []
for _ in range(count):
pool.append(self._get_struct_string())
yield obj
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _handle_actiongeturl(self, _):
"""Handle the ActionGetURL action."""
|
obj = _make_object("ActionGetURL")
obj.UrlString = self._get_struct_string()
obj.TargetString = self._get_struct_string()
yield obj
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _handle_actionpush(self, length):
"""Handle the ActionPush action."""
|
init_pos = self._src.tell()
while self._src.tell() < init_pos + length:
obj = _make_object("ActionPush")
obj.Type = unpack_ui8(self._src)
# name and how to read each type
push_types = {
0: ("String", self._get_struct_string),
1: ("Float", lambda: unpack_float(self._src)),
2: ("Null", lambda: None),
4: ("RegisterNumber", lambda: unpack_ui8(self._src)),
5: ("Boolean", lambda: unpack_ui8(self._src)),
6: ("Double", lambda: unpack_double(self._src)),
7: ("Integer", lambda: unpack_ui32(self._src)),
8: ("Constant8", lambda: unpack_ui8(self._src)),
9: ("Constant16", lambda: unpack_ui16(self._src)),
}
name, func = push_types[obj.Type]
setattr(obj, name, func())
yield obj
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _handle_actiondefinefunction(self, _):
"""Handle the ActionDefineFunction action."""
|
obj = _make_object("ActionDefineFunction")
obj.FunctionName = self._get_struct_string()
obj.NumParams = unpack_ui16(self._src)
for i in range(1, obj.NumParams + 1):
setattr(obj, "param" + str(i), self._get_struct_string())
obj.CodeSize = unpack_ui16(self._src)
yield obj
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _handle_actionif(self, _):
"""Handle the ActionIf action."""
|
obj = _make_object("ActionIf")
obj.BranchOffset = unpack_si16(self._src)
yield obj
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _handle_actiondefinefunction2(self, _):
"""Handle the ActionDefineFunction2 action."""
|
obj = _make_object("ActionDefineFunction2")
obj.FunctionName = self._get_struct_string()
obj.NumParams = unpack_ui16(self._src)
obj.RegisterCount = unpack_ui8(self._src)
bc = BitConsumer(self._src)
obj.PreloadParentFlag = bc.u_get(1)
obj.PreloadRootFlag = bc.u_get(1)
obj.SupressSuperFlag = bc.u_get(1)
obj.PreloadSuperFlag = bc.u_get(1)
obj.SupressArgumentsFlag = bc.u_get(1)
obj.PreloadArgumentsFlag = bc.u_get(1)
obj.SupressThisFlag = bc.u_get(1)
obj.PreloadThisFlag = bc.u_get(1)
obj.Reserved = bc.u_get(7)
obj.PreloadGlobalFlag = bc.u_get(1)
obj.Parameters = parameters = []
for _ in range(obj.NumParams):
parameter = _make_object("Parameter")
parameters.append(parameter)
parameter.Register = unpack_ui8(self._src)
parameter.ParamName = self._get_struct_string()
obj.CodeSize = unpack_ui16(self._src)
yield obj
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def coverage(self):
"""Calculate the coverage of a file."""
|
items_unk = collections.Counter()
items_ok = collections.Counter()
def _go_deep(obj):
"""Recursive function to find internal attributes."""
if type(obj).__name__ in ('UnknownObject', 'UnknownAction'):
# blatantly unknown
items_unk[obj.name] += 1
elif obj.name in ('DefineMorphShape2', 'ClipActions'):
# these are incomplete, see FIXMEs in the code above
items_unk[obj.name] += 1
else:
# fully parsed
items_ok[obj.name] += 1
for name in obj._attribs:
attr = getattr(obj, name)
if isinstance(attr, SWFObject):
_go_deep(attr)
for tag in self.tags:
_go_deep(tag)
full_count = sum(items_ok.values()) + sum(items_unk.values())
coverage = 100 * sum(items_ok.values()) / full_count
print("Coverage is {:.1f}% of {} total items".format(coverage,
full_count))
print("Most common parsed objects:")
for k, v in items_ok.most_common(3):
print("{:5d} {}".format(v, k))
if items_unk:
print("Most common Unknown objects")
for k, v in items_unk.most_common(3):
print("{:5d} {}".format(v, k))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def checkerboard(img_spec1=None, img_spec2=None, patch_size=10, view_set=(0, 1, 2), num_slices=(10,), num_rows=2, rescale_method='global', background_threshold=0.05, annot=None, padding=5, output_path=None, figsize=None, ):
""" Checkerboard mixer. Parameters img_spec1 : str or nibabel image-like object MR image (or path to one) to be visualized img_spec2 : str or nibabel image-like object MR image (or path to one) to be visualized patch_size : int or list or (int, int) or None size of checker patch (either square or rectangular) If None, number of voxels/patch are chosen such that, there will be 7 patches through the width/height. view_set : iterable Integers specifying the dimensions to be visualized. Choices: one or more of (0, 1, 2) for a 3D image num_slices : int or iterable of size as view_set number of slices to be selected for each view Must be of the same length as view_set, each element specifying the number of slices for each dimension. If only one number is given, same number will be chosen for all dimensions. num_rows : int number of rows (top to bottom) per each of 3 dimensions rescale_method : bool or str or list or None Range to rescale the intensity values to Default: 'global', min and max values computed based on ranges from both images. If false or None, no rescaling is done (does not work yet). background_threshold : float or str A threshold value below which all the background voxels will be set to zero. Default : 0.05. Other option is a string specifying a percentile: '5%', '10%'. Specify None if you don't want any thresholding. annot : str Text to display to annotate the visualization padding : int number of voxels to pad around each panel. output_path : str path to save the generate collage to. figsize : list Size of figure in inches to be passed on to plt.figure() e.g. [12, 12] or [20, 20] Returns ------- fig : figure handle handle to the collage figure generated. """
|
img_one, img_two = _preprocess_images(img_spec1,
img_spec2,
rescale_method=rescale_method,
bkground_thresh=background_threshold,
padding=padding)
display_params = dict(interpolation='none', aspect='auto', origin='lower',
cmap='gray', vmin=0.0, vmax=1.0)
mixer = partial(_checker_mixer, checker_size=patch_size)
collage = Collage(view_set=view_set, num_slices=num_slices, num_rows=num_rows,
figsize=figsize, display_params=display_params)
collage.transform_and_attach((img_one, img_two), func=mixer)
collage.save(output_path=output_path, annot=annot)
return collage
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def voxelwise_diff(img_spec1=None, img_spec2=None, abs_value=True, cmap='gray', overlay_image=False, overlay_alpha=0.8, num_rows=2, num_cols=6, rescale_method='global', background_threshold=0.05, annot=None, padding=5, output_path=None, figsize=None):
""" Voxel-wise difference map. Parameters img_spec1 : str or nibabel image-like object MR image (or path to one) to be visualized img_spec2 : str or nibabel image-like object MR image (or path to one) to be visualized abs_value : bool Flag indicating whether to take the absolute value of the diffenence or not. Default: True, display absolute differences only (so order of images does not matter) Colormap to show the difference values. overlay_image : bool Flag to specify whether to overlay the difference values on the original image. .. note: This feature is not reliable and supported well yet. num_rows : int number of rows (top to bottom) per each of 3 dimensions num_cols : int number of panels (left to right) per row of each dimension. rescale_method : bool or str or list or None Range to rescale the intensity values to Default: 'global', min and max values computed based on ranges from both images. If false or None, no rescaling is done (does not work yet). background_threshold : float or str A threshold value below which all the background voxels will be set to zero. Default : 0.05. Other option is a string specifying a percentile: '5%', '10%'. Specify None if you don't want any thresholding. annot : str Text to display to annotate the visualization padding : int number of voxels to pad around each panel. output_path : str path to save the generate collage to. figsize : list Size of figure in inches to be passed on to plt.figure() e.g. [12, 12] or [20, 20] Returns ------- fig : figure handle handle to the collage figure generated. """
|
if not isinstance(abs_value, bool):
abs_value = bool(abs_value)
mixer_params = dict(abs_value=abs_value,
cmap=cmap,
overlay_image=overlay_image,
overlay_alpha=overlay_alpha)
fig = _compare(img_spec1,
img_spec2,
num_rows=num_rows,
num_cols=num_cols,
mixer='voxelwise_diff',
annot=annot,
padding=padding,
rescale_method=rescale_method,
bkground_thresh=background_threshold,
output_path=output_path,
figsize=figsize,
**mixer_params)
return fig
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _compare(img_spec1, img_spec2, num_rows=2, num_cols=6, mixer='checker_board', rescale_method='global', annot=None, padding=5, bkground_thresh=0.05, output_path=None, figsize=None, **kwargs):
""" Produces checkerboard comparison plot of two 3D images. Parameters img_spec1 : str or nibabel image-like object MR image (or path to one) to be visualized img_spec2 : str or nibabel image-like object MR image (or path to one) to be visualized num_rows : int number of rows (top to bottom) per each of 3 dimensions num_cols : int number of panels (left to right) per row of each dimension. mixer : str type of mixer to produce the comparison figure. Options: checker_board, color_mix, diff_abs, rescale_method : bool or str or list or None Method to rescale the intensity values to. Choices : 'global', 'each', False or None. Default: 'global', min and max values computed based on ranges from both images. If 'each', rescales each image separately to [0, 1]. This option is useful when overlaying images with very different intensity ranges e.g. from different modalities altogether. If False or None, no rescaling is done (does not work yet). annot : str Text to display to annotate the visualization padding : int number of voxels to pad around each panel. output_path : str path to save the generate collage to. figsize : list Size of figure in inches to be passed on to plt.figure() e.g. [12, 12] or [20, 20] kwargs : dict Additional arguments specific to the particular mixer e.g. alpha_channels = [1, 1] for the color_mix mixer Returns ------- """
|
num_rows, num_cols, padding = check_params(num_rows, num_cols, padding)
img1, img2 = check_images(img_spec1, img_spec2, bkground_thresh=bkground_thresh)
img1, img2 = crop_to_extents(img1, img2, padding)
num_slices_per_view = num_rows * num_cols
slices = pick_slices(img2, num_slices_per_view)
rescale_images, img1, img2, min_value, max_value = check_rescaling(img1, img2, rescale_method)
plt.style.use('dark_background')
num_axes = 3
if figsize is None:
figsize = [3 * num_axes * num_rows, 3 * num_cols]
fig, ax = plt.subplots(num_axes * num_rows, num_cols, figsize=figsize)
# displaying some annotation text if provided
# good choice would be the location of the input images (for future refwhen image is shared or misplaced!)
if annot is not None:
fig.suptitle(annot, backgroundcolor='black', color='g')
display_params = dict(interpolation='none', aspect='equal', origin='lower')
ax = ax.flatten()
ax_counter = 0
for dim_index in range(3):
for slice_num in slices[dim_index]:
plt.sca(ax[ax_counter])
ax_counter = ax_counter + 1
slice1 = get_axis(img1, dim_index, slice_num)
slice2 = get_axis(img2, dim_index, slice_num)
mixed, mixer_spec_params = _generic_mixer(slice1, slice2, mixer, **kwargs)
display_params.update(mixer_spec_params)
plt.imshow(mixed, vmin=min_value, vmax=max_value, **display_params)
# adjustments for proper presentation
plt.axis('off')
fig.tight_layout()
if output_path is not None:
output_path = output_path.replace(' ', '_')
fig.savefig(output_path + '.png', bbox_inches='tight')
# plt.close()
return fig
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _generic_mixer(slice1, slice2, mixer_name, **kwargs):
""" Generic mixer to process two slices with appropriate mixer and return the composite to be displayed. """
|
mixer_name = mixer_name.lower()
if mixer_name in ['color_mix', 'rgb']:
mixed = _mix_color(slice1, slice2, **kwargs)
cmap = None # data is already RGB-ed
elif mixer_name in ['checkerboard', 'checker', 'cb', 'checker_board']:
checkers = _get_checkers(slice1.shape, **kwargs)
mixed = _checker_mixer(slice1, slice2, checkers)
cmap = 'gray'
elif mixer_name in ['diff', 'voxelwise_diff', 'vdiff']:
mixed, cmap = _diff_image(slice1, slice2, **kwargs)
# if kwargs['overlay_image'] is True:
# diff_cmap = diff_colormap()
# plt.imshow(slice1, alpha=kwargs['overlay_alpha'], **display_params)
# plt.hold(True)
# plt.imshow(mixed,
# cmap=diff_cmap,
# vmin=min_value, vmax=max_value,
# **display_params)
# else:
# plt.imshow(mixed, cmap=cmap,
# vmin=min_value, vmax=max_value,
# **display_params)
else:
raise ValueError('Invalid mixer name chosen.')
disp_params = dict(cmap=cmap)
return mixed, disp_params
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_rescaling(img1, img2, rescale_method):
"""Estimates the intensity range to clip the visualizations to"""
|
# estimating intensity ranges
if rescale_method is None:
# this section is to help user to avoid all intensity rescaling altogther!
# TODO bug does not work yet, as pyplot does not offer any easy way to control it
rescale_images = False
min_value = None
max_value = None
norm_image = None # mpl.colors.NoNorm doesn't work yet. data is getting linearly normalized to [0, 1]
elif isinstance(rescale_method, str):
if rescale_method.lower() in ['global']:
# TODO need a way to alert the user if one of the distributions is too narrow
# in which case that image will be collapsed to an uniform value
combined_distr = np.concatenate((img1.flatten(), img2.flatten()))
min_value = combined_distr.min()
max_value = combined_distr.max()
elif rescale_method.lower() in ['each']:
img1 = scale_0to1(img1)
img2 = scale_0to1(img2)
min_value = 0.0
max_value = 1.0
else:
raise ValueError('rescaling method can only be "global" or "each"')
rescale_images = True
norm_image = mpl.colors.Normalize
elif len(rescale_method) == 2:
min_value = min(rescale_method)
max_value = max(rescale_method)
rescale_images = True
norm_image = mpl.colors.Normalize
else:
raise ValueError('Invalid intensity range!. It must be either : '
'1) a list/tuple of two distinct values or'
'2) "global" indicating rescaling based on min/max values derived from both images or'
'3) None, no rescaling or norming altogether. ')
return rescale_images, img1, img2, min_value, max_value
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_images(img_spec1, img_spec2, bkground_thresh=0.05):
"""Reads the two images and assers identical shape."""
|
img1 = read_image(img_spec1, bkground_thresh)
img2 = read_image(img_spec2, bkground_thresh)
if img1.shape != img2.shape:
raise ValueError('size mismatch! First image: {} Second image: {}\n'
'Two images to be compared must be of the same size in all dimensions.'.format(
img1.shape,
img2.shape))
return img1, img2
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_checkers(slice_shape, patch_size):
"""Creates checkerboard of a given tile size, filling a given slice."""
|
if patch_size is not None:
patch_size = check_patch_size(patch_size)
else:
# 7 patches in each axis, min voxels/patch = 3
# TODO make 7 a user settable parameter
patch_size = np.round(np.array(slice_shape) / 7).astype('int16')
patch_size = np.maximum(patch_size, np.array([3, 3]))
black = np.zeros(patch_size)
white = np.ones(patch_size)
tile = np.vstack((np.hstack([black, white]), np.hstack([white, black])))
# using ceil so we can clip the extra portions
num_tiles = np.ceil(np.divide(slice_shape, tile.shape)).astype(int)
checkers = np.tile(tile, num_tiles)
# clipping any extra columns or rows
if any(np.greater(checkers.shape, slice_shape)):
if checkers.shape[0] > slice_shape[0]:
checkers = np.delete(checkers, np.s_[slice_shape[0]:], axis=0)
if checkers.shape[1] > slice_shape[1]:
checkers = np.delete(checkers, np.s_[slice_shape[1]:], axis=1)
return checkers
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _mix_color(slice1, slice2, alpha_channels, color_space):
"""Mixing them as red and green channels"""
|
if slice1.shape != slice2.shape:
raise ValueError('size mismatch between cropped slices and checkers!!!')
alpha_channels = np.array(alpha_channels)
if len(alpha_channels) != 2:
raise ValueError('Alphas must be two value tuples.')
slice1, slice2 = scale_images_0to1(slice1, slice2)
# masking background
combined_distr = np.concatenate((slice1.flatten(), slice2.flatten()))
image_eps = np.percentile(combined_distr, 5)
background = np.logical_or(slice1 <= image_eps, slice2 <= image_eps)
if color_space.lower() in ['rgb']:
red = alpha_channels[0] * slice1
grn = alpha_channels[1] * slice2
blu = np.zeros_like(slice1)
# foreground = np.logical_not(background)
# blu[foreground] = 1.0
mixed = np.stack((red, grn, blu), axis=2)
elif color_space.lower() in ['hsv']:
raise NotImplementedError(
'This method (color_space="hsv") is yet to fully conceptualized and implemented.')
# TODO other ideas: hue/saturation/intensity value driven by difference in intensity?
hue = alpha_channels[0] * slice1
sat = alpha_channels[1] * slice2
val = np.ones_like(slice1)
hue[background] = 1.0
sat[background] = 0.0
val[background] = 0.0
mixed = np.stack((hue, sat, val), axis=2)
# converting to RGB
mixed = mpl.colors.hsv_to_rgb(mixed)
# ensuring all values are clipped to [0, 1]
mixed[mixed <= 0.0] = 0.0
mixed[mixed >= 1.0] = 1.0
return mixed
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _checker_mixer(slice1, slice2, checker_size=None):
"""Mixes the two slices in alternating areas specified by checkers"""
|
checkers = _get_checkers(slice1.shape, checker_size)
if slice1.shape != slice2.shape or slice2.shape != checkers.shape:
raise ValueError('size mismatch between cropped slices and checkers!!!')
mixed = slice1.copy()
mixed[checkers > 0] = slice2[checkers > 0]
return mixed
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.