Instruction:
Here you have a function in Python 3, explain what it does
def create_items(self, session_items):
        pks = list(session_items.keys())
        items = {}
        item_class = self.item_class
        process_object = self.process_object
        for obj in self.get_queryset(pks):
            pk = str(obj.pk)
            obj = process_object(obj)
            items[pk] = item_class(obj, **session_items[pk])
        if len(items) < len(session_items):
            self._stale_pks = set(session_items).difference(items)
        return items

Response: Instantiate items from session data.


Instruction:
How would you implement a function in Python 3 that
updates the cart s items and items attributes based on the items attribute.

Response:
def update(self):
        """Update the cart.

        First this method updates attributes dependent on the cart's
        `items`, such as `total_price` or `item_count`.
        After that, it saves the new cart state to the session.

        Generally, you'll need to call this method by yourself, only
        when implementing new methods that directly change the `items`
        attribute.

        """
        self.item_count = self.count_items()
        self.total_price = self.count_total_price()
        # Update the session
        session = self.request.session
        session_items = {}
        for pk, item in self.items.items():
            session_items[pk] = dict(quantity=item.quantity, **item._kwargs)
        session_data = session[session_key]
        session_data['items'] = session_items
        session_data['itemCount'] = self.item_count
        # The price can be of a type that can't be serialized to JSON
        session_data['totalPrice'] = str(self.total_price)
        session.modified = True


Instruction:
Here you have a function in Python 3, explain what it does
def count_items(self, unique=True):
        if unique:
            return len(self.items)
        return sum([item.quantity for item in self.items.values()])

Response: Count the number of items in the cart.


Instruction:
Can you generate the documentation for the following Python 3 function
def copy_file(self, path, prefixed_path, source_storage):
        if (settings.STATICFILES_STORAGE == 'cloudinary_storage.storage.StaticCloudinaryStorage' or
                self.upload_unhashed_files):
            super(Command, self).copy_file(path, prefixed_path, source_storage)

Response: Overwritten to execute only with upload_unhashed_files param or StaticCloudinaryStorage


Instruction:
Can you write a function in Python 3 where it
implements a basic hill climbing algorithm. Has two stopping conditions: 1. Maximum number of iterations; 2. A known lower bound, a none is passed then this is not used. If acceptance_criteria (a callable) is not None then this is used to obtain an upper bound on some other measure (different to the objective function). In practice this is used when optimising the objective function to ensure that we don't accept a solution that improves the objective function but tht adds more constraint violations.

Response:
def hill_climber(objective_function,
                 initial_array,
                 lower_bound=-float('inf'),
                 acceptance_criteria=None,
                 max_iterations=10 ** 3):
    """
    Implement a basic hill climbing algorithm.

    Has two stopping conditions:

    1. Maximum number of iterations;
    2. A known lower bound, a none is passed then this is not used.

    If acceptance_criteria (a callable) is not None then this is used to obtain
    an upper bound on some other measure (different to the objective function).
    In practice this is used when optimising the objective function to ensure
    that we don't accept a solution that improves the objective function but tht
    adds more constraint violations.
    """

    X = initial_array
    if acceptance_criteria is not None:
        acceptance_bound = acceptance_criteria(X)

    iterations = 0
    current_energy = objective_function(X)

    while current_energy > lower_bound and iterations <= max_iterations:

        iterations += 1
        candidate = element_from_neighbourhood(X)
        candidate_energy = objective_function(candidate)

        if (candidate_energy < current_energy and
            (acceptance_criteria is None or
             acceptance_criteria(candidate) <= acceptance_bound)):

            X = candidate
            current_energy = candidate_energy

    if lower_bound > -float('inf') and current_energy != lower_bound:
        warnings.warn(f"Lower bound {lower_bound} not achieved after {max_iterations} iterations")

    return X


Instruction:
Write a Python 3 function that can
implement a simulated annealing algorithm with exponential cooling

Response:
def simulated_annealing(objective_function,
                        initial_array,
                        initial_temperature=10 ** 4,
                        cooldown_rate=0.7,
                        acceptance_criteria=None,
                        lower_bound=-float('inf'),
                        max_iterations=10 ** 3):
    """
    Implement a simulated annealing algorithm with exponential cooling

    Has two stopping conditions:

    1. Maximum number of iterations;
    2. A known lower bound, a none is passed then this is not used.

    Note that starting with an initial_temperature corresponds to a hill
    climbing algorithm
    """

    X = initial_array
    if acceptance_criteria is not None:
        acceptance_bound = acceptance_criteria(X)
    best_X = X

    iterations = 0
    current_energy = objective_function(X)
    best_energy = current_energy
    temperature = initial_temperature

    while current_energy > lower_bound and iterations <= max_iterations:

        iterations += 1
        candidate = element_from_neighbourhood(X)
        candidate_energy = objective_function(candidate)

        delta = candidate_energy - current_energy

        if (candidate_energy < best_energy and
            (acceptance_criteria is None or
             acceptance_criteria(candidate) <= acceptance_bound)):

            best_energy = candidate_energy
            best_X = candidate

        if delta < 0 or (temperature > 0 and
                         np.random.random() < np.exp(-delta / temperature)):
            X = candidate
            current_energy = candidate_energy

        temperature *= (cooldown_rate) ** iterations

    if lower_bound > -float('inf') and current_energy != lower_bound:
        warnings.warn(f"Lower bound {lower_bound} not achieved after {max_iterations} iterations")

    return best_X


Instruction:
How would you explain what the following Python 3 function does
def _events_available_during_other_events(
    events, slots, X, summation_type=None, **kwargs
):
    """
    Constraint that ensures that an event is not scheduled at the same time as
    another event for which it is unavailable. Unavailability of events is
    either because it is explicitly defined or because they share a tag.
    """
    summation = lpu.summation_functions[summation_type]
    event_availability_array = lpu.event_availability_array(events)

    label = 'Event clashes with another event'
    for slot1, slot2 in lpu.concurrent_slots(slots):
        for row, event in enumerate(event_availability_array):
            if events[row].unavailability:
                for col, availability in enumerate(event):
                    if availability == 0:
                        yield Constraint(
                            f'{label} - event: {row} and event: {col}',
                            summation(
                                (X[row, slot1], X[col, slot2])
                            ) <= 1 + availability
                        )

Response: A constraint that ensures that an event is not scheduled at the same time as another event.


Instruction:
Make a summary of the following Python 3 code
def heuristic(events,
              slots,
              objective_function=None,
              algorithm=heu.hill_climber,
              initial_solution=None,
              initial_solution_algorithm_kwargs={},
              objective_function_algorithm_kwargs={},
              **kwargs):
    """
    Compute a schedule using a heuristic

    Parameters
    ----------
    events : list or tuple
        of :py:class:`resources.Event` instances
    slots : list or tuple
        of :py:class:`resources.Slot` instances
    algorithm : callable
       a heuristic algorithm from conference_scheduler.heuristics
    initial_solution_algorithm_kwargs : dict
       kwargs for the heuristic algorithm for the initial solution
    objective_function_algorithm_kwargs : dict
       kwargs for the heuristic algorithm for the objective function (if
       necessary.
    objective_function: callable
        from lp_problem.objective_functions
    kwargs : keyword arguments
        arguments for the objective function

    Returns
    -------
    list
        A list of tuples giving the event and slot index (for the given
        events and slots lists) for all scheduled items.

    Example
    -------
    For a solution where

        * event 0 is scheduled in slot 1
        * event 1 is scheduled in slot 4
        * event 2 is scheduled in slot 5

    the resulting list would be::

        [(0, 1), (1, 4), (2, 5)]
    """
    def count_violations(array):
        return len(list(val.array_violations(array, events, slots)))

    if initial_solution is None:
        X = heu.get_initial_array(events=events, slots=slots)
        X = algorithm(initial_array=X,
                      objective_function=count_violations,
                      lower_bound=0,
                      **initial_solution_algorithm_kwargs)
    else:
        X = initial_solution

    if objective_function is not None:

        kwargs["beta"] = float('inf')
        def func(array):
            return objective_function(
                events=events, slots=slots, X=array, **kwargs)

        X = algorithm(initial_array=X,
                      objective_function=func,
                      acceptance_criteria=count_violations,
                      **objective_function_algorithm_kwargs)

    return list(zip(*np.nonzero(X)))

Response: Compute a schedule using a heuristic algorithm.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def solution(events, slots, objective_function=None, solver=None, **kwargs):
    shape = Shape(len(events), len(slots))
    problem = pulp.LpProblem()
    X = lp.utils.variables(shape)
    beta = pulp.LpVariable("upper_bound")

    for constraint in lp.constraints.all_constraints(
        events, slots, X, beta, 'lpsum'
    ):
        problem += constraint.condition

    if objective_function is not None:
        problem += objective_function(events=events, slots=slots, X=X,
                                      beta=beta,
                                      **kwargs)

    status = problem.solve(solver=solver)
    if status == 1:
        return [item for item, variable in X.items() if variable.value() > 0]
    else:
        raise ValueError('No valid solution found')

Response: Compute a schedule in solution form


Instruction:
Given the following Python 3 function, write the documentation
def array(events, slots, objective_function=None, solver=None, **kwargs):
    return conv.solution_to_array(
        solution(events, slots, objective_function, solver=solver, **kwargs),
        events, slots
    )

Response: Compute a schedule in array form


Instruction:
Write a Python 3 script to
compute a schedule in schedule form.

Response:
def schedule(events, slots, objective_function=None, solver=None, **kwargs):
    """Compute a schedule in schedule form

    Parameters
    ----------
    events : list or tuple
        of :py:class:`resources.Event` instances
    slots : list or tuple
        of :py:class:`resources.Slot` instances
    solver : pulp.solver
        a pulp solver
    objective_function : callable
        from lp_problem.objective_functions
    kwargs : keyword arguments
        arguments for the objective function

    Returns
    -------
    list
        A list of instances of :py:class:`resources.ScheduledItem`
    """
    return conv.solution_to_schedule(
        solution(events, slots, objective_function, solver=solver, **kwargs),
        events, slots
    )


Instruction:
How would you explain what the following Python 3 function does
def event_schedule_difference(old_schedule, new_schedule):
    old = {item.event.name: item for item in old_schedule}
    new = {item.event.name: item for item in new_schedule}

    common_events = set(old.keys()).intersection(new.keys())
    added_events = new.keys() - old.keys()
    removed_events = old.keys() - new.keys()

    changed = [
        ChangedEventScheduledItem(
            old[event].event, old[event].slot, new[event].slot)
        for event in common_events
        if old[event].slot != new[event].slot
    ]
    added = [
        ChangedEventScheduledItem(new[event].event, None, new[event].slot)
        for event in added_events
    ]
    removed = [
        ChangedEventScheduledItem(old[event].event, old[event].slot, None)
        for event in removed_events
    ]
    return sorted(changed + added + removed, key=lambda item: item.event.name)

