Instruction:
Write a Python 3 function for
returning a list of frequencies for frequency hopping

Response:
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 = max_freq - min_freq
        hopping = True if freq_range >= sample_rate_crop else False
        hop_size = self.nearest_freq(sample_rate_crop, bin_size)
        hops = math.ceil(freq_range / hop_size) if hopping else 1
        min_center_freq = min_freq + (hop_size / 2) if hopping else min_freq + (freq_range / 2)
        max_center_freq = min_center_freq + ((hops - 1) * hop_size)

        freq_list = [min_center_freq + (i * hop_size) for i in range(hops)]

        if not quiet:
            logger.info('overlap: {:.5f}'.format(overlap))
            logger.info('bin_size: {:.2f} Hz'.format(bin_size))
            logger.info('bins: {}'.format(bins))
            logger.info('bins (after crop): {}'.format(bins_crop))
            logger.info('sample_rate: {:.3f} MHz'.format(self.device.sample_rate / 1e6))
            logger.info('sample_rate (after crop): {:.3f} MHz'.format(sample_rate_crop / 1e6))
            logger.info('freq_range: {:.3f} MHz'.format(freq_range / 1e6))
            logger.info('hopping: {}'.format('YES' if hopping else 'NO'))
            logger.info('hop_size: {:.3f} MHz'.format(hop_size / 1e6))
            logger.info('hops: {}'.format(hops))
            logger.info('min_center_freq: {:.3f} MHz'.format(min_center_freq / 1e6))
            logger.info('max_center_freq: {:.3f} MHz'.format(max_center_freq / 1e6))
            logger.info('min_freq (after crop): {:.3f} MHz'.format((min_center_freq - (hop_size / 2)) / 1e6))
            logger.info('max_freq (after crop): {:.3f} MHz'.format((max_center_freq + (hop_size / 2)) / 1e6))

            logger.debug('Frequency hops table:')
            logger.debug('  {:8s}      {:8s}      {:8s}'.format('Min:', 'Center:', 'Max:'))
            for f in freq_list:
                logger.debug('  {:8.3f} MHz  {:8.3f} MHz  {:8.3f} MHz'.format(
                    (f - (self.device.sample_rate / 2)) / 1e6,
                    f / 1e6,
                    (f + (self.device.sample_rate / 2)) / 1e6,
                ))

        return freq_list


Instruction:
Can you write a function in Python 3 where it
creates a buffer for reading samples

Response:
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 buffer size about 100 MB
            max_buffer_size = (100 * 1024**2) / 8

        if max_buffer_size > 0:
            max_buffer_size = math.ceil(max_buffer_size / base_buffer_size) * base_buffer_size
            if buffer_size > max_buffer_size:
                logger.warning('Required buffer size ({}) will be shrinked to max_buffer_size ({})!'.format(
                    buffer_size, max_buffer_size
                ))
                buffer_repeats = math.ceil(buffer_size / max_buffer_size)
                buffer_size = max_buffer_size

        logger.info('repeats: {}'.format(repeats))
        logger.info('samples: {} (time: {:.5f} s)'.format(samples, samples / self.device.sample_rate))
        if max_buffer_size > 0:
            logger.info('max_buffer_size (samples): {} (repeats: {:.2f}, time: {:.5f} s)'.format(
                max_buffer_size, max_buffer_size / bins, max_buffer_size / self.device.sample_rate
            ))
        else:
            logger.info('max_buffer_size (samples): UNLIMITED')
        logger.info('buffer_size (samples): {} (repeats: {:.2f}, time: {:.5f} s)'.format(
            buffer_size, buffer_size / bins, buffer_size / self.device.sample_rate
        ))
        logger.info('buffer_repeats: {}'.format(buffer_repeats))

        return (buffer_repeats, zeros(buffer_size, numpy.complex64))


Instruction:
Create a Python 3 function to
prepare samples buffer and start streaming samples from device

