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 _resize(self, shape, format=None, internalformat=None): """Internal method for resize. """
shape = self._normalize_shape(shape) # Check if not self._resizable: raise RuntimeError("Texture is not resizable") # Determine format if format is None: format = self._formats[shape[-1]] # Keep current format if channels match i...
<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_data(self, data, offset=None, copy=False): """Internal method for set_data. """
# Copy if needed, check/normalize shape data = np.array(data, copy=copy) data = self._normalize_shape(data) # Maybe resize to purge DATA commands? if offset is None: self._resize(data.shape) elif all([i == 0 for i in offset]) and data.shape ...
<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_free_region(self, width, height): """Get a free region of given size and allocate it Parameters width : int Width of region to allocate height : int Heig...
best_height = best_width = np.inf best_index = -1 for i in range(len(self._atlas_nodes)): y = self._fit(i, width, height) if y >= 0: node = self._atlas_nodes[i] if (y+height < best_height or (y+height == best_height...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _vector_or_scalar(x, type='row'): """Convert an object to either a scalar or a row or column vector."""
if isinstance(x, (list, tuple)): x = np.array(x) if isinstance(x, np.ndarray): assert x.ndim == 1 if type == 'column': x = x[:, None] return x
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _vector(x, type='row'): """Convert an object to a row or column vector."""
if isinstance(x, (list, tuple)): x = np.array(x, dtype=np.float32) elif not isinstance(x, np.ndarray): x = np.array([x], dtype=np.float32) assert x.ndim == 1 if type == 'column': x = x[:, None] return x
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def smoothstep(edge0, edge1, x): """ performs smooth Hermite interpolation between 0 and 1 when edge0 < x < edge1. """
# Scale, bias and saturate x to 0..1 range x = np.clip((x - edge0)/(edge1 - edge0), 0.0, 1.0) # Evaluate polynomial return x*x*(3 - 2*x)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _glsl_mix(controls=None): """Generate a GLSL template function from a given interpolation patterns and control points."""
assert (controls[0], controls[-1]) == (0., 1.) ncolors = len(controls) assert ncolors >= 2 if ncolors == 2: s = " return mix($color_0, $color_1, t);\n" else: s = "" for i in range(ncolors-1): if i == 0: ifs = 'if (t < %.6f)' % (controls[i+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 get_colormap(name, *args, **kwargs): """Obtain a colormap Some colormaps can have additional configuration parameters. Refer to their corresponding documenta...
if isinstance(name, BaseColormap): cmap = name else: if not isinstance(name, string_types): raise TypeError('colormap must be a Colormap or string name') if name not in _colormaps: raise KeyError('colormap name %s not found' % name) cmap = _colormaps[name...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def visual_border_width(self): """ The border width in visual coordinates """
render_to_doc = \ self.transforms.get_transform('document', 'visual') vec = render_to_doc.map([self.border_width, self.border_width, 0]) origin = render_to_doc.map([0, 0, 0]) visual_border_width = [vec[0] - origin[0], vec[1] - origin[1]] # we need to flip the y a...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self, fig): """ Run the exporter on the given figure Parmeters --------- fig : matplotlib.Figure instance The figure to export """
# Calling savefig executes the draw() command, putting elements # in the correct place. fig.savefig(io.BytesIO(), format='png', dpi=fig.dpi) if self.close_mpl: import matplotlib.pyplot as plt plt.close(fig) self.crawl_fig(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 process_transform(transform, ax=None, data=None, return_trans=False, force_trans=None): """Process the transform and convert data to figure or data coordinat...
if isinstance(transform, transforms.BlendedGenericTransform): warnings.warn("Blended transforms not yet supported. " "Zoom behavior may not work as expected.") if force_trans is not None: if data is not None: data = (transform - force_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 crawl_fig(self, fig): """Crawl the figure and process all axes"""
with self.renderer.draw_figure(fig=fig, props=utils.get_figure_properties(fig)): for ax in fig.axes: self.crawl_ax(ax)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def crawl_ax(self, ax): """Crawl the axes and process all elements within"""
with self.renderer.draw_axes(ax=ax, props=utils.get_axes_properties(ax)): for line in ax.lines: self.draw_line(ax, line) for text in ax.texts: self.draw_text(ax, text) for (text, ttp) in zip([ax.xaxis.label...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def crawl_legend(self, ax, legend): """ Recursively look through objects in legend children """
legendElements = list(utils.iter_all_children(legend._legend_box, skipContainers=True)) legendElements.append(legend.legendPatch) for child in legendElements: # force a large zorder so it appears on top child.set_zord...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def draw_line(self, ax, line, force_trans=None): """Process a matplotlib line and call renderer.draw_line"""
coordinates, data = self.process_transform(line.get_transform(), ax, line.get_xydata(), force_trans=force_trans) linestyle = utils.get_line_style(line) if linestyle['dasharray'] is 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 draw_text(self, ax, text, force_trans=None, text_type=None): """Process a matplotlib text object and call renderer.draw_text"""
content = text.get_text() if content: transform = text.get_transform() position = text.get_position() coords, position = self.process_transform(transform, ax, position, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def draw_patch(self, ax, patch, force_trans=None): """Process a matplotlib patch object and call renderer.draw_path"""
vertices, pathcodes = utils.SVG_path(patch.get_path()) transform = patch.get_transform() coordinates, vertices = self.process_transform(transform, ax, vertices, force_trans=force_trans)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def draw_collection(self, ax, collection, force_pathtrans=None, force_offsettrans=None): """Process a matplotlib collection and call renderer.draw_collection"""
(transform, transOffset, offsets, paths) = collection._prepare_points() offset_coords, offsets = self.process_transform( transOffset, ax, offsets, force_trans=force_offsettrans) path_coords = self.process_transform( transform, ax, force_trans=force_pathtrans) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def draw_image(self, ax, image): """Process a matplotlib image object and call renderer.draw_image"""
self.renderer.draw_image(imdata=utils.image_to_base64(image), extent=image.get_extent(), coordinates="data", style={"alpha": image.get_alpha(), "zorder": image.get_zorder()...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def draw_marked_line(self, data, coordinates, linestyle, markerstyle, label, mplobj=None): """Draw a line that also has markers. If this isn't reimplemented by a...
if linestyle is not None: self.draw_line(data, coordinates, linestyle, label, mplobj) if markerstyle is not None: self.draw_markers(data, coordinates, markerstyle, label, mplobj)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _iter_path_collection(paths, path_transforms, offsets, styles): """Build an iterator over the elements of the path collection"""
N = max(len(paths), len(offsets)) if not path_transforms: path_transforms = [np.eye(3)] edgecolor = styles['edgecolor'] if np.size(edgecolor) == 0: edgecolor = ['none'] facecolor = styles['facecolor'] if np.size(facecolor) == 0: face...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def draw_path(self, data, coordinates, pathcodes, style, offset=None, offset_coordinates="data", mplobj=None): """ Draw a path. In matplotlib, paths are created ...
raise NotImplementedError()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_times(cls, times, delta_t=DEFAULT_OBSERVATION_TIME): """ Create a TimeMOC from a `astropy.time.Time` Parameters times : `astropy.time.Time` astropy obse...
times_arr = np.asarray(times.jd * TimeMOC.DAY_MICRO_SEC, dtype=int) intervals_arr = np.vstack((times_arr, times_arr + 1)).T # degrade the TimeMoc to the order computer from ``delta_t`` order = TimeMOC.time_resolution_to_order(delta_t) return TimeMOC(IntervalSet(intervals_arr))....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_time_ranges(cls, min_times, max_times, delta_t=DEFAULT_OBSERVATION_TIME): """ Create a TimeMOC from a range defined by two `astropy.time.Time` Parameter...
min_times_arr = np.asarray(min_times.jd * TimeMOC.DAY_MICRO_SEC, dtype=int) max_times_arr = np.asarray(max_times.jd * TimeMOC.DAY_MICRO_SEC, dtype=int) intervals_arr = np.vstack((min_times_arr, max_times_arr + 1)).T # degrade the TimeMoc to the order computer from ``delta_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 add_neighbours(self): """ Add all the pixels at max order in the neighbourhood of the moc """
time_delta = 1 << (2*(IntervalSet.HPY_MAX_ORDER - self.max_order)) intervals_arr = self._interval_set._intervals intervals_arr[:, 0] = np.maximum(intervals_arr[:, 0] - time_delta, 0) intervals_arr[:, 1] = np.minimum(intervals_arr[:, 1] + time_delta, (1 << 58) - 1) self._interv...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_neighbours(self): """ Remove all the pixels at max order located at the bound of the moc """
time_delta = 1 << (2*(IntervalSet.HPY_MAX_ORDER - self.max_order)) intervals_arr = self._interval_set._intervals intervals_arr[:, 0] = np.minimum(intervals_arr[:, 0] + time_delta, (1 << 58) - 1) intervals_arr[:, 1] = np.maximum(intervals_arr[:, 1] - time_delta, 0) good_interva...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def intersection(self, another_moc, delta_t=DEFAULT_OBSERVATION_TIME): """ Intersection between self and moc. ``delta_t`` gives the possibility to the user to se...
order_op = TimeMOC.time_resolution_to_order(delta_t) self_degraded, moc_degraded = self._process_degradation(another_moc, order_op) return super(TimeMOC, self_degraded).intersection(moc_degraded)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def total_duration(self): """ Get the total duration covered by the temporal moc Returns ------- duration : `~astropy.time.TimeDelta` total duration of all the o...
if self._interval_set.empty(): return 0 total_time_us = 0 # The interval set is checked for consistency before looping over all the intervals for (start_time, stop_time) in self._interval_set._intervals: total_time_us = total_time_us + (stop_time - start_time) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def consistency(self): """ Get a percentage of fill between the min and max time the moc is defined. A value near 0 shows a sparse temporal moc (i.e. the moc doe...
result = self.total_duration.jd / (self.max_time - self.min_time).jd return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def min_time(self): """ Get the `~astropy.time.Time` time of the tmoc first observation Returns ------- min_time : `astropy.time.Time` time of the first observat...
min_time = Time(self._interval_set.min / TimeMOC.DAY_MICRO_SEC, format='jd', scale='tdb') return min_time
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def max_time(self): """ Get the `~astropy.time.Time` time of the tmoc last observation Returns ------- max_time : `~astropy.time.Time` time of the last observati...
max_time = Time(self._interval_set.max / TimeMOC.DAY_MICRO_SEC, format='jd', scale='tdb') return max_time
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot(self, title='TimeMoc', view=(None, None)): """ Plot the TimeMoc in a time window. This method uses interactive matplotlib. The user can move its mouse t...
from matplotlib.colors import LinearSegmentedColormap import matplotlib.pyplot as plt if self._interval_set.empty(): print('Nothing to print. This TimeMoc object is empty.') return plot_order = 15 if self.max_order > plot_order: plotted_moc ...
<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(self, client, subhooks=()): """Handle a new update. Fetches new data from the client, then compares it to the previous lookup. Returns: (bool, new_dat...
new_data = self.fetch(client) # Holds the list of updated fields. updated = {} if not subhooks: # We always want to compare to previous values. subhooks = [self.name] for subhook in subhooks: new_key = self.extract_key(new_data, subhook) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _load_char(self, char): """Build and store a glyph corresponding to an individual character Parameters char : str A single character to be represented. """
assert isinstance(char, string_types) and len(char) == 1 assert char not in self._glyphs # load new glyph data from font _load_glyph(self._font, char, self._glyphs) # put new glyph into the texture glyph = self._glyphs[char] bitmap = glyph['bitmap'] # co...
<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_font(self, face, bold=False, italic=False): """Get a font described by face and size"""
key = '%s-%s-%s' % (face, bold, italic) if key not in self._fonts: font = dict(face=face, bold=bold, italic=italic) self._fonts[key] = TextureFont(font, self._renderer) return self._fonts[key]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fft_freqs(n_fft, fs): """Return frequencies for DFT Parameters n_fft : int Number of points in the FFT. fs : float The sampling rate. """
return np.arange(0, (n_fft // 2 + 1)) / float(n_fft) * float(fs)
<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_data(self, pos=None, color=None, width=None, connect=None, arrows=None): """Set the data used for this visual Parameters pos : array color : Color, tuple...
if arrows is not None: self._arrows = arrows self._arrows_changed = True LineVisual.set_data(self, pos, color, width, connect)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def strip_html(text): """ Get rid of ugly twitter html """
def reply_to(text): replying_to = [] split_text = text.split() for index, token in enumerate(split_text): if token.startswith('@'): replying_to.append(token[1:]) else: message = split_text[index:] break rply_msg = "" if...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def post_tweet(user_id, message, additional_params={}): """ Helper function to post a tweet """
url = "https://api.twitter.com/1.1/statuses/update.json" params = { "status" : message } params.update(additional_params) r = make_twitter_request(url, user_id, params, request_type='POST') print (r.text) return "Successfully posted a tweet {}".format(message)
<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_twitter_request(url, user_id, params={}, request_type='GET'): """ Generically make a request to twitter API using a particular user's authorization """
if request_type == "GET": return requests.get(url, auth=get_twitter_auth(user_id), params=params) elif request_type == "POST": return requests.post(url, auth=get_twitter_auth(user_id), params=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 geo_search(user_id, search_location): """ Search for a location - free form """
url = "https://api.twitter.com/1.1/geo/search.json" params = {"query" : search_location } response = make_twitter_request(url, user_id, params).json() return response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_out_tweets(processed_tweets, speech_convertor=None): """ Input - list of processed 'Tweets' output - list of spoken responses """
return ["tweet number {num} by {user}. {text}.".format(num=index+1, user=user, text=text) for index, (user, text) in enumerate(processed_tweets)]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search_for_tweets_about(user_id, params): """ Search twitter API """
url = "https://api.twitter.com/1.1/search/tweets.json" response = make_twitter_request(url, user_id, params) return process_tweets(response.json()["statuses"])
<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_val(self, val): """add value in form of dict"""
if not isinstance(val, type({})): raise ValueError(type({})) self.read() self.config.update(val) self.save()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_mesh(fname): """Read mesh data from file. Parameters fname : str File name to read. Format will be inferred from the filename. Currently only '.obj' and...
# Check format fmt = op.splitext(fname)[1].lower() if fmt == '.gz': fmt = op.splitext(op.splitext(fname)[0])[1].lower() if fmt in ('.obj'): return WavefrontReader.read(fname) elif not format: raise ValueError('read_mesh needs could not determine format.') 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 write_mesh(fname, vertices, faces, normals, texcoords, name='', format='obj', overwrite=False, reshape_faces=True): """ Write mesh data to file. Parameters f...
# Check file if op.isfile(fname) and not overwrite: raise IOError('file "%s" exists, use overwrite=True' % fname) # Check format if format not in ('obj'): raise ValueError('Only "obj" format writing currently supported') WavefrontWriter.write(fname, vertices, faces, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parse_variables_from_code(self): """ Parse uniforms, attributes and varyings from the source code. """
# Get one string of code with comments removed code = '\n\n'.join(self._shaders) code = re.sub(r'(.*)(//.*)', r'\1', code, re.M) # Regexp to look for variable names var_regexp = ("\s*VARIABLE\s+" # kind of variable "((highp|mediump|lowp)\...
<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_pending_variables(self): """ Try to apply the variables that were set but not known yet. """
# Clear our list of pending variables self._pending_variables, pending = {}, self._pending_variables # Try to apply it. On failure, it will be added again for name, data in pending.items(): self[name] = 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 draw(self, mode='triangles', indices=None, check_error=True): """ Draw the attribute arrays in the specified mode. Parameters mode : str | GL_ENUM 'points', ...
# Invalidate buffer (data has already been sent) self._buffer = None # Check if mode is valid mode = check_enum(mode) if mode not in ['points', 'lines', 'line_strip', 'line_loop', 'triangles', 'triangle_strip', 'triangle_fan']: ...
<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_data(self, x=None, y=None, z=None, colors=None): """Update the data in this surface plot. Parameters x : ndarray | None 1D array of values specifying the...
if x is not None: if self._x is None or len(x) != len(self._x): self.__vertices = None self._x = x if y is not None: if self._y is None or len(y) != len(self._y): self.__vertices = None self._y = y if z is not Non...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def simplified(self): """A simplified representation of the same transformation. """
if self._simplified is None: self._simplified = SimplifiedChainTransform(self) return self._simplified
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def imap(self, coords): """Inverse map coordinates Parameters coords : array-like Coordinates to inverse map. Returns ------- coords : ndarray Coordinates. """
for tr in self.transforms: coords = tr.imap(coords) return coords
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def append(self, tr): """ Add a new transform to the end of this chain. Parameters tr : instance of Transform The transform to use. """
self.transforms.append(tr) tr.changed.connect(self._subtr_changed) self._rebuild_shaders() self.update()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepend(self, tr): """ Add a new transform to the beginning of this chain. Parameters tr : instance of Transform The transform to use. """
self.transforms.insert(0, tr) tr.changed.connect(self._subtr_changed) self._rebuild_shaders() self.update()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def source_changed(self, event): """Generate a simplified chain by joining adjacent transforms. """
# bail out early if the chain is empty transforms = self._chain.transforms[:] if len(transforms) == 0: self.transforms = [] return # If the change signal comes from a transform that already appears in # our simplified transform list, then there i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def pack_iterable(messages): '''Pack an iterable of messages in the TCP protocol format''' # [ 4-byte body size ] # [ 4-byte num messages ] # [ 4-byte message #1 size ][ N-byte binary data ] # ... (repeated <num_messages> times) return pack_string( struct.pack('>l', len(messages)) +...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def hexify(message): '''Print out printable characters, but others in hex''' import string hexified = [] for char in message: if (char in '\n\r \t') or (char not in string.printable): hexified.append('\\x%02x' % ord(char)) else: hexified.append(char) 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 clean(self): """Clean queue items from a previous session. In case a previous session crashed and there are still some running entries in the queue ('running...
for _, item in self.queue.items(): if item['status'] in ['paused', 'running', 'stopping', 'killing']: item['status'] = 'queued' item['start'] = '' item['end'] = ''
<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(self): """Remove all completed tasks from the queue."""
for key in list(self.queue.keys()): if self.queue[key]['status'] in ['done', 'failed']: del self.queue[key] self.write()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def next(self): """Get the next processable item of the queue. A processable item is supposed to have the status `queued`. Returns: None : If no key is found. In...
smallest = None for key in self.queue.keys(): if self.queue[key]['status'] == 'queued': if smallest is None or key < smallest: smallest = key return smallest
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write(self): """Write the current queue to a file. We need this to continue an earlier session."""
queue_path = os.path.join(self.config_dir, 'queue') queue_file = open(queue_path, 'wb+') try: pickle.dump(self.queue, queue_file, -1) except Exception: print('Error while writing to queue file. Wrong file permissions?') queue_file.close()
<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_new(self, command): """Add a new entry to the queue."""
self.queue[self.next_key] = command self.queue[self.next_key]['status'] = 'queued' self.queue[self.next_key]['returncode'] = '' self.queue[self.next_key]['stdout'] = '' self.queue[self.next_key]['stderr'] = '' self.queue[self.next_key]['start'] = '' self.queue[se...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove(self, key): """Remove a key from the queue, return `False` if no such key exists."""
if key in self.queue: del self.queue[key] self.write() return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def restart(self, key): """Restart a previously finished entry."""
if key in self.queue: if self.queue[key]['status'] in ['failed', 'done']: new_entry = {'command': self.queue[key]['command'], 'path': self.queue[key]['path']} self.add_new(new_entry) self.write() return Tru...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def switch(self, first, second): """Switch two entries in the queue. Return False if an entry doesn't exist."""
allowed_states = ['queued', 'stashed'] if first in self.queue and second in self.queue \ and self.queue[first]['status'] in allowed_states\ and self.queue[second]['status'] in allowed_states: tmp = self.queue[second].copy() self.queue[second] = s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def receive_data(socket): """Receive an answer from the daemon and return the response. Args: socket (socket.socket): A socket that is connected to the daemon. ...
answer = b"" while True: packet = socket.recv(4096) if not packet: break answer += packet response = pickle.loads(answer) socket.close() return response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connect_socket(root_dir): """Connect to a daemon's socket. Args: root_dir (str): The directory that used as root by the daemon. Returns: socket.socket: A so...
# Get config directory where the daemon socket is located config_dir = os.path.join(root_dir, '.config/pueue') # Create Socket and exit with 1, if socket can't be created try: client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) socket_path = os.path.join(config_dir, 'pueue.sock'...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def from_raw(conn, raw): '''Return a new response from a raw buffer''' frame_type = struct.unpack('>l', raw[0:4])[0] message = raw[4:] if frame_type == FRAME_TYPE_MESSAGE: return Message(conn, frame_type, message) elif frame_type == FRAME_TYPE_RESPONSE: re...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def pack(cls, data): '''Pack the provided data into a Response''' return struct.pack('>ll', len(data) + 4, cls.FRAME_TYPE) + 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 fin(self): '''Indicate that this message is finished processing''' self.connection.fin(self.id) self.processed = True
<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(self): '''Make sure this message gets either 'fin' or 'req'd''' try: yield self except: # Requeue the message and raise the original exception typ, value, trace = sys.exc_info() if not self.processed: try: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def find(cls, name): '''Find the exception class by name''' if not cls.mapping: # pragma: no branch for _, obj in inspect.getmembers(exceptions): if inspect.isclass(obj): if issubclass(obj, exceptions.NSQException): # pragma: no branch ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def exception(self): '''Return an instance of the corresponding exception''' code, _, message = self.data.partition(' ') return self.find(code)(message)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_gdb_version(line): r"""Parse the gdb version from the gdb header. From GNU coding standards: the version starts after the last space of the first line....
if line.startswith('~"') and line.endswith(r'\n"'): version = line[2:-3].rsplit(' ', 1) if len(version) == 2: # Strip after first non digit or '.' character. Allow for linux # Suse non conformant implementation that encloses the version in # brackets. ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def spawn_gdb(pid, address=DFLT_ADDRESS, gdb='gdb', verbose=False, ctx=None, proc_iut=None): """Spawn gdb and attach to a process."""
parent, child = socket.socketpair() proc = Popen([gdb, '--interpreter=mi', '-nx'], bufsize=0, stdin=child, stdout=child, stderr=STDOUT) child.close() connections = {} gdb = GdbSocket(ctx, address, proc, proc_iut, parent, verbose, connections) gdb.mi_com...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def attach_loop(argv): """Spawn the process, then repeatedly attach to the process."""
# Check if the pdbhandler module is built into python. p = Popen((sys.executable, '-X', 'pdbhandler', '-c', 'import pdbhandler; pdbhandler.get_handler().host'), stdout=PIPE, stderr=STDOUT) p.wait() use_xoption = True if p.returncode == 0 else False # Spawn the proce...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def skip(self): """Skip this py-pdb command to avoid attaching within the same loop."""
line = self.line self.line = '' # 'line' is the statement line of the previous py-pdb command. if line in self.lines: if not self.skipping: self.skipping = True printflush('Skipping lines', end='') printflush('.', end='') ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rotate(self, log): """Move the current log to a new file with timestamp and create a new empty log file."""
self.write(log, rotate=True) self.write({})
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write(self, log, rotate=False): """Write the output of all finished processes to a compiled log file."""
# Get path for logfile if rotate: timestamp = time.strftime('-%Y%m%d-%H%M') logPath = os.path.join(self.log_dir, 'queue{}.log'.format(timestamp)) else: logPath = os.path.join(self.log_dir, 'queue.log') # Remove existing Log if os.path.exists(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_old(self, max_log_time): """Remove all logs which are older than the specified time."""
files = glob.glob('{}/queue-*'.format(self.log_dir)) files = list(map(lambda x: os.path.basename(x), files)) for log_file in files: # Get time stamp from filename name = os.path.splitext(log_file)[0] timestamp = name.split('-', maxsplit=1)[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 wrap(function, *args, **kwargs): '''Wrap a function that returns a request with some exception handling''' try: req = function(*args, **kwargs) logger.debug('Got %s: %s', req.status_code, req.content) if req.status_code == 200: return req else: raise C...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def json_wrap(function, *args, **kwargs): '''Return the json content of a function that returns a request''' try: # Some responses have data = None, but they generally signal a # successful API call as well. response = json.loads(function(*args, **kwargs).content) if 'data' in re...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def ok_check(function, *args, **kwargs): '''Ensure that the response body is OK''' req = function(*args, **kwargs) if req.content.lower() != 'ok': raise ClientException(req.content) return req.content
<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(self, path, *args, **kwargs): '''GET the provided endpoint''' target = self._host.relative(path).utf8 if not isinstance(target, basestring): # on older versions of the `url` library, .utf8 is a method, not a property target = target() params = kwargs.get('...
<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_hash_info(fd, unit_size=None): """Get MediaFireHashInfo structure from the fd, unit_size fd -- file descriptor - expects exclusive access because of ...
logger.debug("compute_hash_info(%s, unit_size=%s)", fd, unit_size) fd.seek(0, os.SEEK_END) file_size = fd.tell() fd.seek(0, os.SEEK_SET) units = [] unit_counter = 0 file_hash = hashlib.sha256() unit_hash = hashlib.sha256() for chunk in iter(lambda: fd.read(HASH_CHUNK_SIZE_BYTES...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def upload(self, fd, name=None, folder_key=None, filedrop_key=None, path=None, action_on_duplicate=None): """Upload file, returns UploadResult object fd -- file-...
# Get file handle content length in the most reliable way fd.seek(0, os.SEEK_END) size = fd.tell() fd.seek(0, os.SEEK_SET) if size > UPLOAD_SIMPLE_LIMIT_BYTES: resumable = True else: resumable = False logger.debug("Calculating checksum"...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _poll_upload(self, upload_key, action): """Poll upload until quickkey is found upload_key -- upload_key returned by upload/* functions """
if len(upload_key) != UPLOAD_KEY_LENGTH: # not a regular 11-char-long upload key # There is no API to poll filedrop uploads return UploadResult( action=action, quickkey=None, hash_=None, filename=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 _upload_none(self, upload_info, check_result): """Dummy upload function for when we don't actually upload"""
return UploadResult( action=None, quickkey=check_result['duplicate_quickkey'], hash_=upload_info.hash_info.file, filename=upload_info.name, size=upload_info.size, created=None, revision=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 _upload_instant(self, upload_info, _=None): """Instant upload and return quickkey Can be used when the file is already stored somewhere in MediaFire upload_i...
result = self._api.upload_instant( upload_info.name, upload_info.size, upload_info.hash_info.file, path=upload_info.path, folder_key=upload_info.folder_key, filedrop_key=upload_info.filedrop_key, action_on_duplicate=upload_inf...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _upload_simple(self, upload_info, _=None): """Simple upload and return quickkey Can be used for small files smaller than UPLOAD_SIMPLE_LIMIT_BYTES upload_inf...
upload_result = self._api.upload_simple( upload_info.fd, upload_info.name, folder_key=upload_info.folder_key, filedrop_key=upload_info.filedrop_key, path=upload_info.path, file_size=upload_info.size, file_hash=upload_info.hash...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _upload_resumable_all(self, upload_info, bitmap, number_of_units, unit_size): """Prepare and upload all resumable units and return upload_key upload_info -- ...
fd = upload_info.fd upload_key = None for unit_id in range(number_of_units): upload_status = decode_resumable_upload_bitmap( bitmap, number_of_units) if upload_status[unit_id]: logger.debug("Skipping unit %d/%d - already uploaded", ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _upload_resumable(self, upload_info, check_result): """Resumable upload and return quickkey upload_info -- UploadInfo object check_result -- dict of upload/c...
resumable_upload = check_result['resumable_upload'] unit_size = int(resumable_upload['unit_size']) number_of_units = int(resumable_upload['number_of_units']) # make sure we have calculated the right thing logger.debug("number_of_units=%s (expected %s)", n...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reset(self): """Remove from sys.modules the modules imported by the debuggee."""
if not self.hooked: self.hooked = True sys.path_hooks.append(self) sys.path.insert(0, self.PATH_ENTRY) return for modname in self: if modname in sys.modules: del sys.modules[modname] submods = [] ...
<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_func_lno(self, funcname): """The first line number of the last defined 'funcname' function."""
class FuncLineno(ast.NodeVisitor): def __init__(self): self.clss = [] def generic_visit(self, node): for child in ast.iter_child_nodes(node): for item in self.visit(child): yield item def visit_Cl...
<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_actual_bp(self, lineno): """Get the actual breakpoint line number. When an exact match cannot be found in the lnotab expansion of the module code object ...
def _distance(code, module_level=False): """The shortest distance to the next valid statement.""" subcodes = dict((c.co_firstlineno, c) for c in code.co_consts if isinstance(c, types.CodeType) and not c.co_name.startsw...
<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_breakpoints(self, lineno): """Return the list of breakpoints set at lineno."""
try: firstlineno, actual_lno = self.bdb_module.get_actual_bp(lineno) except BdbSourceError: return [] if firstlineno not in self: return [] code_bps = self[firstlineno] if actual_lno not in code_bps: return [] return [bp 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 settrace(self, do_set): """Set or remove the trace function."""
if do_set: sys.settrace(self.trace_dispatch) else: sys.settrace(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 restart(self): """Restart the debugger after source code changes."""
_module_finder.reset() linecache.checkcache() for module_bpts in self.breakpoints.values(): module_bpts.reset()
<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_until(self, frame, lineno=None): """Stop when the current line number in frame is greater than lineno or when returning from frame."""
if lineno is None: lineno = frame.f_lineno + 1 self._set_stopinfo(frame, lineno)
<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_trace(self, frame=None): """Start debugging from `frame`. If frame is not specified, debugging starts from caller's frame. """
# First disable tracing temporarily as set_trace() may be called while # tracing is in use. For example when called from a signal handler and # within a debugging session started with runcall(). self.settrace(False) if not frame: frame = sys._getframe().f_back ...