output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Write this parameter group with parameters to a file handle.
Can you generate a brief explanation for the following Python 3 code def write(self, group_id, handle): '''Write this parameter group, with parameters, to a file handle. Parameters ---------- group_id : int The numerical ID of the group. handle : file handle ...
As a python code expert, you are capable of creating scripts from specifications.
def check_metadata(self): '''Ensure that the metadata in our file is self-consistent.''' assert self.header.point_count == self.point_used, ( 'inconsistent point count! {} header != {} POINT:USED'.format( self.header.point_count, self.point_used, )...
Implement a Python 3 function for ensuring that the metadata in our file is self - consistent.
You are a Python code analyst, evaluating scripts for potential improvements.
def add_group(self, group_id, name, desc): '''Add a new parameter group. Parameters ---------- group_id : int The numeric ID for a group to check or create. name : str, optional If a group is created, assign this name to the group. desc : str, opt...
Can you write a function in Python 3 where it adds a new parameter group.
As a Python code analyst, you investigate and solve complex coding mysteries
Get a group or parameter from the cache.
Explain what the following Python 3 code does def get(self, group, default=None): '''Get a group or parameter. Parameters ---------- group : str If this string contains a period (.), then the part before the period will be used to retrieve a group, and the part a...
You are a Python code generator, capable of creating scripts from specifications.
Compute the size in 512B blocks of the parameter section.
Given the following Python 3 function, write the documentation def parameter_blocks(self): '''Compute the size (in 512B blocks) of the parameter section.''' bytes = 4. + sum(g.binary_size() for g in self.groups.values()) return int(np.ceil(bytes / 512))
As a Python code analyst, you investigate and solve complex coding mysteries
Iterate over the data frames from our C3D file handle.
Make a summary of the following Python 3 code def read_frames(self, copy=True): '''Iterate over the data frames from our C3D file handle. Parameters ---------- copy : bool If False, the reader returns a reference to the same data buffers for every frame. The defa...
As a python code expert, you are capable of creating scripts from specifications.
Pad the file with 0s to the end of the next block boundary.
Make a summary of the following Python 3 code def _pad_block(self, handle): '''Pad the file with 0s to the end of the next block boundary.''' extra = handle.tell() % 512 if extra: handle.write(b'\x00' * (512 - extra))
As a Python code translator, you convert algorithms and pseudocode into Python.
def _write_metadata(self, handle): '''Write metadata to a file handle. Parameters ---------- handle : file Write metadata and C3D motion frames to the given file handle. The writer does not close the handle. ''' self.check_metadata() # he...
Can you create a Python 3 function that writes the metadata to a given file handle.
As a Python code analyst, you investigate and solve complex coding mysteries
Write our frame data to the given file handle.
Can you tell what is the following Python 3 function doing def _write_frames(self, handle): '''Write our frame data to the given file handle. Parameters ---------- handle : file Write metadata and C3D motion frames to the given file handle. The writer does not cl...
As a python code expert, you are capable of creating scripts from specifications.
Writes metadata and point + analog frames to a given file handle.
Given the following Python 3 function, write the documentation def write(self, handle): '''Write metadata and point + analog frames to a file handle. Parameters ---------- handle : file Write metadata and C3D motion frames to the given file handle. The writer doe...
As a python code expert, you are capable of creating scripts from specifications.
def aggregate_per_prefix(self, start_time, end_time, limit=0, net_masks='', exclude_net_masks=False, filter_proto=None): """ Given a time range aggregates bytes per prefix. Args: start_time: A string representing the starting time of the time range end_time: A string...
Implement a Python 3 function for giving a time range aggregates bytes per prefix. Args: start_time: A string representing the starting time of the time range end_time: A string representing the ending time of the time range limit: An optional integer. If it's >0 it will limit the amount of prefixes returned. filter_pr...
You are a Python code analyst, evaluating scripts for potential improvements.
def aggregate_per_as(self, start_time, end_time): """ Given a time range aggregates bytes per ASNs. Args: start_time: A string representing the starting time of the time range end_time: A string representing the ending time of the time range Returns: ...
Implement a Python 3 function for giving a time range aggregates bytes per ASNs. Args: start_time: A string representing the starting time of the time range end_time: A string representing the ending time of the time range Returns: A list of prefixes sorted by sum_bytes. For example: [ {'key': '6500', 'sum_bytes': 3000...
You are a Python code analyst, evaluating scripts for potential improvements.
def _workaround_no_vector_images(project): """Replace vector images with fake ones.""" RED = (255, 0, 0) PLACEHOLDER = kurt.Image.new((32, 32), RED) for scriptable in [project.stage] + project.sprites: for costume in scriptable.costumes: if costume.image.format == "SVG": ...
Write a Python 3 function that can replace vector images with fake ones.
As a python code expert, you are capable of creating scripts from specifications.
Make Stage - specific variables global ( move them to Project
How would you explain what the following Python 3 function does def _workaround_no_stage_specific_variables(project): for (name, var) in project.stage.variables.items(): yield "variable %s" % name for (name, _list) in project.stage.lists.items(): yield "list %s" % name project.variables.upda...
As a python code expert, you are capable of creating scripts from specifications.
def register(cls, plugin): """Register a new :class:`KurtPlugin`. Once registered, the plugin can be used by :class:`Project`, when: * :attr:`Project.load` sees a file with the right extension * :attr:`Project.convert` is called with the format as a parameter """ cls....
Can you implement a function in Python 3 that registers a new KurtPlugin.
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_plugin(cls, name=None, **kwargs): """Returns the first format plugin whose attributes match kwargs. For example:: get_plugin(extension="scratch14") Will return the :class:`KurtPlugin` whose :attr:`extension <KurtPlugin.extension>` attribute is ``"scratch14"``. ...
How would you implement a function in Python 3 that returns the first format plugin whose attributes match kwargs.
As a python code expert, you are capable of creating scripts from specifications.
Return the block with the given command. Returns None if the block is not found.
Can you tell what is the following Python 3 function doing def block_by_command(cls, command): for block in cls.blocks: if block.has_command(command): return block
You are a Python code generator, capable of creating scripts from specifications.
Return a list of blocks matching the given text.
Can you generate the documentation for the following Python 3 function def blocks_by_text(cls, text): text = kurt.BlockType._strip_text(text) matches = [] for block in cls.blocks: for pbt in block.conversions: if pbt.stripped_text == text: matches....
As a Python code composer, you craft elegant and concise scripts.
Clean up the given list of scripts in - place so none of the scripts overlap.
How would you explain what the following Python 3 function does def clean_up(scripts): scripts_with_pos = [s for s in scripts if s.pos] scripts_with_pos.sort(key=lambda s: (s.pos[1], s.pos[0])) scripts = scripts_with_pos + [s for s in scripts if not s.pos] y = 20 for script in scripts: scri...
As a Python code translator, you convert algorithms and pseudocode into Python.
def obj_classes_from_module(module): """Return a list of classes in a module that have a 'classID' attribute.""" for name in dir(module): if not name.startswith('_'): cls = getattr(module, name) if getattr(cls, 'classID', None): yield (name, cls)
How would you implement a function in Python 3 that returns a list of classes in a module that have a classID attribute.
As a Python code composer, you craft elegant and concise scripts.
def decode_network(objects): """Return root object from ref-containing obj table entries""" def resolve_ref(obj, objects=objects): if isinstance(obj, Ref): # first entry is 1 return objects[obj.index - 1] else: return obj # Reading the ObjTable backwards ...
How would you code a function in Python 3 to decode obj table entries into a single object.
As a Python code translator, you convert algorithms and pseudocode into Python.
Yields the object table entries from the object network.
How would you explain what the following Python 3 function does def encode_network(root): orig_objects = [] objects = [] def get_ref(value, objects=objects): """Returns the index of the given object in the object table, adding it if needed. """ value = PythonicAdapter(Pass)...
As a Python code analyst, you investigate and solve complex coding mysteries
def encode_network(root): """Yield ref-containing obj table entries from object network""" def fix_values(obj): if isinstance(obj, Container): obj.update((k, get_ref(v)) for (k, v) in obj.items() if k != 'class_name') fixed_obj = obj ...
Write a Python 3 script to yield ref - containing obj table entries from object network
As a Python code analyst, you investigate and solve complex coding mysteries
Converts user - class objects to a list of user - class objects.
Make a summary of the following Python 3 code def decode_obj_table(table_entries, plugin): entries = [] for entry in table_entries: if isinstance(entry, Container): assert not hasattr(entry, '__recursion_lock__') user_obj_def = plugin.user_objects[entry.classID] asser...
As a Python code analyst, you investigate and solve complex coding mysteries
def encode_obj_table(root, plugin): """Return list of obj table entries. Converts user-class objects""" entries = encode_network(root) table_entries = [] for entry in entries: if isinstance(entry, Container): assert not hasattr(entry, '__recursion_lock__') user_obj_def =...
Write a Python 3 script for returning list of obj table entries. Converts user - class objects into Container objects.
As a Python code translator, you convert algorithms and pseudocode into Python.
def _encode(self, obj, context): """Encodes a class to a lower-level object using the class' own to_construct function. If no such function is defined, returns the object unchanged. """ func = getattr(obj, 'to_construct', None) if callable(func): return func(c...
Write a Python 3 script for encoding a class to a lower - level object using the class own to_construct function.
As a Python code translator, you convert algorithms and pseudocode into Python.
def _decode(self, obj, context): """Initialises a new Python class from a construct using the mapping passed to the adapter. """ cls = self._get_class(obj.classID) return cls.from_construct(obj, context)
How would you implement a function in Python 3 that initialises a new Python class from a construct using the mapping passed to the adapter.
As a python code expert, you are capable of creating scripts from specifications.
Write file contents string into archive.
Given the following Python 3 function, write the documentation def write_file(self, name, contents): # TODO: find a way to make ZipFile accept a file object. zi = zipfile.ZipInfo(name) zi.date_time = time.localtime(time.time())[:6] zi.compress_type = zipfile.ZIP_DEFLATED zi.exter...
As a python code expert, you are capable of creating scripts from specifications.
def load_midi_file(path): """Yield (pitch, start_beat, end_beat) for each note in midi file.""" midi_notes = [] def register_note(track, channel, pitch, velocity, start, end): midi_notes.append((pitch, start, end)) midi.register_note = register_note global m m = midi.MidiFile() m.o...
Can you implement a function in Python 3 that loads a MIDI file into a sequence of MIDI objects.
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_media(self, v14_scriptable): """Return (images, sounds)""" images = [] sounds = [] for media in v14_scriptable.media: if media.class_name == 'SoundMedia': sounds.append(media) elif media.class_name == 'ImageMedia': images.ap...
How would you code a function in Python 3 to return a list of images and sounds from a v14 scriptable.
You are a Python code analyst, evaluating scripts for potential improvements.
def from_byte_array(cls, bytes_): """Decodes a run-length encoded ByteArray and returns a Bitmap. The ByteArray decompresses to a sequence of 32-bit values, which are stored as a byte string. (The specific encoding depends on Form.depth.) """ runs = cls._length_run_coding.parse(b...
How would you code a function in Python 3 to decode a run - length encoded ByteArray and returns a Bitmap. The ByteArray decompresses to a sequence of 32 - bit values which are stored as a byte string.
As a python code expert, you are capable of creating scripts from specifications.
Returns a Form with 32 - bit RGBA pixels Accepts string containing raw RGBA color values
Can you tell what is the following Python 3 function doing def from_string(cls, width, height, rgba_string): # Convert RGBA string to ARGB raw = "" for i in range(0, len(rgba_string), 4): raw += rgba_string[i+3] # alpha raw += rgba_string[i:i+3] # rgb assert le...
As a python code expert, you are capable of creating scripts from specifications.
Opens Explorer or Finder with given path depending on platform
Here you have a function in Python 3, explain what it does def open_file(path): if sys.platform=='win32': os.startfile(path) #subprocess.Popen(['start', path], shell= True) elif sys.platform=='darwin': subprocess.Popen(['open', path]) else: try: subproce...
You are a Python code analyst, evaluating scripts for potential improvements.
Update the file_path Entry widget
Here you have a function in Python 3, explain what it does def set_file_path(self, path): self.file_path.delete(0, END) self.file_path.insert(0, path)
As a Python code analyst, you investigate and solve complex coding mysteries
Load a Kurt project from file.
Can you tell what is the following Python 3 function doing def load(cls, path, format=None): path_was_string = isinstance(path, basestring) if path_was_string: (folder, filename) = os.path.split(path) (name, extension) = os.path.splitext(filename) if format is None: ...
You are a Python code generator, capable of creating scripts from specifications.
def copy(self): """Return a new Project instance, deep-copying all the attributes.""" p = Project() p.name = self.name p.path = self.path p._plugin = self._plugin p.stage = self.stage.copy() p.stage.project = p for sprite in self.sprites: s = ...
Write a Python 3 script to return a new Project instance deep - copying all the attributes.
As a Python code composer, you craft elegant and concise scripts.
def convert(self, format): """Convert the project in-place to a different file format. Returns a list of :class:`UnsupportedFeature` objects, which may give warnings about the conversion. :param format: :attr:`KurtFileFormat.name` eg. ``"scratch14"``. :raises: :class:`ValueErr...
Create a Python 3 function for converting the project in - place to a different file format.
You are a Python code architect, reviewing and designing scalable and efficient code
def save(self, path=None, debug=False): """Save project to file. :param path: Path or file pointer. If you pass a file pointer, you're responsible for closing it. If path is not given, the :attr:`path` attribute is used, ...
Implement a Python 3 function for saving the project to file.
You are a Python code generator, capable of creating scripts from specifications.
Convert the project to a standardised form for the current plugin.
Can you generate the documentation for the following Python 3 function def _normalize(self): unique_sprite_names = set(sprite.name for sprite in self.sprites) if len(unique_sprite_names) < len(self.sprites): raise ValueError, "Sprite names must be unique" # sync self.sprites and se...
As a Python code analyst, you investigate and solve complex coding mysteries
Return a new instance deep - copying all the attributes.
Explain what the following Python 3 code does def copy(self, o=None): if o is None: o = self.__class__(self.project) o.scripts = [s.copy() for s in self.scripts] o.variables = dict((n, v.copy()) for (n, v) in self.variables.items()) o.lists = dict((n, l.copy()) for (n, l) in self.lists.i...
You are a Python code generator, capable of creating scripts from specifications.
def parse(self, text): """Parse the given code and add it to :attr:`scripts`. The syntax matches :attr:`Script.stringify()`. See :mod:`kurt.text` for reference. """ self.scripts.append(kurt.text.parse(text, self))
Can you implement a function in Python 3 that parses the given code and add it to the scripts list.
You are a Python code analyst, evaluating scripts for potential improvements.
def copy(self): """Return a new instance, deep-copying all the attributes.""" o = self.__class__(self.project, self.name) Scriptable.copy(self, o) o.position = tuple(self.position) o.direction = self.direction o.rotation_style = self.rotation_style o.size = self.s...
Write a Python 3 script to return a new instance deep - copying all the attributes.
You are a Python code generator, capable of creating scripts from specifications.
def copy(self): """Return a new instance with the same attributes.""" o = self.__class__(self.target, self.block.copy(), self.style, self.is_visible, self.pos) o.slider_min = self.slider_min o.slider_max = self.slider_max ...
Create a Python 3 function to return a copy of the current instance with the same attributes.
As a Python code analyst, you investigate and solve complex coding mysteries
The type of value to watch based on the block type.
Can you generate a brief explanation for the following Python 3 code def kind(self): if self.block.type.has_command('readVariable'): return 'variable' elif self.block.type.has_command('contentsOfList:'): return 'list' else: return 'block'
You are a Python code generator, capable of creating scripts from specifications.
Return the value of the attribute.
How would you explain what the following Python 3 function does def value(self): if self.kind == 'variable': return self.target.variables[self.block.args[0]] elif self.kind == 'list': return self.target.lists[self.block.args[0]]
You are a Python code analyst, evaluating scripts for potential improvements.
Returns the color value in hexcode format.
Make a summary of the following Python 3 code def stringify(self): hexcode = "#" for x in self.value: part = hex(x)[2:] if len(part) < 2: part = "0" + part hexcode += part return hexcode
As a Python code analyst, you investigate and solve complex coding mysteries
Return a list of valid options to a menu insert given a Scriptable for context.
Can you generate the documentation for the following Python 3 function def options(self, scriptable=None): options = list(Insert.KIND_OPTIONS.get(self.kind, [])) if scriptable: if self.kind == 'var': options += scriptable.variables.keys() options += scriptable...
You are a Python code analyst, evaluating scripts for potential improvements.
The text with spaces and inserts removed.
Can you generate a brief explanation for the following Python 3 code def stripped_text(self): return BaseBlockType._strip_text( self.text % tuple((i.default if i.shape == 'inline' else '%s') for i in self.inserts))
As a Python code translator, you convert algorithms and pseudocode into Python.
def _strip_text(text): """Returns text with spaces and inserts removed.""" text = re.sub(r'[ ,?:]|%s', "", text.lower()) for chr in "-%": new_text = text.replace(chr, "") if new_text: text = new_text return text.lower()
Write a Python 3 function for returning text with spaces and inserts removed.
As a python code expert, you are capable of creating scripts from specifications.
def has_insert(self, shape): """Returns True if any of the inserts have the given shape.""" for insert in self.inserts: if insert.shape == shape: return True return False
Write a Python 3 function that can return True if any of the inserts have the given shape.
You are a Python code architect, reviewing and designing scalable and efficient code
Add a new conversion.
Can you generate the documentation for the following Python 3 function def _add_conversion(self, plugin, pbt): assert self.shape == pbt.shape assert len(self.inserts) == len(pbt.inserts) for (i, o) in zip(self.inserts, pbt.inserts): assert i.shape == o.shape assert i.kind...
You are a Python code generator, capable of creating scripts from specifications.
Return a : class : PluginBlockType for the given plugin name.
Here you have a function in Python 3, explain what it does def convert(self, plugin=None): if plugin: plugin = kurt.plugin.Kurt.get_plugin(plugin) if plugin.name in self._plugins: return self._plugins[plugin.name] else: err = BlockNotSupported(...
As a Python code translator, you convert algorithms and pseudocode into Python.
def has_conversion(self, plugin): """Return True if the plugin supports this block.""" plugin = kurt.plugin.Kurt.get_plugin(plugin) return plugin.name in self._plugins
Can you create a Python 3 function that returns True if the plugin supports this block.
As a Python code analyst, you investigate and solve complex coding mysteries
Returns True if any of the plugins have the given command.
Can you generate a brief explanation for the following Python 3 code def has_command(self, command): for pbt in self._plugins.values(): if pbt.command == command: return True return False
You are a Python code generator, capable of creating scripts from specifications.
def get(cls, block_type): """Return a :class:`BlockType` instance from the given parameter. * If it's already a BlockType instance, return that. * If it exactly matches the command on a :class:`PluginBlockType`, return the corresponding BlockType. * If it loosely matches the...
Implement a function in Python 3 to return a : class : BlockType instance from the given parameter.
As a Python code translator, you convert algorithms and pseudocode into Python.
Return a new Block instance with the same attributes.
Here you have a function in Python 3, explain what it does def copy(self): args = [] for arg in self.args: if isinstance(arg, Block): arg = arg.copy() elif isinstance(arg, list): arg = [b.copy() for b in arg] args.append(arg) re...
As a Python code composer, you craft elegant and concise scripts.
def copy(self): """Return a new instance with the same attributes.""" return self.__class__([b.copy() for b in self.blocks], tuple(self.pos) if self.pos else None)
Write a Python 3 function that can return a new instance with the same attributes.
As a Python code composer, you craft elegant and concise scripts.
Load a Costume from an image file.
How would you explain what the following Python 3 function does def load(self, path): (folder, filename) = os.path.split(path) (name, extension) = os.path.splitext(filename) return Costume(name, Image.load(path))
You are a Python code architect, reviewing and designing scalable and efficient code
A : class : PIL. Image instance containing the image data.
Can you tell what is the following Python 3 function doing def pil_image(self): if not self._pil_image: if self._format == "SVG": raise VectorImageError("can't rasterise vector images") self._pil_image = PIL.Image.open(StringIO(self.contents)) return self._pil_ima...
As a Python code analyst, you investigate and solve complex coding mysteries
def format(self): """The format of the image file. An uppercase string corresponding to the :attr:`PIL.ImageFile.ImageFile.format` attribute. Valid values include ``"JPEG"`` and ``"PNG"``. """ if self._format: return self._format elif self.pil_image...
Write a Python 3 script to return the format of the image file.
As a python code expert, you are capable of creating scripts from specifications.
def size(self): """``(width, height)`` in pixels.""" if self._size and not self._pil_image: return self._size else: return self.pil_image.size
Create a Python 3 function for returning the size of the image.
As a Python code analyst, you investigate and solve complex coding mysteries
def load(cls, path): """Load image from file.""" assert os.path.exists(path), "No such file: %r" % path (folder, filename) = os.path.split(path) (name, extension) = os.path.splitext(filename) image = Image(None) image._path = path image._format = Image.image_for...
Can you write a function in Python 3 where it loads image from file.
As a Python code composer, you craft elegant and concise scripts.
Convert an image to one of the given formats.
Can you generate a brief explanation for the following Python 3 code def convert(self, *formats): for format in formats: format = Image.image_format(format) if self.format == format: return self else: return self._convert(format)
As a Python code analyst, you investigate and solve complex coding mysteries
Return a new Image instance with the given format.
Can you generate the documentation for the following Python 3 function def _convert(self, format): if self.format == format: return self else: image = Image(self.pil_image) image._format = format return image
As a Python code translator, you convert algorithms and pseudocode into Python.
def save(self, path): """Save image to file path. The image format is guessed from the extension. If path has no extension, the image's :attr:`format` is used. :returns: Path to the saved file. """ (folder, filename) = os.path.split(path) (name, extension) = os...
Write a Python 3 function for saving the image to file path.
You are a Python code generator, capable of creating scripts from specifications.
Return a new Image instance filled with a color.
Can you tell what is the following Python 3 function doing def new(self, size, fill): return Image(PIL.Image.new("RGB", size, fill))
You are a Python code generator, capable of creating scripts from specifications.
Return a new Image instance with the given size.
Here you have a function in Python 3, explain what it does def resize(self, size): return Image(self.pil_image.resize(size, PIL.Image.ANTIALIAS))
As a Python code composer, you craft elegant and concise scripts.
def paste(self, other): """Return a new Image with the given image pasted on top. This image will show through transparent areas of the given image. """ r, g, b, alpha = other.pil_image.split() pil_image = self.pil_image.copy() pil_image.paste(other.pil_image, mask=alph...
Write a Python 3 script to return a new Image with the given image pasted on top.
As a Python code translator, you convert algorithms and pseudocode into Python.
Load a sound from a wave file.
Explain what the following Python 3 code does def load(self, path): (folder, filename) = os.path.split(path) (name, extension) = os.path.splitext(filename) return Sound(name, Waveform.load(path))
As a Python code translator, you convert algorithms and pseudocode into Python.
Save the sound to a wave file at the given path.
How would you explain what the following Python 3 function does def save(self, path): (folder, filename) = os.path.split(path) if not filename: filename = _clean_filename(self.name) path = os.path.join(folder, filename) return self.waveform.save(path)
As a Python code composer, you craft elegant and concise scripts.
The raw file contents as a string.
Explain what the following Python 3 code does def contents(self): if not self._contents: if self._path: # Read file into memory so we don't run out of file descriptors f = open(self._path, "rb") self._contents = f.read() f.close() ...
As a python code expert, you are capable of creating scripts from specifications.
def _wave(self): """Return a wave.Wave_read instance from the ``wave`` module.""" try: return wave.open(StringIO(self.contents)) except wave.Error, err: err.message += "\nInvalid wave file: %s" % self err.args = (err.message,) raise
Create a Python 3 function for returning a wave. Wave_read instance from the wave module.
You are a Python code analyst, evaluating scripts for potential improvements.
def load(cls, path): """Load Waveform from file.""" assert os.path.exists(path), "No such file: %r" % path (folder, filename) = os.path.split(path) (name, extension) = os.path.splitext(filename) wave = Waveform(None) wave._path = path return wave
Write a Python 3 script for loading Waveform from file.
As a Python code translator, you convert algorithms and pseudocode into Python.
Save the waveform to file path as a WAV file.
Can you generate the documentation for the following Python 3 function def save(self, path): (folder, filename) = os.path.split(path) (name, extension) = os.path.splitext(filename) if not name: raise ValueError, "name is required" path = os.path.join(folder, name + self.ext...
As a python code expert, you are capable of creating scripts from specifications.
def sort_nicely(l): """Sort the given list in the way that humans expect.""" convert = lambda text: int(text) if text.isdigit() else text alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)] l.sort(key=alphanum_key)
How would you code a function in Python 3 to sort the given list in the way that humans expect.
As a Python code analyst, you investigate and solve complex coding mysteries
def open_channel(self): """ Open a new channel on this connection. This method is a :ref:`coroutine <coroutine>`. :return: The new :class:`Channel` object. """ if self._closing: raise ConnectionClosed("Closed by application") if self.closed.done(): ...
How would you implement a function in Python 3 that opens a new channel on this connection.
As a python code expert, you are capable of creating scripts from specifications.
def close(self): """ Close the connection by handshaking with the server. This method is a :ref:`coroutine <coroutine>`. """ if not self.is_closed(): self._closing = True # Let the ConnectionActor do the actual close operations. # It will do t...
Can you create a Python 3 function that closes the connection by handshaking with the server.
You are a Python code architect, reviewing and designing scalable and efficient code
def handle_PoisonPillFrame(self, frame): """ Is sent in case protocol lost connection to server.""" # Will be delivered after Close or CloseOK handlers. It's for channels, # so ignore it. if self.connection.closed.done(): return # If connection was not closed already ...
Write a Python 3 function that can handle a Poison Pill frame.
As a python code expert, you are capable of creating scripts from specifications.
Handle a ConnectionClose frame.
Can you generate a brief explanation for the following Python 3 code def handle_ConnectionClose(self, frame): # Notify server we are OK to close. self.sender.send_CloseOK() exc = ConnectionClosed(frame.payload.reply_text, frame.payload.reply_code) self._cl...
You are a Python code architect, reviewing and designing scalable and efficient code
Publish a message on the exchange to be asynchronously delivered to queues.
Explain what the following Python 3 code does def publish(self, message, routing_key, *, mandatory=True): self.sender.send_BasicPublish(self.name, routing_key, mandatory, message)
You are a Python code analyst, evaluating scripts for potential improvements.
def delete(self, *, if_unused=True): """ Delete the exchange. This method is a :ref:`coroutine <coroutine>`. :keyword bool if_unused: If true, the exchange will only be deleted if it has no queues bound to it. """ self.sender.send_ExchangeDelete(self.name, i...
Can you write a function in Python 3 where it deletes the exchange. This method is a :ref:`coroutine <coroutine>`. :keyword bool if_unused: If true, the exchange will only be deleted if it has no queues bound to it.
As a Python code analyst, you investigate and solve complex coding mysteries
Reject the message. :keyword bool requeue: if true, the broker will attempt to requeue the message and deliver it to an alternate consumer.
Here you have a function in Python 3, explain what it does def reject(self, *, requeue=True): self.sender.send_BasicReject(self.delivery_tag, requeue)
As a Python code translator, you convert algorithms and pseudocode into Python.
Declare an exchange on the broker.
Can you tell what is the following Python 3 function doing def declare_exchange(self, name, type, *, durable=True, auto_delete=False, passive=False, internal=False, nowait=False, arguments=None): """ Declare an :class:`Exchange` on the broker. If the exc...
You are a Python code architect, reviewing and designing scalable and efficient code
def declare_queue(self, name='', *, durable=True, exclusive=False, auto_delete=False, passive=False, nowait=False, arguments=None): """ Declare a queue on the broker. If the queue does not exist, it will be created. This method is a :ref:`coroutine <c...
Implement a function in Python 3 to declare a queue on the broker.
You are a Python code generator, capable of creating scripts from specifications.
Set the quality of service for the current locale.
Can you tell what is the following Python 3 function doing def set_qos(self, prefetch_size=0, prefetch_count=0, apply_globally=False): self.sender.send_BasicQos(prefetch_size, prefetch_count, apply_globally) yield from self.synchroniser.wait(spec.BasicQosOK) self.reader.ready()
You are a Python code architect, reviewing and designing scalable and efficient code
def close(self): """ Close the channel by handshaking with the server. This method is a :ref:`coroutine <coroutine>`. """ # If we aren't already closed ask for server to close if not self.is_closed(): self._closing = True # Let the ChannelActor do...
Create a Python 3 function to close the channel by handshaking with the server.
As a python code expert, you are capable of creating scripts from specifications.
Handle a channel close.
Given the following Python 3 function, write the documentation def handle_ChannelClose(self, frame): # By docs: # The response to receiving a Close after sending Close must be to # send Close-Ok. # # No need for additional checks self.sender.send_CloseOK() exc = ...
You are a Python code generator, capable of creating scripts from specifications.
def handle_ChannelCloseOK(self, frame): """ AMQP server closed channel as per our request """ assert self.channel._closing, "received a not expected CloseOk" # Release the `close` method's future self.synchroniser.notify(spec.ChannelCloseOK) exc = ChannelClosed() self._c...
How would you implement a function in Python 3 that handles a ChannelCloseOK frame.
You are a Python code generator, capable of creating scripts from specifications.
def bind(self, exchange, routing_key, *, arguments=None): """ Bind a queue to an exchange, with the supplied routing key. This action 'subscribes' the queue to the routing key; the precise meaning of this varies with the exchange type. This method is a :ref:`coroutine <coroutin...
Create a Python 3 function to bind a queue to an exchange with the supplied routing key.
As a Python code translator, you convert algorithms and pseudocode into Python.
Start a consumer on the queue. Messages will be delivered asynchronously to the consumer.
Explain what the following Python 3 code does def consume(self, callback, *, no_local=False, no_ack=False, exclusive=False, arguments=None): if self.deleted: raise Deleted("Queue {} was deleted".format(self.name)) self.sender.send_BasicConsume(self.name, no_local, no_ack, exclusive, argumen...
You are a Python code architect, reviewing and designing scalable and efficient code
Synchronously get a message from the queue.
Can you generate a brief explanation for the following Python 3 code def get(self, *, no_ack=False): if self.deleted: raise Deleted("Queue {} was deleted".format(self.name)) self.sender.send_BasicGet(self.name, no_ack) tag_msg = yield from self.synchroniser.wait(spec.BasicGetOK, spe...
As a Python code analyst, you investigate and solve complex coding mysteries
Purge all undelivered messages from the queue.
Can you generate the documentation for the following Python 3 function def purge(self): self.sender.send_QueuePurge(self.name) yield from self.synchroniser.wait(spec.QueuePurgeOK) self.reader.ready()
As a Python code analyst, you investigate and solve complex coding mysteries
def delete(self, *, if_unused=True, if_empty=True): """ Delete the queue. This method is a :ref:`coroutine <coroutine>`. :keyword bool if_unused: If true, the queue will only be deleted if it has no consumers. :keyword bool if_empty: If true, the queue will only be ...
Can you write a function in Python 3 where it deletes the queue. This method is a :ref:`coroutine <coroutine>`. :keyword bool if_unused: If true, the queue will only be deleted if it has no consumers. :keyword bool if_empty: If true, the queue will only be deleted if it has no unacknowledged messages.
You are a Python code generator, capable of creating scripts from specifications.
def unbind(self, arguments=None): """ Unbind the queue from the exchange. This method is a :ref:`coroutine <coroutine>`. """ if self.deleted: raise Deleted("Queue {} was already unbound from exchange {}".format(self.queue.name, self.exchange.name)) self.send...
Write a Python 3 script to unbind the queue from the exchange.
As a python code expert, you are capable of creating scripts from specifications.
Cancel the consumer and stop recieving messages.
How would you explain what the following Python 3 function does def cancel(self): self.sender.send_BasicCancel(self.tag) try: yield from self.synchroniser.wait(spec.BasicCancelOK) except AMQPError: pass else: # No need to call ready if channel closed. ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Send a hello world message and then reads it from the queue.
Can you tell what is the following Python 3 function doing def hello_world(): # connect to the RabbitMQ broker connection = yield from asynqp.connect('localhost', 5672, username='guest', password='guest') # Open a communications channel channel = yield from connection.open_channel() # Create a que...
You are a Python code generator, capable of creating scripts from specifications.
def killall(self, exc): """ Connection/Channel was closed. All subsequent and ongoing requests should raise an error """ self.connection_exc = exc # Set an exception for all others for method, futs in self._futures.items(): for fut in futs: ...
Write a Python 3 script to kill all ongoing requests and clear the internal state.
You are a Python code analyst, evaluating scripts for potential improvements.
Connect to an AMQP server.
Explain what the following Python 3 code does def connect(host='localhost', port=5672, username='guest', password='guest', virtual_host='/', on_connection_close=None, *, loop=None, sock=None, **kwargs): """ Connect to an AMQP server on the given host a...
As a python code expert, you are capable of creating scripts from specifications.
Connect to an AMQP server and open a channel on the connection.
Explain what the following Python 3 code does def connect_and_open_channel(host='localhost', port=5672, username='guest', password='guest', virtual_host='/', on_connection_close=None, *, ...
You are a Python code architect, reviewing and designing scalable and efficient code
Called by heartbeat_monitor when heartbeat_timeout expires.
Can you generate the documentation for the following Python 3 function def heartbeat_timeout(self): assert not self._closed, "Did we not stop heartbeat_monitor on close?" log.error("Heartbeat time out") poison_exc = ConnectionLostError('Heartbeat timed out') poison_frame = frames.PoisonP...
As a python code expert, you are capable of creating scripts from specifications.