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 fetc...
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", j...
<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 aroun...
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...
<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),...
<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....
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)...
<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. Conv...
# 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] ...
<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...
# 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.downlo...
<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 ca...
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) ...
<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 i...
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 ra...
# 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 ...
<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_shor...
<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) # ) ...
<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...
<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 ...
<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.ki...
<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*...
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....
<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...
<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 callb...
<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_ca...
<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() ...
<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() ...
<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- pre...
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 ac...
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 "{}({})".fo...
<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 rea...
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 conte...
<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 ...
<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 =...
<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) ...
<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) ...
<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) ...
<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...
<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()) ...
<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.UsesN...
<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 = BitC...
<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.FontF...
<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 = [] ...
<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) ...
<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._...
<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...
<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 asser...
<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) # rota...
<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(nb...
<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...
<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 (0x...
<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)] ...
<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: ...
<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[::-...
<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...
<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_ob...
<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 ("...
<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_f...
<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.Knocko...
<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_fixed1...
<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 ...
<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...
<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), ...
<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) ...
<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_ge...
<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.nam...
<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....
img_one, img_two = _preprocess_images(img_spec1, img_spec2, rescale_method=rescale_method, bkground_thresh=background_threshold, padding=padding) ...
<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='gl...
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_sp...
<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_pat...
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) ...
<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) ...
<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...
<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( ...
<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.arra...
<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) ...
<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