Response:
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 streaming samples from device"""
        if self.device.is_streaming:
            self.device.stop_stream()

        base_buffer = self.device.start_stream(buffer_size=base_buffer_size)
        self._bins = bins
        self._repeats = repeats
        self._base_buffer_size = len(base_buffer)
        self._max_buffer_size = max_buffer_size
        self._buffer_repeats, self._buffer = self.create_buffer(
            bins, repeats, self._base_buffer_size, self._max_buffer_size
        )
        self._tune_delay = tune_delay
        self._reset_stream = reset_stream
        self._psd = psd.PSD(bins, self.device.sample_rate, fft_window=fft_window, fft_overlap=fft_overlap,
                            crop_factor=crop_factor, log_scale=log_scale, remove_dc=remove_dc, detrend=detrend,
                            lnb_lo=lnb_lo, max_threads=max_threads, max_queue_size=max_queue_size)
        self._writer = writer.formats[self._output_format](self._output)


Instruction:
Can you implement a function in Python 3 that
stops streaming samples from device and delete samples buffer

Response:
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
        self._max_buffer_size = None
        self._buffer_repeats = None
        self._buffer = None
        self._tune_delay = None
        self._reset_stream = None
        self._psd = None
        self._writer = None


Instruction:
Explain what the following Python 3 code does
def psd(self, freq):
        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 hop: {:.2f} Hz'.format(freq))
        t_freq = time.time()
        if self.device.freq != freq:
            # Deactivate streaming before tuning
            if self._reset_stream:
                self.device.device.deactivateStream(self.device.stream)

            # Actually tune to new center frequency
            self.device.freq = freq

            # Reactivate straming after tuning
            if self._reset_stream:
                self.device.device.activateStream(self.device.stream)

            # Delay reading samples after tuning
            if self._tune_delay:
                t_delay = time.time()
                while True:
                    self.device.read_stream()
                    t_delay_end = time.time()
                    if t_delay_end - t_delay >= self._tune_delay:
                        break
                logger.debug('    Tune delay: {:.3f} s'.format(t_delay_end - t_delay))
        else:
            logger.debug('    Same frequency as before, tuning skipped')
        psd_state = self._psd.set_center_freq(freq)
        t_freq_end = time.time()
        logger.debug('    Tune time: {:.3f} s'.format(t_freq_end - t_freq))

        for repeat in range(self._buffer_repeats):
            logger.debug('    Repeat: {}'.format(repeat + 1))
            # Read samples from SDR in main thread
            t_acq = time.time()
            acq_time_start = datetime.datetime.utcnow()
            self.device.read_stream_into_buffer(self._buffer)
            acq_time_stop = datetime.datetime.utcnow()
            t_acq_end = time.time()
            logger.debug('      Acquisition time: {:.3f} s'.format(t_acq_end - t_acq))

            # Start FFT computation in another thread
            self._psd.update_async(psd_state, numpy.copy(self._buffer))

            t_final = time.time()

            if _shutdown:
                break

        psd_future = self._psd.result_async(psd_state)
        logger.debug('    Total hop time: {:.3f} s'.format(t_final - t_freq))

        return (psd_future, acq_time_start, acq_time_stop)

Response: Tune to specified frequency and compute Power Spectral Density


Instruction:
Implement a Python 3 function for
sweeping the audio file using frequency hopping.

Response:
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=0):
        """Sweep spectrum using frequency hopping"""
        self.setup(
            bins, repeats, base_buffer_size, max_buffer_size,
            fft_window=fft_window, fft_overlap=fft_overlap, crop_factor=overlap if crop else 0,
            log_scale=log_scale, remove_dc=remove_dc, detrend=detrend, lnb_lo=lnb_lo, tune_delay=tune_delay,
            reset_stream=reset_stream, max_threads=max_threads, max_queue_size=max_queue_size
        )

        try:
            freq_list = self.freq_plan(min_freq - lnb_lo, max_freq - lnb_lo, bins, overlap)
            t_start = time.time()
            run = 0
            while not _shutdown and (runs == 0 or run < runs):
                run += 1
                t_run_start = time.time()
                logger.debug('Run: {}'.format(run))

                for freq in freq_list:
                    # Tune to new frequency, acquire samples and compute Power Spectral Density
                    psd_future, acq_time_start, acq_time_stop = self.psd(freq)

                    # Write PSD to stdout (in another thread)
                    self._writer.write_async(psd_future, acq_time_start, acq_time_stop,
                                             len(self._buffer) * self._buffer_repeats)

                    if _shutdown:
                        break

                # Write end of measurement marker (in another thread)
                write_next_future = self._writer.write_next_async()
                t_run = time.time()
                logger.debug('  Total run time: {:.3f} s'.format(t_run - t_run_start))

                # End measurement if time limit is exceeded
                if time_limit and (time.time() - t_start) >= time_limit:
                    logger.info('Time limit of {} s exceeded, completed {} runs'.format(time_limit, run))
                    break

            # Wait for last write to be finished
            write_next_future.result()

            # Debug thread pool queues
            logging.debug('Number of USB buffer overflow errors: {}'.format(self.device.buffer_overflow_count))
            logging.debug('PSD worker threads: {}'.format(self._psd._executor._max_workers))
            logging.debug('Max. PSD queue size: {} / {}'.format(self._psd._executor.max_queue_size_reached,
                                                                self._psd._executor.max_queue_size))
            logging.debug('Writer worker threads: {}'.format(self._writer._executor._max_workers))
            logging.debug('Max. Writer queue size: {} / {}'.format(self._writer._executor.max_queue_size_reached,
                                                                   self._writer._executor.max_queue_size))
        finally:
            # Shutdown SDR
            self.stop()
            t_stop = time.time()
            logger.info('Total time: {:.3f} s'.format(t_stop - t_start))


Instruction:
Given the following Python 3 function, write the documentation
def close(self):
        os.close(self._fd)
        self._fd = -1
        self._addr = -1
        self._pec = 0

Response: Disconnects the object from the bus.


Instruction:
Create a Python 3 function for
opening the object to the specified SMBus.

Response:
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_RDWR, 0)
        except OSError as e:
            raise IOError(e.errno)


Instruction:
How would you implement a function in Python 3 that
performs SMBus Quick transaction.

Response:
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)


Instruction:
Explain what the following Python 3 code does
def read_byte(self, addr):
        self._set_addr(addr)
        result = SMBUS.i2c_smbus_read_byte(self._fd)
        if result == -1:
            raise IOError(ffi.errno)
        return result

Response: Read a byte from the cache.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def write_byte(self, addr, val):
        self._set_addr(addr)
        if SMBUS.i2c_smbus_write_byte(self._fd, ffi.cast("__u8", val)) == -1:
            raise IOError(ffi.errno)

Response: Write a byte to the memory mapped by the base address.


Instruction:
How would you implement a function in Python 3 that
performs a SMBus Read Byte Data transaction.

Response:
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)
        return res


Instruction:
Here you have a function in Python 3, explain what it does
def write_byte_data(self, addr, cmd, val):
        self._set_addr(addr)
        if SMBUS.i2c_smbus_write_byte_data(self._fd,
                                           ffi.cast("__u8", cmd),
                                           ffi.cast("__u8", val)) == -1:
            raise IOError(ffi.errno)

Response: Write a byte to a resource in the current thread.


Instruction:
Write a Python 3 script to
read word data from the specified address and return the result.

Response:
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)
        return result


Instruction:
Make a summary of the following Python 3 code
def write_word_data(self, addr, cmd, val):
        self._set_addr(addr)
        if SMBUS.i2c_smbus_write_word_data(self._fd,
                                           ffi.cast("__u8", cmd),
                                           ffi.cast("__u16", val)) == -1:
            raise IOError(ffi.errno)

Response: Write word data to a resource in the cache.


Instruction:
Explain what the following Python 3 code does
def process_call(self, addr, cmd, val):
        self._set_addr(addr)
        ret = SMBUS.i2c_smbus_process_call(self._fd,
                                           ffi.cast("__u8", cmd),
                                           ffi.cast("__u16", val))
        if ret == -1:
            raise IOError(ffi.errno)
        if self._compat:
            return ret

Response: Process a call from the specified address and return the result.


Instruction:
Can you generate the documentation for the following Python 3 function
def read_block_data(self, addr, cmd):
        # XXX untested, the raspberry pi i2c driver does not support this
        # command
        self._set_addr(addr)
        data = ffi.new("union i2c_smbus_data *")
        if SMBUS.i2c_smbus_access(self._fd,
                                  int2byte(SMBUS.I2C_SMBUS_READ),
                                  ffi.cast("__u8", cmd),
                                  SMBUS.I2C_SMBUS_BLOCK_DATA,
                                  data):
            raise IOError(ffi.errno)
        return smbus_data_to_list(data)

Response: Perform SMBus Read Block Data transaction.


Instruction:
Here you have a function in Python 3, explain what it does
def write_block_data(self, addr, cmd, vals):
        self._set_addr(addr)
        data = ffi.new("union i2c_smbus_data *")
        list_to_smbus_data(data, vals)
        if SMBUS.i2c_smbus_access(self._fd,
                                  int2byte(SMBUS.I2C_SMBUS_WRITE),
                                  ffi.cast("__u8", cmd),
                                  SMBUS.I2C_SMBUS_BLOCK_DATA,
                                  data):
            raise IOError(ffi.errno)

Response: Write block data to a resource.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def block_process_call(self, addr, cmd, vals):
        self._set_addr(addr)
        data = ffi.new("union i2c_smbus_data *")
        list_to_smbus_data(data, vals)
        if SMBUS.i2c_smbus_access(self._fd, SMBUS.I2C_SMBUS_WRITE,
                                  ffi.cast("__u8", cmd),
                                  SMBUS.I2C_SMBUS_BLOCK_PROC_CALL,
                                  data):
            raise IOError(ffi.errno)
        return smbus_data_to_list(data)

Response: Perform SMBus Block Process Call transaction.


Instruction:
Explain what the following Python 3 code does
def read_i2c_block_data(self, addr, cmd, len=32):
        self._set_addr(addr)
        data = ffi.new("union i2c_smbus_data *")
        data.block[0] = len
        if len == 32:
            arg = SMBUS.I2C_SMBUS_I2C_BLOCK_BROKEN
        else:
            arg = SMBUS.I2C_SMBUS_I2C_BLOCK_DATA
        if SMBUS.i2c_smbus_access(self._fd,
                                  int2byte(SMBUS.I2C_SMBUS_READ),
                                  ffi.cast("__u8", cmd),
                                  arg, data):
            raise IOError(ffi.errno)
        return smbus_data_to_list(data)

Response: Read the block of data from the i2c bus.


Instruction:
Here you have a function in Python 3, explain what it does
def pec(self, value):
        pec = bool(value)
        if pec != self._pec:
            if ioctl(self._fd, SMBUS.I2C_PEC, pec):
                raise IOError(ffi.errno)
            self._pec = pec

Response: Set Packet Error Codes ( PEC ).


Instruction:
Can you tell what is the following Python 3 function doing
def run_cmake(arg=""):
    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
    try:
        build_dir = op.join(op.split(__file__)[0], 'build')
        dd.mkpath(build_dir)
        os.chdir("build")
        ds.spawn(['cmake', '..'] + cmake_args.split())
        ds.spawn(['make', 'clean'])
        ds.spawn(['make'])
        os.chdir("..")
    except ds.DistutilsExecError:
        print "Error while running cmake"
        print "run 'setup.py build --help' for build options"
        print "You may also try editing the settings in CMakeLists.txt file and re-running setup"
        sys.exit(-1)

Response: Run cmake with the given arguments


Instruction:
Here you have a function in Python 3, explain what it does
def start(cls, now, number, **options):
        return (cls.mask(now, **options) -
                timedelta(**{cls.__name__.lower(): number - 1}))

Response: Return the starting datetime of the specified number of units before now.


Instruction:
Can you generate the documentation for the following Python 3 function
def filter(cls, datetimes, number, now=None, **options):
        if not isinstance(number, int) or number < 0:
            raise ValueError('Invalid number: %s' % number)

        datetimes = tuple(datetimes)

        # Sample the first datetime to see if it is timezone-aware
        tzinfo = None
        if datetimes and datetimes[0].tzinfo is not None:
            tzinfo = UTC()

        if now is None:
            now = datetime.now(tzinfo)

        if not hasattr(now, 'second'):
            # now looks like a date, so convert it into a datetime
            now = datetime.combine(now, time(23, 59, 59, 999999, tzinfo=tzinfo))

        # Always keep datetimes from the future
        future = set(dt for dt in datetimes if dt > now)

        if number == 0:
            return future

        # Don't consider datetimes from before the start
        start = cls.start(now, number, **options)
        valid = (dt for dt in datetimes if start <= dt <= now)

        # Deduplicate datetimes with the same mask() value by keeping
        # the oldest.
        kept = {}
        for dt in sorted(valid):
            kept.setdefault(cls.mask(dt, **options), dt)

        return set(kept.values()) | future

Response: Return a set of datetimes after filtering datetimes.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def mask(cls, dt, **options):
        return dt.replace(hour=0, minute=0, second=0, microsecond=0)

Response:
Return a datetime with the same value as dt to a
        resolution of days.


Instruction:
Can you write a function in Python 3 where it
returns the starting datetime for the given number of weeks before now.

Response:
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, **options)
        days = (number - 1) * cls.DAYS_IN_WEEK
        return week - timedelta(days=days)


Instruction:
How would you code a function in Python 3 to
return a datetime with the same value as dt.

Response:
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) % cls.DAYS_IN_WEEK
        week = dt - timedelta(days=correction)
        return week.replace(hour=0, minute=0, second=0, microsecond=0)


Instruction:
Write a Python 3 script to
return the starting datetime for the given number of months before now.

Response:
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)
            month = month % cls.MONTHS_IN_YEAR
        # Handle December
        if month == 0:
            year = year - 1
            month = 12
        return cls.mask(now, **options).replace(year=year, month=month)


Instruction:
Write a Python 3 function for
returning the starting datetime of the specified number of years before now.

Response:
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))


Instruction:
How would you explain what the following Python 3 function does
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``, ``minutes``, and ``seconds`` in the past.

    When keeping weeks, it prefers to keep ``firstweekday``, which
    defaults to Saturday.

    If ``now`` is None, it will base its calculations on
    ``datetime.datetime.now()``. Datetimes after this point will always be
    kept.
    """
    datetimes = set(datetimes)
    return (filters.Years.filter(datetimes, number=years, now=now) |
            filters.Months.filter(datetimes, number=months, now=now) |
            filters.Weeks.filter(datetimes, number=weeks,
                                 firstweekday=firstweekday, now=now) |
            filters.Days.filter(datetimes, number=days, now=now) |
            filters.Hours.filter(datetimes, number=hours, now=now) |
            filters.Minutes.filter(datetimes, number=minutes, now=now) |
            filters.Seconds.filter(datetimes, number=seconds, now=now))

Response: Returns a set of datetimes that should be kept out of the current date.