Response: Compute the difference between two schedules from an event perspective


Instruction:
Given the following Python 3 function, write the documentation
def slot_schedule_difference(old_schedule, new_schedule):
    old = {item.slot: item for item in old_schedule}
    new = {item.slot: item for item in new_schedule}

    common_slots = set(old.keys()).intersection(new.keys())
    added_slots = new.keys() - old.keys()
    removed_slots = old.keys() - new.keys()

    changed = [
        ChangedSlotScheduledItem(
            old[slot].slot, old[slot].event, new[slot].event)
        for slot in common_slots
        if old[slot].event != new[slot].event
    ]
    added = [
        ChangedSlotScheduledItem(new[slot].slot, None, new[slot].event)
        for slot in added_slots
    ]
    removed = [
        ChangedSlotScheduledItem(old[slot].slot, old[slot].event, None)
        for slot in removed_slots
    ]
    return sorted(
        changed + added + removed,
        key=lambda item: (item.slot.venue, item.slot.starts_at)
    )

Response: Compute the difference between two schedules from a slot perspective


Instruction:
How would you explain what the following Python 3 function does
def array_violations(array, events, slots, beta=None):
    return (
        c.label
        for c in constraints.all_constraints(events, slots, array, beta=beta)
        if not c.condition
    )

Response:
Take a schedule in array form and return any violated constraints
AttributeNames


Instruction:
Can you tell what is the following Python 3 function doing
def is_valid_array(array, events, slots):

    if len(array) == 0:
        return False
    violations = sum(1 for c in (array_violations(array, events, slots)))
    return violations == 0

Response:
Take a schedule in array form and return whether it is a valid
    solution for the given constraints


Instruction:
Write a Python 3 script for
taking a solution and return whether it is valid for the given constraints

Response:
def is_valid_solution(solution, events, slots):
    """Take a solution and return whether it is valid for the
    given constraints

    Parameters
    ----------
        solution: list or tuple
            a schedule in solution form
        events : list or tuple
            of resources.Event instances
        slots : list or tuple
            of resources.Slot instances

    Returns
    -------
        bool
            True if schedule is a valid solution
    """
    if len(solution) == 0:
        return False
    array = converter.solution_to_array(solution, events, slots)
    return is_valid_array(array, events, slots)


Instruction:
Can you create a Python 3 function that
takes a solution and return a list of violated constraints

Response:
def solution_violations(solution, events, slots):
    """Take a solution and return a list of violated constraints

    Parameters
    ----------
        solution: list or tuple
            a schedule in solution form
        events : list or tuple
            of resources.Event instances
        slots : list or tuple
            of resources.Slot instances

    Returns
    -------
        Generator
            of a list of strings indicating the nature of the violated
            constraints
    """
    array = converter.solution_to_array(solution, events, slots)
    return array_violations(array, events, slots)


Instruction:
Create a Python 3 function for
taking a schedule and return whether it is a valid solution for the given constraints

Response:
def is_valid_schedule(schedule, events, slots):
    """Take a schedule and return whether it is a valid solution for the
    given constraints

    Parameters
    ----------
        schedule : list or tuple
            a schedule in schedule form
        events : list or tuple
            of resources.Event instances
        slots : list or tuple
            of resources.Slot instances

    Returns
    -------
        bool
            True if schedule is a valid solution
    """
    if len(schedule) == 0:
        return False
    array = converter.schedule_to_array(schedule, events, slots)
    return is_valid_array(array, events, slots)


Instruction:
Write a Python 3 function that can
take a schedule and return a list of violated constraints

Response:
def schedule_violations(schedule, events, slots):
    """Take a schedule and return a list of violated constraints

    Parameters
    ----------
        schedule : list or tuple
            a schedule in schedule form
        events : list or tuple
            of resources.Event instances
        slots : list or tuple
            of resources.Slot instances

    Returns
    -------
        Generator
            of a list of strings indicating the nature of the violated
            constraints
    """
    array = converter.schedule_to_array(schedule, events, slots)
    return array_violations(array, events, slots)


Instruction:
Implement a Python 3 function for
returning a numpy array mapping events to tags

Response:
def tag_array(events):
    """
    Return a numpy array mapping events to tags

    - Rows corresponds to events
    - Columns correspond to tags
    """
    all_tags = sorted(set(tag for event in events for tag in event.tags))
    array = np.zeros((len(events), len(all_tags)))
    for row, event in enumerate(events):
        for tag in event.tags:
            array[row, all_tags.index(tag)] = 1
    return array


Instruction:
Implement a function in Python 3 to
return a numpy array mapping sessions to slots

Response:
def session_array(slots):
    """
    Return a numpy array mapping sessions to slots

    - Rows corresponds to sessions
    - Columns correspond to slots
    """
    # Flatten the list: this assumes that the sessions do not share slots
    sessions = sorted(set([slot.session for slot in slots]))
    array = np.zeros((len(sessions), len(slots)))
    for col, slot in enumerate(slots):
        array[sessions.index(slot.session), col] = 1
    return array


Instruction:
Write a Python 3 function that can
return a numpy array mapping events to slots

Response:
def slot_availability_array(events, slots):
    """
    Return a numpy array mapping events to slots

    - Rows corresponds to events
    - Columns correspond to stags

    Array has value 0 if event cannot be scheduled in a given slot
    (1 otherwise)
    """
    array = np.ones((len(events), len(slots)))
    for row, event in enumerate(events):
        for col, slot in enumerate(slots):
            if slot in event.unavailability or event.duration > slot.duration:
                array[row, col] = 0
    return array


Instruction:
Can you write a function in Python 3 where it
returns a numpy array mapping events to events

Response:
def event_availability_array(events):
    """
    Return a numpy array mapping events to events

    - Rows corresponds to events
    - Columns correspond to events

    Array has value 0 if event cannot be scheduled at same time as other event
    (1 otherwise)
    """
    array = np.ones((len(events), len(events)))
    for row, event in enumerate(events):
        for col, other_event in enumerate(events):
            if row != col:
                tags = set(event.tags)
                events_share_tag = len(tags.intersection(other_event.tags)) > 0
                if (other_event in event.unavailability) or events_share_tag:
                    array[row, col] = 0
                    array[col, row] = 0
    return array


Instruction:
Can you implement a function in Python 3 that
returns whether or not two events overlap

Response:
def slots_overlap(slot, other_slot):
    """
    Return boolean: whether or not two events overlap
    """
    slot_ends_at = ends_at(slot)
    other_ends_at = ends_at(other_slot)
    if (slot.starts_at >= other_slot.starts_at and
        slot_ends_at <= other_ends_at
    ):
        return True
    if (other_slot.starts_at >= slot.starts_at and
        other_ends_at <= slot_ends_at
    ):
        return True
    return False


Instruction:
Given the following Python 3 function, write the documentation
def concurrent_slots(slots):
    for i, slot in enumerate(slots):
        for j, other_slot in enumerate(slots[i + 1:]):
            if slots_overlap(slot, other_slot):
                yield (i, j + i + 1)

Response: Yields all concurrent slot indices.


Instruction:
Can you implement a function in Python 3 that
returns the indices of the events with a different tag in common as tag

Response:
def _events_with_diff_tag(talk, tag_array):
    """
    Return the indices of the events with no tag in common as tag
    """
    event_categories = np.nonzero(tag_array[talk])[0]
    return np.nonzero(sum(tag_array.transpose()[event_categories]) == 0)[0]


Instruction:
Can you generate a brief explanation for the following Python 3 code
def solution_to_array(solution, events, slots):
    array = np.zeros((len(events), len(slots)), dtype=np.int8)
    for item in solution:
        array[item[0], item[1]] = 1
    return array

Response: Convert a schedule from solution to array form


Instruction:
Here you have a function in Python 3, explain what it does
def solution_to_schedule(solution, events, slots):
    return [
        ScheduledItem(
            event=events[item[0]],
            slot=slots[item[1]]
        )
        for item in solution
    ]

Response: Convert a schedule from solution to schedule form


Instruction:
Write a Python 3 script for
converting a schedule from schedule to array form

Response:
def schedule_to_array(schedule, events, slots):
    """Convert a schedule from schedule to array form

    Parameters
    ----------
    schedule : list or tuple
        of instances of :py:class:`resources.ScheduledItem`
    events : list or tuple
        of :py:class:`resources.Event` instances
    slots : list or tuple
        of :py:class:`resources.Slot` instances

    Returns
    -------
    np.array
        An E by S array (X) where E is the number of events and S the
        number of slots. Xij is 1 if event i is scheduled in slot j and
        zero otherwise
    """
    array = np.zeros((len(events), len(slots)), dtype=np.int8)
    for item in schedule:
        array[events.index(item.event), slots.index(item.slot)] = 1
    return array


Instruction:
Can you tell what is the following Python 3 function doing
def array_to_schedule(array, events, slots):
    scheduled = np.transpose(np.nonzero(array))
    return [
        ScheduledItem(event=events[item[0]], slot=slots[item[1]])
        for item in scheduled
    ]

Response: Convert a schedule from array to schedule form


Instruction:
Implement a function in Python 3 to
append one line of generated reST to the output.

Response:
def add_line(self, line, source, *lineno):
    """Append one line of generated reST to the output."""
    if 'conference_scheduler.scheduler' in source:
        module = 'scheduler'
    else:
        module = 'resources'
    rst[module].append(line)
    self.directive.result.append(self.indent + line, source, *lineno)


Instruction:
Can you generate the documentation for the following Python 3 function
def efficiency_capacity_demand_difference(slots, events, X, **kwargs):
    overflow = 0
    for row, event in enumerate(events):
        for col, slot in enumerate(slots):
            overflow += (event.demand - slot.capacity) * X[row, col]
    return overflow

Response: A function that calculates the total difference between demand for an event and the slot capacity it is scheduled in.


Instruction:
Given the following Python 3 function, write the documentation
def number_of_changes(slots, events, original_schedule, X, **kwargs):
    changes = 0
    original_array = schedule_to_array(original_schedule, events=events,
                                       slots=slots)
    for row, event in enumerate(original_array):
        for col, slot in enumerate(event):
            if slot == 0:
                changes += X[row, col]
            else:
                changes += 1 - X[row, col]
    return changes

Response: A function that counts the number of changes between a given schedule and an array of events.


