output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
def _get_coordinator_for_group(self, group): """ Returns the coordinator broker for a consumer group. ConsumerCoordinatorNotAvailableCode will be raised if the coordinator does not currently exist for the group. OffsetsLoadInProgressCode is raised if the coordinator is availabl...
Write a Python 3 script for returning the coordinator broker for a given consumer group.
You are a Python code architect, reviewing and designing scalable and efficient code
def _send_broker_unaware_request(self, payloads, encoder_fn, decoder_fn): """ Attempt to send a broker-agnostic request to one of the available brokers. Keep trying until you succeed. """ for (host, port) in self.hosts: requestId = self._next_id() log.debu...
How would you implement a function in Python 3 that sends a request to one of the available brokers.
As a Python code composer, you craft elegant and concise scripts.
Send a list of payloads to the broker for that topic + partition using the supplied encode and decode functions.
Given the following Python 3 function, write the documentation def _send_broker_aware_request(self, payloads, encoder_fn, decoder_fn): # encoders / decoders do not maintain ordering currently # so we need to keep this so we can rebuild order before returning original_ordering = [(p.topic, p.part...
As a Python code composer, you craft elegant and concise scripts.
def _send_consumer_aware_request(self, group, payloads, encoder_fn, decoder_fn): """ Send a list of requests to the consumer coordinator for the group specified using the supplied encode/decode functions. As the payloads that use consumer-aware requests do not contain the group (e.g. ...
Implement a Python 3 function for sending a list of requests to the consumer coordinator for the specified group and list of payloads.
As a Python code translator, you convert algorithms and pseudocode into Python.
def copy(self): """ Create an inactive copy of the client object, suitable for passing to a separate thread. Note that the copied connections are not initialized, so reinit() must be called on the returned copy. """ c = copy.deepcopy(self) for key in c.co...
Implement a Python 3 function for creating an inactive copy of the client object suitable for passing to a separate thread.
As a Python code translator, you convert algorithms and pseudocode into Python.
def load_metadata_for_topics(self, *topics): """ Fetch broker and topic-partition metadata from the server, and update internal data: broker list, topic/partition list, and topic/parition -> broker map This method should be called after receiving any error Arguments: ...
Write a Python 3 script for loading broker and topic - partition metadata for the specified topics.
As a Python code translator, you convert algorithms and pseudocode into Python.
Consume messages from kafka using the Kazoo SetPartitioner and return a list of KafkaConsumer objects.
Can you generate the documentation for the following Python 3 function def _partition(self): # KazooClient and SetPartitioner objects need to be instantiated after # the consumer process has forked. Instantiating prior to forking # gives the appearance that things are working but after forking...
You are a Python code architect, reviewing and designing scalable and efficient code
Drive the robot in the simulation field.
Explain what the following Python 3 code does def drive(self, speed, rotation_speed, tm_diff): # if the robot is disabled, don't do anything if not self.robot_enabled: return distance = speed * tm_diff angle = rotation_speed * tm_diff x = distance * math.cos(angle)...
As a python code expert, you are capable of creating scripts from specifications.
def vector_drive(self, vx, vy, vw, tm_diff): """Call this from your :func:`PhysicsEngine.update_sim` function. Will update the robot's position on the simulation field. This moves the robot using a velocity vector relative to the robot instead of by speed/rotation sp...
Can you create a Python 3 function that calls this from your :func:`PhysicsEngine.update_sim` function. Will update the robot's position on the simulation field. This moves the robot using a velocity vector relative to the robot instead of by speed/rotation speed. :param vx: Speed in x direction relative to robot in ft...
As a Python code composer, you craft elegant and concise scripts.
This function updates the robot s position and angle based on the distance of the robot.
Make a summary of the following Python 3 code def distance_drive(self, x, y, angle): with self._lock: self.vx += x self.vy += y self.angle += angle c = math.cos(self.angle) s = math.sin(self.angle) self.x += x * c - y * s self...
You are a Python code architect, reviewing and designing scalable and efficient code
def get_position(self): """ :returns: Robot's current position on the field as `(x,y,angle)`. `x` and `y` are specified in feet, `angle` is in radians """ with self._lock: return self.x, self.y, self.angle
Create a Python 3 function to return the current position of the robot.
As a Python code composer, you craft elegant and concise scripts.
def get_offset(self, x, y): """ Computes how far away and at what angle a coordinate is located. Distance is returned in feet, angle is returned in degrees :returns: distance,angle offset of the given x,y coordinate ....
Implement a Python 3 function for returning the distance and angle offset of the given x y coordinate.
As a Python code translator, you convert algorithms and pseudocode into Python.
def _check_sleep(self, idx): """This ensures that the robot code called Wait() at some point""" # TODO: There are some cases where it would be ok to do this... if not self.fake_time.slept[idx]: errstr = ( "%s() function is not calling wpilib.Timer.delay() in its loop...
How would you code a function in Python 3 to check if the robot code called Wait at some point
You are a Python code generator, capable of creating scripts from specifications.
Return two motors drivetrain.
Can you generate a brief explanation for the following Python 3 code def two_motor_drivetrain(l_motor, r_motor, x_wheelbase=2, speed=5, deadzone=None): return TwoMotorDrivetrain(x_wheelbase, speed, deadzone).get_vector(l_motor, r_motor)
As a python code expert, you are capable of creating scripts from specifications.
Get a FourMotorDrivetrain vector.
Can you tell what is the following Python 3 function doing def four_motor_drivetrain( lr_motor, rr_motor, lf_motor, rf_motor, x_wheelbase=2, speed=5, deadzone=None ): """ .. deprecated:: 2018.2.0 Use :class:`FourMotorDrivetrain` instead """ return FourMotorDrivetrain(x_wheelbase, spee...
You are a Python code generator, capable of creating scripts from specifications.
.. deprecated:: 2018.2.0 Use :class:`MecanumDrivetrain` instead
Can you generate the documentation for the following Python 3 function def mecanum_drivetrain( lr_motor, rr_motor, lf_motor, rf_motor, x_wheelbase=2, y_wheelbase=3, speed=5, deadzone=None, ): """ .. deprecated:: 2018.2.0 Use :class:`MecanumDrivetrain` instead "...
As a Python code analyst, you investigate and solve complex coding mysteries
Gets the vector of distance and speed for your robot.
Can you tell what is the following Python 3 function doing def get_vector(self, l_motor: float, r_motor: float) -> typing.Tuple[float, float]: if self.deadzone: l_motor = self.deadzone(l_motor) r_motor = self.deadzone(r_motor) l = -l_motor * self.speed r = r_motor * self...
You are a Python code architect, reviewing and designing scalable and efficient code
def get_vector( self, lr_motor: float, rr_motor: float, lf_motor: float, rf_motor: float ) -> typing.Tuple[float, float]: """ :param lr_motor: Left rear motor value (-1 to 1); -1 is forward :param rr_motor: Right rear motor value (-1 to 1); 1 is forward :param...
Create a Python 3 function for returning the vector of the robot in the current state.
As a Python code composer, you craft elegant and concise scripts.
def get_vector( self, lr_motor: float, rr_motor: float, lf_motor: float, rf_motor: float ) -> typing.Tuple[float, float, float]: """ Given motor values, retrieves the vector of (distance, speed) for your robot :param lr_motor: Left rear motor value (-1 to 1); 1 is ...
Write a Python 3 function for getting the vector of the robot from the given motors.
As a Python code composer, you craft elegant and concise scripts.
Connect to MySQL with retries.
Can you generate a brief explanation for the following Python 3 code def connect_mysql(host, port, user, password, database): return pymysql.connect( host=host, port=port, user=user, passwd=password, db=database )
As a Python code analyst, you investigate and solve complex coding mysteries
Start main part of the wait script.
Can you generate a brief explanation for the following Python 3 code def main(): logger.info('Waiting for database: `%s`', MYSQL_DB) connect_mysql( host=MYSQL_HOST, port=MYSQL_PORT, user=MYSQL_USER, password=MYSQL_PASSWORD, database=MYSQL_DB ) logger.info('Database `%s` found',...
As a Python code translator, you convert algorithms and pseudocode into Python.
def specify_data_set(self, x_input, y_input): """ Define input to ACE. Parameters ---------- x_input : list list of iterables, one for each independent variable y_input : array the dependent observations """ self.x = x_input ...
Create a Python 3 function to define input to ACE.
As a Python code translator, you convert algorithms and pseudocode into Python.
Run the ACE calculational loop.
Given the following Python 3 function, write the documentation def solve(self): self._initialize() while self._outer_error_is_decreasing() and self._outer_iters < MAX_OUTERS: print('* Starting outer iteration {0:03d}. Current err = {1:12.5E}' ''.format(self._outer_iters, se...
You are a Python code generator, capable of creating scripts from specifications.
Set up and normalize initial data once input data is specified.
Can you generate the documentation for the following Python 3 function def _initialize(self): self.y_transform = self.y - numpy.mean(self.y) self.y_transform /= numpy.std(self.y_transform) self.x_transforms = [numpy.zeros(len(self.y)) for _xi in self.x] self._compute_sorted_indices()
As a Python code composer, you craft elegant and concise scripts.
Compute the sorted indices of the possible smoothers.
Can you tell what is the following Python 3 function doing def _compute_sorted_indices(self): sorted_indices = [] for to_sort in [self.y] + self.x: data_w_indices = [(val, i) for (i, val) in enumerate(to_sort)] data_w_indices.sort() sorted_indices.append([i for val, i...
As a Python code composer, you craft elegant and concise scripts.
True if outer iteration error is decreasing.
Given the following Python 3 function, write the documentation def _outer_error_is_decreasing(self): is_decreasing, self._last_outer_error = self._error_is_decreasing(self._last_outer_error) return is_decreasing
As a Python code analyst, you investigate and solve complex coding mysteries
True if current error is less than last_error.
How would you explain what the following Python 3 function does def _error_is_decreasing(self, last_error): current_error = self._compute_error() is_decreasing = current_error < last_error return is_decreasing, current_error
As a Python code analyst, you investigate and solve complex coding mysteries
def _iterate_to_update_x_transforms(self): """Perform the inner iteration.""" self._inner_iters = 0 self._last_inner_error = float('inf') while self._inner_error_is_decreasing(): print(' Starting inner iteration {0:03d}. Current err = {1:12.5E}' ''.format(s...
Can you create a Python 3 function that performs the inner iteration.
You are a Python code analyst, evaluating scripts for potential improvements.
def _update_x_transforms(self): """ Compute a new set of x-transform functions phik. phik(xk) = theta(y) - sum of phii(xi) over i!=k This is the first of the eponymous conditional expectations. The conditional expectations are computed using the SuperSmoother. """ ...
Create a Python 3 function for updating the x - transform functions of the main expession with the new transform functions.
As a Python code composer, you craft elegant and concise scripts.
def _update_y_transform(self): """ Update the y-transform (theta). y-transform theta is forced to have mean = 0 and stddev = 1. This is the second conditional expectation """ # sort all phis wrt increasing y. sorted_data_indices = self._yi_sorted sorted_...
Write a Python 3 function for updating the y - transform.
You are a Python code analyst, evaluating scripts for potential improvements.
Write y and x values used in this run to a space - delimited txt file.
Here you have a function in Python 3, explain what it does def write_input_to_file(self, fname='ace_input.txt'): self._write_columns(fname, self.x, self.y)
As a Python code analyst, you investigate and solve complex coding mysteries
Write y and x transforms used in this run to a space - delimited txt file.
Can you generate the documentation for the following Python 3 function def write_transforms_to_file(self, fname='ace_transforms.txt'): self._write_columns(fname, self.x_transforms, self.y_transform)
As a python code expert, you are capable of creating scripts from specifications.
def build_sample_smoother_problem_friedman82(N=200): """Sample problem from supersmoother publication.""" x = numpy.random.uniform(size=N) err = numpy.random.standard_normal(N) y = numpy.sin(2 * math.pi * (1 - x) ** 2) + x * err return x, y
Can you create a Python 3 function that samples problem from supersmoother publication.
You are a Python code analyst, evaluating scripts for potential improvements.
def run_friedman82_basic(): """Run Friedman's test of fixed-span smoothers from Figure 2b.""" x, y = build_sample_smoother_problem_friedman82() plt.figure() # plt.plot(x, y, '.', label='Data') for span in smoother.DEFAULT_SPANS: smooth = smoother.BasicFixedSpanSmoother() smooth.speci...
Can you create a Python 3 function that runs Friedman s test of fixed - span smoothers from Figure 2b.
You are a Python code architect, reviewing and designing scalable and efficient code
def add_moving_element(self, element): """Add elements to the board""" element.initialize(self.canvas) self.elements.append(element)
Write a Python 3 script for adding a moving element to the board
You are a Python code generator, capable of creating scripts from specifications.
Called when a key is pressed on the keyboard.
Given the following Python 3 function, write the documentation def on_key_pressed(self, event): return # TODO if event.keysym == "Up": self.manager.set_joystick(0.0, -1.0, 0) elif event.keysym == "Down": self.manager.set_joystick(0.0, 1.0, 0) elif event...
As a Python code translator, you convert algorithms and pseudocode into Python.
Loads a json file from the simulation and creates a dictionary of the information available to the testing code.
Explain what the following Python 3 code does def _load_config(robot_path): from . import config config_obj = config.config_obj sim_path = join(robot_path, "sim") config_file = join(sim_path, "config.json") if exists(config_file): with open(config_file, "r") as fp: config_obj...
You are a Python code analyst, evaluating scripts for potential improvements.
Add a new data point to the data set to be smoothed.
How would you explain what the following Python 3 function does def add_data_point_xy(self, x, y): self.x.append(x) self.y.append(y)
You are a Python code generator, capable of creating scripts from specifications.
Fully define data by lists of x values and y values.
Can you generate the documentation for the following Python 3 function def specify_data_set(self, x_input, y_input, sort_data=False): if sort_data: xy = sorted(zip(x_input, y_input)) x, y = zip(*xy) x_input_list = list(x_input) self._original_index_of_xvalue = [x_...
As a Python code translator, you convert algorithms and pseudocode into Python.
def plot(self, fname=None): """ Plot the input data and resulting smooth. Parameters ---------- fname : str, optional name of file to produce. If none, will show interactively. """ plt.figure() xy = sorted(zip(self.x, self.smooth_result)) ...
Create a Python 3 function to plot the input data and resulting smooth.
As a Python code translator, you convert algorithms and pseudocode into Python.
def _store_unsorted_results(self, smooth, residual): """Convert sorted smooth/residual back to as-input order.""" if self._original_index_of_xvalue: # data was sorted. Unsort it here. self.smooth_result = numpy.zeros(len(self.y)) self.cross_validated_residual = numpy....
Implement a function in Python 3 to convert sorted smooth and residual back to as - input order.
As a python code expert, you are capable of creating scripts from specifications.
Perform the smoothing operations.
Can you tell what is the following Python 3 function doing def compute(self): self._compute_window_size() smooth = [] residual = [] x, y = self.x, self.y # step through x and y data with a window window_size wide. self._update_values_in_window() self._update_mea...
You are a Python code architect, reviewing and designing scalable and efficient code
def _compute_window_size(self): """Determine characteristics of symmetric neighborhood with J/2 values on each side.""" self._neighbors_on_each_side = int(len(self.x) * self._span) // 2 self.window_size = self._neighbors_on_each_side * 2 + 1 if self.window_size <= 1: # cannot...
How would you implement a function in Python 3 that determines characteristics of symmetric neighborhood with J / 2 values on each side.
You are a Python code analyst, evaluating scripts for potential improvements.
Update which values are in the current window.
Here you have a function in Python 3, explain what it does def _update_values_in_window(self): window_bound_upper = self._window_bound_lower + self.window_size self._x_in_window = self.x[self._window_bound_lower:window_bound_upper] self._y_in_window = self.y[self._window_bound_lower:window_bound...
As a Python code analyst, you investigate and solve complex coding mysteries
Compute mean in window
How would you explain what the following Python 3 function does def _update_mean_in_window(self): self._mean_x_in_window = numpy.mean(self._x_in_window) self._mean_y_in_window = numpy.mean(self._y_in_window)
As a python code expert, you are capable of creating scripts from specifications.
Compute variance and covariance in window using all values in window.
Explain what the following Python 3 code does def _update_variance_in_window(self): self._covariance_in_window = sum([(xj - self._mean_x_in_window) * (yj - self._mean_y_in_window) for xj, yj in zip(self._x_in_window, self._y_in_...
You are a Python code generator, capable of creating scripts from specifications.
Update values in current window and the current window means and variances.
How would you explain what the following Python 3 function does def _advance_window(self): x_to_remove, y_to_remove = self._x_in_window[0], self._y_in_window[0] self._window_bound_lower += 1 self._update_values_in_window() x_to_add, y_to_add = self._x_in_window[-1], self._y_in_window[-1...
You are a Python code generator, capable of creating scripts from specifications.
def _remove_observation(self, x_to_remove, y_to_remove): """Remove observation from window, updating means/variance efficiently.""" self._remove_observation_from_variances(x_to_remove, y_to_remove) self._remove_observation_from_means(x_to_remove, y_to_remove) self.window_size -= 1
Implement a Python 3 function for removing observation from window updating means and variance efficiently.
As a Python code composer, you craft elegant and concise scripts.
def _add_observation(self, x_to_add, y_to_add): """Add observation to window, updating means/variance efficiently.""" self._add_observation_to_means(x_to_add, y_to_add) self._add_observation_to_variances(x_to_add, y_to_add) self.window_size += 1
Write a Python 3 function for adding observation to window updating means and variance efficiently.
You are a Python code generator, capable of creating scripts from specifications.
Update the means without recalculating for the addition of one observation.
Make a summary of the following Python 3 code def _add_observation_to_means(self, xj, yj): self._mean_x_in_window = ((self.window_size * self._mean_x_in_window + xj) / (self.window_size + 1.0)) self._mean_y_in_window = ((self.window_size * self._mean_y_in_window + yj) /...
You are a Python code analyst, evaluating scripts for potential improvements.
Update the means without recalculating for the deletion of one observation.
Can you generate the documentation for the following Python 3 function def _remove_observation_from_means(self, xj, yj): self._mean_x_in_window = ((self.window_size * self._mean_x_in_window - xj) / (self.window_size - 1.0)) self._mean_y_in_window = ((self.window_size * ...
You are a Python code analyst, evaluating scripts for potential improvements.
def _add_observation_to_variances(self, xj, yj): """ Quickly update the variance and co-variance for the addition of one observation. See Also -------- _update_variance_in_window : compute variance considering full window """ term1 = (self.window_size + 1.0) / se...
How would you code a function in Python 3 to add observation to the variance and co - variance.
As a Python code translator, you convert algorithms and pseudocode into Python.
def _compute_smooth_during_construction(self, xi): """ Evaluate value of smooth at x-value xi. Parameters ---------- xi : float Value of x where smooth value is desired Returns ------- smooth_here : float Value of smooth s(xi) ...
Create a Python 3 function to compute the value of the smooth at x - value xi.
You are a Python code analyst, evaluating scripts for potential improvements.
Compute cross validated residual.
Given the following Python 3 function, write the documentation def _compute_cross_validated_residual_here(self, xi, yi, smooth_here): denom = (1.0 - 1.0 / self.window_size - (xi - self._mean_x_in_window) ** 2 / self._variance_in_window) if denom == 0.0: # ca...
You are a Python code architect, reviewing and designing scalable and efficient code
def build_sample_ace_problem_breiman85(N=200): """Sample problem from Breiman 1985.""" x_cubed = numpy.random.standard_normal(N) x = scipy.special.cbrt(x_cubed) noise = numpy.random.standard_normal(N) y = numpy.exp((x ** 3.0) + noise) return [x], y
Create a Python 3 function for sampling problem from Breiman 1985.
You are a Python code generator, capable of creating scripts from specifications.
def build_sample_ace_problem_breiman2(N=500): """Build sample problem y(x) = exp(sin(x)).""" x = numpy.linspace(0, 1, N) # x = numpy.random.uniform(0, 1, size=N) noise = numpy.random.standard_normal(N) y = numpy.exp(numpy.sin(2 * numpy.pi * x)) + 0.0 * noise return [x], y
Can you write a function in Python 3 where it builds sample problem y x = 1 y = 2
As a Python code translator, you convert algorithms and pseudocode into Python.
Run Breiman 85 sample.
Can you generate the documentation for the following Python 3 function def run_breiman85(): x, y = build_sample_ace_problem_breiman85(200) ace_solver = ace.ACESolver() ace_solver.specify_data_set(x, y) ace_solver.solve() try: ace.plot_transforms(ace_solver, 'sample_ace_breiman85.png') ex...
As a Python code composer, you craft elegant and concise scripts.
def run_breiman2(): """Run Breiman's other sample problem.""" x, y = build_sample_ace_problem_breiman2(500) ace_solver = ace.ACESolver() ace_solver.specify_data_set(x, y) ace_solver.solve() try: plt = ace.plot_transforms(ace_solver, None) except ImportError: pass plt.sub...
Write a Python 3 function that can run Breiman s other sample problem.
You are a Python code architect, reviewing and designing scalable and efficient code
def publish(self, topic, messages, key=None): """Takes messages and puts them on the supplied kafka topic """ if not isinstance(messages, list): messages = [messages] first = True success = False if key is None: key = int(time.time() * 1000) ...
Can you implement a function in Python 3 that takes messages and puts them on the supplied kafka topic ovaova
As a Python code translator, you convert algorithms and pseudocode into Python.
def create_gzip_message(payloads, key=None, compresslevel=None): """ Construct a Gzipped Message containing multiple Messages The given payloads will be encoded, compressed, and sent as a single atomic message to Kafka. Arguments: payloads: list(bytes), a list of payload to send be sent to...
How would you code a function in Python 3 to construct a Gzipped Message containing multiple Messages
As a python code expert, you are capable of creating scripts from specifications.
def _encode_message(cls, message): """ Encode a single message. The magic number of a message is a format version number. The only supported magic number right now is zero Format ====== Message => Crc MagicByte Attributes Key Value Crc => int32 ...
Implement a Python 3 function for encoding a single message.
As a Python code composer, you craft elegant and concise scripts.
def _decode_message_set_iter(cls, data): """ Iteratively decode a MessageSet Reads repeated elements of (offset, message), calling decode_message to decode a single message. Since compressed messages contain futher MessageSets, these two methods have been decoupled so that they ...
Can you write a function in Python 3 where it iterates over the message set data.
You are a Python code generator, capable of creating scripts from specifications.
Decode a single MessageSet.
Here you have a function in Python 3, explain what it does def _decode_message(cls, data, offset): ((crc, magic, att), cur) = relative_unpack('>IBB', data, 0) if crc != crc32(data[4:]): raise ChecksumError("Message checksum failed") (key, cur) = read_int_string(data, cur) (v...
As a Python code analyst, you investigate and solve complex coding mysteries
def encode_produce_request(cls, client_id, correlation_id, payloads=None, acks=1, timeout=1000): """ Encode some ProduceRequest structs Arguments: client_id: string correlation_id: int payloads: list of ProduceRequest ...
Implement a Python 3 function for encoding ProduceRequest structs into a string that can be sent to Kafka.
As a Python code translator, you convert algorithms and pseudocode into Python.
Decodes a bytes to a ProduceResponse object
Can you tell what is the following Python 3 function doing def decode_produce_response(cls, data): ((correlation_id, num_topics), cur) = relative_unpack('>ii', data, 0) for _ in range(num_topics): ((strlen,), cur) = relative_unpack('>h', data, cur) topic = data[cur:cur + strlen]...
As a Python code composer, you craft elegant and concise scripts.
Encodes some FetchRequest structs into a string that can be sent to Kafka.
Explain what the following Python 3 code does def encode_fetch_request(cls, client_id, correlation_id, payloads=None, max_wait_time=100, min_bytes=4096): """ Encodes some FetchRequest structs Arguments: client_id: string correlation_id: int ...
You are a Python code generator, capable of creating scripts from specifications.
Decode bytes to a FetchResponse object
Given the following Python 3 function, write the documentation def decode_fetch_response(cls, data): ((correlation_id, num_topics), cur) = relative_unpack('>ii', data, 0) for _ in range(num_topics): (topic, cur) = read_short_string(data, cur) ((num_partitions,), cur) = relative_...
As a Python code analyst, you investigate and solve complex coding mysteries
Decode bytes to an OffsetResponse
Given the following Python 3 function, write the documentation def decode_offset_response(cls, data): ((correlation_id, num_topics), cur) = relative_unpack('>ii', data, 0) for _ in range(num_topics): (topic, cur) = read_short_string(data, cur) ((num_partitions,), cur) = relative...
You are a Python code analyst, evaluating scripts for potential improvements.
def encode_metadata_request(cls, client_id, correlation_id, topics=None, payloads=None): """ Encode a MetadataRequest Arguments: client_id: string correlation_id: int topics: list of strings """ if payloads is N...
Implement a Python 3 function for encoding a MetadataRequest object.
As a python code expert, you are capable of creating scripts from specifications.
def decode_metadata_response(cls, data): """ Decode bytes to a MetadataResponse Arguments: data: bytes to decode """ ((correlation_id, numbrokers), cur) = relative_unpack('>ii', data, 0) # Broker info brokers = [] for _ in range(numbrokers): ...
Write a Python 3 script to decode the bytes to a MetadataResponse object.
As a Python code translator, you convert algorithms and pseudocode into Python.
Encode some OffsetCommitRequest structs that are used to commit the offsets for a specific consumer group.
Can you generate a brief explanation for the following Python 3 code def encode_offset_commit_request(cls, client_id, correlation_id, group, payloads): """ Encode some OffsetCommitRequest structs Arguments: client_id: string correlati...
You are a Python code generator, capable of creating scripts from specifications.
Decode bytes to an OffsetCommitResponse object
Given the following Python 3 function, write the documentation def decode_offset_commit_response(cls, data): ((correlation_id,), cur) = relative_unpack('>i', data, 0) ((num_topics,), cur) = relative_unpack('>i', data, cur) for _ in xrange(num_topics): (topic, cur) = read_short_strin...
You are a Python code architect, reviewing and designing scalable and efficient code
Encode some OffsetFetchRequest structs.
How would you explain what the following Python 3 function does def encode_offset_fetch_request(cls, client_id, correlation_id, group, payloads, from_kafka=False): """ Encode some OffsetFetchRequest structs. The request is encoded using version 0 if from_kafka...
As a Python code composer, you craft elegant and concise scripts.
def decode_offset_fetch_response(cls, data): """ Decode bytes to an OffsetFetchResponse Arguments: data: bytes to decode """ ((correlation_id,), cur) = relative_unpack('>i', data, 0) ((num_topics,), cur) = relative_unpack('>i', data, cur) for _ in r...
Can you create a Python 3 function that decodes bytes to an OffsetFetchResponse object
As a Python code composer, you craft elegant and concise scripts.
def _get_module(target): """Import a named class, module, method or function. Accepts these formats: ".../file/path|module_name:Class.method" ".../file/path|module_name:Class" ".../file/path|module_name:function" "module_name:Class" "module_name:function" "module...
Write a Python 3 function for importing a named class module method or function.
As a Python code analyst, you investigate and solve complex coding mysteries
Get the actual implementation of the target.
Given the following Python 3 function, write the documentation def load(target, source_module=None): module, klass, function = _get_module(target) if not module and source_module: module = source_module if not module: raise MissingModule( "No module name supplied or source_module...
You are a Python code generator, capable of creating scripts from specifications.
This function changes the class references to not have the intermediate module name by hacking at the doctree
Explain what the following Python 3 code does def process_child(node): # Edit descriptions to be nicer if isinstance(node, sphinx.addnodes.desc_addname): if len(node.children) == 1: child = node.children[0] text = child.astext() if text.startswith("wpilib.") and text...
You are a Python code analyst, evaluating scripts for potential improvements.
def commit(self, partitions=None): """Commit stored offsets to Kafka via OffsetCommitRequest (v0) Keyword Arguments: partitions (list): list of partitions to commit, default is to commit all of them Returns: True on success, False on failure """ # s...
How would you implement a function in Python 3 that commits stored offsets to Kafka via OffsetCommitRequest.
You are a Python code generator, capable of creating scripts from specifications.
def read_column_data_from_txt(fname): """ Read data from a simple text file. Format should be just numbers. First column is the dependent variable. others are independent. Whitespace delimited. Returns ------- x_values : list List of x columns y_values : list list o...
Write a Python 3 script to read data from a simple text file.
As a python code expert, you are capable of creating scripts from specifications.
def build_model_from_txt(self, fname): """ Construct the model and perform regressions based on data in a txt file. Parameters ---------- fname : str The name of the file to load. """ x_values, y_values = read_column_data_from_txt(fname) self....
Create a Python 3 function for building the model based on the data in a txt file.
As a python code expert, you are capable of creating scripts from specifications.
Construct the model and perform regressions based on x and y data.
How would you explain what the following Python 3 function does def build_model_from_xy(self, x_values, y_values): self.init_ace(x_values, y_values) self.run_ace() self.build_interpolators()
You are a Python code generator, capable of creating scripts from specifications.
def build_interpolators(self): """Compute 1-D interpolation functions for all the transforms so they're continuous..""" self.phi_continuous = [] for xi, phii in zip(self.ace.x, self.ace.x_transforms): self.phi_continuous.append(interp1d(xi, phii)) self.inverse_theta_continuou...
Can you create a Python 3 function that computes 1 - D interpolation functions for all the transforms so they re continuous..
You are a Python code analyst, evaluating scripts for potential improvements.
def eval(self, x_values): """ Evaluate the ACE regression at any combination of independent variable values. Parameters ---------- x_values : iterable a float x-value for each independent variable, e.g. (1.5, 2.5) """ if len(x_values) != len(self.phi_...
How would you implement a function in Python 3 that evaluates the ACE regression at any combination of independent variable values.
You are a Python code generator, capable of creating scripts from specifications.
Returns True if user answers y
How would you explain what the following Python 3 function does def yesno(prompt): prompt += " [y/n]" a = "" while a not in ["y", "n"]: a = input(prompt).lower() return a == "y"
As a Python code analyst, you investigate and solve complex coding mysteries
def retry(retries=KAFKA_WAIT_RETRIES, delay=KAFKA_WAIT_INTERVAL, check_exceptions=()): """Retry decorator.""" def decorator(func): """Decorator.""" def f_retry(*args, **kwargs): """Retry running function on exception after delay.""" for i in range(1, retries + 1...
How would you code a function in Python 3 to retry a function on exception after a given number of times.
You are a Python code generator, capable of creating scripts from specifications.
Check if topics exist in Kafka.
Make a summary of the following Python 3 code def check_topics(client, req_topics): client.update_cluster() logger.debug('Found topics: %r', client.topics.keys()) for req_topic in req_topics: if req_topic not in client.topics.keys(): err_topic_not_found = 'Topic not found: {}'.format(re...
You are a Python code generator, capable of creating scripts from specifications.
Start main part of the wait script.
Explain what the following Python 3 code does def main(): logger.info('Checking for available topics: %r', repr(REQUIRED_TOPICS)) client = connect_kafka(hosts=KAFKA_HOSTS) check_topics(client, REQUIRED_TOPICS)
You are a Python code architect, reviewing and designing scalable and efficient code
def collect_hosts(hosts, randomize=True): """ Collects a comma-separated set of hosts (host:port) and optionally randomize the returned list. """ if isinstance(hosts, six.string_types): hosts = hosts.strip().split(',') result = [] for host_port in hosts: res = host_port.sp...
Implement a Python 3 function for collecting a comma - separated set of hosts and optionally randomize the returned list.
As a Python code translator, you convert algorithms and pseudocode into Python.
def send(self, request_id, payload): """ Send a request to Kafka Arguments:: request_id (int): can be any int (used only for debug logging...) payload: an encoded kafka packet (see KafkaProtocol) """ log.debug("About to send %d bytes to Kafka, request %d...
Write a Python 3 script for sending a request to Kafka
You are a Python code analyst, evaluating scripts for potential improvements.
Read a response packet from the server
Here you have a function in Python 3, explain what it does def recv(self, request_id): log.debug("Reading response %d from Kafka" % request_id) # Make sure we have a connection if not self._sock: self.reinit() # Read the size off of the header resp = self._read_byte...
You are a Python code analyst, evaluating scripts for potential improvements.
def copy(self): """ Create an inactive copy of the connection object, suitable for passing to a background thread. The returned copy is not connected; you must call reinit() before using. """ c = copy.deepcopy(self) # Python 3 doesn't copy custom attribut...
Implement a function in Python 3 to create an inactive copy of the connection object suitable for passing to a background thread.
You are a Python code architect, reviewing and designing scalable and efficient code
Closes the socket connection and returns None
Here you have a function in Python 3, explain what it does def close(self): log.debug("Closing socket connection for %s:%d" % (self.host, self.port)) if self._sock: # Call shutdown to be a good TCP client # But expect an error if the socket has already been # closed b...
You are a Python code analyst, evaluating scripts for potential improvements.
def configure(self, **configs): """Configure the consumer instance Configuration settings can be passed to constructor, otherwise defaults will be used: Keyword Arguments: bootstrap_servers (list): List of initial broker nodes the consumer should contact to ...
How would you implement a function in Python 3 that configures the consumer instance Configuration settings can be passed to constructor, otherwise defaults will be used: Keyword Arguments: bootstrap_servers (list): List of initial broker nodes the consumer should contact to bootstrap initial cluster metadata. This doe...
As a Python code analyst, you investigate and solve complex coding mysteries
Sets the topic and partition lists to consume from the given topics.
Can you tell what is the following Python 3 function doing def set_topic_partitions(self, *topics): self._topics = [] self._client.load_metadata_for_topics() # Setup offsets self._offsets = OffsetsStruct(fetch=dict(), commit=dict(), ...
You are a Python code analyst, evaluating scripts for potential improvements.
Return the next available KafkaMessage from the message iterator
Given the following Python 3 function, write the documentation def next(self): self._set_consumer_timeout_start() while True: try: return six.next(self._get_message_iterator()) # Handle batch completion except StopIteration: self._res...
You are a Python code analyst, evaluating scripts for potential improvements.
def fetch_messages(self): """Sends FetchRequests for all topic/partitions set for consumption Returns: Generator that yields KafkaMessage structs after deserializing with the configured `deserializer_class` Note: Refreshes metadata on errors, and resets fetc...
Can you implement a function in Python 3 that sends FetchRequests for all topics and partitions and returns a generator that yields KafkaMessage structs for each of them.
You are a Python code generator, capable of creating scripts from specifications.
def get_partition_offsets(self, topic, partition, request_time_ms, max_num_offsets): """Request available fetch offsets for a single topic/partition Keyword Arguments: topic (str): topic for offset request partition (int): partition for offset request request_time_ms...
Write a Python 3 function that can request available fetch offsets for a single topic and partition.
As a Python code composer, you craft elegant and concise scripts.
def offsets(self, group=None): """Get internal consumer offset values Keyword Arguments: group: Either "fetch", "commit", "task_done", or "highwater". If no group specified, returns all groups. Returns: A copy of internal offsets struct """ ...
Write a Python 3 script to get internal consumer offset values.
As a python code expert, you are capable of creating scripts from specifications.
def task_done(self, message): """Mark a fetched message as consumed. Offsets for messages marked as "task_done" will be stored back to the kafka cluster for this consumer group on commit() Arguments: message (KafkaMessage): the message to mark as complete Returns: ...
Can you write a function in Python 3 where it marks a message as consumed and store the offset of the next message to fetch.
As a Python code translator, you convert algorithms and pseudocode into Python.
def commit(self): """Store consumed message offsets (marked via task_done()) to kafka cluster for this consumer_group. Returns: True on success, or False if no offsets were found for commit Note: this functionality requires server version >=0.8.1.1 h...
Implement a Python 3 function for committing consumed message offsets to kafka cluster.
You are a Python code analyst, evaluating scripts for potential improvements.