code
stringlengths
1
18.2k
return TimeMOC(IntervalSet(intervals_arr)).degrade_to_order(order)
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(interv...
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] =...
def _process_degradation(self, another_moc, order_op): """ Degrade (down-sampling) self and ``another_moc`` to ``order_op`` order Parameters ---------- another_moc : `~mocpy.tmoc.TimeMoc` order_op : int the order in which self and ``another_moc`` will be down-sampled to. Returns ------- result : (`~mocpy.tmoc.TimeMoc`,...
'The TimeMoc object resulting from the operation is of time resolution {0} sec.'.format( TimeMOC.order_to_time_resolution(max_order).sec) warnings.warn(message, UserWarning) self_degradation = self.degrade_to_order(order_op) another_moc_degradation = another_moc.degrade_to_order(order_op) result = self_degradation, ano...
def intersection(self, another_moc, delta_t=DEFAULT_OBSERVATION_TIME): """ Intersection between self and moc. ``delta_t`` gives the possibility to the user to set a time resolution for performing the tmoc intersection Parameters ---------- another_moc : `~mocpy.abstract_moc.AbstractMOC` the MOC/TimeMOC used for perform...
the more efficient TimeMoc order to represent the observations. (Best order = the less precise order which is able to discriminate two observations separated by ``delta_t``) Returns ------- result : `~mocpy.moc.MOC` or `~mocpy.tmoc.TimeMOC` MOC object whose interval set corresponds to : self & ``moc`` """ order_op = Ti...
def total_duration(self): """ Get the total duration covered by the temporal moc Returns ------- duration : `~astropy.time.TimeDelta` total duration of all the observation times of the tmoc total duration of all the observation times of the tmoc """ if self._interval_set.empty(): return 0 total_time_us = 0 # The interv...
total_time_us = total_time_us + (stop_time - start_time) duration = TimeDelta(total_time_us / 1e6, format='sec', scale='tdb') return duration
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 does not cover a lot of time and covers very distant times. A value near 1 means that the moc covers a lot of time without big pauses. Returns ------- result : fl...
percentage (between 0 and 1.) """ result = self.total_duration.jd / (self.max_time - self.min_time).jd return result
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 observation """ min_time = Time(self._interval_set.min / TimeMOC.DAY_MICRO_SEC, format='jd', scale='tdb') return min_time
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 observation """ max_time = Time(self._interval_set.max / TimeMOC.DAY_MICRO_SEC, format='jd', scale='tdb') return max_time
def contains(self, times, keep_inside=True, delta_t=DEFAULT_OBSERVATION_TIME): """ Get a mask array (e.g. a numpy boolean array) of times being inside (or outside) the TMOC instance. Parameters ---------- times : `astropy.time.Time` astropy times to check whether they are contained in the TMOC or not. keep_inside : boo...
is False, the filtered table contains all observations lying outside the MOC. delta_t : `astropy.time.TimeDelta`, optional the duration of one observation. It is set to 30 min by default. This data is used to compute the more efficient TimeMOC order to represent the observations (Best order = the less precise order whi...
: `~numpy.darray` A mask boolean array """ # the requested order for filtering the astropy observations table is more precise than the order # of the TimeMoc object current_max_order = self.max_order new_max_order = TimeMOC.time_resolution_to_order(delta_t) if new_max_order > current_max_order: message = 'Requested tim...
pix_arr = (times.jd * TimeMOC.DAY_MICRO_SEC) pix_arr = pix_arr.astype(int) intervals_arr = rough_tmoc._interval_set._intervals inf_arr = np.vstack([pix_arr[i] >= intervals_arr[:, 0] for i in range(pix_arr.shape[0])]) sup_arr = np.vstack([pix_arr[i] <= intervals_arr[:, 1] for i in range(pix_arr.shape[0])]) if keep_insid...
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 through the plot to see the time (at the mouse position). Parameters ---------- title : str, optional The title of the plot. Set to 'TimeMoc' by default. view :...
are plotted. Set to (None, None) by default (i.e. all the observation time window is rendered). """ 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 > plo...
else view[1].jd if max_jd < min_jd: raise ValueError("Invalid selection: max_jd = {0} must be > to min_jd = {1}".format(max_jd, min_jd)) fig1 = plt.figure(figsize=(9.5, 5)) ax = fig1.add_subplot(111) ax.set_xlabel('iso') ax.get_yaxis().set_visible(False) size = 2000 delta = (max_jd - min_jd) / size min_jd_time = min_jd...
/ delta) e_index = int((e_time_us / TimeMOC.DAY_MICRO_SEC - min_jd_time) / delta) y[s_index:(e_index+1)] = 1.0 # hack in case of full time mocs. if np.all(y): y[0] = 0 z = np.tile(y, (int(size//10), 1)) plt.title(title) color_map = LinearSegmentedColormap.from_list('w2r', ['#fffff0', '#aa0000']) color_map.set_under('w'...
format='jd', scale='tdb') tx = '{0}'.format(time.iso) text.set_position((event.xdata - 50, 700)) text.set_rotation(70) text.set_text(tx) cid = fig1.canvas.mpl_connect('motion_notify_event', on_mouse_motion) plt.show()
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_data): whether changes occurred, and the new value. """ new_data = self.fetch(client) # Holds the list of updated fields. updated = {} if not subhooks: # We alway...
new_key = self.extract_key(new_data, subhook) if new_key != self.previous_keys.get(subhook): updated[subhook] = new_key if updated: logger.debug("Hook %s: data changed from %r to %r", self.name, self.previous_keys, updated) self.previous_keys.update(updated) return (True, new_data) return (False, None)
def _text_to_vbo(text, font, anchor_x, anchor_y, lowres_size): """Convert text characters to VBO""" # Necessary to flush commands before requesting current viewport because # There may be a set_viewport command waiting in the queue. # TODO: would be nicer if each canvas just remembers and manages its own # viewport, ra...
2), ('a_texcoord', np.float32, 2)]) vertices = np.zeros(len(text) * 4, dtype=text_vtype) prev = None width = height = ascender = descender = 0 ratio, slop = 1. / font.ratio, font.slop x_off = -slop # Need to make sure we have a unicode string here (Py2.7 mis-interprets # characters like "•" otherwise) if sys.version[0]...
the original viewport, because the font[char] will # trigger SDF rendering, which changes our viewport # todo: get rid of call to glGetParameter! orig_viewport = canvas.context.get_viewport() for ii, char in enumerate(text): glyph = font[char] kerning = glyph['kerning'].get(prev, 0.) * ratio x0 = x_off + glyph['offset'...
- glyph['size'][1] u0, v0, u1, v1 = glyph['texcoords'] position = [[x0, y0], [x0, y1], [x1, y1], [x1, y0]] texcoords = [[u0, v0], [u0, v1], [u1, v1], [u1, v0]] vi = ii * 4 vertices['a_position'][vi:vi+4] = position vertices['a_texcoord'][vi:vi+4] = texcoords x_move = glyph['advance'] * ratio + kerning x_off += x_move a...
height = max(height, glyph['size'][1] - 2*slop) prev = char # Also analyse chars with large ascender and descender, otherwise the # vertical alignment can be very inconsistent for char in 'hy': glyph = font[char] y0 = glyph['offset'][1] * ratio + slop y1 = y0 - glyph['size'][1] ascender = max(ascender, y0 - slop) desce...
if orig_viewport is not None: canvas.context.set_viewport(*orig_viewport) # Tight bounding box (loose would be width, font.height /.asc / .desc) width -= glyph['advance'] * ratio - (glyph['size'][0] - 2*slop) dx = dy = 0 if anchor_y == 'top': dy = -ascender elif anchor_y in ('center', 'middle'): dy = -(height / 2 + des...
elif anchor_y == 'baseline': # dy = -descender if anchor_x == 'right': dx = -width elif anchor_x == 'center': dx = -width / 2. vertices['a_position'] += (dx, dy) vertices['a_position'] /= lowres_size return vertices
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...
array data = np.zeros((bitmap.shape[0] + 2*self._spread, bitmap.shape[1] + 2*self._spread), np.uint8) data[self._spread:-self._spread, self._spread:-self._spread] = bitmap # Store, while scaling down to proper size height = data.shape[0] // self.ratio width = data.shape[1] // self.ratio region = self._atlas.get_free_re...
1, w - 2, h - 2 self._renderer.render_to_texture(data, self._atlas, (x, y), (w, h)) u0 = x / float(self._atlas.shape[1]) v0 = y / float(self._atlas.shape[0]) u1 = (x+w) / float(self._atlas.shape[1]) v1 = (y+h) / float(self._atlas.shape[0]) texcoords = (u0, v0, u1, v1) glyph.update(dict(size=(w, h), texcoords=texcoords)...
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]
def stft(x, n_fft=1024, step=512, fs=2*np.pi, window='hann'): """Compute the STFT Parameters ---------- x : array-like 1D signal to operate on. ``If len(x) < n_fft``, x will be zero-padded to length ``n_fft``. n_fft : int Number of FFT points. Much faster for powers of two. step : int | None Step size between calculati...
sample rate of the data. window : str | None Window function to use. Can be ``'hann'`` for Hann window, or None for no windowing. Returns ------- stft : ndarray Spectrogram of the data, shape (n_freqs, n_steps). See also -------- fft_freqs """ x = np.asarray(x, float) if x.ndim != 1: raise ValueError('x must be 1D') if...
('hann',): raise ValueError('window must be "hann" or None') w = np.hanning(n_fft) else: w = np.ones(n_fft) n_fft = int(n_fft) step = max(n_fft // 2, 1) if step is None else int(step) fs = float(fs) zero_pad = n_fft - len(x) if zero_pad > 0: x = np.concatenate((x, np.zeros(zero_pad, float))) n_freqs = n_fft // 2 + 1 n_...
= np.empty((n_freqs, n_estimates), np.complex128) for ii in range(n_estimates): result[:, ii] = np.fft.rfft(w * x[ii * step:ii * step + n_fft]) / n_fft return result
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)
def set_data(self, pos=None, color=None, width=None, connect=None, arrows=None): """Set the data used for this visual Parameters ---------- pos : array Array of shape (..., 2) or (..., 3) specifying vertex coordinates. color : Color, tuple, or array The color to use when drawing the line. If an array is given, it must ...
also be a colormap name, or appropriate `Function`. width: The width of the line in px. Line widths > 1px are only guaranteed to work when using 'agg' method. connect : str or array Determines which vertices are connected by lines. * "strip" causes the line to be drawn with each vertex connected to the next. * "segment...
draw an independent line segment * numpy arrays specify the exact set of segment pairs to connect. arrows : array A Nx4 matrix where each row contains the x and y coordinate of the first and second vertex of the arrow body. Remember that the second vertex is used as center point for the arrow head, and the first vertex...
determining the arrow head orientation. """ if arrows is not None: self._arrows = arrows self._arrows_changed = True LineVisual.set_data(self, pos, color, width, connect)
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 len(replying_to) > 0: rply_msg = "Replyin...
".join(message) text = reply_to(text) text = text.replace('@', ' ') return " ".join([token for token in text.split() if ('http:' not in token) and ('https:' not in token)])
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 "Successfull...
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=g...
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
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)]
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"])
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()
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 '.obj.gz' are supported. Returns ------- vertices : array Vertices. faces : array | None Triangle face definitions. normals : array Normals for the...
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: raise ValueError('read_mesh does not understand format %s.' % fmt)
def write_mesh(fname, vertices, faces, normals, texcoords, name='', format='obj', overwrite=False, reshape_faces=True): """ Write mesh data to file. Parameters ---------- fname : str Filename to write. Must end with ".obj" or ".gz". vertices : array Vertices. faces : array | None Triangle face definitions. normals : ar...
: str Currently only "obj" is supported. overwrite : bool If the file exists, overwrite it. reshape_faces : bool Reshape the `faces` array to (Nf, 3). Set to `False` if you need to write a mesh with non triangular faces. """ # Check file if op.isfile(fname) and not overwrite: raise IOError('file "%s" exists, use overwr...
('obj'): raise ValueError('Only "obj" format writing currently supported') WavefrontWriter.write(fname, vertices, faces, normals, texcoords, name, reshape_faces)
def _set_config(config): """Set gl configuration""" pyglet_config = pyglet.gl.Config() pyglet_config.red_size = config['red_size'] pyglet_config.green_size = config['green_size'] pyglet_config.blue_size = config['blue_size'] pyglet_config.alpha_size = config['alpha_size'] pyglet_config.accum_red_size = 0 pyglet_config....
def set_shaders(self, vert, frag): """ Set the vertex and fragment shaders. Parameters ---------- vert : str Source code for vertex shader. frag : str Source code for fragment shaders. """ if not vert or not frag: raise ValueError('Vertex and fragment code must both be non-empty') # pre-process shader code for #include...
glir, parse the code for variables self._shaders = vert, frag self._glir.command('SHADERS', self._id, vert, frag) # All current variables become pending variables again for key, val in self._user_variables.items(): self._pending_variables[key] = val self._user_variables = {} # Parse code (and process pending variables)...
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 variab...
"\s*;" # end ) # Parse uniforms, attributes and varyings self._code_variables = {} for kind in ('uniform', 'attribute', 'varying', 'const'): regex = re.compile(var_regexp.replace('VARIABLE', kind), flags=re.MULTILINE) for m in re.finditer(regex, code): gtype = m.group('type') size = int(m.group('size')) if m.group('siz...
% (m.group('name'), i) self._code_variables[name] = kind, gtype, name, -1 this_kind = 'uniform_array' name = m.group('name') self._code_variables[name] = this_kind, gtype, name, size # Now that our code variables are up-to date, we can process # the variables that were set but yet unknown. self._process_pending_variabl...
def bind(self, data): """ Bind a VertexBuffer that has structured data Parameters ---------- data : VertexBuffer The vertex buffer to bind. The field names of the array are mapped to attribute names in GLSL. """ # Check if not isinstance(data, VertexBuffer): raise ValueError('Program.bind() requires a VertexBuffer.') #...
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
def draw(self, mode='triangles', indices=None, check_error=True): """ Draw the attribute arrays in the specified mode. Parameters ---------- mode : str | GL_ENUM 'points', 'lines', 'line_strip', 'line_loop', 'triangles', 'triangle_strip', or 'triangle_fan'. indices : array Array of indices to draw. check_error: Check e...
mode not in ['points', 'lines', 'line_strip', 'line_loop', 'triangles', 'triangle_strip', 'triangle_fan']: raise ValueError('Invalid draw mode: %r' % mode) # Check leftover variables, warn, discard them # In GLIR we check whether all attributes are indeed set for name in self._pending_variables: logger.warn('Variable %...
DataBuffer)] sizes = [a.size for a in attributes] if len(attributes) < 1: raise RuntimeError('Must have at least one attribute') if not all(s == sizes[0] for s in sizes[1:]): msg = '\n'.join(['%s: %s' % (str(a), a.size) for a in attributes]) raise RuntimeError('All attributes must have the same size, got:\n' '%s' % msg...
canvas is not None # Associate canvas canvas.context.glir.associate(self.glir) # Indexbuffer if isinstance(indices, IndexBuffer): canvas.context.glir.associate(indices.glir) logger.debug("Program drawing %r with index buffer" % mode) gltypes = {np.dtype(np.uint8): 'UNSIGNED_BYTE', np.dtype(np.uint16): 'UNSIGNED_SHORT',...
(must be IndexBuffer)" % indices) # Process GLIR commands canvas.context.flush_commands()
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 x positions of vertices in the grid. If None, values will be assumed to be integers. y : ndarray | None 1D array of values specifying the x positio...
be assumed to be integers. z : ndarray 2D array of height values for each grid vertex. colors : ndarray (width, height, 4) array of vertex colors. """ 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._...
= y if z is not None: if self._x is not None and z.shape[0] != len(self._x): raise TypeError('Z values must have shape (len(x), len(y))') if self._y is not None and z.shape[1] != len(self._y): raise TypeError('Z values must have shape (len(x), len(y))') self._z = z if (self.__vertices is not None and self._z.shape != s...
new_vertices = False # Generate vertex and face array if self.__vertices is None: new_vertices = True self.__vertices = np.empty((self._z.shape[0], self._z.shape[1], 3), dtype=np.float32) self.generate_faces() self.__meshdata.set_faces(self.__faces) update_mesh = True # Copy x, y, z data into vertex array if new_vertic...
update_mesh = True if new_vertices or y is not None: if y is None: if self._y is None: y = np.arange(self._z.shape[1]) else: y = self._y self.__vertices[:, :, 1] = y.reshape(1, len(y)) update_mesh = True if new_vertices or z is not None: self.__vertices[..., 2] = self._z update_mesh = True if colors is not None: self._...
* self.__vertices.shape[1], 3)) MeshVisual.set_data(self, meshdata=self.__meshdata)
def simplified(self): """A simplified representation of the same transformation. """ if self._simplified is None: self._simplified = SimplifiedChainTransform(self) return self._simplified
def map(self, coords): """Map coordinates Parameters ---------- coords : array-like Coordinates to map. Returns ------- coords : ndarray Coordinates. """ for tr in reversed(self.transforms): coords = tr.map(coords) return coords
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
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()
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()
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 tr...
in event.sources[::-1]: if source in self.transforms: self.update(event) return # First flatten the chain by expanding all nested chains new_chain = [] while len(transforms) > 0: tr = transforms.pop(0) if isinstance(tr, ChainTransform) and not tr.dynamic: transforms = tr.transforms[:] + transforms else: new_chain.appen...
t2 in tr[1:]: t1 = new_tr[-1] pr = t1 * t2 if (not t1.dynamic and not t2.dynamic and not isinstance(pr, ChainTransform)): cont = True new_tr.pop() new_tr.append(pr) else: new_tr.append(t2) tr = new_tr self.transforms = tr
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)) + ''.join(map(pack_string, messages)))
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 ''.join(hexified)
def distribute(total, objects): '''Generator for (count, object) tuples that distributes count evenly among the provided objects''' for index, obj in enumerate(objects): start = (index * total) / len(objects) stop = ((index + 1) * total) / len(objects) yield (stop - start, obj)
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', 'stopping', 'killing'), we clean those and enqueue them again. """ for _, item in self.queue.items(): if item['status'] in ['paused', 'running', 'stopping',...
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()
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. Int: If a valid entry is found. """ smallest = None for key in self.queue.keys(): if self.queue[key]['status'] == 'queued': if smallest is None or key < smallest...
def read(self): """Read the queue of the last pueue session or set `self.queue = {}`.""" queue_path = os.path.join(self.config_dir, 'queue') if os.path.exists(queue_path): queue_file = open(queue_path, 'rb') try: self.queue = pickle.load(queue_file) except Exception: print('Queue file corrupted, deleting old queue') os...
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?...
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.q...
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
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 True return False
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...
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. Returns: dir or string: The unpickled answer. """ answer = b"" while True: packet = socket.recv(4096) if not packet: break answer += packet response = pickle.lo...
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 socket that is connected to the daemon. """ # Get config directory where the daemon socket is located config_dir = os.path.join(root_dir, '.config/pueue') # Creat...
'pueue.sock') if os.path.exists(socket_path): client.connect(socket_path) else: print("Socket doesn't exist") raise Exception except: print("Error connecting to socket. Make sure the daemon is running") sys.exit(1) return client
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: return Response(conn, frame_type, message) elif frame_type == FRAM...