Instruction:
Can you generate the documentation for the following Python 3 function
def element_from_neighbourhood(X):

    m, n = X.shape
    new_X = np.copy(X)

    event_to_move = np.random.randint(m)
    current_event_slot = np.where(new_X[event_to_move, :] == 1)[0][0]

    slot_to_move_to = np.random.randint(n - 1)
    if slot_to_move_to >= current_event_slot:
        slot_to_move_to += 1
    scheduled_events_in_slot = np.where(new_X[:, slot_to_move_to] == 1)[0]

    if len(scheduled_events_in_slot) == 0:  # No event in that slot
        new_X[event_to_move] = np.zeros(n)
        new_X[event_to_move, slot_to_move_to] = 1

    else: # There is an event in that slot
        swap_rows = [event_to_move, scheduled_events_in_slot[0]]
        new_X[swap_rows] = new_X[swap_rows[::-1]]

    return new_X

Response: Randomly move an event to a random slot or to an empty event


Instruction:
Create a Python 3 function to
obtain a random initial array.

Response:
def get_initial_array(events, slots, seed=None):
    """
    Obtain a random initial array.
    """
    if seed is not None:
        np.random.seed(seed)

    m = len(events)
    n = len(slots)
    X = np.zeros((m, n))
    for i, row in enumerate(X):
        X[i, i] = 1
    np.random.shuffle(X)
    return X


Instruction:
Can you write a function in Python 3 where it
generates bitstream of FCS CRC checksum for given bits.

Response:
def fcs(bits):
	'''
	Append running bitwise FCS CRC checksum to end of generator
	'''
	fcs = FCS()
	for bit in bits:
		yield bit
		fcs.update_bit(bit)

#	test = bitarray()
#	for byte in (digest & 0xff, digest >> 8):
#		print byte
#		for i in range(8):
#			b = (byte >> i) & 1 == 1
#			test.append(b)
#			yield b

	# append fcs digest to bit stream

	# n.b. wire format is little-bit-endianness in addition to little-endian
	digest = bitarray(endian="little")
	digest.frombytes(fcs.digest())
	for bit in digest:
		yield bit


Instruction:
Given the following Python 3 function, write the documentation
def encode(binary_data):
	'''
	Encode binary data using Bell-202 AFSK

	Expects a bitarray.bitarray() object of binary data as its argument.
	Returns a generator of sound samples suitable for use with the
	audiogen module.
	'''
	framed_data = frame(binary_data)

	# set volume to 1/2, preceed packet with 1/20 s silence to allow for startup glitches
	for sample in itertools.chain(
		audiogen.silence(1.05),
		multiply(modulate(framed_data), constant(0.5)),
		audiogen.silence(1.05),
	):
		yield sample

Response:
Encode the given binary data using Bell - 202 AFSK
	.


Instruction:
Can you implement a function in Python 3 that
modulates the AFSK samples for the given symbol generator and produce AFSK samples for the given raw wire symbols.

Response:
def modulate(data):
	'''
	Generate Bell 202 AFSK samples for the given symbol generator

	Consumes raw wire symbols and produces the corresponding AFSK samples.
	'''
	seconds_per_sample = 1.0 / audiogen.sampler.FRAME_RATE
	phase, seconds, bits = 0, 0, 0

	# construct generators
	clock = (x / BAUD_RATE for x in itertools.count(1))
	tones = (MARK_HZ if bit else SPACE_HZ for bit in data)

	for boundary, frequency in itertools.izip(clock, tones):
		# frequency of current symbol is determined by how much
		# we advance the signal's phase in each audio frame
		phase_change_per_sample = TWO_PI / (audiogen.sampler.FRAME_RATE / frequency)

		# produce samples for the current symbol
		# until we reach the next clock boundary
		while seconds < boundary:
			yield math.sin(phase)

			seconds += seconds_per_sample
			phase += phase_change_per_sample

			if phase > TWO_PI:
				phase -= TWO_PI

		bits += 1
		logger.debug("bits = %d, time = %.7f ms, expected time = %.7f ms, error = %.7f ms, baud rate = %.6f Hz" \
			% (bits, 1000 * seconds, 1000 * bits / BAUD_RATE, 1000 * (seconds - bits / BAUD_RATE), bits / seconds))


Instruction:
Write a Python 3 function for
packeting uses NRZI (non-return to zero inverted) encoding, which means that a 0 is encoded as a change in tone, and a 1 is encoded as no change in tone.

Response:
def nrzi(data):
	'''
	Packet uses NRZI (non-return to zero inverted) encoding, which means
	that a 0 is encoded as a change in tone, and a 1 is encoded as
	no change in tone.
	'''
	current = True
	for bit in data:
		if not bit:
			current = not current
		yield current


Instruction:
Can you generate the documentation for the following Python 3 function
def _get_sync(self, url):
        response = self.session.get(url)
        if response.status_code == requests.codes.ok:
            return response.json()
        else:
            raise HTTPError

Response: Internal method used for GET requests to retrieve the information about the specified Individual URL.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_item(self, item_id, expand=False):
        url = urljoin(self.item_url, F"{item_id}.json")
        response = self._get_sync(url)

        if not response:
            raise InvalidItemID

        item = Item(response)
        if expand:
            item.by = self.get_user(item.by)
            item.kids = self.get_items_by_ids(item.kids) if item.kids else None
            item.parent = self.get_item(item.parent) if item.parent else None
            item.poll = self.get_item(item.poll) if item.poll else None
            item.parts = (
                self.get_items_by_ids(item.parts) if item.parts else None
            )

        return item

Response: Fetches the data from the Hacker News item API.


Instruction:
Create a Python 3 function to
give a list of item ids return all the Item objects for that list of item IDs and item type

Response:
def get_items_by_ids(self, item_ids, item_type=None):
        """Given a list of item ids, return all the Item objects

        Args:
            item_ids (obj): List of item IDs to query
            item_type (str): (optional) Item type to filter results with

        Returns:
            List of `Item` objects for given item IDs and given item type

        """
        urls = [urljoin(self.item_url, F"{i}.json") for i in item_ids]
        result = self._run_async(urls=urls)
        items = [Item(r) for r in result if r]
        if item_type:
            return [item for item in items if item.item_type == item_type]
        else:
            return items


Instruction:
How would you explain what the following Python 3 function does
def get_user(self, user_id, expand=False):
        url = urljoin(self.user_url, F"{user_id}.json")
        response = self._get_sync(url)

        if not response:
            raise InvalidUserID

        user = User(response)
        if expand and user.submitted:
            items = self.get_items_by_ids(user.submitted)
            user_opt = {
                'stories': 'story',
                'comments': 'comment',
                'jobs': 'job',
                'polls': 'poll',
                'pollopts': 'pollopt'
            }
            for key, value in user_opt.items():
                setattr(
                    user,
                    key,
                    [i for i in items if i.item_type == value]
                )

        return user

Response: Fetches a user from the Hacker News API and returns a User object.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_users_by_ids(self, user_ids):
        urls = [urljoin(self.user_url, F"{i}.json") for i in user_ids]
        result = self._run_async(urls=urls)
        return [User(r) for r in result if r]

Response: Given a list of user ids return all the User objects that match the given list of user ids


Instruction:
Can you tell what is the following Python 3 function doing
def top_stories(self, raw=False, limit=None):
        top_stories = self._get_stories('topstories', limit)
        if raw:
            top_stories = [story.raw for story in top_stories]
        return top_stories

Response: Returns a list of item ids of current top stories.


Instruction:
Create a Python 3 function for
returning list of item ids of current new stories.

Response:
def new_stories(self, raw=False, limit=None):
        """Returns list of item ids of current new stories

        Args:
            limit (int): specifies the number of stories to be returned.
            raw (bool): Flag to indicate whether to transform all
                objects into raw json.

        Returns:
            `list` object containing ids of new stories.

        """
        new_stories = self._get_stories('newstories', limit)
        if raw:
            new_stories = [story.raw for story in new_stories]
        return new_stories


Instruction:
Can you create a Python 3 function that
returns list of item ids of latest Ask HN stories.

Response:
def ask_stories(self, raw=False, limit=None):
        """Returns list of item ids of latest Ask HN stories

        Args:
            limit (int): specifies the number of stories to be returned.
            raw (bool): Flag to indicate whether to transform all
                objects into raw json.

        Returns:
            `list` object containing ids of Ask HN stories.

        """
        ask_stories = self._get_stories('askstories', limit)
        if raw:
            ask_stories = [story.raw for story in ask_stories]
        return ask_stories


Instruction:
Create a Python 3 function to
return list of item ids of latest Show HN stories.

Response:
def show_stories(self, raw=False, limit=None):
        """Returns list of item ids of latest Show HN stories

        Args:
            limit (int): specifies the number of stories to be returned.
            raw (bool): Flag to indicate whether to transform all
                objects into raw json.

        Returns:
            `list` object containing ids of Show HN stories.

        """
        show_stories = self._get_stories('showstories', limit)
        if raw:
            show_stories = [story.raw for story in show_stories]
        return show_stories


Instruction:
Can you implement a function in Python 3 that
returns list of item ids of latest Job stories.

Response:
def job_stories(self, raw=False, limit=None):
        """Returns list of item ids of latest Job stories

        Args:
            limit (int): specifies the number of stories to be returned.
            raw (bool): Flag to indicate whether to transform all
                objects into raw json.

        Returns:
            `list` object containing ids of Job stories.

        """
        job_stories = self._get_stories('jobstories', limit)
        if raw:
            job_stories = [story.raw for story in job_stories]
        return job_stories


Instruction:
Create a Python 3 function to
return list of item ids and user ids that have been changed / updated recently.

Response:
def updates(self):
        """Returns list of item ids and user ids that have been
        changed/updated recently.

        Fetches data from URL:
            https://hacker-news.firebaseio.com/v0/updates.json

        Returns:
            `dict` with two keys whose values are `list` objects

        """
        url = urljoin(self.base_url, 'updates.json')
        response = self._get_sync(url)
        return {
            'items': self.get_items_by_ids(item_ids=response['items']),
            'profiles': self.get_users_by_ids(user_ids=response['profiles'])
        }


Instruction:
Here you have a function in Python 3, explain what it does
def get_max_item(self, expand=False):
        url = urljoin(self.base_url, 'maxitem.json')
        response = self._get_sync(url)
        if expand:
            return self.get_item(response)
        else:
            return response

Response: Gets the current largest item id.


Instruction:
Given the following Python 3 function, write the documentation
def get_last(self, num=10):
        max_item = self.get_max_item()
        urls = [urljoin(self.item_url, F"{i}.json") for i in range(
            max_item - num + 1, max_item + 1)]
        result = self._run_async(urls=urls)
        return [Item(r) for r in result if r]

