Search is not available for this dataset
text
stringlengths
75
104k
def set_value(self, key, value): """ Set a value within the configuration based on its key. The key may be nested, any nested levels that do not exist prior to the final segment of the key path will be created. *Note*: In order to write changes to the file, ensure that :m...
def unlock_connection(cls, conf, dsn, key=None): """ A class method to unlock a connection (given by :code:`dsn`) in the specified configuration file. Automatically opens the file and writes to it before closing. :param str conf: The configuration file to modify :param s...
def unset_value(self, key): """ Remove a value at the given key -- and any nested values -- from the configuration. *Note*: In order to write changes to the file, ensure that :meth:`~giraffez.config.Config.write` is called prior to exit. :param str key: A path to the val...
def write(self, settings=None): """ Save the current configuration to its file (as given by :code:`self._config_file`). Optionally, settings may be passed in to override the current settings before writing. Returns :code:`None` if the file could not be written to, either due to p...
def write_default(self, conf=None): """ A class method to write a default configuration file structure to a file. Note that the contents of the file will be overwritten if it already exists. :param str conf: The name of the file to write to. Defaults to :code:`None`, for ~/.girafferc ...
def get(self, column_name): """ Retrieve a column from the list with name value :code:`column_name` :param str column_name: The name of the column to get :return: :class:`~giraffez.types.Column` with the specified name, or :code:`None` if it does not exist. """ column_na...
def set_filter(self, names=None): """ Set the names of columns to be used when iterating through the list, retrieving names, etc. :param list names: A list of names to be used, or :code:`None` for all """ _names = [] if names: for name in names: ...
def serialize(self): """ Serializes the columns into the giraffez archive header binary format:: 0 1 2 +------+------+------+------+------+------+------+------+ | Header | Header Data | | Length | ...
def deserialize(cls, data): """ Deserializes giraffez Archive header. See :meth:`~giraffez.types.Columns.serialize` for more information. :param str data: data in giraffez Archive format, to be deserialized :return: :class:`~giraffez.types.Columns` object decoded from data ...
def items(self): """ Represents the contents of the row as a :code:`dict` with the column names as keys, and the row's fields as values. :rtype: dict """ return {k.name: v for k, v in zip(self.columns, self)}
def query(self, query): """ Set the query to be run and initiate the connection with Teradata. Only necessary if the query/table name was not specified as an argument to the constructor of the instance. :param str query: Valid SQL query to be executed """ if quer...
def to_archive(self, writer): """ Writes export archive files in the Giraffez archive format. This takes a `giraffez.io.Writer` and writes archive chunks to file until all rows for a given statement have been exhausted. .. code-block:: python with giraffez.BulkExpor...
def to_str(self, delimiter='|', null='NULL'): """ Sets the current encoder output to Python `str` and returns a row iterator. :param str null: The string representation of null values :param str delimiter: The string delimiting values in the output string :r...
def float_with_multiplier(string): """Convert string with optional k, M, G, T multiplier to float""" match = re_float_with_multiplier.search(string) if not match or not match.group('num'): raise ValueError('String "{}" is not numeric!'.format(string)) num = float(match.group('num')) multi =...
def specific_gains(string): """Convert string with gains of individual amplification elements to dict""" if not string: return {} gains = {} for gain in string.split(','): amp_name, value = gain.split('=') gains[amp_name.strip()] = float(value.strip()) return gains
def device_settings(string): """Convert string with SoapySDR device settings to dict""" if not string: return {} settings = {} for setting in string.split(','): setting_name, value = setting.split('=') settings[setting_name.strip()] = value.strip() return settings
def wrap(text, indent=' '): """Wrap text to terminal width with default indentation""" wrapper = textwrap.TextWrapper( width=int(os.environ.get('COLUMNS', 80)), initial_indent=indent, subsequent_indent=indent ) return '\n'.join(wrapper.wrap(text))
def detect_devices(soapy_args=''): """Returns detected SoapySDR devices""" devices = simplesoapy.detect_devices(soapy_args, as_string=True) text = [] text.append('Detected SoapySDR devices:') if devices: for i, d in enumerate(devices): text.append(' {}'.format(d)) else: ...
def device_info(soapy_args=''): """Returns info about selected SoapySDR device""" text = [] try: device = simplesoapy.SoapyDevice(soapy_args) text.append('Selected device: {}'.format(device.hardware)) text.append(' Available RX channels:') text.append(' {}'.format(', '.jo...
def setup_argument_parser(): """Setup command line parser""" # Fix help formatter width if 'COLUMNS' not in os.environ: os.environ['COLUMNS'] = str(shutil.get_terminal_size().columns) parser = argparse.ArgumentParser( prog='soapy_power', formatter_class=argparse.RawDescriptionHe...
def set_center_freq(self, center_freq): """Set center frequency and clear averaged PSD data""" psd_state = { 'repeats': 0, 'freq_array': self._base_freq_array + self._lnb_lo + center_freq, 'pwr_array': None, 'update_lock': threading.Lock(), 'fu...
def result(self, psd_state): """Return freqs and averaged PSD for given center frequency""" freq_array = numpy.fft.fftshift(psd_state['freq_array']) pwr_array = numpy.fft.fftshift(psd_state['pwr_array']) if self._crop_factor: crop_bins_half = round((self._crop_factor * self....
def wait_for_result(self, psd_state): """Wait for all PSD threads to finish and return result""" if len(psd_state['futures']) > 1: concurrent.futures.wait(psd_state['futures']) elif psd_state['futures']: psd_state['futures'][0].result() return self.result(psd_stat...
def update(self, psd_state, samples_array): """Compute PSD from samples and update average for given center frequency""" freq_array, pwr_array = simplespectral.welch(samples_array, self._sample_rate, nperseg=self._bins, window=self._fft_window, noverl...
def update_async(self, psd_state, samples_array): """Compute PSD from samples and update average for given center frequency (asynchronously in another thread)""" future = self._executor.submit(self.update, psd_state, samples_array) future.add_done_callback(self._release_future_memory) ps...
def write_async(self, psd_data_or_future, time_start, time_stop, samples): """Write PSD of one frequncy hop (asynchronously in another thread)""" return self._executor.submit(self.write, psd_data_or_future, time_start, time_stop, samples)
def read(self, f): """Read data from file-like object""" magic = f.read(len(self.magic)) if not magic: return None if magic != self.magic: raise ValueError('Magic bytes not found! Read data: {}'.format(magic)) header = self.header._make( self....
def write(self, f, time_start, time_stop, start, stop, step, samples, pwr_array): """Write data to file-like object""" f.write(self.magic) f.write(self.header_struct.pack( self.version, time_start, time_stop, start, stop, step, samples, pwr_array.nbytes )) #pwr_array....
def write(self, psd_data_or_future, time_start, time_stop, samples): """Write PSD of one frequency hop""" try: # Wait for result of future f_array, pwr_array = psd_data_or_future.result() except AttributeError: f_array, pwr_array = psd_data_or_future ...
def write(self, psd_data_or_future, time_start, time_stop, samples): """Write PSD of one frequency hop""" try: # Wait for result of future f_array, pwr_array = psd_data_or_future.result() except AttributeError: f_array, pwr_array = psd_data_or_future ...
def write(self, psd_data_or_future, time_start, time_stop, samples): """Write PSD of one frequency hop""" try: # Wait for result of future f_array, pwr_array = psd_data_or_future.result() except AttributeError: f_array, pwr_array = psd_data_or_future ...
def submit(self, fn, *args, **kwargs): """Submits a callable to be executed with the given arguments. Count maximum reached work queue size in ThreadPoolExecutor.max_queue_size_reached. """ future = super().submit(fn, *args, **kwargs) work_queue_size = self._work_queue.qsize() ...
def nearest_bins(self, bins, even=False, pow2=False): """Return nearest number of FFT bins (even or power of two)""" if pow2: bins_log2 = math.log(bins, 2) if bins_log2 % 1 != 0: bins = 2**math.ceil(bins_log2) logger.warning('number of FFT bins sho...
def nearest_overlap(self, overlap, bins): """Return nearest overlap/crop factor based on number of bins""" bins_overlap = overlap * bins if bins_overlap % 2 != 0: bins_overlap = math.ceil(bins_overlap / 2) * 2 overlap = bins_overlap / bins logger.warning('numb...
def time_to_repeats(self, bins, integration_time): """Convert integration time to number of repeats""" return math.ceil((self.device.sample_rate * integration_time) / bins)
def freq_plan(self, min_freq, max_freq, bins, overlap=0, quiet=False): """Returns list of frequencies for frequency hopping""" bin_size = self.bins_to_bin_size(bins) bins_crop = round((1 - overlap) * bins) sample_rate_crop = (1 - overlap) * self.device.sample_rate freq_range = m...
def create_buffer(self, bins, repeats, base_buffer_size, max_buffer_size=0): """Create buffer for reading samples""" samples = bins * repeats buffer_repeats = 1 buffer_size = math.ceil(samples / base_buffer_size) * base_buffer_size if not max_buffer_size: # Max buffe...
def setup(self, bins, repeats, base_buffer_size=0, max_buffer_size=0, fft_window='hann', fft_overlap=0.5, crop_factor=0, log_scale=True, remove_dc=False, detrend=None, lnb_lo=0, tune_delay=0, reset_stream=False, max_threads=0, max_queue_size=0): """Prepare samples buffer and start st...
def stop(self): """Stop streaming samples from device and delete samples buffer""" if not self.device.is_streaming: return self.device.stop_stream() self._writer.close() self._bins = None self._repeats = None self._base_buffer_size = None sel...
def psd(self, freq): """Tune to specified center frequency and compute Power Spectral Density""" if not self.device.is_streaming: raise RuntimeError('Streaming is not initialized, you must run setup() first!') # Tune to new frequency in main thread logger.debug(' Frequency ...
def sweep(self, min_freq, max_freq, bins, repeats, runs=0, time_limit=0, overlap=0, fft_window='hann', fft_overlap=0.5, crop=False, log_scale=True, remove_dc=False, detrend=None, lnb_lo=0, tune_delay=0, reset_stream=False, base_buffer_size=0, max_buffer_size=0, max_threads=0, max_queue_size=...
def close(self): """close() Disconnects the object from the bus. """ os.close(self._fd) self._fd = -1 self._addr = -1 self._pec = 0
def open(self, bus): """open(bus) Connects the object to the specified SMBus. """ bus = int(bus) path = "/dev/i2c-%d" % (bus,) if len(path) >= MAXPATH: raise OverflowError("Bus number is invalid.") try: self._fd = os.open(path, os.O_RD...
def _set_addr(self, addr): """private helper method""" if self._addr != addr: ioctl(self._fd, SMBUS.I2C_SLAVE, addr) self._addr = addr
def write_quick(self, addr): """write_quick(addr) Perform SMBus Quick transaction. """ self._set_addr(addr) if SMBUS.i2c_smbus_write_quick(self._fd, SMBUS.I2C_SMBUS_WRITE) != 0: raise IOError(ffi.errno)
def read_byte(self, addr): """read_byte(addr) -> result Perform SMBus Read Byte transaction. """ self._set_addr(addr) result = SMBUS.i2c_smbus_read_byte(self._fd) if result == -1: raise IOError(ffi.errno) return result
def write_byte(self, addr, val): """write_byte(addr, val) Perform SMBus Write Byte transaction. """ self._set_addr(addr) if SMBUS.i2c_smbus_write_byte(self._fd, ffi.cast("__u8", val)) == -1: raise IOError(ffi.errno)
def read_byte_data(self, addr, cmd): """read_byte_data(addr, cmd) -> result Perform SMBus Read Byte Data transaction. """ self._set_addr(addr) res = SMBUS.i2c_smbus_read_byte_data(self._fd, ffi.cast("__u8", cmd)) if res == -1: raise IOError(ffi.errno) ...
def write_byte_data(self, addr, cmd, val): """write_byte_data(addr, cmd, val) Perform SMBus Write Byte Data transaction. """ self._set_addr(addr) if SMBUS.i2c_smbus_write_byte_data(self._fd, ffi.cast("__u8", cmd), ...
def read_word_data(self, addr, cmd): """read_word_data(addr, cmd) -> result Perform SMBus Read Word Data transaction. """ self._set_addr(addr) result = SMBUS.i2c_smbus_read_word_data(self._fd, ffi.cast("__u8", cmd)) if result == -1: raise IOError(ffi.errno) ...
def write_word_data(self, addr, cmd, val): """write_word_data(addr, cmd, val) Perform SMBus Write Word Data transaction. """ self._set_addr(addr) if SMBUS.i2c_smbus_write_word_data(self._fd, ffi.cast("__u8", cmd), ...
def process_call(self, addr, cmd, val): """process_call(addr, cmd, val) Perform SMBus Process Call transaction. Note: although i2c_smbus_process_call returns a value, according to smbusmodule.c this method does not return a value by default. Set _compat = False on the SMBus in...
def read_block_data(self, addr, cmd): """read_block_data(addr, cmd) -> results Perform SMBus Read Block Data transaction. """ # XXX untested, the raspberry pi i2c driver does not support this # command self._set_addr(addr) data = ffi.new("union i2c_smbus_data *")...
def write_block_data(self, addr, cmd, vals): """write_block_data(addr, cmd, vals) Perform SMBus Write Block Data transaction. """ self._set_addr(addr) data = ffi.new("union i2c_smbus_data *") list_to_smbus_data(data, vals) if SMBUS.i2c_smbus_access(self._fd, ...
def block_process_call(self, addr, cmd, vals): """block_process_call(addr, cmd, vals) -> results Perform SMBus Block Process Call transaction. """ self._set_addr(addr) data = ffi.new("union i2c_smbus_data *") list_to_smbus_data(data, vals) if SMBUS.i2c_smbus_acce...
def read_i2c_block_data(self, addr, cmd, len=32): """read_i2c_block_data(addr, cmd, len=32) -> results Perform I2C Block Read transaction. """ self._set_addr(addr) data = ffi.new("union i2c_smbus_data *") data.block[0] = len if len == 32: arg = SMBUS....
def pec(self, value): """True if Packet Error Codes (PEC) are enabled""" pec = bool(value) if pec != self._pec: if ioctl(self._fd, SMBUS.I2C_PEC, pec): raise IOError(ffi.errno) self._pec = pec
def run_cmake(arg=""): """ Forcing to run cmake """ if ds.find_executable('cmake') is None: print "CMake is required to build zql" print "Please install cmake version >= 2.8 and re-run setup" sys.exit(-1) print "Configuring zql build with CMake.... " cmake_args = arg ...
def start(cls, now, number, **options): """ Return the starting datetime: ``number`` of units before ``now``. """ return (cls.mask(now, **options) - timedelta(**{cls.__name__.lower(): number - 1}))
def filter(cls, datetimes, number, now=None, **options): """Return a set of datetimes, after filtering ``datetimes``. The result will be the ``datetimes`` which are ``number`` of units before ``now``, until ``now``, with approximately one unit between each of them. The first datetime f...
def mask(cls, dt, **options): """ Return a datetime with the same value as ``dt``, to a resolution of days. """ return dt.replace(hour=0, minute=0, second=0, microsecond=0)
def start(cls, now, number, firstweekday=calendar.SATURDAY, **options): """ Return the starting datetime: ``number`` of weeks before ``now``. ``firstweekday`` determines when the week starts. It defaults to Saturday. """ week = cls.mask(now, firstweekday=firstweekday, **...
def mask(cls, dt, firstweekday=calendar.SATURDAY, **options): """ Return a datetime with the same value as ``dt``, to a resolution of weeks. ``firstweekday`` determines when the week starts. It defaults to Saturday. """ correction = (dt.weekday() - firstweekday) ...
def start(cls, now, number, **options): """ Return the starting datetime: ``number`` of months before ``now``. """ year = now.year month = now.month - number + 1 # Handle negative months if month < 0: year = year + (month // cls.MONTHS_IN_YEAR) ...
def start(cls, now, number, **options): """ Return the starting datetime: ``number`` of years before ``now``. """ return cls.mask(now).replace(year=(now.year - number + 1))
def to_keep(datetimes, years=0, months=0, weeks=0, days=0, hours=0, minutes=0, seconds=0, firstweekday=SATURDAY, now=None): """ Return a set of datetimes that should be kept, out of ``datetimes``. Keeps up to ``years``, ``months``, ``weeks``, ``days``, ``hours``, ``m...
def to_delete(datetimes, years=0, months=0, weeks=0, days=0, hours=0, minutes=0, seconds=0, firstweekday=SATURDAY, now=None): """ Return a set of datetimes that should be deleted, out of ``datetimes``. See ``to_keep`` for a description of arguments. """ dat...
def dates_to_keep(dates, years=0, months=0, weeks=0, days=0, firstweekday=SATURDAY, now=None): """ Return a set of dates that should be kept, out of ``dates``. See ``to_keep`` for a description of arguments. """ datetimes = to_keep((datetime.combine(d, time()) fo...
def dates_to_delete(dates, years=0, months=0, weeks=0, days=0, firstweekday=SATURDAY, now=None): """ Return a set of date that should be deleted, out of ``dates``. See ``to_keep`` for a description of arguments. """ dates = set(dates) return dates - dates...
def _get_spi_control_byte(self, read_write_cmd): """Returns an SPI control byte. The MCP23S17 is a slave SPI device. The slave address contains four fixed bits and three user-defined hardware address bits (if enabled via IOCON.HAEN) (pins A2, A1 and A0) with the read/write bit f...
def read_bit(self, bit_num, address): """Returns the bit specified from the address. :param bit_num: The bit number to read from. :type bit_num: int :param address: The address to read from. :type address: int :returns: int -- the bit value from the address """ ...
def write_bit(self, value, bit_num, address): """Writes the value given to the bit in the address specified. :param value: The value to write. :type value: int :param bit_num: The bit number to write to. :type bit_num: int :param address: The address to write to. ...
def get_bit_num(bit_pattern): """Returns the lowest bit num from a given bit pattern. Returns None if no bits set. :param bit_pattern: The bit pattern. :type bit_pattern: int :returns: int -- the bit number :returns: None -- no bits set >>> pifacecommon.core.get_bit_num(0) None >>>...
def watch_port_events(port, chip, pin_function_maps, event_queue, return_after_kbdint=False): """Waits for a port event. When a port event occurs it is placed onto the event queue. :param port: The port we are waiting for interrupts on (GPIOA/GPIOB). :type port: int :param chi...
def handle_events( function_maps, event_queue, event_matches_function_map, terminate_signal): """Waits for events on the event queue and calls the registered functions. :param function_maps: A list of classes that have inheritted from :class:`FunctionMap`\ s describing what to do with e...
def bring_gpio_interrupt_into_userspace(): # activate gpio interrupt """Bring the interrupt pin on the GPIO into Linux userspace.""" try: # is it already there? with open(GPIO_INTERRUPT_DEVICE_VALUE): return except IOError: # no, bring it into userspace with open...
def set_gpio_interrupt_edge(edge='falling'): """Set the interrupt edge on the userspace GPIO pin. :param edge: The interrupt edge ('none', 'falling', 'rising'). :type edge: string """ # we're only interested in the falling edge (1 -> 0) start_time = time.time() time_limit = start_time + FIL...
def wait_until_file_exists(filename): """Wait until a file exists. :param filename: The name of the file to wait for. :type filename: string """ start_time = time.time() time_limit = start_time + FILE_IO_TIMEOUT while time.time() < time_limit: try: with open(filename): ...
def add_event(self, event): """Adds events to the queue. Will ignore events that occur before the settle time for that pin/direction. Such events are assumed to be bouncing. """ # print("Trying to add event:") # print(event) # find out the pin settle time ...
def register(self, pin_num, direction, callback, settle_time=DEFAULT_SETTLE_TIME): """Registers a pin number and direction to a callback function. :param pin_num: The pin pin number. :type pin_num: int :param direction: The event direction (use: IODIR_ON/IOD...
def deregister(self, pin_num=None, direction=None): """De-registers callback functions :param pin_num: The pin number. If None then all functions are de-registered :type pin_num: int :param direction: The event direction. If None then all functions for the give...
def deactivate(self): """When deactivated the :class:`PortEventListener` will not run anything. """ self.event_queue.put(self.TERMINATE_SIGNAL) self.dispatcher.join() self.detector.terminate() self.detector.join()
def gpio_interrupts_enable(self): """Enables GPIO interrupts.""" try: bring_gpio_interrupt_into_userspace() set_gpio_interrupt_edge() except Timeout as e: raise InterruptEnableException( "There was an error bringing gpio%d into userspace. %s" %...
def spisend(self, bytes_to_send): """Sends bytes via the SPI bus. :param bytes_to_send: The bytes to send on the SPI device. :type bytes_to_send: bytes :returns: bytes -- returned bytes from SPI device :raises: InitError """ # make some buffer space to store read...
def render(self, form, form_style, context, template_pack=TEMPLATE_PACK): """ Re-implement almost the same code from crispy_forms but passing ``form`` instance to item ``render_link`` method. """ links, content = '', '' # accordion group needs the parent div id to set `d...
def has_errors(self, form): """ Find tab fields listed as invalid """ return any([fieldname_error for fieldname_error in form.errors.keys() if fieldname_error in self])
def render_link(self, form, template_pack=TEMPLATE_PACK, **kwargs): """ Render the link for the tab-pane. It must be called after render so ``css_class`` is updated with ``active`` class name if needed. """ link_template = self.link_template % template_pack return render_...
def _extract_version(package_name): """ Get package version from installed distribution or configuration file if not installed """ try: return pkg_resources.get_distribution(package_name).version except pkg_resources.DistributionNotFound: _conf = read_configuration(os.path.join(P...
def get_form_kwargs(self): """ Pass template pack argument """ kwargs = super(FormContainersMixin, self).get_form_kwargs() kwargs.update({ 'pack': "foundation-{}".format(self.kwargs.get('foundation_version')) }) return kwargs
def _check_status(cls, response_json): """Check the status of the incoming response, raise exception if status is not 200. Args: response_json (dict): results of the response of the GET request. Returns: None """ status = response_json['status'] ...
def _get(self, url, params=None): """Used by every other method, it makes a GET request with the given params. Args: url (str): relative path of a specific service (account_info, ...). params (:obj:`dict`, optional): contains parameters to be sent in the GET request. Re...
def get_download_link(self, file_id, ticket, captcha_response=None): """Requests direct download link for requested file, this method makes use of the response of prepare_download, prepare_download must be called first. Args: file_id (str): id of the file to be downloaded. ...
def upload_link(self, folder_id=None, sha1=None, httponly=False): """Makes a request to prepare for file upload. Note: If folder_id is not provided, it will make and upload link to the ``Home`` folder. Args: folder_id (:obj:`str`, optional): folder-ID to upload to. ...
def upload_file(self, file_path, folder_id=None, sha1=None, httponly=False): """Calls upload_link request to get valid url, then it makes a post request with given file to be uploaded. No need to call upload_link explicitly since upload_file calls it. Note: If folder_id is not provi...
def remote_upload(self, remote_url, folder_id=None, headers=None): """Used to make a remote file upload to openload.co Note: If folder_id is not provided, the file will be uploaded to ``Home`` folder. Args: remote_url (str): direct link of file to be remotely downloaded...
def remote_upload_status(self, limit=None, remote_upload_id=None): """Checks a remote file upload to status. Args: limit (:obj:`int`, optional): Maximum number of results (Default: 5, Maximum: 100). remote_upload_id (:obj:`str`, optional): Remote Upload ID. Returns: ...
def list_folder(self, folder_id=None): """Request a list of files and folders in specified folder. Note: if folder_id is not provided, ``Home`` folder will be listed Args: folder_id (:obj:`str`, optional): id of the folder to be listed. Returns: dic...
def running_conversions(self, folder_id=None): """Shows running file converts by folder Note: If folder_id is not provided, ``Home`` folder will be used. Args: folder_id (:obj:`str`, optional): id of the folder to list conversions of files exist in it. Returns:...
def calc_heat_index(temp, hum): ''' calculates the heat index based upon temperature (in F) and humidity. http://www.srh.noaa.gov/bmx/tables/heat_index.html returns the heat index in degrees F. ''' if (temp < 80): return temp else: return -42.379 + 2.04901523 * temp + 1...
def calc_wind_chill(t, windspeed, windspeed10min=None): ''' calculates the wind chill value based upon the temperature (F) and wind. returns the wind chill in degrees F. ''' w = max(windspeed10min, windspeed) return 35.74 + 0.6215 * t - 35.75 * (w ** 0.16) + 0.4275 * t * (w ** 0.16);