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 update(self, sequence): """ Update the set with the given iterable sequence, then return the index of the last element inserted. Example: 4 OrderedSet([1, 2,...
item_index = None try: for item in sequence: item_index = self.add(item) except TypeError: raise ValueError( "Argument needs to be an iterable, got %s" % type(sequence) ) return item_index
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pop(self): """ Remove and return the last element from the set. Raises KeyError if the set is empty. Example: 3 """
if not self.items: raise KeyError("Set is empty") elem = self.items[-1] del self.items[-1] del self.map[elem] return elem
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def union(self, *sets): """ Combines all unique items. Each items order is defined by its first appearance. Example: OrderedSet([3, 1, 4, 5, 2, 0]) OrderedSet([3...
cls = self.__class__ if isinstance(self, OrderedSet) else OrderedSet containers = map(list, it.chain([self], sets)) items = it.chain.from_iterable(containers) return cls(items)
<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, *sets): """ Returns elements in common between all sets. Order is defined only by the first set. Example: OrderedSet([1, 2, 3]) OrderedSet...
cls = self.__class__ if isinstance(self, OrderedSet) else OrderedSet if sets: common = set.intersection(*map(set, sets)) items = (item for item in self if item in common) else: items = self return cls(items)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def difference(self, *sets): """ Returns all elements that are in this set but not the others. Example: OrderedSet([1, 3]) OrderedSet([1]) OrderedSet([1, 3]) Ord...
cls = self.__class__ if sets: other = set.union(*map(set, sets)) items = (item for item in self if item not in other) else: items = self return cls(items)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def issubset(self, other): """ Report whether another set contains this set. Example: False True False """
if len(self) > len(other): # Fast check for obvious cases return False return all(item in other for item in 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 issuperset(self, other): """ Report whether this set contains another set. Example: False True False """
if len(self) < len(other): # Fast check for obvious cases return False return all(item in self for item in other)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def symmetric_difference(self, other): """ Return the symmetric difference of two OrderedSets as a new set. That is, the new set will contain all elements that a...
cls = self.__class__ if isinstance(self, OrderedSet) else OrderedSet diff1 = cls(self).difference(other) diff2 = cls(other).difference(self) return diff1.union(diff2)
<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_items(self, items): """ Replace the 'items' list of this OrderedSet with a new one, updating self.map accordingly. """
self.items = items self.map = {item: idx for (idx, item) in enumerate(items)}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def difference_update(self, *sets): """ Update this OrderedSet to remove items from one or more other sets. Example: OrderedSet([1, 3]) OrderedSet([3, 5]) """
items_to_remove = set() for other in sets: items_to_remove |= set(other) self._update_items([item for item in self.items if item not in items_to_remove])
<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_update(self, other): """ Update this OrderedSet to keep only items in another set, preserving their order in this set. Example: OrderedSet([1, 3...
other = set(other) self._update_items([item for item in self.items if item in other])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def symmetric_difference_update(self, other): """ Update this OrderedSet to remove items from another set, then add items from the other set that were not presen...
items_to_add = [item for item in other if item not in self] items_to_remove = set(other) self._update_items( [item for item in self.items if item not in items_to_remove] + items_to_add )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_response(self): """Raises an exception if there was an error. Otherwise, do nothing. Clients should handle these errors, since these require custom ...
if self.is_success(): return # Handle the error if we have any information if self.details: error = self.details.get('error', None) if error == PushResponse.ERROR_DEVICE_NOT_REGISTERED: raise DeviceNotRegisteredError(self) elif e...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_exponent_push_token(cls, token): """Returns `True` if the token is an Exponent push token"""
import six return ( isinstance(token, six.string_types) and token.startswith('ExponentPushToken'))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _publish_internal(self, push_messages): """Send push notifications The server will validate any type of syntax errors and the client will raise the proper ex...
# Delayed import because this file is immediately read on install, and # the requests library may not be installed yet. import requests response = requests.post( self.host + self.api_url + '/push/send', data=json.dumps([pm.get_payload() for pm in push_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 get_dict_from_buffer(buf, keys=['DISTNAME', 'MAJOR', 'MINOR', 'PATCHLEVEL', 'PYTHON', 'MIN_PYTHON_MAJOR', 'MIN_PYTHON_MINOR', 'MIN_NUMPY_MAJOR', 'MIN_NUMPY_MI...
pairs = dict() if keys is None: keys = "\S+" regex = re.compile(r''' \n # all key-value pairs are on separate lines \s* # there might be some leading spaces ( # start group to return (?:{0}\s*) # placeholder for tags to detec...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def replace_first_key_in_makefile(buf, key, replacement, outfile=None): ''' Replaces first line in 'buf' matching 'key' with 'replacement'. Optionally, writes out this new buffer into 'outfile'. Returns: Buffer after replacement has been done ''' regexp = re.compile(r''' \n\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 settings_to_cmd_args(settings_dict): """ Copied from django 1.8 MySQL backend DatabaseClient - where the runshell commandline creation has been extracted and...
args = ['mysql'] db = settings_dict['OPTIONS'].get('db', settings_dict['NAME']) user = settings_dict['OPTIONS'].get('user', settings_dict['USER']) passwd = settings_dict['OPTIONS'].get('passwd', settings_dict['PASSWORD']) host = settings_dict['OPTIONS'].get('host', settings_dict['HOST']) port =...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def modify_sql(sql, add_comments, add_hints, add_index_hints): """ Parse the start of the SQL, injecting each string in add_comments in individual SQL comments a...
match = query_start_re.match(sql) if not match: # We don't understand what kind of query this is, don't rewrite it return sql tokens = [match.group('keyword')] comments = match.group('comments').strip() if comments: tokens.append(comments) # Inject comments after all e...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_key(self, key): """ Django normally warns about maximum key length, but we error on it. """
if len(key) > 250: raise ValueError( "Cache key is longer than the maxmimum 250 characters: {}" .format(key), ) return super(MySQLCache, self).validate_key(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 decode(self, value, value_type): """ Take a value blob and its value_type one-char code and convert it back to a python object """
if value_type == 'i': return int(value) if value_type == 'z': value = zlib.decompress(value) value_type = 'p' if value_type == 'p': return pickle.loads(force_bytes(value)) raise ValueError( "Unknown value_type '{}' read from...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _is_simple_query(cls, query): """ Inspect the internals of the Query and say if we think its WHERE clause can be used in a HANDLER statement """
return ( not query.low_mark and not query.high_mark and not query.select and not query.group_by and not query.distinct and not query.order_by and len(query.alias_map) <= 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 animate(self, seq_name): """ Returns a generator which "executes" an animation sequence for the given ``seq_name``, inasmuch as the next frame for the given ...
while True: index = 0 anim = getattr(self.animations, seq_name) speed = anim.speed if hasattr(anim, "speed") else 1 num_frames = len(anim.frames) while index < num_frames: frame = anim.frames[int(index)] index += speed ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def effective_FPS(self): """ Calculates the effective frames-per-second - this should largely correlate to the desired FPS supplied in the constructor, but no gu...
if self.start_time is None: self.start_time = 0 elapsed = monotonic() - self.start_time return self.called / elapsed
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _crop_box(self, size): """ Helper that calculates the crop box for the offset within the image. :param size: The width and height of the image composition. :...
(left, top) = self.offset right = left + min(size[0], self.width) bottom = top + min(size[1], self.height) return (left, top, right, bottom)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def refresh(self): """ Clears the composition and renders all the images taking into account their position and offset. """
self._clear() for img in self.composed_images: self._background_image.paste(img.image(self._device.size), img.position) self._background_image.crop(box=self._device.bounding_box)
<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): """ Helper that clears the composition. """
draw = ImageDraw.Draw(self._background_image) draw.rectangle(self._device.bounding_box, fill="black") del draw
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def inflate_bbox(self): """ Realign the left and right edges of the bounding box such that they are inflated to align modulo 4. This method is optional, and used...
left, top, right, bottom = self.bounding_box self.bounding_box = ( left & 0xFFFC, top, right if right % 4 == 0 else (right & 0xFFFC) + 0x04, bottom) return self.bounding_box
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def println(self, text=""): """ Prints the supplied text to the device, scrolling where necessary. The text is always followed by a newline. :param text: The tex...
if self.word_wrap: # find directives in complete text directives = ansi_color.find_directives(text, self) # strip ansi from text clean_text = ansi_color.strip_ansi_codes(text) # wrap clean text clean_lines = self.tw.wrap(clean_text) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def newline(self): """ Advances the cursor position ot the left hand side, and to the next line. If the cursor is on the lowest line, the displayed contents are ...
self.carriage_return() if self._cy + (2 * self._ch) >= self._device.height: # Simulate a vertical scroll copy = self._backing_image.crop((0, self._ch, self._device.width, self._device.height)) self._backing_image.paste(copy, (0, 0)) 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 backspace(self): """ Moves the cursor one place to the left, erasing the character at the current position. Cannot move beyond column zero, nor onto the prev...
if self._cx + self._cw >= 0: self.erase() self._cx -= self._cw self.flush()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def erase(self): """ Erase the contents of the cursor's current position without moving the cursor's position. """
bounds = (self._cx, self._cy, self._cx + self._cw, self._cy + self._ch) self._canvas.rectangle(bounds, fill=self._bgcolor)
<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): """ Resets the foreground and background color value back to the original when initialised. """
self._fgcolor = self.default_fgcolor self._bgcolor = self.default_bgcolor
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reverse_colors(self): """ Flips the foreground and background colors. """
self._bgcolor, self._fgcolor = self._fgcolor, self._bgcolor
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def savepoint(self): """ Copies the last displayed image. """
if self._last_image: self._savepoints.append(self._last_image) self._last_image = 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 restore(self, drop=0): """ Restores the last savepoint. If ``drop`` is supplied and greater than zero, then that many savepoints are dropped, and the next sa...
assert(drop >= 0) while drop > 0: self._savepoints.pop() drop -= 1 img = self._savepoints.pop() self.display(img)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def text(self, value): """ Updates the seven-segment display with the given value. If there is not enough space to show the full text, an ``OverflowException`` i...
self._text_buffer = observable(mutable_string(value), observer=self._flush)
<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_task(self, func, *args, **kargs): """ Add a task to the queue. """
self.tasks.put((func, args, kargs))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def capabilities(self, width, height, rotate, mode="1"): """ Assigns attributes such as ``width``, ``height``, ``size`` and ``bounding_box`` correctly oriented f...
assert mode in ("1", "RGB", "RGBA") assert rotate in (0, 1, 2, 3) self._w = width self._h = height self.width = width if rotate % 2 == 0 else height self.height = height if rotate % 2 == 0 else width self.size = (self.width, self.height) self.bounding_box...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def show_message(device, msg, y_offset=0, fill=None, font=None, scroll_delay=0.03): """ Scrolls a message right-to-left across the devices display. :param device...
fps = 0 if scroll_delay == 0 else 1.0 / scroll_delay regulator = framerate_regulator(fps) font = font or DEFAULT_FONT with canvas(device) as draw: w, h = textsize(msg, font) x = device.width virtual = viewport(device, width=w + x + x, height=device.height) with canvas(virtual) as ...
<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_str(text): """ Given a string of characters, for each normal ASCII character, yields a directive consisting of a 'putch' instruction followed by the ch...
prog = re.compile(r'^\033\[(\d+(;\d+)*)m', re.UNICODE) while text != "": result = prog.match(text) if result: for code in result.group(1).split(";"): directive = valid_attributes.get(int(code), None) if directive: yield directive ...
<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_directives(text, klass): """ Find directives on class ``klass`` in string ``text``. Returns list of ``(method, args)`` tuples. .. versionadded:: 0.9.0 :...
directives = [] for directive in parse_str(text): method = klass.__getattribute__(directive[0]) args = directive[1:] directives.append((method, args)) return directives
<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_display_types(): """ Get ordered dict containing available display types from available luma sub-projects. :rtype: collections.OrderedDict """
display_types = OrderedDict() for namespace in get_supported_libraries(): display_types[namespace] = get_choices('luma.{0}.device'.format( namespace)) return display_types
<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_config(path): """ Load device configuration from file path and return list with parsed lines. :param path: Location of configuration file. :type path: s...
args = [] with open(path, 'r') as fp: for line in fp.readlines(): if line.strip() and not line.startswith("#"): args.append(line.replace("\n", "")) return args
<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_device(args, display_types=None): """ Create and return device. :type args: object :type display_types: dict """
device = None if display_types is None: display_types = get_display_types() if args.display in display_types.get('oled'): import luma.oled.device Device = getattr(luma.oled.device, args.display) Serial = getattr(make_serial(args), args.interface) device = Device(Ser...
<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_output(*popenargs, **kwargs): r"""Run command with arguments and return its output as a byte string. If the exit code was non-zero it raises a CalledPr...
if 'stdout' in kwargs: raise ValueError('stdout argument not allowed, it will be overridden.') process = Popen(stdout=PIPE, *popenargs, **kwargs) output, unused_err = process.communicate() retcode = process.poll() if retcode: cmd = kwargs.get("args") if cmd 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 simulate(self): """ Runs the particle simulation. Simulates one time step, dt, of the particle motion. Calculates the force between each pair of particles an...
# Main simulation loop for i in range(self.iterations): for a in self.particles: if a.fixed: continue ftot = vector(0, 0, 0) # total force acting on particle a for b in self.particles: if a.negligible 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 addCutterTool(actor): """Create handles to cut away parts of a mesh. .. hint:: |cutter| |cutter.py|_ """
if isinstance(actor, vtk.vtkVolume): return _addVolumeCutterTool(actor) elif isinstance(actor, vtk.vtkImageData): from vtkplotter import Volume return _addVolumeCutterTool(Volume(actor)) vp = settings.plotter_instance if not vp.renderer: save_int = vp.interactive ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def isSequence(arg): """Check if input is iterable."""
if hasattr(arg, "strip"): return False if hasattr(arg, "__getslice__"): return True if hasattr(arg, "__iter__"): 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 flatten(list_to_flatten): """Flatten out a list."""
def genflatten(lst): for elem in lst: if isinstance(elem, (list, tuple)): for x in flatten(elem): yield x else: yield elem return list(genflatten(list_to_flatten))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def humansort(l): """Sort in place a given list the way humans expect. E.g. ['file11', 'file1'] -> ['file1', 'file11'] """
import re def alphanum_key(s): # Turn a string into a list of string and number chunks. # e.g. "z23a" -> ["z", 23, "a"] def tryint(s): if s.isdigit(): return int(s) return s return [tryint(c) for c in re.split("([0-9]+)", s)] l.sort...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lin_interp(x, rangeX, rangeY): """ Interpolate linearly variable x in rangeX onto rangeY. """
s = (x - rangeX[0]) / mag(rangeX[1] - rangeX[0]) y = rangeY[0] * (1 - s) + rangeY[1] * s return y
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def versor(v): """Return the unit vector. Input can be a list of vectors."""
if isinstance(v[0], np.ndarray): return np.divide(v, mag(v)[:, None]) else: return v / mag(v)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mag(z): """Get the magnitude of a vector."""
if isinstance(z[0], np.ndarray): return np.array(list(map(np.linalg.norm, z))) else: return np.linalg.norm(z)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def precision(x, p): """ Returns a string representation of `x` formatted with precision `p`. Based on the webkit javascript implementation taken `from here <htt...
import math x = float(x) if x == 0.0: return "0." + "0" * (p - 1) out = [] if x < 0: out.append("-") x = -x e = int(math.log10(x)) tens = math.pow(10, e - p + 1) n = math.floor(x / tens) if n < math.pow(10, p - 1): e = e - 1 tens = math.p...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def spher2cart(rho, theta, phi): """Spherical to Cartesian coordinate conversion."""
st = np.sin(theta) sp = np.sin(phi) ct = np.cos(theta) cp = np.cos(phi) rhost = rho * st x = rhost * cp y = rhost * sp z = rho * ct return np.array([x, y, z])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cart2spher(x, y, z): """Cartesian to Spherical coordinate conversion."""
hxy = np.hypot(x, y) r = np.hypot(hxy, z) theta = np.arctan2(z, hxy) phi = np.arctan2(y, x) return r, theta, phi
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cart2pol(x, y): """Cartesian to Polar coordinates conversion."""
theta = np.arctan2(y, x) rho = np.hypot(x, y) return theta, rho
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pol2cart(theta, rho): """Polar to Cartesian coordinates conversion."""
x = rho * np.cos(theta) y = rho * np.sin(theta) return x, y
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def isIdentity(M, tol=1e-06): """Check if vtkMatrix4x4 is Identity."""
for i in [0, 1, 2, 3]: for j in [0, 1, 2, 3]: e = M.GetElement(i, j) if i == j: if np.abs(e - 1) > tol: return False elif np.abs(e) > tol: return False return 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 grep(filename, tag, firstOccurrence=False): """Greps the line that starts with a specific `tag` string from inside a file."""
import re try: afile = open(filename, "r") except: print("Error in utils.grep(): cannot open file", filename) exit() content = None for line in afile: if re.search(tag, line): content = line.split() if firstOccurrence: break ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def makeBands(inputlist, numberOfBands): """ Group values of a list into bands of equal value. :param int numberOfBands: number of bands, a positive integer > 2....
if numberOfBands < 2: return inputlist vmin = np.min(inputlist) vmax = np.max(inputlist) bb = np.linspace(vmin, vmax, numberOfBands, endpoint=0) dr = bb[1] - bb[0] bb += dr / 2 tol = dr / 2 * 1.001 newlist = [] for s in inputlist: for b in bb: if abs(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 clear(actor=()): """ Clear specific actor or list of actors from the current rendering window. """
if not settings.plotter_instance: return settings.plotter_instance.clear(actor) return settings.plotter_instance
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getVolumes(self, obj=None, renderer=None): """ Return the list of the rendered Volumes. """
if renderer is None: renderer = self.renderer elif isinstance(renderer, int): renderer = self.renderers.index(renderer) else: return [] if obj is None or isinstance(obj, int): if obj is None: acs = renderer.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 getActors(self, obj=None, renderer=None): """ Return an actors list. If ``obj`` is: ``None``, return actors of current renderer ``int``, return actors in giv...
if renderer is None: renderer = self.renderer elif isinstance(renderer, int): renderer = self.renderers.index(renderer) else: return [] if obj is None or isinstance(obj, int): if obj is None: acs = renderer.GetActors()...
<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(self, actors): """Append input object to the internal list of actors to be shown. :return: returns input actor for possible concatenation. """
if utils.isSequence(actors): for a in actors: if a not in self.actors: self.actors.append(a) return None else: self.actors.append(actors) return actors
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def light( self, pos=(1, 1, 1), fp=(0, 0, 0), deg=25, diffuse="y", ambient="r", specular="b", showsource=False, ): """ Generate a source of light placed at pos, ...
if isinstance(fp, vtk.vtkActor): fp = fp.GetPosition() light = vtk.vtkLight() light.SetLightTypeToSceneLight() light.SetPosition(pos) light.SetPositional(1) light.SetConeAngle(deg) light.SetFocalPoint(fp) light.SetDiffuseColor(colors.getColor(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def removeActor(self, a): """Remove ``vtkActor`` or actor index from current renderer."""
if not self.initializedPlotter: save_int = self.interactive self.show(interactive=0) self.interactive = save_int return if self.renderer: self.renderer.RemoveActor(a) if hasattr(a, 'renderedAt'): ir = self.renderers...
<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, actors=()): """Delete specified list of actors, by default delete all."""
if not utils.isSequence(actors): actors = [actors] if len(actors): for a in actors: self.removeActor(a) else: for a in settings.collectable_actors: self.removeActor(a) settings.collectable_actors = [] 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 morph(clm1, clm2, t, lmax): """Interpolate linearly the two sets of sph harm. coeeficients."""
clm = (1 - t) * clm1 + t * clm2 grid_reco = clm.expand(lmax=lmax) # cut "high frequency" components agrid_reco = grid_reco.to_array() pts = [] for i, longs in enumerate(agrid_reco): ilat = grid_reco.lats()[i] for j, value in enumerate(longs): ilong = grid_reco.lons()[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 mergeActors(actors, tol=0): """ Build a new actor formed by the fusion of the polydatas of input objects. Similar to Assembly, but in this case the input obj...
polylns = vtk.vtkAppendPolyData() for a in actors: polylns.AddInputData(a.polydata()) polylns.Update() pd = polylns.GetOutput() return Actor(pd)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def isosurface(image, smoothing=0, threshold=None, connectivity=False): """Return a ``vtkActor`` isosurface extracted from a ``vtkImageData`` object. :param floa...
if smoothing: smImg = vtk.vtkImageGaussianSmooth() smImg.SetDimensionality(3) smImg.SetInputData(image) smImg.SetStandardDeviations(smoothing, smoothing, smoothing) smImg.Update() image = smImg.GetOutput() scrange = image.GetScalarRange() if scrange[1] > 1e1...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def show( self, at=None, shape=(1, 1), N=None, pos=(0, 0), size="auto", screensize="auto", title="", bg="blackboard", bg2=None, axes=4, infinity=False, verbose=Tr...
from vtkplotter.plotter import show return show( self, at=at, shape=shape, N=N, pos=pos, size=size, screensize=screensize, title=title, bg=bg, bg2=bg2, axes=axes, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addPos(self, dp_x=None, dy=None, dz=None): """Add vector to current actor position."""
p = np.array(self.GetPosition()) if dz is None: # assume dp_x is of the form (x,y,z) self.SetPosition(p + dp_x) else: self.SetPosition(p + [dp_x, dy, dz]) if self.trail: self.updateTrail() return 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 rotate(self, angle, axis=(1, 0, 0), axis_point=(0, 0, 0), rad=False): """Rotate ``Actor`` around an arbitrary `axis` passing through `axis_point`."""
if rad: anglerad = angle else: anglerad = angle / 57.29578 axis = utils.versor(axis) a = np.cos(anglerad / 2) b, c, d = -axis * np.sin(anglerad / 2) aa, bb, cc, dd = a * a, b * b, c * c, d * d bc, ad, ac, ab, bd, cd = b * c, a * d, a * 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 rotateX(self, angle, axis_point=(0, 0, 0), rad=False): """Rotate around x-axis. If angle is in radians set ``rad=True``."""
if rad: angle *= 57.29578 self.RotateX(angle) if self.trail: self.updateTrail() return 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 rotateY(self, angle, axis_point=(0, 0, 0), rad=False): """Rotate around y-axis. If angle is in radians set ``rad=True``."""
if rad: angle *= 57.29578 self.RotateY(angle) if self.trail: self.updateTrail() return 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 rotateZ(self, angle, axis_point=(0, 0, 0), rad=False): """Rotate around z-axis. If angle is in radians set ``rad=True``."""
if rad: angle *= 57.29578 self.RotateZ(angle) if self.trail: self.updateTrail() return 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 addTrail(self, offset=None, maxlength=None, n=25, c=None, alpha=None, lw=1): """Add a trailing line to actor. :param offset: set an offset vector from the ob...
if maxlength is None: maxlength = self.diagonalSize() * 20 if maxlength == 0: maxlength = 1 if self.trail is None: pos = self.GetPosition() self.trailPoints = [None] * n self.trailSegmentSize = maxlength / n self.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 updateMesh(self, polydata): """ Overwrite the polygonal mesh of the actor with a new one. """
self.poly = polydata self.mapper.SetInputData(polydata) self.mapper.Modified() return 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 addScalarBar(self, c=None, title="", horizontal=False, vmin=None, vmax=None): """ Add a 2D scalar bar to actor. .. hint:: |mesh_bands| |mesh_bands.py|_ """
# book it, it will be created by Plotter.show() later self.scalarbar = [c, title, horizontal, vmin, vmax] return 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 addScalarBar3D( self, pos=(0, 0, 0), normal=(0, 0, 1), sx=0.1, sy=2, nlabels=9, ncols=256, cmap=None, c="k", alpha=1, ): """ Draw a 3D scalar bar to actor. ....
# book it, it will be created by Plotter.show() later self.scalarbar = [pos, normal, sx, sy, nlabels, ncols, cmap, c, alpha] return 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 texture(self, name, scale=1, falsecolors=False, mapTo=1): """Assign a texture to actor from image file or predefined texture name."""
import os if mapTo == 1: tmapper = vtk.vtkTextureMapToCylinder() elif mapTo == 2: tmapper = vtk.vtkTextureMapToSphere() elif mapTo == 3: tmapper = vtk.vtkTextureMapToPlane() tmapper.SetInputData(self.polydata(False)) if mapTo == 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 computeNormals(self): """Compute cell and vertex normals for the actor's mesh. .. warning:: Mesh gets modified, can have a different nr. of vertices. """
poly = self.polydata(False) pnormals = poly.GetPointData().GetNormals() cnormals = poly.GetCellData().GetNormals() if pnormals and cnormals: return self pdnorm = vtk.vtkPolyDataNormals() pdnorm.SetInputData(poly) pdnorm.ComputePointNormalsOn() ...
<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, tol=None): """ Clean actor's polydata. Can also be used to decimate a mesh if ``tol`` is large. If ``tol=None`` only removes coincident points. :...
poly = self.polydata(False) cleanPolyData = vtk.vtkCleanPolyData() cleanPolyData.PointMergingOn() cleanPolyData.ConvertLinesToPointsOn() cleanPolyData.ConvertPolysToLinesOn() cleanPolyData.SetInputData(poly) if tol: cleanPolyData.SetTolerance(tol) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def averageSize(self): """Calculate the average size of a mesh. This is the mean of the vertex distances from the center of mass."""
cm = self.centerOfMass() coords = self.coordinates(copy=False) if not len(coords): return 0 s, c = 0.0, 0.0 n = len(coords) step = int(n / 10000.0) + 1 for i in np.arange(0, n, step): s += utils.mag(coords[i] - cm) c += 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 diagonalSize(self): """Get the length of the diagonal of actor bounding box."""
b = self.polydata().GetBounds() return np.sqrt((b[1] - b[0]) ** 2 + (b[3] - b[2]) ** 2 + (b[5] - b[4]) ** 2)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def maxBoundSize(self): """Get the maximum dimension in x, y or z of the actor bounding box."""
b = self.polydata(True).GetBounds() return max(abs(b[1] - b[0]), abs(b[3] - b[2]), abs(b[5] - b[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 centerOfMass(self): """Get the center of mass of actor. .. hint:: |fatlimb| |fatlimb.py|_ """
cmf = vtk.vtkCenterOfMass() cmf.SetInputData(self.polydata(True)) cmf.Update() c = cmf.GetCenter() return np.array(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 closestPoint(self, pt, N=1, radius=None, returnIds=False): """ Find the closest point on a mesh given from the input point `pt`. :param int N: if greater tha...
poly = self.polydata(True) if N > 1 or radius: plocexists = self.point_locator if not plocexists or (plocexists and self.point_locator is None): point_locator = vtk.vtkPointLocator() point_locator.SetDataSet(poly) point_locator.Bu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def transformMesh(self, transformation): """ Apply this transformation to the polygonal `mesh`, not to the actor's transformation, which is reset. :param transfo...
if isinstance(transformation, vtk.vtkMatrix4x4): tr = vtk.vtkTransform() tr.SetMatrix(transformation) transformation = tr tf = vtk.vtkTransformPolyDataFilter() tf.SetTransform(transformation) tf.SetInputData(self.polydata()) tf.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 normalize(self): """ Shift actor's center of mass at origin and scale its average size to unit. """
cm = self.centerOfMass() coords = self.coordinates() if not len(coords): return pts = coords - cm xyz2 = np.sum(pts * pts, axis=0) scale = 1 / np.sqrt(np.sum(xyz2) / len(pts)) t = vtk.vtkTransform() t.Scale(scale, scale, scale) t.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 mirror(self, axis="x"): """ Mirror the actor polydata along one of the cartesian axes. .. note:: ``axis='n'``, will flip only mesh normals. .. hint:: |mirror...
poly = self.polydata(transformed=True) polyCopy = vtk.vtkPolyData() polyCopy.DeepCopy(poly) sx, sy, sz = 1, 1, 1 dx, dy, dz = self.GetPosition() if axis.lower() == "x": sx = -1 elif axis.lower() == "y": sy = -1 elif axis.lower() =...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shrink(self, fraction=0.85): """Shrink the triangle polydata in the representation of the input mesh. Example: .. code-block:: python from vtkplotter import ...
poly = self.polydata(True) shrink = vtk.vtkShrinkPolyData() shrink.SetInputData(poly) shrink.SetShrinkFactor(fraction) shrink.Update() return self.updateMesh(shrink.GetOutput())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stretch(self, q1, q2): """Stretch actor between points `q1` and `q2`. Mesh is not affected. .. hint:: |aspring| |aspring.py|_ .. note:: for ``Actors`` like h...
if self.base is None: colors.printc('~times Error in stretch(): Please define vectors \ actor.base and actor.top at creation. Exit.', c='r') exit(0) p1, p2 = self.base, self.top q1, q2, z = np.array(q1), np.array(q2), np.array([0, 0, 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 cutWithPlane(self, origin=(0, 0, 0), normal=(1, 0, 0), showcut=False): """ Takes a ``vtkActor`` and cuts it with the plane defined by a point and a normal. :...
if normal is "x": normal = (1,0,0) elif normal is "y": normal = (0,1,0) elif normal is "z": normal = (0,0,1) plane = vtk.vtkPlane() plane.SetOrigin(origin) plane.SetNormal(normal) self.computeNormals() poly = self.poly...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cutWithMesh(self, mesh, invert=False): """ Cut an ``Actor`` mesh with another ``vtkPolyData`` or ``Actor``. :param bool invert: if True return cut off part o...
if isinstance(mesh, vtk.vtkPolyData): polymesh = mesh if isinstance(mesh, Actor): polymesh = mesh.polydata() else: polymesh = mesh.GetMapper().GetInput() poly = self.polydata() # Create an array to hold distance information signedDist...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cap(self, returnCap=False): """ Generate a "cap" on a clipped actor, or caps sharp edges. .. hint:: |cutAndCap| |cutAndCap.py|_ """
poly = self.polydata(True) fe = vtk.vtkFeatureEdges() fe.SetInputData(poly) fe.BoundaryEdgesOn() fe.FeatureEdgesOff() fe.NonManifoldEdgesOff() fe.ManifoldEdgesOff() fe.Update() stripper = vtk.vtkStripper() stripper.SetInputData(fe.GetOut...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def threshold(self, scalars, vmin=None, vmax=None, useCells=False): """ Extracts cells where scalar value satisfies threshold criterion. :param scalars: name of ...
if utils.isSequence(scalars): self.addPointScalars(scalars, "threshold") scalars = "threshold" elif self.scalars(scalars) is None: colors.printc("~times No scalars found with name", scalars, c=1) exit() thres = vtk.vtkThreshold() thres.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 triangle(self, verts=True, lines=True): """ Converts actor polygons and strips to triangles. """
tf = vtk.vtkTriangleFilter() tf.SetPassLines(lines) tf.SetPassVerts(verts) tf.SetInputData(self.poly) tf.Update() return self.updateMesh(tf.GetOutput())