Response: Download all the HN articles and return them as Item objects


Instruction:
Explain what the following Python 3 code does
def load(self, path):
        self.dct = wrapper.Dictionary.load(path)
        return self

Response: Loads a DAWG from a file.


Instruction:
Write a Python 3 script to
return all variants of key in this DAWG according to replaces.

Response:
def similar_keys(self, key, replaces):
        """
        Returns all variants of ``key`` in this DAWG according to
        ``replaces``.

        ``replaces`` is an object obtained from
        ``DAWG.compile_replaces(mapping)`` where mapping is a dict
        that maps single-char unicode sitrings to another single-char
        unicode strings.

        This may be useful e.g. for handling single-character umlauts.
        """
        return self._similar_keys("", key, self.dct.ROOT, replaces)


Instruction:
Can you tell what is the following Python 3 function doing
def prefixes(self, key):
        '''
        Returns a list with keys of this DAWG that are prefixes of the ``key``.
        '''
        res = []
        index = self.dct.ROOT
        if not isinstance(key, bytes):
            key = key.encode('utf8')

        pos = 1

        for ch in key:
            index = self.dct.follow_char(int_from_byte(ch), index)
            if not index:
                break

            if self._has_value(index):
                res.append(key[:pos].decode('utf8'))
            pos += 1

        return res

Response: Returns a list with keys of this DAWG that are prefixes of the key.


Instruction:
Implement a function in Python 3 to
load a DAWG from a file.

Response:
def load(self, path):
        """
        Loads DAWG from a file.
        """
        self.dct = wrapper.Dictionary()
        self.guide = wrapper.Guide()

        with open(path, 'rb') as f:
            self.dct.read(f)
            self.guide.read(f)

        return self


Instruction:
Can you tell what is the following Python 3 function doing
def get(self, key, default=None):
        if not isinstance(key, bytes):
            key = key.encode('utf8')

        return self.b_get_value(key) or default

Response: Returns a list of payloads for a given key.


Instruction:
Can you write a function in Python 3 where it
returns a list of tuples for all variants of key and value that are similar to the key in this DAWG.

Response:
def similar_items(self, key, replaces):
        """
        Returns a list of (key, value) tuples for all variants of ``key``
        in this DAWG according to ``replaces``.

        ``replaces`` is an object obtained from
        ``DAWG.compile_replaces(mapping)`` where mapping is a dict
        that maps single-char unicode sitrings to another single-char
        unicode strings.
        """
        return self._similar_items("", key, self.dct.ROOT, replaces)


Instruction:
How would you code a function in Python 3 to
return a list of values for all variants of the key that are similar to the key in this DAWG.

Response:
def similar_item_values(self, key, replaces):
        """
        Returns a list of values for all variants of the ``key``
        in this DAWG according to ``replaces``.

        ``replaces`` is an object obtained from
        ``DAWG.compile_replaces(mapping)`` where mapping is a dict
        that maps single-char unicode sitrings to another single-char
        unicode strings.
        """
        return self._similar_item_values(0, key, self.dct.ROOT, replaces)


Instruction:
Make a summary of the following Python 3 code
def value(self, index):
        "Gets a value from a given index."
        offset = units.offset(self._units[index])
        value_index = (index ^ offset) & units.PRECISION_MASK
        return units.value(self._units[value_index])

Response: Gets a value from a given index.


Instruction:
How would you code a function in Python 3 to
read a dictionary from an input stream.

Response:
def read(self, fp):
        "Reads a dictionary from an input stream."
        base_size = struct.unpack(str("=I"), fp.read(4))[0]
        self._units.fromfile(fp, base_size)


Instruction:
Given the following Python 3 function, write the documentation
def find(self, key):
        "Exact matching (returns value)"
        index = self.follow_bytes(key, self.ROOT)
        if index is None:
            return -1
        if not self.has_value(index):
            return -1
        return self.value(index)

Response: Exact matching ( returns value )


Instruction:
Can you implement a function in Python 3 that
gets the next key

Response:
def next(self):
        "Gets the next key"

        if not self._index_stack:
            return False

        index = self._index_stack[-1]

        if self._last_index != self._dic.ROOT:

            child_label = self._guide.child(index)  # UCharType

            if child_label:
                # Follows a transition to the first child.
                index = self._follow(child_label, index)
                if index is None:
                    return False
            else:
                while True:
                    sibling_label = self._guide.sibling(index)
                    # Moves to the previous node.
                    if len(self.key) > 0:
                        self.key.pop()
                        #self.key[-1] = 0

                    self._index_stack.pop()
                    if not self._index_stack:
                        return False

                    index = self._index_stack[-1]
                    if sibling_label:
                        # Follows a transition to the next sibling.
                        index = self._follow(sibling_label, index)
                        if index is None:
                            return False
                        break

        return self._find_terminal(index)


Instruction:
Given the following Python 3 function, write the documentation
def convert_response(check_response, project_id):
    if not check_response or not check_response.checkErrors:
        return _IS_OK

    # only check the first error for now, as per ESP
    theError = check_response.checkErrors[0]
    error_tuple = _CHECK_ERROR_CONVERSION.get(theError.code, _IS_UNKNOWN)
    if error_tuple[1].find(u'{') == -1:  # no replacements needed:
        return error_tuple

    updated_msg = error_tuple[1].format(project_id=project_id, detail=theError.detail or u'')
    return error_tuple[0], updated_msg, error_tuple[2]

Response: Converts a CheckResponse to a tuple.


Instruction:
Implement a function in Python 3 to
return a secure hash for an operation in a CheckRequest.

Response:
def sign(check_request):
    """Obtains a signature for an operation in a `CheckRequest`

    Args:
       op (:class:`endpoints_management.gen.servicecontrol_v1_messages.Operation`): an
         operation used in a `CheckRequest`

    Returns:
       string: a secure hash generated from the operation
    """
    if not isinstance(check_request, sc_messages.CheckRequest):
        raise ValueError(u'Invalid request')
    op = check_request.operation
    if op is None or op.operationName is None or op.consumerId is None:
        logging.error(u'Bad %s: not initialized => not signed', check_request)
        raise ValueError(u'check request must be initialized with an operation')
    md5 = hashlib.md5()
    md5.update(op.operationName.encode('utf-8'))
    md5.update(b'\x00')
    md5.update(op.consumerId.encode('utf-8'))
    if op.labels:
        signing.add_dict_to_hash(md5, encoding.MessageToPyValue(op.labels))
    for value_set in op.metricValueSets:
        md5.update(b'\x00')
        md5.update(value_set.metricName.encode('utf-8'))
        for mv in value_set.metricValues:
            metric_value.update_hash(md5, mv)

    md5.update(b'\x00')
    if op.quotaProperties:
        # N.B: this differs form cxx implementation, which serializes the
        # protobuf. This should be OK as the exact hash used does not need to
        # match across implementations.
        md5.update(repr(op.quotaProperties).encode('utf-8'))

    md5.update(b'\x00')
    return md5.digest()


Instruction:
Create a Python 3 function to
make a ServicecontrolServicesCheckRequest from this instance.

Response:
def as_check_request(self, timer=datetime.utcnow):
        """Makes a `ServicecontrolServicesCheckRequest` from this instance

        Returns:
          a ``ServicecontrolServicesCheckRequest``

        Raises:
          ValueError: if the fields in this instance are insufficient to
            to create a valid ``ServicecontrolServicesCheckRequest``

        """
        if not self.service_name:
            raise ValueError(u'the service name must be set')
        if not self.operation_id:
            raise ValueError(u'the operation id must be set')
        if not self.operation_name:
            raise ValueError(u'the operation name must be set')
        op = super(Info, self).as_operation(timer=timer)
        labels = {}
        if self.android_cert_fingerprint:
            labels[_KNOWN_LABELS.SCC_ANDROID_CERT_FINGERPRINT.label_name] = self.android_cert_fingerprint

        if self.android_package_name:
            labels[_KNOWN_LABELS.SCC_ANDROID_PACKAGE_NAME.label_name] = self.android_package_name

        if self.client_ip:
            labels[_KNOWN_LABELS.SCC_CALLER_IP.label_name] = self.client_ip

        if self.ios_bundle_id:
            labels[_KNOWN_LABELS.SCC_IOS_BUNDLE_ID.label_name] = self.ios_bundle_id

        if self.referer:
            labels[_KNOWN_LABELS.SCC_REFERER.label_name] = self.referer

        # Forcibly add system label reporting here, as the base service
        # config does not specify it as a label.
        labels[_KNOWN_LABELS.SCC_SERVICE_AGENT.label_name] = SERVICE_AGENT
        labels[_KNOWN_LABELS.SCC_USER_AGENT.label_name] = USER_AGENT

        op.labels = encoding.PyValueToMessage(
            sc_messages.Operation.LabelsValue, labels)
        check_request = sc_messages.CheckRequest(operation=op)
        return sc_messages.ServicecontrolServicesCheckRequest(
            serviceName=self.service_name,
            checkRequest=check_request)


Instruction:
Explain what the following Python 3 code does
def flush(self):
        if self._cache is None:
            return []
        with self._cache as c:
            flushed_items = list(c.out_deque)
            c.out_deque.clear()
            cached_reqs = [item.extract_request() for item in flushed_items]
            cached_reqs = [req for req in cached_reqs if req is not None]
            return cached_reqs

Response: Flushes this instance s cache.


Instruction:
Can you tell what is the following Python 3 function doing
def clear(self):
        if self._cache is not None:
            with self._cache as c:
                c.clear()
                c.out_deque.clear()

Response: Clears this instance s cache.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def add_response(self, req, resp):
        if self._cache is None:
            return
        signature = sign(req.checkRequest)
        with self._cache as c:
            now = self._timer()
            quota_scale = 0  # WIP
            item = c.get(signature)
            if item is None:
                c[signature] = CachedItem(
                    resp, self.service_name, now, quota_scale)
            else:
                # Update the cached item to reflect that it is updated
                item.last_check_time = now
                item.response = resp
                item.quota_scale = quota_scale
                item.is_flushing = False
                c[signature] = item

Response: Adds the response from sending to req to this instance s cache.


Instruction:
Can you implement a function in Python 3 that
checks if the request is in the cache and returns a CheckResponse.