Instruction:
Explain what the following Python 3 code does
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.
    """
    datetimes = set(datetimes)
    return datetimes - to_keep(datetimes,
                               years=years, months=months,
                               weeks=weeks, days=days,
                               hours=hours, minutes=minutes, seconds=seconds,
                               firstweekday=firstweekday, now=now)

Response: Return a set of datetimes that should be deleted out of the specified datetimes.


Instruction:
Implement a function in Python 3 to
return a set of dates that should be kept out of dates.

Response:
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()) for d in dates),
                        years=years, months=months, weeks=weeks, days=days,
                        hours=0, minutes=0, seconds=0,
                        firstweekday=firstweekday, now=now)
    return set(dt.date() for dt in datetimes)


Instruction:
How would you explain what the following Python 3 function does
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_to_keep(dates,
                                 years=years, months=months,
                                 weeks=weeks, days=days,
                                 firstweekday=firstweekday, now=now)

Response: Return a set of dates that should be deleted out of a sequence of dates.


Instruction:
Make a summary of the following Python 3 code
def _get_spi_control_byte(self, read_write_cmd):
        # board_addr_pattern = (self.hardware_addr & 0b111) << 1
        board_addr_pattern = (self.hardware_addr << 1) & 0xE
        rw_cmd_pattern = read_write_cmd & 1  # make sure it's just 1 bit long
        return 0x40 | board_addr_pattern | rw_cmd_pattern

Response: Returns an SPI control byte.


Instruction:
Given the following Python 3 function, write the documentation
def read_bit(self, bit_num, address):
        value = self.read(address)
        bit_mask = get_bit_mask(bit_num)
        return 1 if value & bit_mask else 0

Response: Reads a single bit from the address.


Instruction:
Write a Python 3 function for
writing the value given to the bit in the address specified.

Response:
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.
        :type address: int
        """
        bit_mask = get_bit_mask(bit_num)
        old_byte = self.read(address)
         # generate the new byte
        if value:
            new_byte = old_byte | bit_mask
        else:
            new_byte = old_byte & ~bit_mask
        self.write(new_byte, address)


Instruction:
Implement a function in Python 3 to
return the lowest bit number from a given bit pattern.

Response:
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
    >>> pifacecommon.core.get_bit_num(0b1)
    0
    >>> pifacecommon.core.get_bit_num(0b11000)
    3
    """
    if bit_pattern == 0:
        return None

    bit_num = 0  # assume bit 0
    while (bit_pattern & 1) == 0:
        bit_pattern = bit_pattern >> 1
        bit_num += 1
        if bit_num > 7:
            bit_num = 0
            break

    return bit_num


Instruction:
Implement a function in Python 3 to
wait for a port event.

Response:
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 chip: The chip we are waiting for interrupts on.
    :type chip: :class:`pifacecommon.mcp23s17.MCP23S17`
    :param pin_function_maps: A list of classes that have inheritted from
        :class:`FunctionMap`\ s describing what to do with events.
    :type pin_function_maps: list
    :param event_queue: A queue to put events on.
    :type event_queue: :py:class:`multiprocessing.Queue`
    """
    # set up epoll
    gpio25 = open(GPIO_INTERRUPT_DEVICE_VALUE, 'r')  # change to use 'with'?
    epoll = select.epoll()
    epoll.register(gpio25, select.EPOLLIN | select.EPOLLET)

    while True:
        # wait here until input
        try:
            events = epoll.poll()
        except KeyboardInterrupt as e:
            if return_after_kbdint:
                return
            else:
                raise e
        except IOError as e:
            # ignore "Interrupted system call" error.
            # I don't really like this solution. Ignoring problems is bad!
            if e.errno != errno.EINTR:
                raise

        # find out where the interrupt came from and put it on the event queue
        if port == pifacecommon.mcp23s17.GPIOA:
            interrupt_flag = chip.intfa.value
        else:
            interrupt_flag = chip.intfb.value

        if interrupt_flag == 0:
            continue  # The interrupt has not been flagged on this board
        else:
            if port == pifacecommon.mcp23s17.GPIOA:
                interrupt_capture = chip.intcapa.value
            else:
                interrupt_capture = chip.intcapb.value
            event_queue.add_event(InterruptEvent(
                interrupt_flag, interrupt_capture, chip, time.time()))

    epoll.close()


Instruction:
Write a Python 3 script to
wait for events on the event queue and calls the registered functions.

Response:
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 events.
    :type function_maps: list
    :param event_queue: A queue to put events on.
    :type event_queue: :py:class:`multiprocessing.Queue`
    :param event_matches_function_map: A function that determines if the given
        event and :class:`FunctionMap` match.
    :type event_matches_function_map: function
    :param terminate_signal: The signal that, when placed on the event queue,
        causes this function to exit.
    """
    while True:
        # print("HANDLE: Waiting for events!")
        event = event_queue.get()
        # print("HANDLE: It's an event!")
        if event == terminate_signal:
            return
        # if matching get the callback function, else function is None
        functions = map(
            lambda fm: fm.callback
            if event_matches_function_map(event, fm) else None,
            function_maps)
        # reduce to just the callback functions (remove None)
        # TODO: I think this can just be filter(None, functions)
        functions = filter(lambda f: f is not None, functions)

        for function in functions:
            function(event)


Instruction:
Can you tell what is the following Python 3 function doing
def bring_gpio_interrupt_into_userspace():  # activate gpio interrupt
    try:
        # is it already there?
        with open(GPIO_INTERRUPT_DEVICE_VALUE):
            return
    except IOError:
        # no, bring it into userspace
        with open(GPIO_EXPORT_FILE, 'w') as export_file:
            export_file.write(str(GPIO_INTERRUPT_PIN))

        wait_until_file_exists(GPIO_INTERRUPT_DEVICE_VALUE)

Response: Bring the interrupt pin on the GPIO into Linux userspace.


Instruction:
How would you explain what the following Python 3 function does
def set_gpio_interrupt_edge(edge='falling'):
    # we're only interested in the falling edge (1 -> 0)
    start_time = time.time()
    time_limit = start_time + FILE_IO_TIMEOUT
    while time.time() < time_limit:
        try:
            with open(GPIO_INTERRUPT_DEVICE_EDGE, 'w') as gpio_edge:
                gpio_edge.write(edge)
                return
        except IOError:
            pass

Response: Set the interrupt edge on the userspace GPIO pin.


Instruction:
Explain what the following Python 3 code does
def wait_until_file_exists(filename):
    start_time = time.time()
    time_limit = start_time + FILE_IO_TIMEOUT
    while time.time() < time_limit:
        try:
            with open(filename):
                return
        except IOError:
            pass

    raise Timeout("Waiting too long for %s." % filename)

Response: Wait until a file exists.


Instruction:
Can you implement a function in Python 3 that
adds an event to the event queue.

Response:
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
        for pin_function_map in self.pin_function_maps:
            if _event_matches_pin_function_map(event, pin_function_map):
            # if pin_function_map.pin_num == event.pin_num and (
            #         pin_function_map.direction == event.direction or
            #         pin_function_map.direction == IODIR_BOTH):
                pin_settle_time = pin_function_map.settle_time
                # print("EventQueue: Found event in map.")
                break
        else:
            # Couldn't find event in map, don't bother adding it to the queue
            # print("EventQueue: Couldn't find event in map:")
            # for pin_function_map in self.pin_function_maps:
            #     print(pin_function_map)
            return

        threshold_time = self.last_event_time[event.pin_num] + pin_settle_time
        if event.timestamp > threshold_time:
            self.put(event)
            self.last_event_time[event.pin_num] = event.timestamp


Instruction:
Implement a Python 3 function for
registering a pin number and direction to a callback function.

Response:
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/IODIR_OFF/IODIR_BOTH)
        :type direction: int
        :param callback: The function to run when event is detected.
        :type callback: function
        :param settle_time: Time within which subsequent events are ignored.
        :type settle_time: int
        """
        self.pin_function_maps.append(
            PinFunctionMap(pin_num, direction, callback, settle_time))


Instruction:
Here you have a function in Python 3, explain what it does
def deregister(self, pin_num=None, direction=None):
        to_delete = []
        for i, function_map in enumerate(self.pin_function_maps):
            if ( pin_num == None
                 or ( function_map.pin_num == pin_num
                      and ( direction == None
                            or function_map.direction == direction ) ) ):
                to_delete.append(i)
        for i in reversed(to_delete):
            del self.pin_function_maps[i]

Response:
De - registers callback functions
       .


Instruction:
Can you generate a brief explanation for the following Python 3 code
def deactivate(self):
        self.event_queue.put(self.TERMINATE_SIGNAL)
        self.dispatcher.join()
        self.detector.terminate()
        self.detector.join()

Response: When the port event listener is deactivated the event dispatcher and detector are terminated.


Instruction:
Can you generate the documentation for the following Python 3 function
def spisend(self, bytes_to_send):
        # make some buffer space to store reading/writing
        wbuffer = ctypes.create_string_buffer(bytes_to_send,
                                              len(bytes_to_send))
        rbuffer = ctypes.create_string_buffer(len(bytes_to_send))

        # create the spi transfer struct
        transfer = spi_ioc_transfer(
            tx_buf=ctypes.addressof(wbuffer),
            rx_buf=ctypes.addressof(rbuffer),
            len=ctypes.sizeof(wbuffer),
            speed_hz=ctypes.c_uint32(self.speed_hz)
        )

        if self.spi_callback is not None:
            self.spi_callback(bytes_to_send)
        # send the spi command
        ioctl(self.fd, SPI_IOC_MESSAGE(1), transfer)
        return ctypes.string_at(rbuffer, ctypes.sizeof(rbuffer))

Response: Sends a number of bytes to the SPI bus.


Instruction:
Make a summary of the following Python 3 code
def render(self, form, form_style, context, template_pack=TEMPLATE_PACK):
        links, content = '', ''

        # accordion group needs the parent div id to set `data-parent` (I don't
        # know why). This needs to be a unique id
        if not self.css_id:
            self.css_id = "-".join(["tabsholder",
                                    text_type(randint(1000, 9999))])

        for tab in self.fields:
            tab.active = False

        # Activate item
        self.open_target_group_for_form(form)

        for tab in self.fields:
            content += render_field(
                tab, form, form_style, context, template_pack=template_pack
            )
            links += tab.render_link(form, template_pack)

        context.update({
            'tabs': self,
            'links': links,
            'content': content
        })

        template = self.get_template_name(template_pack)
        return render_to_string(template, context.flatten())

