text
stringlengths
81
112k
Respond to the client by serving a file, either directly or as an attachment. :param str file_path: The path to the file to serve, this does not need to be in the web root. :param bool attachment: Whether to serve the file as a download by setting the Content-Disposition header. def respond_file(self, file_path...
Respond to the client with an HTML page listing the contents of the specified directory. :param str dir_path: The path of the directory to list the contents of. def respond_list_directory(self, dir_path, query=None): """ Respond to the client with an HTML page listing the contents of the specified directory...
Respond to the client with a 301 message and redirect them with a Location header. :param str location: The new location to redirect the client to. def respond_redirect(self, location='/'): """ Respond to the client with a 301 message and redirect them with a Location header. :param str location: The new...
Handle an internal server error, logging a traceback if executed within an exception handler. :param int status: The status code to respond to the client with. :param str status_line: The status message to respond to the client with. :param str message: The body of the response that is sent to the client. def...
Respond to the client that the request is unauthorized. :param bool request_authentication: Whether to request basic authentication information by sending a WWW-Authenticate header. def respond_unauthorized(self, request_authentication=False): """ Respond to the client that the request is unauthorized. :para...
Dispatch functions based on the established handler_map. It is generally not necessary to override this function and doing so will prevent any handlers from being executed. This function is executed automatically when requests of either GET, HEAD, or POST are received. :param dict query: Parsed query paramet...
Guess an appropriate MIME type based on the extension of the provided path. :param str path: The of the file to analyze. :return: The guessed MIME type of the default if non are found. :rtype: str def guess_mime_type(self, path): """ Guess an appropriate MIME type based on the extension of the provided ...
Check for the presence of a basic auth Authorization header and if the credentials contained within in are valid. :return: Whether or not the credentials are valid. :rtype: bool def check_authorization(self): """ Check for the presence of a basic auth Authorization header and if the credentials contained ...
Check for a cookie value by name. :param str name: Name of the cookie value to retreive. :return: Returns the cookie value if it's set or None if it's not found. def cookie_get(self, name): """ Check for a cookie value by name. :param str name: Name of the cookie value to retreive. :return: Returns the c...
Set the value of a client cookie. This can only be called while headers can be sent. :param str name: The name of the cookie value to set. :param str value: The value of the cookie to set. def cookie_set(self, name, value): """ Set the value of a client cookie. This can only be called while headers can be...
Inspect the Content-Type header to retrieve the charset that the client has specified. :param str default: The default charset to return if none exists. :return: The charset of the request. :rtype: str def get_content_type_charset(self, default='UTF-8'): """ Inspect the Content-Type header to retrieve the...
Close the web socket connection and stop processing results. If the connection is still open, a WebSocket close message will be sent to the peer. def close(self): """ Close the web socket connection and stop processing results. If the connection is still open, a WebSocket close message will be sent to the ...
Send a message to the peer over the socket. :param int opcode: The opcode for the message to send. :param bytes message: The message data to send. def send_message(self, opcode, message): """ Send a message to the peer over the socket. :param int opcode: The opcode for the message to send. :param bytes m...
The primary dispatch function to handle incoming WebSocket messages. :param int opcode: The opcode of the message that was received. :param bytes message: The data contained within the message. def on_message(self, opcode, message): """ The primary dispatch function to handle incoming WebSocket messages. :...
Build a serializer object from a MIME Content-Type string. :param str content_type: The Content-Type string to parse. :return: A new serializer instance. :rtype: :py:class:`.Serializer` def from_content_type(cls, content_type): """ Build a serializer object from a MIME Content-Type string. :param str con...
Serialize a python data type for transmission or storage. :param data: The python object to serialize. :return: The serialized representation of the object. :rtype: bytes def dumps(self, data): """ Serialize a python data type for transmission or storage. :param data: The python object to serialize. :r...
Deserialize the data into it's original python object. :param bytes data: The serialized object to load. :return: The original python object. def loads(self, data): """ Deserialize the data into it's original python object. :param bytes data: The serialized object to load. :return: The original python ob...
Add an SSL certificate for a specific hostname as supported by SSL's Server Name Indicator (SNI) extension. See :rfc:`3546` for more details on SSL extensions. In order to use this method, the server instance must have been initialized with at least one address configured for SSL. .. warning:: This method ...
Remove the SSL Server Name Indicator (SNI) certificate configuration for the specified *hostname*. .. warning:: This method will raise a :py:exc:`RuntimeError` if either the SNI extension is not available in the :py:mod:`ssl` module or if SSL was not enabled at initialization time through the use of argu...
.. versionadded:: 2.2.0 :return: Return a tuple of :py:class:`~.SSLSNICertificate` instances for each of the certificates that are configured. :rtype: tuple def sni_certs(self): """ .. versionadded:: 2.2.0 :return: Return a tuple of :py:class:`~.SSLSNICertificate` instances for each of the certificates tha...
Start handling requests. This method must be called and does not return unless the :py:meth:`.shutdown` method is called from another thread. :param bool fork: Whether to fork or not before serving content. :return: The child processes PID if *fork* is set to True. :rtype: int def serve_forever(self, fork=F...
Shutdown the server and stop responding to requests. def shutdown(self): """Shutdown the server and stop responding to requests.""" self.__should_stop.set() if self.__server_thread == threading.current_thread(): self.__is_shutdown.set() self.__is_running.clear() else: if self.__wakeup_fd is not None: ...
Enable or disable requiring authentication on all incoming requests. :param bool status: Whether to enable or disable requiring authentication. def auth_set(self, status): """ Enable or disable requiring authentication on all incoming requests. :param bool status: Whether to enable or disable requiring authe...
Delete the credentials for a specific username if specified or all stored credentials. :param str username: The username of the credentials to delete. def auth_delete_creds(self, username=None): """ Delete the credentials for a specific username if specified or all stored credentials. :param str username...
Add a valid set of credentials to be accepted for authentication. Calling this function will automatically enable requiring authentication. Passwords can be provided in either plaintext or as a hash by specifying the hash type in the *pwtype* argument. :param str username: The username of the credentials to be...
Context manager to temporarily change the values of object attributes while executing a function. Example ------- >>> class Foo: pass >>> f = Foo(); f.attr = 'hello' >>> with setattr_context(f, attr='goodbye'): ... print(f.attr) goodbye >>> print(f.attr) hello def setattr_c...
Validate input arrays This checks that - Arrays are mutually broadcastable - Broadcasted arrays are one-dimensional Optionally, arrays are sorted according to the ``sort_by`` argument. Parameters ---------- *args : ndarrays All non-keyword arguments are arrays which will be valida...
Private function to prepare & check variables for smooth utilities def _prep_smooth(t, y, dy, span, t_out, span_out, period): """Private function to prepare & check variables for smooth utilities""" # If period is provided, sort by phases. Otherwise sort by t if period: t = t % period if t...
Perform a moving-average smooth of the data Parameters ---------- t, y, dy : array_like time, value, and error in value of the input data span : array_like the integer spans of the data cv : boolean (default=True) if True, treat the problem as a cross-validation, i.e. don't ...
Perform a linear smooth of the data Parameters ---------- t, y, dy : array_like time, value, and error in value of the input data span : array_like the integer spans of the data cv : boolean (default=True) if True, treat the problem as a cross-validation, i.e. don't use ...
Multiple linear interpolations Parameters ---------- x : array_like, shape=(N,) sorted array of x values y : array_like, shape=(N, M) array of y values corresponding to each x value xquery : array_like, shape=(M,) array of query values slow : boolean, default=False ...
Create a consulate.session object, and query for its leader to ensure that the connection is made. :param test_connection: call .leader() to ensure that the connection is valid :type test_connection: bool :return consulate.Session instance def _create_session(self, test_con...
Applies all config values defined in consul's kv store to self.app. There is no guarantee that these values will not be overwritten later elsewhere. :param namespace: kv namespace/directory. Defaults to DEFAULT_KV_NAMESPACE :return: None def apply_remote_config(self, n...
register this service with consul kwargs passed to Consul.agent.service.register def register_service(self, **kwargs): """ register this service with consul kwargs passed to Consul.agent.service.register """ kwargs.setdefault('name', self.app.name) self.session.a...
Query the consul DNS server for the service IP and port def _resolve(self): """ Query the consul DNS server for the service IP and port """ endpoints = {} r = self.resolver.query(self.service, 'SRV') for rec in r.response.additional: name = rec.name.to_text()...
Proxy to requests.request :param method: str formatted http method :param endpoint: service endpoint :param kwargs: kwargs passed directly to requests.request :return: def request(self, method, endpoint, **kwargs): """ Proxy to requests.request :param method: str...
Decorator that wraps an entire function in a try/except clause. On requests.exceptions.ConnectionError, will re-run the function code until success or max_tries is reached. :param max_tries: maximum number of attempts before giving up :param sleep: time to sleep between tries, or None def with_retry_c...
Crop the generator to a finite number of frames Return a generator which outputs the provided generator limited to enough samples to produce seconds seconds of audio (default 5s) at the provided frame rate. def crop(gens, seconds=5, cropper=None): ''' Crop the generator to a finite number of frames Return a ge...
Crop the generator, ending at a zero-crossing Crop the generator to produce approximately seconds seconds (default 5s) of audio at the provided FRAME_RATE, attempting to end the clip at a zero crossing point to avoid clicking. def crop_at_zero_crossing(gen, seconds=5, error=0.1): ''' Crop the generator, ending...
Change the volume of gen by dB decibles def volume(gen, dB=0): '''Change the volume of gen by dB decibles''' if not hasattr(dB, 'next'): # not a generator scale = 10 ** (dB / 20.) else: def scale_gen(): while True: yield 10 ** (next(dB) / 20.) scale = scale_gen() return envelope(gen, scale)
Mix `inputs` together based on `mix` tuple `inputs` should be a tuple of *n* generators. `mix` should be a tuple of *m* tuples, one per desired output channel. Each of the *m* tuples should contain *n* generators, corresponding to the time-sequence of the desired mix levels for each of the *n* input channels. ...
Break multi-channel generator into one sub-generator per channel Takes a generator producing n-tuples of samples and returns n generators, each producing samples for a single channel. Since multi-channel generators are the only reasonable way to synchronize samples across channels, and the sampler functions only ...
Returns True if file `f` is seekable, and False if not Useful to determine, for example, if `f` is STDOUT to a pipe. def file_is_seekable(f): ''' Returns True if file `f` is seekable, and False if not Useful to determine, for example, if `f` is STDOUT to a pipe. ''' try: f.tell() logger.info("File is...
Convert audio waveform generator into packed sample generator. def sample(generator, min=-1, max=1, width=SAMPLE_WIDTH): '''Convert audio waveform generator into packed sample generator.''' # select signed char, short, or in based on sample width fmt = { 1: '<B', 2: '<h', 4: '<i' }[width] return (struct.pack(fmt, ...
Convert list of audio waveform generators into list of packed sample generators. def sample_all(generators, *args, **kwargs): '''Convert list of audio waveform generators into list of packed sample generators.''' return [sample(gen, *args, **kwargs) for gen in generators]
Buffer the generator into byte strings of buffer_size samples Return a generator that outputs reasonably sized byte strings containing buffer_size samples from the generator stream. This allows us to outputing big chunks of the audio stream to disk at once for faster writes. def buffer(stream, buffer_size=BUFF...
True if wave module can write data size of 0xFFFFFFFF, False otherwise. def wave_module_patched(): '''True if wave module can write data size of 0xFFFFFFFF, False otherwise.''' f = StringIO() w = wave.open(f, "wb") w.setparams((1, 2, 44100, 0, "NONE", "no compression")) patched = True try: w.setnframes((0xFFFF...
Decorator to cache audio samples produced by the wrapped generator. def cache_finite_samples(f): '''Decorator to cache audio samples produced by the wrapped generator.''' cache = {} def wrap(*args): key = FRAME_RATE, args if key not in cache: cache[key] = [sample for sample in f(*args)] return (sample for ...
Play the contents of the generator using PyAudio Play to the system soundcard using PyAudio. PyAudio, an otherwise optional depenency, must be installed for this feature to work. def play(channels, blocking=True, raw_samples=False): ''' Play the contents of the generator using PyAudio Play to the system soundca...
Compute the windowed sum of the given arrays. This is a slow function, used primarily for testing and validation of the faster version of ``windowed_sum()`` Parameters ---------- arrays : tuple of arrays arrays to window span : int or array of ints The span to use for the sum a...
Compute the windowed sum of the given arrays. Parameters ---------- arrays : tuple of arrays arrays to window span : int or array of ints The span to use for the sum at each point. If array is provided, it must be broadcastable with ``indices`` indices : array the in...
Internal routine to pad arrays for periodic models. def _pad_arrays(t, arrays, indices, span, period): """Internal routine to pad arrays for periodic models.""" N = len(t) if indices is None: indices = np.arange(N) pad_left = max(0, 0 - np.min(indices - span // 2)) pad_right = max(0, np.ma...
Search all the available I2C devices in the system def get_i2c_bus_numbers(glober = glob.glob): """Search all the available I2C devices in the system""" res = [] for device in glober("/dev/i2c-*"): r = re.match("/dev/i2c-([\d]){1,2}", device) res.append(int(r.group(1))) ...
Parse the name for led number :param name: attribute name, like: led_1 def get_led_register_from_name(self, name): """Parse the name for led number :param name: attribute name, like: led_1 """ res = re.match('^led_([0-9]{1,2})$', name) if res is None: raise...
Set PWM value for the specified LED :param led_num: LED number (0-15) :param value: the 12 bit value (0-4095) def set_pwm(self, led_num, value): """Set PWM value for the specified LED :param led_num: LED number (0-15) :param value: the 12 bit value (0-4095) """ ...
Generic getter for all LED PWM value def get_pwm(self, led_num): """Generic getter for all LED PWM value""" self.__check_range('led_number', led_num) register_low = self.calc_led_register(led_num) return self.__get_led_value(register_low)
Send the controller to sleep def sleep(self): """Send the controller to sleep""" logger.debug("Sleep the controller") self.write(Registers.MODE_1, self.mode_1 | (1 << Mode1.SLEEP))
Write raw byte value to the specified register :param reg: the register number (0-69, 250-255) :param value: byte value def write(self, reg, value): """Write raw byte value to the specified register :param reg: the register number (0-69, 250-255) :param value: byte value ...
Set the frequency for all PWM output :param value: the frequency in Hz def set_pwm_frequency(self, value): """Set the frequency for all PWM output :param value: the frequency in Hz """ self.__check_range('pwm_frequency', value) reg_val = self.calc_pre_scale(value) ...
Calculates the normalized Levenshtein distance between two string arguments. The result will be a float in the range [0.0, 1.0], with 1.0 signifying the biggest possible distance between strings with these lengths def levenshtein_norm(source, target): """Calculates the normalized Levenshtein distance betwe...
Check if the color provided by the user is valid. If color is invalid the default is returned. def check_valid_color(color): """Check if the color provided by the user is valid. If color is invalid the default is returned. """ if color in list(mcolors.CSS4_COLORS.keys()) + ["#4CB391"]: lo...
Check if the specified figure format is valid. If format is invalid the default is returned. Probably installation-dependent def check_valid_format(figformat): """Check if the specified figure format is valid. If format is invalid the default is returned. Probably installation-dependent """ ...
Create bivariate plots. Create four types of bivariate plots of x vs y, containing marginal summaries -A scatter plot with histograms on axes -A hexagonal binned plot with histograms on axes -A kernel density plot with density curves on axes -A pauvre-style plot using code from https://github.com/c...
Make sure both arrays for bivariate ("scatter") plot have a stddev > 0 def contains_variance(arrays, names): """ Make sure both arrays for bivariate ("scatter") plot have a stddev > 0 """ for ar, name in zip(arrays, names): if np.std(ar) == 0: sys.stderr.write( "No v...
Create histogram of normal and log transformed read lengths. def length_plots(array, name, path, title=None, n50=None, color="#4CB391", figformat="png"): """Create histogram of normal and log transformed read lengths.""" logging.info("Nanoplotter: Creating length plots for {}.".format(name)) maxvalx = np.a...
Make the physical layout of the MinION flowcell. based on https://bioinformatics.stackexchange.com/a/749/681 returned as a numpy array def make_layout(maxval): """Make the physical layout of the MinION flowcell. based on https://bioinformatics.stackexchange.com/a/749/681 returned as a numpy array ...
Taking channel information and creating post run channel activity plots. def spatial_heatmap(array, path, title=None, color="Greens", figformat="png"): """Taking channel information and creating post run channel activity plots.""" logging.info("Nanoplotter: Creating heatmap of reads per channel using {} reads....
Generate CSV files from a CronosPro/CronosPlus database. def main(database_dir, target_dir): """Generate CSV files from a CronosPro/CronosPlus database.""" if not os.path.isdir(database_dir): raise click.ClickException("Database directory does not exist!") try: os.makedirs(target_dir) e...
Check if the data contains reads created within the same `days` timeframe. if not, print warning and only return part of the data which is within `days` days Resetting the index twice to get also an "index" column for plotting the cum_yield_reads plot def check_valid_time_and_sort(df, timescol, days=5, warnin...
Making plots of time vs read length, time vs quality and cumulative yield. def time_plots(df, path, title=None, color="#4CB391", figformat="png", log_length=False, plot_settings=None): """Making plots of time vs read length, time vs quality and cumulative yield.""" dfs = check_valid_time_and_sor...
Create a violin or boxplot from the received DataFrame. The x-axis should be divided based on the 'dataset' column, the y-axis is specified in the arguments def violin_or_box_plot(df, y, figformat, path, y_name, title=None, plot="violin", log=False, palette=None): """Create a violin...
Create barplots based on number of reads and total sum of nucleotides sequenced. def output_barplot(df, figformat, path, title=None, palette=None): """Create barplots based on number of reads and total sum of nucleotides sequenced.""" logging.info("Nanoplotter: Creating barplots for number of reads and total t...
Use plotly to create an overlay of length histograms Return html code, but also save as png Only has 10 colors, which get recycled up to 5 times. def overlay_histogram(df, path, palette=None): """ Use plotly to create an overlay of length histograms Return html code, but also save as png Only...
Plot overlaying histograms with log transformation of length Return both html and fig for png def plot_log_histogram(df, palette, title, histnorm=""): """ Plot overlaying histograms with log transformation of length Return both html and fig for png """ data = [go.Histogram(x=np.log10(df.loc[df[...
Glob for the poor. def get_file(db_folder, file_name): """Glob for the poor.""" if not os.path.isdir(db_folder): return file_name = file_name.lower().strip() for cand_name in os.listdir(db_folder): if cand_name.lower().strip() == file_name: return os.path.join(db_folder, can...
Parse a cronos database. Convert the database located in ``db_folder`` into CSV files in the directory ``out_folder``. def parse(db_folder, out_folder): """ Parse a cronos database. Convert the database located in ``db_folder`` into CSV files in the directory ``out_folder``. """ # The...
Return the base64 encoding of the figure file and insert in html image tag. def encode1(self): """Return the base64 encoding of the figure file and insert in html image tag.""" data_uri = b64encode(open(self.path, 'rb').read()).decode('utf-8').replace('\n', '') return '<img src="data:image/png;...
Return the base64 encoding of the fig attribute and insert in html image tag. def encode2(self): """Return the base64 encoding of the fig attribute and insert in html image tag.""" buf = BytesIO() self.fig.savefig(buf, format='png', bbox_inches='tight', dpi=100) buf.seek(0) stri...
Calculates the normalized restricted Damerau-Levenshtein distance (a.k.a. the normalized optimal string alignment distance) between two string arguments. The result will be a float in the range [0.0, 1.0], with 1.0 signifying the maximum distance between strings with these lengths def rdlevenshtein_norm(so...
Computes the Levenshtein (https://en.wikipedia.org/wiki/Levenshtein_distance) and restricted Damerau-Levenshtein (https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance) distances between two Unicode strings with given lengths using the Wagner-Fischer algorithm (https://en.wikipedia....
The main entry point. def main(): """The main entry point.""" if sys.version_info < (2, 7): sys.exit('crispy requires at least Python 2.7') elif sys.version_info[0] == 3 and sys.version_info < (3, 4): sys.exit('crispy requires at least Python 3.4') kwargs = dict( name='crispy',...
Read the spectra from the files generated by Quanty and store them as a list of spectum objects. def loadFromDisk(self, calculation): """ Read the spectra from the files generated by Quanty and store them as a list of spectum objects. """ suffixes = { 'Isotr...
Populate the widget using data stored in the state object. The order in which the individual widgets are populated follows their arrangment. The models are recreated every time the function is called. This might seem to be an overkill, but in practice it is very fast. Don't try ...
Update the selection to contain only the result specified by the index. This should be the last index of the model. Finally updade the context menu. The selectionChanged signal is used to trigger the update of the Quanty dock widget and result details dialog. :param index: Inde...
Updating the plotting widget should not require any information about the current state of the widget. def updatePlotWidget(self): """Updating the plotting widget should not require any information about the current state of the widget.""" pw = self.getPlotWidget() pw.reset() ...
Return the row of the child. def row(self): """Return the row of the child.""" if self.parent is not None: children = self.parent.getChildren() # The index method of the list object. return children.index(self) else: return 0
Return the index of the item in the model specified by the given row, column, and parent index. def index(self, row, column, parent=QModelIndex()): """Return the index of the item in the model specified by the given row, column, and parent index. """ if parent is not None and no...
Return the index of the parent for a given index of the child. Unfortunately, the name of the method has to be parent, even though a more verbose name like parentIndex, would avoid confusion about what parent actually is - an index or an item. def parent(self, index): """Return the inde...
Return the number of rows under the given parent. When the parentIndex is valid, rowCount() returns the number of children of the parent. For this it uses item() method to extract the parentItem from the parentIndex, and calls the childCount() of the item to get number of children. def ...
Return role specific data for the item referred by index.column(). def data(self, index, role): """Return role specific data for the item referred by index.column().""" if not index.isValid(): return item = self.item(index) column = index.column() va...
Set the role data for the item at index to value. def setData(self, index, value, role): """Set the role data for the item at index to value.""" if not index.isValid(): return False item = self.item(index) column = index.column() if role == Qt.EditRole: ...
Return the active flags for the given index. Add editable flag to items other than the first column. def flags(self, index): """Return the active flags for the given index. Add editable flag to items other than the first column. """ activeFlags = (Qt.ItemIsEnabled | Qt.ItemIsSel...
Return the data contained in the model. def _getModelData(self, modelData, parentItem=None): """Return the data contained in the model.""" if parentItem is None: parentItem = self.rootItem for item in parentItem.getChildren(): key = item.getItemData(0) if it...
Return the check state (disabled, tristate, enable) of all items belonging to a parent. def getNodesCheckState(self, parentItem=None): """Return the check state (disabled, tristate, enable) of all items belonging to a parent. """ if parentItem is None: parentItem = s...
Calculate the hexadecimal version number from the tuple version_info: :param major: integer :param minor: integer :param micro: integer :param relev: integer or string :param serial: integer :return: integerm always increasing with revision numbers def calc_hexversion(major=0, minor=0, micro=0...
Handle plot area customContextMenuRequested signal. :param QPoint pos: Mouse position relative to plot area def _contextMenu(self, pos): """Handle plot area customContextMenuRequested signal. :param QPoint pos: Mouse position relative to plot area """ # Create the context menu...
Convolve an array with a kernel using FFT. Implemntation based on the convolve_fft function from astropy. https://github.com/astropy/astropy/blob/master/astropy/convolution/convolve.py def convolve_fft(array, kernel): """ Convolve an array with a kernel using FFT. Implemntation based on the convol...
Diagonalize the tensor. def diagonalize(self): '''Diagonalize the tensor.''' self.eigvals, self.eigvecs = np.linalg.eig( (self.tensor.transpose() + self.tensor) / 2.0) self.eigvals = np.diag(np.dot( np.dot(self.eigvecs.transpose(), self.tensor), self.eigvecs))
Calculate the Euler angles only if the rotation matrix (eigenframe) has positive determinant. def euler_angles_and_eigenframes(self): '''Calculate the Euler angles only if the rotation matrix (eigenframe) has positive determinant.''' signs = np.array([[1, 1, 1], [-1, 1, 1], [1, -1...
Skip a number of lines from the output. def _skip_lines(self, n): '''Skip a number of lines from the output.''' for i in range(n): self.line = next(self.output) return self.line