Response:
def check(self, req):
        """Determine if ``req`` is in this instances cache.

        Determine if there are cache hits for the request in this aggregator
        instance.

        Not in the cache

        If req is not in the cache, it returns ``None`` to indicate that the
        caller should send the request.

        Cache Hit; response has errors

        When a cached CheckResponse has errors, it's assumed that ``req`` would
        fail as well, so the cached CheckResponse is returned.  However, the
        first CheckRequest after the flush interval has elapsed should be sent
        to the server to refresh the CheckResponse, though until it's received,
        subsequent CheckRequests should fail with the cached CheckResponse.

        Cache behaviour - response passed

        If the cached CheckResponse has no errors, it's assumed that ``req``
        will succeed as well, so the CheckResponse is returned, with the quota
        info updated to the same as requested.  The requested tokens are
        aggregated until flushed.

        Args:
          req (``ServicecontrolServicesCheckRequest``): to be sent to
            the service control service

        Raises:
           ValueError: if the ``req`` service_name is not the same as
             this instances

        Returns:
           ``CheckResponse``: if an applicable response is cached by this
             instance is available for use or None, if there is no applicable
             response

        """
        if self._cache is None:
            return None  # no cache, send request now
        if not isinstance(req, sc_messages.ServicecontrolServicesCheckRequest):
            raise ValueError(u'Invalid request')
        if req.serviceName != self.service_name:
            _logger.error(u'bad check(): service_name %s does not match ours %s',
                          req.serviceName, self.service_name)
            raise ValueError(u'Service name mismatch')
        check_request = req.checkRequest
        if check_request is None:
            _logger.error(u'bad check(): no check_request in %s', req)
            raise ValueError(u'Expected operation not set')
        op = check_request.operation
        if op is None:
            _logger.error(u'bad check(): no operation in %s', req)
            raise ValueError(u'Expected operation not set')
        if op.importance != sc_messages.Operation.ImportanceValueValuesEnum.LOW:
            return None  # op is important, send request now

        signature = sign(check_request)
        with self._cache as cache:
            _logger.debug(u'checking the cache for %r\n%s', signature, cache)
            item = cache.get(signature)
            if item is None:
                return None  # signal to caller to send req
            else:
                return self._handle_cached_response(req, item)


Instruction:
Can you tell what is the following Python 3 function doing
def compare(a, b):
    a_is_text = isinstance(a, basestring)
    b_is_text = isinstance(b, basestring)
    if type(a) != type(b) and not (a_is_text and b_is_text):
        _logger.error(u'Cannot compare %s to %s, types differ %s!=%s',
                      a, b, type(a), type(b))
        raise ValueError(u'cannot compare inputs of differing types')

    if a_is_text:
        a = from_rfc3339(a, with_nanos=True)
        b = from_rfc3339(b, with_nanos=True)

    if a < b:
        return -1
    elif a > b:
        return 1
    else:
        return 0

Response:
Compares two timestamps.

    ``a`` and ``b`` must be the same type, in addition to normal
    representations of timestamps that order naturally, they can be rfc3339
    formatted strings.

    Args:
      a (string|object): a timestamp
      b (string|object): another timestamp

    Returns:
      int: -1 if a < b, 0 if a == b or 1 if a > b

    Raises:
      ValueError: if a or b are not the same type
      ValueError: if a or b strings but not in valid rfc3339 format


Instruction:
Here you have a function in Python 3, explain what it does
def to_rfc3339(timestamp):
    if isinstance(timestamp, datetime.datetime):
        timestamp = timestamp - _EPOCH_START
    if not isinstance(timestamp, datetime.timedelta):
        _logger.error(u'Could not convert %s to a rfc3339 time,', timestamp)
        raise ValueError(u'Invalid timestamp type')
    return strict_rfc3339.timestamp_to_rfc3339_utcoffset(
        timestamp.total_seconds())

Response: Converts a datetime. datetime object to an RFC 3339 date string format.


Instruction:
Write a Python 3 script for
parsing a RFC 3339 date string format to a datetime. date object.

Response:
def from_rfc3339(rfc3339_text, with_nanos=False):
    """Parse a RFC 3339 date string format to datetime.date.

    Example of accepted format: '1972-01-01T10:00:20.021-05:00'

    - By default, the result is a datetime.datetime
    - If with_nanos is true, the result is a 2-tuple, (datetime.datetime,
    nanos), where the second field represents the possible nanosecond
    resolution component of the second field.

    Args:
      rfc3339_text (string): An rfc3339 formatted date string
      with_nanos (bool): Determines if nanoseconds should be parsed from the
        string

    Raises:
      ValueError: if ``rfc3339_text`` is invalid

    Returns:
      :class:`datetime.datetime`: when with_nanos is False
      tuple(:class:`datetime.datetime`, int): when with_nanos is True

    """
    timestamp = strict_rfc3339.rfc3339_to_timestamp(rfc3339_text)
    result = datetime.datetime.utcfromtimestamp(timestamp)
    if with_nanos:
        return (result, int((timestamp - int(timestamp)) * 1e9))
    else:
        return result


Instruction:
Can you generate a brief explanation for the following Python 3 code
def as_operation(self, timer=datetime.utcnow):
        now = timer()
        op = sc_messages.Operation(
            endTime=timestamp.to_rfc3339(now),
            startTime=timestamp.to_rfc3339(now),
            importance=sc_messages.Operation.ImportanceValueValuesEnum.LOW)
        if self.operation_id:
            op.operationId = self.operation_id
        if self.operation_name:
            op.operationName = self.operation_name
        if self.api_key and self.api_key_valid:
            op.consumerId = u'api_key:' + self.api_key
        elif self.consumer_project_id:
            op.consumerId = u'project:' + self.consumer_project_id
        return op

Response: Makes an Operation from this instance.


Instruction:
Write a Python 3 function that can
obtain a single Operation representing this instances contents.

Response:
def as_operation(self):
        """Obtains a single `Operation` representing this instances contents.

        Returns:
           :class:`endpoints_management.gen.servicecontrol_v1_messages.Operation`
        """
        result = encoding.CopyProtoMessage(self._op)
        names = sorted(self._metric_values_by_name_then_sign.keys())
        for name in names:
            mvs = self._metric_values_by_name_then_sign[name]
            result.metricValueSets.append(
                sc_messages.MetricValueSet(
                    metricName=name, metricValues=mvs.values()))
        return result


Instruction:
Can you write a function in Python 3 where it
combines other_op with the operation held by this aggregator.

Response:
def add(self, other_op):
        """Combines `other_op` with the operation held by this aggregator.

        N.B. It merges the operations log entries and metric values, but makes
        the assumption the operation is consistent.  It's the callers
        responsibility to ensure consistency

        Args:
           other_op (
             class:`endpoints_management.gen.servicecontrol_v1_messages.Operation`):
             an operation merge into this one

        """
        self._op.logEntries.extend(other_op.logEntries)
        self._merge_timestamps(other_op)
        self._merge_metric_values(other_op)


Instruction:
Given the following Python 3 function, write the documentation
def create_exponential(num_finite_buckets, growth_factor, scale):
    if num_finite_buckets <= 0:
        raise ValueError(_BAD_NUM_FINITE_BUCKETS)
    if growth_factor <= 1.0:
        raise ValueError(_BAD_FLOAT_ARG % (u'growth factor', 1.0))
    if scale <= 0.0:
        raise ValueError(_BAD_FLOAT_ARG % (u'scale', 0.0))
    return sc_messages.Distribution(
        bucketCounts=[0] * (num_finite_buckets + 2),
        exponentialBuckets=sc_messages.ExponentialBuckets(
            numFiniteBuckets=num_finite_buckets,
            growthFactor=growth_factor,
            scale=scale))

Response: Creates an instance of distribution with exponential buckets.


Instruction:
Make a summary of the following Python 3 code
def create_linear(num_finite_buckets, width, offset):
    if num_finite_buckets <= 0:
        raise ValueError(_BAD_NUM_FINITE_BUCKETS)
    if width <= 0.0:
        raise ValueError(_BAD_FLOAT_ARG % (u'width', 0.0))
    return sc_messages.Distribution(
        bucketCounts=[0] * (num_finite_buckets + 2),
        linearBuckets=sc_messages.LinearBuckets(
            numFiniteBuckets=num_finite_buckets,
            width=width,
            offset=offset))

Response: Creates a new instance of distribution with linear buckets.


Instruction:
Write a Python 3 script for
creating an explicit distribution with explicit buckets.

Response:
def create_explicit(bounds):
    """Creates a new instance of distribution with explicit buckets.

    bounds is an iterable of ordered floats that define the explicit buckets

    Args:
       bounds (iterable[float]): initializes the bounds

    Return:
       :class:`endpoints_management.gen.servicecontrol_v1_messages.Distribution`

    Raises:
       ValueError: if the args are invalid for creating an instance
    """
    safe_bounds = sorted(float(x) for x in bounds)
    if len(safe_bounds) != len(set(safe_bounds)):
        raise ValueError(u'Detected two elements of bounds that are the same')
    return sc_messages.Distribution(
        bucketCounts=[0] * (len(safe_bounds) + 1),
        explicitBuckets=sc_messages.ExplicitBuckets(bounds=safe_bounds))


Instruction:
Can you write a function in Python 3 where it
adds a sample to the current distribution and updates its existing buckets.

Response:
def add_sample(a_float, dist):
    """Adds `a_float` to `dist`, updating its existing buckets.

    Args:
      a_float (float): a new value
      dist (:class:`endpoints_management.gen.servicecontrol_v1_messages.Distribution`):
        the Distribution being updated

    Raises:
      ValueError: if `dist` does not have known bucket options defined
      ValueError: if there are not enough bucket count fields in `dist`
    """
    dist_type, _ = _detect_bucket_option(dist)
    if dist_type == u'exponentialBuckets':
        _update_general_statistics(a_float, dist)
        _update_exponential_bucket_count(a_float, dist)
    elif dist_type == u'linearBuckets':
        _update_general_statistics(a_float, dist)
        _update_linear_bucket_count(a_float, dist)
    elif dist_type == u'explicitBuckets':
        _update_general_statistics(a_float, dist)
        _update_explicit_bucket_count(a_float, dist)
    else:
        _logger.error(u'Could not determine bucket option type for %s', dist)
        raise ValueError(u'Unknown bucket option type')