Response: Render the items of the current item.


Instruction:
Implement a function in Python 3 to
return True if the given form has any errors.

Response:
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])


Instruction:
How would you explain what the following Python 3 function does
def render_link(self, form, template_pack=TEMPLATE_PACK, **kwargs):
        link_template = self.link_template % template_pack
        return render_to_string(link_template,
                                {
                                    'link': self,
                                    'item_has_errors': self.has_errors(form)
                                })

Response: Render the link for the tab - pane.


Instruction:
Given the following Python 3 function, write the documentation
def _extract_version(package_name):
    try:
        return pkg_resources.get_distribution(package_name).version
    except pkg_resources.DistributionNotFound:
        _conf = read_configuration(os.path.join(PROJECT_DIR, "setup.cfg"))
    return _conf["metadata"]["version"]

Response: Get package version from installed distribution or configuration file.


Instruction:
How would you explain what the following Python 3 function does
def get_form_kwargs(self):
        kwargs = super(FormContainersMixin, self).get_form_kwargs()
        kwargs.update({
            'pack': "foundation-{}".format(self.kwargs.get('foundation_version'))
        })
        return kwargs

Response:
Pass template pack argument
            = nationale - version


Instruction:
Can you tell what is the following Python 3 function doing
def _check_status(cls, response_json):
        status = response_json['status']
        msg = response_json['msg']

        if status == 400:
            raise BadRequestException(msg)
        elif status == 403:
            raise PermissionDeniedException(msg)
        elif status == 404:
            raise FileNotFoundException(msg)
        elif status == 451:
            raise UnavailableForLegalReasonsException(msg)
        elif status == 509:
            raise BandwidthUsageExceeded(msg)
        elif status >= 500:
            raise ServerErrorException(msg)

Response: Check the status of the incoming response and raise exception if it is not 200.


Instruction:
Make a summary of the following Python 3 code
def _get(self, url, params=None):
        if not params:
            params = {}

        params.update({'login': self.login, 'key': self.key})

        response_json = requests.get(self.api_url + url, params).json()

        return self._process_response(response_json)

Response: Used by every other method it makes a GET request with the given params.


Instruction:
Implement a Python 3 function for
requesting 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. ticket (str): preparation ticket is found in prepare_download response,\ this is why we need to call prepare_download before get_download_link. captcha_response (:obj:`str`, optional): sometimes prepare_download will have captcha url to be solved, \ first, this is the solution of the captcha. Returns: dict: dictionary containing (file info, download url, ...). :: { "name": "The quick brown fox.txt", "size": 12345, "sha1": "2fd4e1c67a2d28fced849ee1bb76e7391b93eb12", "content_type": "plain/text", "upload_at": "2011-01-26 13:33:37", "url": "https://abvzps.example.com/dl/l/4spxX_-cSO4/The+quick+brown+fox.txt", "token": "4spxX_-cSO4" }

Response:
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.

            ticket (str): preparation ticket is found in prepare_download response,\
                          this is why we need to call prepare_download before get_download_link.

            captcha_response (:obj:`str`, optional): sometimes prepare_download will have captcha url to be solved, \
                                                     first, this is the solution of the captcha.

        Returns:
            dict: dictionary containing (file info, download url, ...). ::

                  {
                    "name": "The quick brown fox.txt",
                    "size": 12345,
                    "sha1": "2fd4e1c67a2d28fced849ee1bb76e7391b93eb12",
                    "content_type": "plain/text",
                    "upload_at": "2011-01-26 13:33:37",
                    "url": "https://abvzps.example.com/dl/l/4spxX_-cSO4/The+quick+brown+fox.txt",
                    "token": "4spxX_-cSO4"
                  }

        """
        params = {'ticket': ticket, 'file': file_id}

        if captcha_response:
            params['captcha_response'] = captcha_response

        return self._get('file/dl', params)


Instruction:
Create a Python 3 function to
make a request to prepare for file upload.

Response:
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.
            sha1 (:obj:`str`, optional): expected sha1 If sha1 of uploaded file doesn't match this value, upload fails.
            httponly (:obj:`bool`, optional): If this is set to true, use only http upload links.

        Returns:
            dict: dictionary containing (url: will be used in actual upload, valid_until). ::

                {
                    "url": "https://1fiafqj.oloadcdn.net/uls/nZ8H3X9e0AotInbU",
                    "valid_until": "2017-08-19 19:06:46"
                }

        """

        kwargs = {'folder': folder_id, 'sha1': sha1, 'httponly': httponly}
        params = {key: value for key, value in kwargs.items() if value}
        return self._get('file/ul', params=params)


Instruction:
Here you have a function in Python 3, explain what it does
def upload_file(self, file_path, folder_id=None, sha1=None, httponly=False):

        upload_url_response_json = self.upload_link(folder_id=folder_id, sha1=sha1, httponly=httponly)
        upload_url = upload_url_response_json['url']

        with open(file_path, 'rb') as f:
            response_json = requests.post(upload_url, files={'upload_file': f}).json()

        self._check_status(response_json)
        return response_json['result']

Response: Uploads a file to the Knw.


Instruction:
Given the following Python 3 function, write the documentation
def remote_upload(self, remote_url, folder_id=None, headers=None):

        kwargs = {'folder': folder_id, 'headers': headers}
        params = {'url': remote_url}
        params.update({key: value for key, value in kwargs.items() if value})

        return self._get('remotedl/add', params=params)

Response: Used to make a remote file upload to openload. co


Instruction:
Write a Python 3 script to
check a remote file upload to status.

Response:
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:
            dict: dictionary containing all remote uploads, each dictionary element is a dictionary. ::

                {
                    "24": {
                      "id": "24",
                      "remoteurl": "http://proof.ovh.net/files/100Mio.dat",
                      "status": "new",
                      "folderid": "4248",
                      "added": "2015-02-21 09:20:26",
                      "last_update": "2015-02-21 09:20:26",
                      "extid": False,
                      "url": False
                    },
                    "22": {
                      "id": "22",
                      "remoteurl": "http://proof.ovh.net/files/1Gio.dat",
                      "status": "downloading",
                      "bytes_loaded": "823997062",
                      "bytes_total": "1073741824",
                      "folderid": "4248",
                      "added": "2015-02-21 09:20:26",
                      "last_update": "2015-02-21 09:21:56",
                      "extid": False,
                      "url": False
                    },
                    ...
                }

        """

        kwargs = {'limit': limit, 'id': remote_upload_id}
        params = {key: value for key, value in kwargs.items() if value}

        return self._get('remotedl/status', params=params)


Instruction:
How would you code a function in Python 3 to
request a list of files and folders in specified folder.

Response:
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:
            dict: dictionary containing only two keys ("folders", "files"), \
                  each key represents a list of dictionaries. ::

                      {
                        "folders": [
                          {
                            "id": "5144",
                            "name": ".videothumb"
                          },
                          {
                            "id": "5792",
                            "name": ".subtitles"
                          },
                          ...
                        ],
                        "files": [
                          {
                            "name": "big_buck_bunny.mp4.mp4",
                            "sha1": "c6531f5ce9669d6547023d92aea4805b7c45d133",
                            "folderid": "4258",
                            "upload_at": "1419791256",
                            "status": "active",
                            "size": "5114011",
                            "content_type": "video/mp4",
                            "download_count": "48",
                            "cstatus": "ok",
                            "link": "https://openload.co/f/UPPjeAk--30/big_buck_bunny.mp4.mp4",
                            "linkextid": "UPPjeAk--30"
                          },
                          ...
                        ]
                      }

        """
        params = {'folder': folder_id} if folder_id else {}

        return self._get('file/listfolder', params=params)


Instruction:
Write a Python 3 function that can
show running file converts by folder_id

Response:
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:
            list: list of dictionaries, each dictionary represents a file conversion info. ::

                      [
                        {
                          "name": "Geysir.AVI",
                          "id": "3565411",
                          "status": "pending",
                          "last_update": "2015-08-23 19:41:40",
                          "progress": 0.32,
                          "retries": "0",
                          "link": "https://openload.co/f/f02JFG293J8/Geysir.AVI",
                          "linkextid": "f02JFG293J8"
                        },
                        ....
                      ]

        """
        params = {'folder': folder_id} if folder_id else {}
        return self._get('file/runningconverts', params=params)


Instruction:
Given the following Python 3 function, write the documentation
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 + 10.14333127 * hum - 0.22475541 * \
               temp * hum - 6.83783 * (10 ** -3) * (temp ** 2) - 5.481717 * \
               (10 ** -2) * (hum ** 2) + 1.22874 * (10 ** -3) * (temp ** 2) * \
               hum + 8.5282 * (10 ** -4) * temp * (hum ** 2) - 1.99 * \
               (10 ** -6) * (temp ** 2) * (hum ** 2);

Response: Calculates the heat index based upon temperature and humidity.


Instruction:
Write a Python 3 script to
calculate the wind chill value based upon the temperature F and windspeed and windspeed10min returns the wind chill in degrees F.

Response:
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);


Instruction:
Can you tell what is the following Python 3 function doing
def calc_humidity(temp, dewpoint):
    '''
    calculates the humidity via the formula from weatherwise.org
    return the relative humidity
    '''

    t = fahrenheit_to_celsius(temp)
    td = fahrenheit_to_celsius(dewpoint)

    num = 112 - (0.1 * t) + td
    denom = 112 + (0.9 * t)

    rh = math.pow((num / denom), 8)

    return rh

Response:
Calculates the humidity via the formula from weatherwise. org
    return the relative humidity


Instruction:
How would you code a function in Python 3 to
calculate the dewpoint via the formula from weatherwise. org return the dewpoint in degrees F.

Response:
def calc_dewpoint(temp, hum):
    '''
    calculates the dewpoint via the formula from weatherwise.org
    return the dewpoint in degrees F.
    '''

    c = fahrenheit_to_celsius(temp)
    x = 1 - 0.01 * hum;

    dewpoint = (14.55 + 0.114 * c) * x;
    dewpoint = dewpoint + ((2.5 + 0.007 * c) * x) ** 3;
    dewpoint = dewpoint + (15.9 + 0.117 * c) * x ** 14;
    dewpoint = c - dewpoint;

    return celsius_to_fahrenheit(dewpoint)


Instruction:
Write a Python 3 script to
perform HTTP session to transmit defined weather values.

Response:
def publish(self):
      '''
      Perform HTTP session to transmit defined weather values.
      '''
      return self._publish( self.args, self.server, self.URI)


Instruction:
Explain what the following Python 3 code does
def get(data):
        '''
        return CRC calc value from raw serial data
        '''
        crc = 0
        for byte in array('B', data):
            crc = (VProCRC.CRC_TABLE[(crc >> 8) ^ byte] ^ ((crc & 0xFF) << 8))
        return crc

Response: get the CRC value from raw serial data


Instruction:
How would you explain what the following Python 3 function does
def verify(data):
        '''
        perform CRC check on raw serial data, return true if valid.
        a valid CRC == 0.
        '''
        if len(data) == 0:
            return False
        crc = VProCRC.get(data)
        if crc:
            log.info("CRC Bad")
        else:
            log.debug("CRC OK")
        return not crc

Response: Verify that the data is valid for a specific object.


Instruction:
Write a Python 3 function that can
give a packed storm date field unpack and return YYYY - MM - DD string.

Response:
def _unpack_storm_date(date):
        '''
        given a packed storm date field, unpack and return 'YYYY-MM-DD' string.
        '''
        year = (date & 0x7f) + 2000  # 7 bits
        day = (date >> 7) & 0x01f  # 5 bits
        month = (date >> 12) & 0x0f  # 4 bits
        return "%s-%s-%s" % (year, month, day)


Instruction:
Write a Python 3 function for
returning True if we re using Rev. B archives otherwise False.

Response:
def _use_rev_b_archive(self, records, offset):
        '''
        return True if weather station returns Rev.B archives
        '''
        # if pre-determined, return result
        if type(self._ARCHIVE_REV_B) is bool:
            return self._ARCHIVE_REV_B
        # assume, B and check 'RecType' field
        data = ArchiveBStruct.unpack_from(records, offset)
        if data['RecType'] == 0:
            log.info('detected archive rev. B')
            self._ARCHIVE_REV_B = True
        else:
            log.info('detected archive rev. A')
            self._ARCHIVE_REV_B = False

        return self._ARCHIVE_REV_B


Instruction:
Given the following Python 3 function, write the documentation
def _wakeup(self):
        '''
        issue wakeup command to device to take out of standby mode.
        '''
        log.info("send: WAKEUP")
        for i in xrange(3):
            self.port.write('\n')  # wakeup device
            ack = self.port.read(len(self.WAKE_ACK))  # read wakeup string
            log_raw('read', ack)
            if ack == self.WAKE_ACK:
                return
        raise NoDeviceException('Can not access weather station')

Response: wakeup device to device to take out of standby mode.


Instruction:
Can you tell what is the following Python 3 function doing
def _cmd(self, cmd, *args, **kw):
        '''
        write a single command, with variable number of arguments. after the
        command, the device must return ACK
        '''
        ok = kw.setdefault('ok', False)

        self._wakeup()
        if args:
            cmd = "%s %s" % (cmd, ' '.join(str(a) for a in args))
        for i in xrange(3):
            log.info("send: " + cmd)
            self.port.write(cmd + '\n')
            if ok:
                ack = self.port.read(len(self.OK))  # read OK
                log_raw('read', ack)
                if ack == self.OK:
                    return
            else:
                ack = self.port.read(len(self.ACK))  # read ACK
                log_raw('read', ack)
                if ack == self.ACK:
                    return
        raise NoDeviceException('Can not access weather station')

Response: write a single command with variable number of arguments. after the command the device must return ACK


Instruction:
Write a Python 3 script to
read a raw string containing data read from the device provided in / dev / XXX format. all reads are non - blocking.

Response:
def _loop_cmd(self):
        '''
        reads a raw string containing data read from the device
        provided (in /dev/XXX) format. all reads are non-blocking.
        '''
        self._cmd('LOOP', 1)
        raw = self.port.read(LoopStruct.size)  # read data
        log_raw('read', raw)
        return raw


Instruction:
How would you code a function in Python 3 to
issue a DMPAFT command to read the archive records after a known time stamp.

Response:
def _dmpaft_cmd(self, time_fields):
        '''
        issue a command to read the archive records after a known time stamp.
        '''
        records = []
        # convert time stamp fields to buffer
        tbuf = struct.pack('2H', *time_fields)

        # 1. send 'DMPAFT' cmd
        self._cmd('DMPAFT')

        # 2. send time stamp + crc
        crc = VProCRC.get(tbuf)
        crc = struct.pack('>H', crc)  # crc in big-endian format
        log_raw('send', tbuf + crc)
        self.port.write(tbuf + crc)  # send time stamp + crc
        ack = self.port.read(len(self.ACK))  # read ACK
        log_raw('read', ack)
        if ack != self.ACK: return  # if bad ack, return

        # 3. read pre-amble data
        raw = self.port.read(DmpStruct.size)
        log_raw('read', raw)
        if not VProCRC.verify(raw):  # check CRC value
            log_raw('send ESC', self.ESC)
            self.port.write(self.ESC)  # if bad, escape and abort
            return
        log_raw('send ACK', self.ACK)
        self.port.write(self.ACK)  # send ACK

        # 4. loop through all page records
        dmp = DmpStruct.unpack(raw)
        log.info('reading %d pages, start offset %d' %
                 (dmp['Pages'], dmp['Offset']))
        for i in xrange(dmp['Pages']):
            # 5. read page data
            raw = self.port.read(DmpPageStruct.size)
            log_raw('read', raw)
            if not VProCRC.verify(raw):  # check CRC value
                log_raw('send ESC', self.ESC)
                self.port.write(self.ESC)  # if bad, escape and abort
                return
            log_raw('send ACK', self.ACK)
            self.port.write(self.ACK)  # send ACK

            # 6. loop through archive records
            page = DmpPageStruct.unpack(raw)
            offset = 0  # assume offset at 0
            if i == 0:
                offset = dmp['Offset'] * ArchiveAStruct.size
            while offset < ArchiveAStruct.size * 5:
                log.info('page %d, reading record at offset %d' %
                         (page['Index'], offset))
                if self._use_rev_b_archive(page['Records'], offset):
                    a = ArchiveBStruct.unpack_from(page['Records'], offset)
                else:
                    a = ArchiveAStruct.unpack_from(page['Records'], offset)
                # 7. verify that record has valid data, and store
                if a['DateStamp'] != 0xffff and a['TimeStamp'] != 0xffff:
                    records.append(a)
                offset += ArchiveAStruct.size
        log.info('read all pages')
        return records


Instruction:
How would you code a function in Python 3 to
return a dictionary of fields from the newest archive record in the device. return None when no records are new.

Response:
def _get_new_archive_fields(self):
        '''
        returns a dictionary of fields from the newest archive record in the
        device. return None when no records are new.
        '''
        for i in xrange(3):
            records = self._dmpaft_cmd(self._archive_time)
            if records is not None: break
            time.sleep(1)

        if records is None:
            raise NoDeviceException('Can not access weather station')

        # find the newest record
        new_rec = None
        for r in records:
            new_time = (r['DateStamp'], r['TimeStamp'])
            if self._archive_time < new_time:
                self._archive_time = new_time
                new_rec = r

        return new_rec


Instruction:
Here you have a function in Python 3, explain what it does
def _calc_derived_fields(self, fields):
        '''
        calculates the derived fields (those fields that are calculated)
        '''
        # convenience variables for the calculations below
        temp = fields['TempOut']
        hum = fields['HumOut']
        wind = fields['WindSpeed']
        wind10min = fields['WindSpeed10Min']
        fields['HeatIndex'] = calc_heat_index(temp, hum)
        fields['WindChill'] = calc_wind_chill(temp, wind, wind10min)
        fields['DewPoint'] = calc_dewpoint(temp, hum)
        # store current data string
        now = time.localtime()
        fields['DateStamp'] = time.strftime("%Y-%m-%d %H:%M:%S", now)
        fields['Year'] = now[0]
        fields['Month'] = str(now[1]).zfill(2)
        now = time.gmtime()
        fields['DateStampUtc'] = time.strftime("%Y-%m-%d %H:%M:%S", now)
        fields['YearUtc'] = now[0]
        fields['MonthUtc'] = str(now[1]).zfill(2)

Response: Calculates the derived fields of the current log entry.


Instruction:
How would you code a function in Python 3 to
read and parse a set of data read from the console and set the fields variable to the values in the dict that are available in the fields variable.

Response:
def parse(self):
        '''
        read and parse a set of data read from the console.  after the
        data is parsed it is available in the fields variable.
        '''
        fields = self._get_loop_fields()
        fields['Archive'] = self._get_new_archive_fields()

        self._calc_derived_fields(fields)

        # set the fields variable the the values in the dict
        self.fields = fields


Instruction:
How would you code a function in Python 3 to
unpack data from buf and returns a dication of named fields.

Response:
def unpack_from(self, buf, offset=0 ):
        '''
        unpacks data from 'buf' and returns a dication of named fields. the
        fields can be post-processed by extending the _post_unpack() method.
        '''
        data = super(Struct,self).unpack_from( buf, offset)
        items = dict(zip(self.fields,data))
        return self._post_unpack(items)


Instruction:
Write a Python 3 script to
get publication services from options

Response:
def get_pub_services(opts):
   '''
   use values in opts data to generate instances of publication services.
   '''
   sites = []
   for p_key in vars(opts).keys():
      args = getattr(opts,p_key)
      if p_key in PUB_SERVICES and args:
         if isinstance(args,tuple):
            ps = PUB_SERVICES[p_key](*args)
         else:
            ps = PUB_SERVICES[p_key](args)
         sites.append( ps )
   return sites


Instruction:
Can you generate the documentation for the following Python 3 function
def get_options(parser):
   '''
   read command line options to configure program behavior.
   '''
   # station services
   # publication services
   pub_g = optparse.OptionGroup( parser, "Publication Services",
         '''One or more publication service must be specified to enable upload
         of weather data.''', )
   pub_g.add_option('-w', '--wundergound', nargs=2, type='string', dest='wug',
         help='Weather Underground service; WUG=[SID(station ID), PASSWORD]')
   pub_g.add_option('-p', '--pws', nargs=2, type='string', dest='pws',
         help='PWS service; PWS=[SID(station ID), PASSWORD]')
   pub_g.add_option('-f', '--file', nargs=1, type='string', dest='file',
         help='Local file; FILE=[FILE_NAME]')
   parser.add_option_group(pub_g)

   parser.add_option('-d', '--debug', dest='debug', action="store_true",
         default=False, help='enable verbose debug logging')
   parser.add_option('-q', '--quiet', dest='quiet', action="store_true",
         default=False, help='disable all console logging')
   parser.add_option('-t', '--tty', dest='tty', default='/dev/ttyS0',
         help='set serial port device [/dev/ttyS0]')
   parser.add_option('-n', '--interval', dest='interval', default=60,
         type='int', help='polling/update interval in seconds [60]')
   return parser.parse_args()

Response: get command line options


Instruction:
Create a Python 3 function for
getting the gust value of the given station and interval

Response:
def get( self, station, interval ):
      '''
      return gust data, if above threshold value and current time is inside
      reporting window period
      '''
      rec = station.fields['Archive']
      # process new data
      if rec:
         threshold = station.fields['WindSpeed10Min'] + GUST_MPH_MIN
         if rec['WindHi'] >= threshold:
            self.value = (rec['WindHi'],rec['WindHiDir'])
            self.count = GUST_TTL * 60 / interval
         else:
            self.value = self.NO_VALUE

      # return gust value, if remaining time is left, and valid
      if self.count:
         self.count -= 1
      else:
         self.value = self.NO_VALUE

      log.debug('wind gust of {0} mph from {1}'.format(*self.value))
      return self.value


Instruction:
Can you generate the documentation for the following Python 3 function
def set( self, pressure='NA', dewpoint='NA', humidity='NA', tempf='NA',
            rainin='NA', rainday='NA', dateutc='NA', windgust='NA',
            windgustdir='NA', windspeed='NA', winddir='NA',
            clouds='NA', weather='NA', *args, **kw):
        '''
        Useful for defining weather data published to the server. Parameters
        not set will be reset and not sent to server. Unknown keyword args will
        be silently ignored, so be careful. This is necessary for publishers
        that support more fields than others.
        '''
        # see: http://wiki.wunderground.com/index.php/PWS_-_Upload_Protocol
        # unused, but valid, parameters are:
        #   windspdmph_avg2m, winddir_avg2m, windgustmph_10m, windgusdir_10m
        #   soiltempf, soilmoisture, leafwetness, solarradiation, UV
        #   indoortempf, indoorhumidity
        self.args.update( {
                'baromin':pressure,
                'clouds':clouds,
                'dailyrainin':rainday,
                'dateutc':dateutc,
                'dewptf':dewpoint,
                'humidity':humidity,
                'rainin':rainin,
                'tempf':tempf,
                'weather':weather,
                'winddir':winddir,
                'windgustdir':windgustdir,
                'windgustmph':windgust,
                'windspeedmph':windspeed,
            } )
        log.debug( self.args )

Response: Sets the parameters of the object to the values in the passed in parameters.


Instruction:
Can you tell what is the following Python 3 function doing
def set( self, **kw):
      '''
      Store keyword args to be written to output file.
      '''
      self.args = kw
      log.debug( self.args )

Response: Store keyword args to be written to output file.


Instruction:
Can you write a function in Python 3 where it
publishes the input file.

Response:
def publish(self):
      '''
      Write output file.
      '''
      with open( self.file_name, 'w') as fh:
         for k,v in self.args.iteritems():
            buf = StringIO.StringIO()
            buf.write(k)
            self._append_vals(buf,v)
            fh.write(buf.getvalue() + '\n')
            buf.close()


Instruction:
Explain what the following Python 3 code does
def requires(*requirements, **opts):

    identity = opts.get("identity")
    on_fail = opts.get("on_fail")
    throws = opts.get("throws")

    def decorator(f):
        @wraps(f)
        def allower(*args, **kwargs):

            result = allows.run(
                requirements,
                identity=identity,
                on_fail=on_fail,
                throws=throws,
                f_args=args,
                f_kwargs=kwargs,
            )

            # authorization failed
            if result is not None:
                return result

            return f(*args, **kwargs)

        return allower

    return decorator

Response: Decorator to apply requirements to routes or class based views.


Instruction:
Make a summary of the following Python 3 code
def guard_entire(requirements, identity=None, throws=None, on_fail=None):

    def guarder():
        if _should_run_requirements():
            return allows.run(
                requirements,
                identity=identity,
                on_fail=on_fail,
                throws=throws,
                f_kwargs=request.view_args,
            )
        return None

    return guarder

Response: This function guards an entire blueprint with a set of requirements.


Instruction:
How would you explain what the following Python 3 function does
def wants_request(f):

    @wraps(f)
    def wrapper(user):
        return f(user, request)

    return wrapper

Response: Decorator for allowing a user to transition to user - only requirements.


Instruction:
Create a Python 3 function to
return a new combinator that uses the given set of requirements to reduce the result of the first False.

Response:
def And(cls, *requirements):
        """
        Short cut helper to construct a combinator that uses
        :meth:`operator.and_` to reduce requirement results and stops
        evaluating on the first False.

        This is also exported at the module level as ``And``
        """
        return cls(*requirements, op=operator.and_, until=False)


Instruction:
Can you generate the documentation for the following Python 3 function
def Or(cls, *requirements):
        return cls(*requirements, op=operator.or_, until=True)

Response: Return a combinator that uses the given set of requirements to reduce the result of evaluating the first True entry in the set.


Instruction:
Create a Python 3 function for
initializing the Flask - Allow object against the provided application.

Response:
def init_app(self, app):
        """
        Initializes the Flask-Allows object against the provided application
        """
        if not hasattr(app, "extensions"):  # pragma: no cover
            app.extensions = {}
        app.extensions["allows"] = self

        @app.before_request
        def start_context(*a, **k):
            self.overrides.push(Override())
            self.additional.push(Additional())

        @app.after_request
        def cleanup(response):
            self.clear_all_overrides()
            self.clear_all_additional()
            return response


Instruction:
Can you tell what is the following Python 3 function doing
def fulfill(self, requirements, identity=None):
        identity = identity or self._identity_loader()

        if self.additional.current:
            all_requirements = chain(iter(self.additional.current), requirements)
        else:
            all_requirements = iter(requirements)

        if self.overrides.current is not None:
            all_requirements = (
                r for r in all_requirements if r not in self.overrides.current
            )

        return all(_call_requirement(r, identity, request) for r in all_requirements)

Response:
Checks that the provided identity meets each requirement
           .


Instruction:
Write a Python 3 script to
add an override to the current context.

Response:
def push(self, override, use_parent=False):
        """
        Binds an override to the current context, optionally use the
        current overrides in conjunction with this override

        If ``use_parent`` is true, a new override is created from the
        parent and child overrides rather than manipulating either
        directly.
        """
        current = self.current
        if use_parent and current:
            override = current + override

        _override_ctx_stack.push((self, override))


Instruction:
Make a summary of the following Python 3 code
def pop(self):
        rv = _override_ctx_stack.pop()
        if rv is None or rv[0] is not self:
            raise RuntimeError(
                "popped wrong override context ({} instead of {})".format(rv, self)
            )

Response: Pops the latest override context from the stack.


Instruction:
How would you code a function in Python 3 to
allow temporarily pushing an override context, yields the new context into the following block.

Response:
def override(self, override, use_parent=False):
        """
        Allows temporarily pushing an override context, yields the new context
        into the following block.
        """
        self.push(override, use_parent)
        yield self.current
        self.pop()


Instruction:
Can you implement a function in Python 3 that
adds an additional context to the current context.

Response:
def push(self, additional, use_parent=False):
        """
        Binds an additional to the current context, optionally use the
        current additionals in conjunction with this additional

        If ``use_parent`` is true, a new additional is created from the
        parent and child additionals rather than manipulating either
        directly.
        """
        current = self.current
        if use_parent and current:
            additional = current + additional

        _additional_ctx_stack.push((self, additional))


Instruction:
Explain what the following Python 3 code does
def pop(self):
        rv = _additional_ctx_stack.pop()
        if rv is None or rv[0] is not self:
            raise RuntimeError(
                "popped wrong additional context ({} instead of {})".format(rv, self)
            )

Response: Pops the latest additional context from the stack.


Instruction:
Implement a function in Python 3 to
allow temporarily pushing an additional context, yields the new context into the following block.

Response:
def additional(self, additional, use_parent=False):
        """
        Allows temporarily pushing an additional context, yields the new context
        into the following block.
        """
        self.push(additional, use_parent)
        yield self.current
        self.pop()


Instruction:
How would you code a function in Python 3 to
append a number to duplicate field names to make them unique.

Response:
def unduplicate_field_names(field_names):
    """Append a number to duplicate field names to make them unique. """
    res = []
    for k in field_names:
        if k in res:
            i = 1
            while k + '_' + str(i) in res:
                i += 1
            k += '_' + str(i)
        res.append(k)
    return res


Instruction:
How would you explain what the following Python 3 function does
def interpret_stats(results):
    stats = results.stats
    contains_updates = stats.pop("contains_updates", False) if stats else False
    if not contains_updates:
        result = '{} rows affected.'.format(len(results))
    else:
        result = ''
        for stat, value in stats.items():
            if value:
                result = "{}\n{} {}.".format(result, value,
                                             stat.replace("_", " "))
    return result.strip()

Response:
Generates the string to be shown as updates after the execution of a
                   .


Instruction:
Here you have a function in Python 3, explain what it does
def extract_params_from_query(query, user_ns):
    # TODO: Optmize this function
    params = {}
    for k, v in user_ns.items():
        try:
            json.dumps(v)
            params[k] = v
        except:
            pass
    return params

Response: Extracts the parameters from a Cypher query


Instruction:
Can you implement a function in Python 3 that
executes a Cypher query and returns raw data a Pandas DataFrame or a NetworkX graph.

Response:
def run(query, params=None, config=None, conn=None, **kwargs):
    """Executes a query and depending on the options of the extensions will
    return raw data, a ``ResultSet``, a Pandas ``DataFrame`` or a
    NetworkX graph.

    :param query: string with the Cypher query
    :param params: dictionary with parameters for the query (default=``None``)
    :param config: Configurable or NamedTuple with extra IPython configuration
                   details. If ``None``, a new object will be created
                   (defaults=``None``)
    :param conn: connection dictionary or string for the Neo4j backend.
                 If ``None``, a new connection will be created
                 (default=``None``)
    :param **kwargs: Any of the cell configuration options.
    """
    if params is None:
        params = {}
    if conn is None:
        conn = Connection.get(DEFAULT_CONFIGURABLE["uri"])
    elif isinstance(conn, string_types):
        conn = Connection.get(conn)
    if config is None:
        default_config = DEFAULT_CONFIGURABLE.copy()
        kwargs.update(default_config)
        config = DefaultConfigurable(**kwargs)
    if query.strip():
        # TODO: Handle multiple queries
        params = extract_params_from_query(query, params)
        result = conn.session.query(query, params,
                                    data_contents=config.data_contents)
        if config.feedback:
            print(interpret_stats(result))
        resultset = ResultSet(result, query, config)
        if config.auto_pandas:
            return resultset.get_dataframe()
        elif config.auto_networkx:
            graph = resultset.get_graph()
            resultset.draw()
            return graph
        else:
            return resultset  # returning only last result, intentionally
    else:
        return 'Connected: %s' % conn.name


Instruction:
Explain what the following Python 3 code does
def get_dataframe(self):
        if pd is None:
            raise ImportError("Try installing Pandas first.")
        frame = pd.DataFrame(self[:], columns=(self and self.keys) or [])
        return frame

Response: Returns a Pandas DataFrame instance built from the result set.


Instruction:
Can you tell what is the following Python 3 function doing
def get_graph(self, directed=True):
        if nx is None:
            raise ImportError("Try installing NetworkX first.")
        if directed:
            graph = nx.MultiDiGraph()
        else:
            graph = nx.MultiGraph()
        for item in self._results.graph:
            for node in item['nodes']:
                properties = copy.deepcopy(node['properties'])
                properties['labels'] = node['labels']
                graph.add_node(node['id'], **properties)
            for rel in item['relationships']:
                properties = copy.deepcopy(rel['properties'])
                properties.update(
                    id=rel['id'],
                    type=rel['type']
                )
                graph.add_edge(rel['startNode'], rel['endNode'],
                               key=rel.get('type'), **properties)
        return graph

Response: Returns a NetworkX Multi - Graph instance built from the result set.


Instruction:
Write a Python 3 script to
draw a multi - graph instance of the current object.

Response:
def draw(self, directed=True, layout="spring",
             node_label_attr=None, show_node_labels=True,
             edge_label_attr=None, show_edge_labels=True,
             node_size=1600, node_color='blue', node_alpha=0.3,
             node_text_size=12,
             edge_color='blue', edge_alpha=0.3, edge_tickness=1,
             edge_text_pos=0.3,
             text_font='sans-serif', ax=None):
        """Plot of a NetworkX multi-graph instance

        :param directed: boolean, optional (default=`True`).
            Whether to return a directed graph or not.
        :param layout: string, optional (default=`"spring"`).
            Layout to apply. Any of the possible NetworkX layouts will work:
            ``'circular_layout'``, ``'random_layout'``, ``'shell_layout'``,
            ``'spring_layout'``, ``'spectral_layout'``,
            or ``'fruchterman_reingold_layout'``.
        :param node_label_attr: string, optional (default=`None`).
            Attribute of the nodes that has to be used as the label.
        :param show_node_labels: boolean, optional (default=`True`).
            Whether to show or not the labels of the nodes.
        :param edge_label_attr: boolean, optional (default=`None`).
            Attribute of the edges that has to be used as the label.
        :param show_edge_labels: . optional (default=`True`).
            Whether to show or not the labels of the edges.
        :param node_size: integer, optional (default=`1600`).
            Desired size for nodes.
        :param node_color: color string, or array of floats, (default=`'blue'`)
            Node color. Can be a single color format string, or a sequence of
            colors with the same length as nodelist. If numeric values are
            specified they will be mapped to colors using the ``cmap`` and
            ``vmin``, ``vmax`` parameters. See ``matplotlib.scatter`` for more
            details.
        :param node_alpha: float, optional (default=`0.3`).
            Between 0 and 1 for transparency of nodes.
        :param node_text_size: integer, optional (default=`12`).
            Size of the node text.
        :param edge_color: color string, or array of floats (default=`'blue'`)
            Edge color. Can be a single color format string, or a sequence of
            colors with the same length as edgelist. If numeric values are
            specified they will be mapped to colors using the ``edge_cmap`` and
            ``edge_vmin``, ``edge_vmax`` parameters.
        :param edge_alpha: float, optional (default=`0.3`)
            Transparency for thee edges.
        :param edge_tickness: float or integer, optional (default=`1`).
            Thickness of the lines drawn for the edges.
        :param edge_text_pos: . Default to optional (d0)=
        :param text_font: . Default to optional (default=`'sans-serif'`).
        :param ax: ``matplotlib.Figure``, optional (default=`None`).
            A ``matplotlib.Figure`` to use when rendering the graph. If `None`,
            a new object is created and returned.----

        :return: a ``matplotlib.Figure`` with the graph rendered.
        """
        graph = self.get_graph(directed=directed)
        pos = getattr(nx, "{}_layout".format(layout))(graph)
        node_labels = {}
        edge_labels = {}
        node_colors = set()
        if show_node_labels:
            for node, props in graph.nodes(data=True):
                labels = props.pop('labels', [])
                for label in labels:
                    node_colors.add(label)
                if node_label_attr is None:
                    node_labels[node] = "$:{}$\n{}".format(
                        ":".join(labels),
                        next(iter(props.values())) if props else "",
                    )
                else:
                    props_list = ["{}: {}".format(k, v)
                                  for k, v in props.items()]
                    node_labels[node] = "$:{}$\n{}".format(
                        ":".join(labels), "\n".join(props_list)
                    )
        node_color = []
        node_colors = list(node_colors)
        legend_colors = []
        colors = list(plt.matplotlib.colors.ColorConverter().cache.items())[2:]
        for _, color_rgb in colors[:len(node_colors)]:
            node_color.append(color_rgb)
            legend_colors.append(color_rgb)
        if show_edge_labels:
            for start, end, props in graph.edges(data=True):
                if edge_label_attr is None:
                    edge_label = props.get("type", '')
                else:
                    edge_label = props.get(edge_label_attr, '')
                edge_labels[(start, end)] = edge_label
        if not ax:
            fig = plt.figure()
            ax = fig.add_subplot(111)
        nodes = nx.draw_networkx_nodes(
            graph, pos=pos, node_color=node_color,
            node_size=node_size, alpha=node_alpha,
            ax=ax
        )
        nx.draw_networkx_labels(
            graph, pos=pos, labels=node_labels,
            font_size=node_text_size,
            font_family=text_font,
            ax=ax
        )
        nx.draw_networkx_edges(
            graph, pos=pos, width=edge_tickness,
            alpha=edge_alpha, edge_color=edge_color,
            ax=ax
        )
        nx.draw_networkx_edge_labels(
            graph, pos=pos, edge_labels=edge_labels,
            ax=ax
        )
        ax.legend([plt.Line2D([0], [0], linestyle="none", marker="o",
                              alpha=node_alpha,
                              markersize=10, markerfacecolor=color)
                  for color in legend_colors],
                  node_colors, loc=(-0.25, 1), numpoints=1, frameon=False)
        ax.set_axis_off()
        return graph, ax, nodes


Instruction:
Make a summary of the following Python 3 code
def pie(self, key_word_sep=" ", title=None, **kwargs):
        if not plt:
            raise ImportError("Try installing matplotlib first.")
        self.guess_pie_columns(xlabel_sep=key_word_sep)
        pie = plt.pie(self.ys[0], labels=self.xlabels, **kwargs)
        plt.title(title or self.ys[0].name)
        return pie

Response: Generates a pylab pie chart from the result set.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def plot(self, title=None, **kwargs):
        if not plt:
            raise ImportError("Try installing matplotlib first.")
        self.guess_plot_columns()
        self.x = self.x or range(len(self.ys[0]))
        coords = reduce(operator.add, [(self.x, y) for y in self.ys])
        plot = plt.plot(*coords, **kwargs)
        if hasattr(self.x, 'name'):
            plt.xlabel(self.x.name)
        ylabel = ", ".join(y.name for y in self.ys)
        plt.title(title or ylabel)
        plt.ylabel(ylabel)
        return plot

Response: Generates a pylab plot from the result set.


Instruction:
How would you implement a function in Python 3 that
generates a pylab bar plot from the result set.

Response:
def bar(self, key_word_sep=" ", title=None, **kwargs):
        """Generates a pylab bar plot from the result set.

        ``matplotlib`` must be installed, and in an
        IPython Notebook, inlining must be on::

            %%matplotlib inline

        The last quantitative column is taken as the Y values;
        all other columns are combined to label the X axis.

        :param title: plot title, defaults to names of Y value columns
        :param key_word_sep: string used to separate column values
                             from each other in labels

        Any additional keyword arguments will be passsed
        through to ``matplotlib.pylab.bar``.
        """
        if not plt:
            raise ImportError("Try installing matplotlib first.")
        self.guess_pie_columns(xlabel_sep=key_word_sep)
        plot = plt.bar(range(len(self.ys[0])), self.ys[0], **kwargs)
        if self.xlabels:
            plt.xticks(range(len(self.xlabels)), self.xlabels,
                       rotation=45)
        plt.xlabel(self.xlabel)
        plt.ylabel(self.ys[0].name)
        return plot


Instruction:
Can you write a function in Python 3 where it
generates a CSV file from the table.

Response:
def csv(self, filename=None, **format_params):
        """Generates results in comma-separated form.  Write to ``filename``
        if given. Any other parameter will be passed on to ``csv.writer``.

        :param filename: if given, the CSV will be written to filename.

        Any additional keyword arguments will be passsed
        through to ``csv.writer``.
        """
        if not self.pretty:
            return None  # no results
        if filename:
            outfile = open(filename, 'w')
        else:
            outfile = StringIO()
        writer = UnicodeWriter(outfile, **format_params)
        writer.writerow(self.field_names)
        for row in self:
            writer.writerow(row)
        if filename:
            outfile.close()
            return CsvResultDescriptor(filename)
        else:
            return outfile.getvalue()


Instruction:
Write a Python 3 function for
adding is_rendered to the context and the widget s context data.

Response:
def get_context_data(self, **kwargs):
        """
        Adds ``is_rendered`` to the context and the widget's context data.

        ``is_rendered`` signals that the AJAX view has been called and that
        we are displaying the full widget now. When ``is_rendered`` is not
        found in the widget template it means that we are seeing the first
        page load and all widgets still have to get their real data from
        this AJAX view.

        """
        ctx = super(RenderWidgetMixin, self).get_context_data(**kwargs)
        ctx.update({
            'is_rendered': True,
            'widget': self.widget,
        })
        ctx.update(self.widget.get_context_data())
        return ctx


Instruction:
Make a summary of the following Python 3 code
def get_widgets_sorted(self):
        result = []
        for widget_name, widget in self.get_widgets().items():
            result.append((widget_name, widget, widget.position))
        result.sort(key=lambda x: x[2])
        return result

Response: Returns the widgets sorted by position.


Instruction:
Implement a Python 3 function for
returning all widgets that need an update.

Response:
def get_widgets_that_need_update(self):
        """
        Returns all widgets that need an update.

        This should be scheduled every minute via crontab.

        """
        result = []
        for widget_name, widget in self.get_widgets().items():
            if widget.should_update():
                result.append(widget)
        return result


Instruction:
How would you implement a function in Python 3 that
registers a widget with the given class.

Response:
def register_widget(self, widget_cls, **widget_kwargs):
        """
        Registers the given widget.

        Widgets must inherit ``DashboardWidgetBase`` and you cannot register
        the same widget twice.

        :widget_cls: A class that inherits ``DashboardWidgetBase``.

        """
        if not issubclass(widget_cls, DashboardWidgetBase):
            raise ImproperlyConfigured(
                'DashboardWidgets must be subclasses of DashboardWidgetBase,'
                ' {0} is not.'.format(widget_cls))

        widget = widget_cls(**widget_kwargs)
        widget_name = widget.get_name()
        if widget_name in self.widgets:
            raise WidgetAlreadyRegistered(
                'Cannot register {0}, a plugin with this name {1} is already '
                'registered.'.format(widget_cls, widget_name))

        self.widgets[widget_name] = widget


Instruction:
Explain what the following Python 3 code does
def unregister_widget(self, widget_cls):
        if widget_cls.__name__ in self.widgets:
            del self.widgets[widget_cls().get_name()]

Response: Unregisters the given widget.


Instruction:
Make a summary of the following Python 3 code
def get_last_update(self):
        instance, created = \
            models.DashboardWidgetLastUpdate.objects.get_or_create(
                widget_name=self.get_name())
        return instance

Response: Gets or creates the last update object for this widget.


Instruction:
Implement a Python 3 function for
returning the setting for this widget from the database.

Response:
def get_setting(self, setting_name, default=None):
        """
        Returns the setting for this widget from the database.

        :setting_name: The name of the setting.
        :default: Optional default value if the setting cannot be found.

        """
        try:
            setting = models.DashboardWidgetSettings.objects.get(
                widget_name=self.get_name(),
                setting_name=setting_name)
        except models.DashboardWidgetSettings.DoesNotExist:
            setting = default
        return setting


Instruction:
Here you have a function in Python 3, explain what it does
def save_setting(self, setting_name, value):
        setting = self.get_setting(setting_name)
        if setting is None:
            setting = models.DashboardWidgetSettings.objects.create(
                widget_name=self.get_name(),
                setting_name=setting_name,
                value=value)
        setting.value = value
        setting.save()
        return setting

Response: Saves the setting value into the database.


Instruction:
Write a Python 3 script for
checking if an update is needed.

Response:
def should_update(self):
        """
        Checks if an update is needed.

        Checks against ``self.update_interval`` and this widgets
        ``DashboardWidgetLastUpdate`` instance if an update is overdue.

        This should be called by
        ``DashboardWidgetPool.get_widgets_that_need_update()``, which in turn
        should be called by an admin command which should be scheduled every
        minute via crontab.

        """
        last_update = self.get_last_update()
        time_since = now() - last_update.last_update
        if time_since.seconds < self.update_interval:
            return False
        return True


Instruction:
Here you have a function in Python 3, explain what it does
def getCityDetails(self, **kwargs):
        params = {}
        available_keys = ["q", "lat", "lon", "city_ids", "count"]
        for key in available_keys:
            if key in kwargs:
                params[key] = kwargs[key]
        cities = self.api.get("/cities", params)
        return cities

Response: Get the details of a city in a Zomato city.


Instruction:
Write a Python 3 script to
return Zomato Restaurant Collections in a city

Response:
def getCollectionsViaCityId(self, city_id, **kwargs):
        """
        :param city_id: id of the city for which collections are needed
        :param lat: latitude
        :param lon: longitude
        :param count: number of max results to display
        Returns Zomato Restaurant Collections in a City. The location/City input can be provided in the following ways
         - Using Zomato City ID
         - Using coordinates of any location within a city
         - List of all restaurants listed in any particular Zomato Collection can be obtained using the '/search' API with Collection ID and Zomato City ID as the input
        """
        params = {"city_id": city_id}
        optional_params = ["lat", "lon", "count"]

        for key in optional_params:
            if key in kwargs:
                params[key] = kwargs[key]
        collections = self.api.get("/collections", params)
        return collections


Instruction:
Can you write a function in Python 3 where it
gets a list of all restaurants in a given city.

Response:
def getEstablishments(self, city_id, **kwargs):
        """
        :param city_id: id of the city for which collections are needed
        :param lat: latitude
        :param lon: longitude
        Get a list of restaurant types in a city. The location/City input can be provided in the following ways
        - Using Zomato City ID
        - Using coordinates of any location within a city
        List of all restaurants categorized under a particular restaurant type can obtained using
        /Search API with Establishment ID and location details as inputs
        """
        params = {"city_id": city_id}
        optional_params = ["lat", "lon"]

        for key in optional_params:
            if key in kwargs:
                params[key] = kwargs[key]
        establishments = self.api.get("/establishments", params)
        return establishments


Instruction:
Write a Python 3 function that can
get the popular cuisines and nearby restaurants around the given coordinates.

Response:
def getByGeocode(self, lat, lon):
        """
        :param lat: latitude
        :param lon: longitude
        Get Foodie and Nightlife Index, list of popular cuisines and nearby restaurants around the given coordinates
        """
        params = {"lat": lat, "lon": lon}
        response = self.api.get("/geocode", params)
        return response


Instruction:
Create a Python 3 function to
get the location details for a given entity

Response:
def getLocationDetails(self, entity_id, entity_type):
        """
        :param entity_id: location id obtained from locations api
        :param entity_type: location type obtained from locations api
        :return:
        Get Foodie Index, Nightlife Index, Top Cuisines and Best rated restaurants in a given location
        """
        params = {"entity_id": entity_id, "entity_type": entity_type}
        location_details = self.api.get("/location_details", params)
        return location_details