Instruction:
Can you tell what is the following Python 3 function doing
def merge(prior, latest):
    if not _buckets_nearly_equal(prior, latest):
        _logger.error(u'Bucket options do not match. From %s To: %s',
                      prior,
                      latest)
        raise ValueError(u'Bucket options do not match')
    if len(prior.bucketCounts) != len(latest.bucketCounts):
        _logger.error(u'Bucket count sizes do not match. From %s To: %s',
                      prior,
                      latest)
        raise ValueError(u'Bucket count sizes do not match')
    if prior.count <= 0:
        return

    old_count = latest.count
    old_mean = latest.mean
    old_summed_variance = latest.sumOfSquaredDeviation
    bucket_counts = latest.bucketCounts

    # Update the latest
    latest.count += prior.count
    latest.maximum = max(prior.maximum, latest.maximum)
    latest.minimum = min(prior.minimum, latest.minimum)
    latest.mean = ((old_count * old_mean + prior.count * prior.mean) /
                   latest.count)
    latest.sumOfSquaredDeviation = (
        old_summed_variance + prior.sumOfSquaredDeviation +
        old_count * (latest.mean - old_mean) ** 2 +
        prior.count * (latest.mean - prior.mean) ** 2)
    for i, (x, y) in enumerate(zip(prior.bucketCounts, bucket_counts)):
        bucket_counts[i] = x + y

Response: Merges prior into latest.


Instruction:
Create a Python 3 function to
determine if two Distributions are approximately equal.

Response:
def _buckets_nearly_equal(a_dist, b_dist):
    """Determines whether two `Distributions` are nearly equal.

    Args:
      a_dist (:class:`Distribution`): an instance
      b_dist (:class:`Distribution`): another instance

    Return:
      boolean: `True` if the two instances are approximately equal, otherwise
        False

    """
    a_type, a_buckets = _detect_bucket_option(a_dist)
    b_type, b_buckets = _detect_bucket_option(b_dist)
    if a_type != b_type:
        return False
    elif a_type == u'linearBuckets':
        return _linear_buckets_nearly_equal(a_buckets, b_buckets)
    elif a_type == u'exponentialBuckets':
        return _exponential_buckets_nearly_equal(a_buckets, b_buckets)
    elif a_type == u'explicitBuckets':
        return _explicit_buckets_nearly_equal(a_buckets, b_buckets)
    else:
        return False


Instruction:
Explain what the following Python 3 code does
def _update_general_statistics(a_float, dist):
    if not dist.count:
        dist.count = 1
        dist.maximum = a_float
        dist.minimum = a_float
        dist.mean = a_float
        dist.sumOfSquaredDeviation = 0
    else:
        old_count = dist.count
        old_mean = dist.mean
        new_mean = ((old_count * old_mean) + a_float) / (old_count + 1)
        delta_sum_squares = (a_float - old_mean) * (a_float - new_mean)
        dist.count += 1
        dist.mean = new_mean
        dist.maximum = max(a_float, dist.maximum)
        dist.minimum = min(a_float, dist.minimum)
        dist.sumOfSquaredDeviation += delta_sum_squares

Response: Adds a_float to the distribution and updates the statistics fields.


Instruction:
Can you tell what is the following Python 3 function doing
def _update_exponential_bucket_count(a_float, dist):
    buckets = dist.exponentialBuckets
    if buckets is None:
        raise ValueError(_BAD_UNSET_BUCKETS % (u'exponential buckets'))
    bucket_counts = dist.bucketCounts
    num_finite_buckets = buckets.numFiniteBuckets
    if len(bucket_counts) < num_finite_buckets + 2:
        raise ValueError(_BAD_LOW_BUCKET_COUNT)
    scale = buckets.scale
    factor = buckets.growthFactor
    if (a_float <= scale):
        index = 0
    else:
        index = 1 + int((math.log(a_float / scale) / math.log(factor)))
        index = min(index, num_finite_buckets + 1)
    bucket_counts[index] += 1
    _logger.debug(u'scale:%f, factor:%f, sample:%f, index:%d',
                  scale, factor, a_float, index)

Response: Adds a_float to dist updating its exponential buckets.


Instruction:
How would you code a function in Python 3 to
add a_float to dist updating the linear buckets count field.

Response:
def _update_linear_bucket_count(a_float, dist):
    """Adds `a_float` to `dist`, updating the its linear buckets.

    Args:
      a_float (float): a new value
      dist (:class:`endpoints_management.gen.servicecontrol_v1_messages.Distribution`):
        the Distribution being updated

    Raises:
      ValueError: if `dist` does not already have linear buckets defined
      ValueError: if there are not enough bucket count fields in `dist`
    """
    buckets = dist.linearBuckets
    if buckets is None:
        raise ValueError(_BAD_UNSET_BUCKETS % (u'linear buckets'))
    bucket_counts = dist.bucketCounts
    num_finite_buckets = buckets.numFiniteBuckets
    if len(bucket_counts) < num_finite_buckets + 2:
        raise ValueError(_BAD_LOW_BUCKET_COUNT)
    width = buckets.width
    lower = buckets.offset
    upper = lower + (num_finite_buckets * width)
    if a_float < lower:
        index = 0
    elif a_float >= upper:
        index = num_finite_buckets + 1
    else:
        index = 1 + int(((a_float - lower) / width))
    bucket_counts[index] += 1
    _logger.debug(u'upper:%f, lower:%f, width:%f, sample:%f, index:%d',
                  upper, lower, width, a_float, index)


Instruction:
Create a Python 3 function to
add a_float to dist updating its explicit buckets.

Response:
def _update_explicit_bucket_count(a_float, dist):
    """Adds `a_float` to `dist`, updating its explicit buckets.

    Args:
      a_float (float): a new value
      dist (:class:`endpoints_management.gen.servicecontrol_v1_messages.Distribution`):
        the Distribution being updated

    Raises:
      ValueError: if `dist` does not already have explict buckets defined
      ValueError: if there are not enough bucket count fields in `dist`
    """
    buckets = dist.explicitBuckets
    if buckets is None:
        raise ValueError(_BAD_UNSET_BUCKETS % (u'explicit buckets'))
    bucket_counts = dist.bucketCounts
    bounds = buckets.bounds
    if len(bucket_counts) < len(bounds) + 1:
        raise ValueError(_BAD_LOW_BUCKET_COUNT)
    bucket_counts[bisect.bisect(bounds, a_float)] += 1


Instruction:
Write a Python 3 function that can
enter a new event at an absolute time.

Response:
def enterabs(self, time, priority, action, argument=(), kwargs=_sentinel):
        """Enter a new event in the queue at an absolute time.

        Returns an ID for the event which can be used to remove it,
        if necessary.

        """
        if kwargs is _sentinel:
            kwargs = {}
        event = Event(time, priority, action, argument, kwargs)
        with self._lock:
            heapq.heappush(self._queue, event)
        return event


Instruction:
Can you generate a brief explanation for the following Python 3 code
def cancel(self, event):
        with self._lock:
            self._queue.remove(event)
            heapq.heapify(self._queue)

Response: Cancel an event from the queue.


Instruction:
Can you implement a function in Python 3 that
executes the scheduled events until the queue is empty and return the deadline of the next scheduled call in the scheduler.

Response:
def run(self, blocking=True):
        """Execute events until the queue is empty.
        If blocking is False executes the scheduled events due to
        expire soonest (if any) and then return the deadline of the
        next scheduled call in the scheduler.

        When there is a positive delay until the first event, the
        delay function is called and the event is left in the queue;
        otherwise, the event is removed from the queue and executed
        (its action function is called, passing it the argument).  If
        the delay function returns prematurely, it is simply
        restarted.

        It is legal for both the delay function and the action
        function to modify the queue or to raise an exception;
        exceptions are not caught but the scheduler's state remains
        well-defined so run() may be called again.

        A questionable hack is added to allow other threads to run:
        just after an event is executed, a delay of 0 is executed, to
        avoid monopolizing the CPU when other threads are also
        runnable.

        """
        # localize variable access to minimize overhead
        # and to improve thread safety
        lock = self._lock
        q = self._queue
        delayfunc = self.delayfunc
        timefunc = self.timefunc
        pop = heapq.heappop
        while True:
            with lock:
                if not q:
                    break
                time, priority, action, argument, kwargs = q[0]
                now = timefunc()
                if time > now:
                    delay = True
                else:
                    delay = False
                    pop(q)
            if delay:
                if not blocking:
                    return time - now
                delayfunc(time - now)
            else:
                action(*argument, **kwargs)
                delayfunc(0)


Instruction:
Here you have a function in Python 3, explain what it does
def check_valid(money):
    if not isinstance(money, sc_messages.Money):
        raise ValueError(u'Inputs should be of type %s' % (sc_messages.Money,))
    currency = money.currencyCode
    if not currency or len(currency) != 3:
        raise ValueError(_MSG_3_LETTERS_LONG)
    units = money.units
    nanos = money.nanos
    if ((units > 0) and (nanos < 0)) or ((units < 0) and (nanos > 0)):
        raise ValueError(_MSG_UNITS_NANOS_MISMATCH)
    if abs(nanos) > MAX_NANOS:
        raise ValueError(_MSG_NANOS_OOB)

Response: Checks if an instance of Money is valid.


Instruction:
Create a Python 3 function for
adding two instances of Money to the internal list of services.

Response:
def add(a, b, allow_overflow=False):
    """Adds two instances of `Money`.

    Args:
      a (:class:`endpoints_management.gen.servicecontrol_v1_messages.Money`): one money
        value
      b (:class:`endpoints_management.gen.servicecontrol_v1_messages.Money`): another
        money value
      allow_overflow: determines if the addition is allowed to overflow

    Return:
      `Money`: an instance of Money

    Raises:
      ValueError: if the inputs do not have the same currency code
      OverflowError: if the sum overflows and allow_overflow is not `True`
    """
    for m in (a, b):
        if not isinstance(m, sc_messages.Money):
            raise ValueError(u'Inputs should be of type %s' % (sc_messages.Money,))
    if a.currencyCode != b.currencyCode:
        raise ValueError(u'Money values need the same currency to be summed')
    nano_carry, nanos_sum = _sum_nanos(a, b)
    units_sum_no_carry = a.units + b.units
    units_sum = units_sum_no_carry + nano_carry

    # Adjust when units_sum and nanos_sum have different signs
    if units_sum > 0 and nanos_sum < 0:
        units_sum -= 1
        nanos_sum += _BILLION
    elif units_sum < 0 and nanos_sum > 0:
        units_sum += 1
        nanos_sum -= _BILLION

    # Return the result, detecting overflow if it occurs
    sign_a = _sign_of(a)
    sign_b = _sign_of(b)
    if sign_a > 0 and sign_b > 0 and units_sum >= _INT64_MAX:
        if not allow_overflow:
            raise OverflowError(u'Money addition positive overflow')
        else:
            return sc_messages.Money(units=_INT64_MAX,
                                     nanos=MAX_NANOS,
                                     currencyCode=a.currencyCode)
    elif (sign_a < 0 and sign_b < 0 and
          (units_sum_no_carry <= -_INT64_MAX or units_sum <= -_INT64_MAX)):
        if not allow_overflow:
            raise OverflowError(u'Money addition negative overflow')
        else:
            return sc_messages.Money(units=_INT64_MIN,
                                     nanos=-MAX_NANOS,
                                     currencyCode=a.currencyCode)
    else:
        return sc_messages.Money(units=units_sum,
                                 nanos=nanos_sum,
                                 currencyCode=a.currencyCode)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _sign_of(money):
    units = money.units
    nanos = money.nanos
    if units:
        if units > 0:
            return 1
        elif units < 0:
            return -1
    if nanos:
        if nanos > 0:
            return 1
        elif nanos < 0:
            return -1
    return 0

Response: Determines the amount sign of a money instance


Instruction:
Can you generate the documentation for the following Python 3 function
def _check_jwt_claims(jwt_claims):
    current_time = time.time()

    expiration = jwt_claims[u"exp"]
    if not isinstance(expiration, INT_TYPES):
        raise suppliers.UnauthenticatedException(u'Malformed claim: "exp" must be an integer')
    if current_time >= expiration:
        raise suppliers.UnauthenticatedException(u"The auth token has already expired")

    if u"nbf" not in jwt_claims:
        return

    not_before_time = jwt_claims[u"nbf"]
    if not isinstance(not_before_time, INT_TYPES):
        raise suppliers.UnauthenticatedException(u'Malformed claim: "nbf" must be an integer')
    if current_time < not_before_time:
        raise suppliers.UnauthenticatedException(u'Current time is less than the "nbf" time')

Response: Checks whether the JWT claims should be accepted.


Instruction:
Explain what the following Python 3 code does
def _verify_required_claims_exist(jwt_claims):
    for claim_name in [u"aud", u"exp", u"iss", u"sub"]:
        if claim_name not in jwt_claims:
            raise suppliers.UnauthenticatedException(u'Missing "%s" claim' % claim_name)

Response: Verifies that the required claims exist.


Instruction:
Write a Python 3 function for
authenticating the current auth token.

Response:
def authenticate(self, auth_token, auth_info, service_name):
        """Authenticates the current auth token.

        Args:
          auth_token: the auth token.
          auth_info: the auth configurations of the API method being called.
          service_name: the name of this service.

        Returns:
          A constructed UserInfo object representing the identity of the caller.

        Raises:
          UnauthenticatedException: When
            * the issuer is not allowed;
            * the audiences are not allowed;
            * the auth token has already expired.
        """
        try:
            jwt_claims = self.get_jwt_claims(auth_token)
        except Exception as error:
            raise suppliers.UnauthenticatedException(u"Cannot decode the auth token",
                                                     error)
        _check_jwt_claims(jwt_claims)

        user_info = UserInfo(jwt_claims)

        issuer = user_info.issuer
        if issuer not in self._issuers_to_provider_ids:
            raise suppliers.UnauthenticatedException(u"Unknown issuer: " + issuer)
        provider_id = self._issuers_to_provider_ids[issuer]

        if not auth_info.is_provider_allowed(provider_id):
            raise suppliers.UnauthenticatedException(u"The requested method does not "
                                                     u"allow provider id: " + provider_id)

        # Check the audiences decoded from the auth token. The auth token is
        # allowed when 1) an audience is equal to the service name, or 2) at least
        # one audience is allowed in the method configuration.
        audiences = user_info.audiences
        has_service_name = service_name in audiences

        allowed_audiences = auth_info.get_allowed_audiences(provider_id)
        intersected_audiences = set(allowed_audiences).intersection(audiences)
        if not has_service_name and not intersected_audiences:
            raise suppliers.UnauthenticatedException(u"Audiences not allowed")

        return user_info


Instruction:
How would you code a function in Python 3 to
decode the auth_token into a JSON object and returns the result.

Response:
def get_jwt_claims(self, auth_token):
        """Decodes the auth_token into JWT claims represented as a JSON object.

        This method first tries to look up the cache and returns the result
        immediately in case of a cache hit. When cache misses, the method tries to
        decode the given auth token, verify its signature, and check the existence
        of required JWT claims. When successful, the decoded JWT claims are loaded
        into the cache and then returned.

        Args:
          auth_token: the auth token to be decoded.

        Returns:
          The decoded JWT claims.

        Raises:
          UnauthenticatedException: When the signature verification fails, or when
            required claims are missing.
        """

        def _decode_and_verify():
            jwt_claims = jwt.JWT().unpack(auth_token).payload()
            _verify_required_claims_exist(jwt_claims)

            issuer = jwt_claims[u"iss"]
            keys = self._jwks_supplier.supply(issuer)
            try:
                return jws.JWS().verify_compact(auth_token, keys)
            except (jwkest.BadSignature, jws.NoSuitableSigningKeys,
                    jws.SignerAlgError) as exception:
                raise suppliers.UnauthenticatedException(u"Signature verification failed",
                                                         exception)

        return self._cache.get_or_create(auth_token, _decode_and_verify)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def create(options, timer=None, use_deque=True):
    if options is None:  # no options, don't create cache
        return None

    if not isinstance(options, (CheckOptions, QuotaOptions, ReportOptions)):
        _logger.error(u'make_cache(): bad options %s', options)
        raise ValueError(u'Invalid options')

    if (options.num_entries <= 0):
        _logger.debug(u"did not create cache, options was %s", options)
        return None

    _logger.debug(u"creating a cache from %s", options)
    if (options.flush_interval > ZERO_INTERVAL):
        # options always has a flush_interval, but may have an expiration
        # field. If the expiration is present, use that instead of the
        # flush_interval for the ttl
        ttl = getattr(options, u'expiration', options.flush_interval)
        cache_cls = DequeOutTTLCache if use_deque else cachetools.TTLCache
        return LockedObject(
            cache_cls(
                options.num_entries,
                ttl=ttl.total_seconds(),
                timer=to_cache_timer(timer)
            ))

    cache_cls = DequeOutLRUCache if use_deque else cachetools.LRUCache
    return LockedObject(cache_cls(options.num_entries))

Response: Create a new cache with the specified options.


Instruction:
Here you have a function in Python 3, explain what it does
def to_cache_timer(datetime_func):
    if datetime_func is None:
        datetime_func = datetime.utcnow

    def _timer():
        """Return the timestamp since the epoch."""
        return (datetime_func() - datetime(1970, 1, 1)).total_seconds()

    return _timer

Response: Converts a datetime_func to a timestamp_func.


Instruction:
Can you generate the documentation for the following Python 3 function
def out_deque(self):
        self.expire()
        expired = {k: v for (k, v) in self._tracking.items() if self.get(k) is None}
        for k, v in expired.items():
            del self._tracking[k]
            self._out_deque.append(v)
        return self._out_deque

Response: The : class : collections. deque to which expired items are added.


Instruction:
Can you create a Python 3 function that
distributes the uranium package

Response:
def distribute(build):
    """ distribute the uranium package """
    build.packages.install("wheel")
    build.packages.install("twine")
    build.executables.run([
        "python", "setup.py",
        "sdist", "bdist_wheel", "--universal", "upload",
    ])
    build.executables.run([
        "twine", "upload", "dist/*"
    ])


Instruction:
Create a Python 3 function for
making Client s started after this use the appengine thread class.

Response:
def use_gae_thread():
    """Makes ``Client``s started after this use the appengine thread class."""
    global _THREAD_CLASS  # pylint: disable=global-statement
    try:
        from google.appengine.api.background_thread import background_thread
        _THREAD_CLASS = background_thread.BackgroundThread
    except ImportError:
        _logger.error(
            u'Could not install appengine background threads!'
            u' Please install the python AppEngine SDK and use this from there')


Instruction:
Create a Python 3 function for
starting processing the current instance of the class.

Response:
def start(self):
        """Starts processing.

        Calling this method

        - starts the thread that regularly flushes all enabled caches.
        - enables the other methods on the instance to be called successfully
        """
        with self._lock:
            if self._running:
                return

            self._stopped = False
            self._running = True
            self._start_idle_timer()
            _logger.debug(u'starting thread of type %s to run the scheduler',
                          _THREAD_CLASS)
            self._thread = create_thread(target=self._schedule_flushes)
            try:
                self._thread.start()
            except Exception:  # pylint: disable=broad-except
                _logger.warn(
                    u'no scheduler thread, scheduler.run() will be invoked by report(...)',
                    exc_info=True)
                self._thread = None
                self._initialize_flushing()


Instruction:
Implement a function in Python 3 to
halt processing This will lead to the reports being flushed, the caches being cleared and a stop to the current processing thread.

Response:
def stop(self):
        """Halts processing

        This will lead to the reports being flushed, the caches being cleared
        and a stop to the current processing thread.

        """
        with self._lock:
            if self._stopped:
                _logger.debug(u'%s is already stopped', self)
                return

            self._flush_all_reports()
            self._stopped = True
            if self._run_scheduler_directly:
                self._cleanup_if_stopped()

            if self._scheduler and self._scheduler.empty():
                # if there are events scheduled, then _running will subsequently
                # be set False by the scheduler thread.  This handles the
                # case where there are no events, e.g because all aggreagation
                # was disabled
                self._running = False
            self._scheduler = None


Instruction:
Make a summary of the following Python 3 code
def check(self, check_req):

        self.start()
        res = self._check_aggregator.check(check_req)
        if res:
            _logger.debug(u'using cached check response for %s: %s',
                          check_request, res)
            return res

        # Application code should not fail because check request's don't
        # complete, They should fail open, so here simply log the error and
        # return None to indicate that no response was obtained
        try:
            transport = self._create_transport()
            resp = transport.services.Check(check_req)
            self._check_aggregator.add_response(check_req, resp)
            return resp
        except exceptions.Error:  # only sink apitools errors
            _logger.error(u'direct send of check request failed %s',
                          check_request, exc_info=True)
            return None

Response: Process a check_request and return a CheckResponse object.


Instruction:
Can you generate the documentation for the following Python 3 function
def report(self, report_req):
        self.start()

        # no thread running, run the scheduler to ensure any pending
        # flush tasks are executed.
        if self._run_scheduler_directly:
            self._scheduler.run(blocking=False)

        if not self._report_aggregator.report(report_req):
            _logger.debug(u'need to send a report request directly')
            try:
                transport = self._create_transport()
                transport.services.Report(report_req)
            except exceptions.Error:  # only sink apitools errors
                _logger.error(u'direct send for report request failed',
                              exc_info=True)

Response: Processes a report request.


Instruction:
Create a Python 3 function to
construct a new metric value.

Response:
def create(labels=None, **kw):
    """Constructs a new metric value.

    This acts as an alternate to MetricValue constructor which
    simplifies specification of labels.  Rather than having to create
    a MetricValue.Labels instance, all that's necessary to specify the
    required string.

    Args:
      labels (dict([string, [string]]):
      **kw: any other valid keyword args valid in the MetricValue constructor

    Returns
      :class:`MetricValue`: the created instance

    """
    if labels is not None:
        kw[u'labels'] = encoding.PyValueToMessage(MetricValue.LabelsValue,
                                                  labels)
    return MetricValue(**kw)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def merge(metric_kind, prior, latest):
    prior_type, _ = _detect_value(prior)
    latest_type, _ = _detect_value(latest)
    if prior_type != latest_type:
        _logger.warn(u'Metric values are not compatible: %s, %s',
                     prior, latest)
        raise ValueError(u'Incompatible delta metric values')
    if prior_type is None:
        _logger.warn(u'Bad metric values, types not known for : %s, %s',
                     prior, latest)
        raise ValueError(u'Unsupported delta metric types')

    if metric_kind == MetricKind.DELTA:
        return _merge_delta_metric(prior, latest)
    else:
        return _merge_cumulative_or_gauge_metrics(prior, latest)

Response: Merges two sets of metrics into one set of objects.


Instruction:
Create a Python 3 function for
adding a metric value to the hash

Response:
def update_hash(a_hash, mv):
    """Adds ``mv`` to ``a_hash``

    Args:
       a_hash (`Hash`): the secure hash, e.g created by hashlib.md5
       mv (:class:`MetricValue`): the instance to add to the hash

    """
    if mv.labels:
        signing.add_dict_to_hash(a_hash, encoding.MessageToPyValue(mv.labels))
    money_value = mv.get_assigned_value(u'moneyValue')
    if money_value is not None:
        a_hash.update(b'\x00')
        a_hash.update(money_value.currencyCode.encode('utf-8'))


Instruction:
Can you generate a brief explanation for the following Python 3 code
def sign(mv):
    md5 = hashlib.md5()
    update_hash(md5, mv)
    return md5.digest()

Response: Obtains a unique signature for a metric value


Instruction:
How would you implement a function in Python 3 that
supplies the jwks_uri for the given issuer.

Response:
def supply(self, issuer):
        """Supplies the `jwks_uri` for the given issuer.

        Args:
          issuer: the issuer.

        Returns:
          The `jwks_uri` that is either statically configured or retrieved via
          OpenId discovery. None is returned when the issuer is unknown or the
          OpenId discovery fails.
        """
        issuer_uri_config = self._issuer_uri_configs.get(issuer)

        if not issuer_uri_config:
            # The issuer is unknown.
            return

        jwks_uri = issuer_uri_config.jwks_uri
        if jwks_uri:
            # When jwks_uri is set, return it directly.
            return jwks_uri

        # When jwksUri is empty, we try to retrieve it through the OpenID
        # discovery.
        open_id_valid = issuer_uri_config.open_id_valid
        if open_id_valid:
            discovered_jwks_uri = _discover_jwks_uri(issuer)
            self._issuer_uri_configs[issuer] = IssuerUriConfig(False,
                                                               discovered_jwks_uri)
            return discovered_jwks_uri


Instruction:
Make a summary of the following Python 3 code
def supply(self, issuer):
        def _retrieve_jwks():
            """Retrieve the JWKS from the given jwks_uri when cache misses."""
            jwks_uri = self._key_uri_supplier.supply(issuer)

            if not jwks_uri:
                raise UnauthenticatedException(u"Cannot find the `jwks_uri` for issuer "
                                               u"%s: either the issuer is unknown or "
                                               u"the OpenID discovery failed" % issuer)

            try:
                response = requests.get(jwks_uri)
                json_response = response.json()
            except Exception as exception:
                message = u"Cannot retrieve valid verification keys from the `jwks_uri`"
                raise UnauthenticatedException(message, exception)

            if u"keys" in json_response:
                # De-serialize the JSON as a JWKS object.
                jwks_keys = jwk.KEYS()
                jwks_keys.load_jwks(response.text)
                return jwks_keys._keys
            else:
                # The JSON is a dictionary mapping from key id to X.509 certificates.
                # Thus we extract the public key from the X.509 certificates and
                # construct a JWKS object.
                return _extract_x509_certificates(json_response)

        return self._jwks_cache.get_or_create(issuer, _retrieve_jwks)

Response: Supplies the Json Web Key Set for the given issuer.


Instruction:
Write a Python 3 script for
determining if a given label descriptor matches this enum instance

Response:
def matches(self, desc):
        """Determines if a given label descriptor matches this enum instance

        Args:
           desc (:class:`endpoints_management.gen.servicemanagement_v1_messages.LabelDescriptor`):
              the instance to test

        Return:
           `True` if desc is supported, otherwise `False`

        """
        desc_value_type = desc.valueType or ValueType.STRING  # default not parsed
        return (self.label_name == desc.key and
                self.value_type == desc_value_type)


Instruction:
Implement a function in Python 3 to
update a dictionary of labels using the assigned update_op_func

Response:
def do_labels_update(self, info, labels):
        """Updates a dictionary of labels using the assigned update_op_func

        Args:
           info (:class:`endpoints_management.control.report_request.Info`): the
              info instance to update
           labels (dict[string[string]]): the labels dictionary

        Return:
           `True` if desc is supported, otherwise `False`

        """
        if self.update_label_func:
            self.update_label_func(self.label_name, info, labels)


Instruction:
Write a Python 3 script for
determining if the given label descriptor is supported.

Response:
def is_supported(cls, desc):
        """Determines if the given label descriptor is supported.

        Args:
           desc (:class:`endpoints_management.gen.servicemanagement_v1_messages.LabelDescriptor`):
             the label descriptor to test

        Return:
           `True` if desc is supported, otherwise `False`

        """
        for l in cls:
            if l.matches(desc):
                return True
        return False


Instruction:
Can you generate a brief explanation for the following Python 3 code
def extract_report_spec(
        service,
        label_is_supported=label_descriptor.KnownLabels.is_supported,
        metric_is_supported=metric_descriptor.KnownMetrics.is_supported):
    """Obtains the used logs, metrics and labels from a service.

    label_is_supported and metric_is_supported are filter functions used to
    determine if label_descriptors or metric_descriptors found in the service
    are supported.

    Args:
       service (:class:`endpoints_management.gen.servicecontrol_v1_messages.Service`):
          a service instance
       label_is_supported (:func): determines if a given label is supported
       metric_is_supported (:func): determines if a given metric is supported

    Return:
       tuple: (
         logs (set[string}), # the logs to report to
         metrics (list[string]), # the metrics to use
         labels (list[string]) # the labels to add
       )
    """
    resource_descs = service.monitoredResources
    labels_dict = {}
    logs = set()
    if service.logging:
        logs = _add_logging_destinations(
            service.logging.producerDestinations,
            resource_descs,
            service.logs,
            labels_dict,
            label_is_supported
        )
    metrics_dict = {}
    monitoring = service.monitoring
    if monitoring:
        for destinations in (monitoring.consumerDestinations,
                             monitoring.producerDestinations):
            _add_monitoring_destinations(destinations,
                                         resource_descs,
                                         service.metrics,
                                         metrics_dict,
                                         metric_is_supported,
                                         labels_dict,
                                         label_is_supported)
    return logs, metrics_dict.keys(), labels_dict.keys()

Response: Extracts the log metrics and labels from a service.


Instruction:
How would you code a function in Python 3 to
extract the authentication configurations from the service.

Response:
def _extract_auth_config(self):
        """Obtains the authentication configurations."""

        service = self._service
        if not service.authentication:
            return {}

        auth_infos = {}
        for auth_rule in service.authentication.rules:
            selector = auth_rule.selector
            provider_ids_to_audiences = {}
            for requirement in auth_rule.requirements:
                provider_id = requirement.providerId
                if provider_id and requirement.audiences:
                    audiences = requirement.audiences.split(u",")
                    provider_ids_to_audiences[provider_id] = audiences
            auth_infos[selector] = AuthInfo(provider_ids_to_audiences)
        return auth_infos


Instruction:
Given the following Python 3 function, write the documentation
def _extract_methods(self):
        service = self._service
        all_urls = set()
        urls_with_options = set()
        if not service.http:
            return
        for rule in service.http.rules:
            http_method, url = _detect_pattern_option(rule)
            if not url or not http_method or not rule.selector:
                _logger.error(u'invalid HTTP binding encountered')
                continue

            # Obtain the method info
            method_info = self._get_or_create_method_info(rule.selector)
            if rule.body:
                method_info.body_field_path = rule.body
            if not self._register(http_method, url, method_info):
                continue  # detected an invalid url
            all_urls.add(url)

            if http_method == self._OPTIONS:
                urls_with_options.add(url)

        self._add_cors_options_selectors(all_urls - urls_with_options)
        self._update_usage()
        self._update_system_parameters()

Response: Extracts the methods used in the service.


Instruction:
How would you explain what the following Python 3 function does
async def get_blueprint_params(request, left: int, right: int) -> str:
    res = left * right
    return "{left}*{right}={res}".format(left=left, right=right, res=res)

Response: Multiplies left and right by left and right.


Instruction:
Write a Python 3 script to
fetch the service config from the Service Management API.

Response:
def fetch_service_config(service_name=None, service_version=None):
    """Fetches the service config from Google Service Management API.

    Args:
      service_name: the service name. When this argument is unspecified, this
        method uses the value of the "SERVICE_NAME" environment variable as the
        service name, and raises ValueError if the environment variable is unset.
      service_version: the service version. When this argument is unspecified,
        this method uses the value of the "SERVICE_VERSION" environment variable
        as the service version, and raises ValueError if the environment variable
        is unset.

    Returns: the fetched service config JSON object.

    Raises:
      ValueError: when the service name/version is neither provided as an
        argument or set as an environment variable; or when the fetched service
        config fails validation.
      Exception: when the Google Service Management API returns non-200 response.
    """
    if not service_name:
        service_name = _get_env_var_or_raise(_SERVICE_NAME_ENV_KEY)
    if not service_version:
        service_version = _get_service_version(_SERVICE_VERSION_ENV_KEY,
                                               service_name)

    _logger.debug(u'Contacting Service Management API for service %s version %s',
                  service_name, service_version)
    response = _make_service_config_request(service_name, service_version)
    _logger.debug(u'obtained service json from the management api:\n%s', response.data)
    service = encoding.JsonToMessage(messages.Service, response.data)
    _validate_service_config(service, service_name, service_version)
    return service