Unnamed: 0
int64
0
2.93k
code
stringlengths
101
62.2k
docs
stringlengths
51
10.7k
doc_len
int64
4
1.74k
words
int64
4
4.82k
lang
stringclasses
1 value
prompt
stringlengths
320
71.2k
400
def _roll_vectorized(M, roll_indices, axis): assert axis in [0, 1] ndim = M.ndim assert ndim == 3 ndim_roll = roll_indices.ndim assert ndim_roll == 1 sh = M.shape r, c = sh[-2:] assert sh[0] == roll_indices.shape[0] vec_indices = np.arange(sh[0], dtype=np.int32) # Builds the rolled matrix M_roll = np.empty_like(M) if axis == 0: for ir in range(r): for ic in range(c): M_roll[:, ir, ic] = M[vec_indices, (-roll_indices+ir) % r, ic] else: # 1 for ir in range(r): for ic in range(c): M_roll[:, ir, ic] = M[vec_indices, ir, (-roll_indices+ic) % c] return M_roll
Roll an array of matrices along *axis* (0: rows, 1: columns) according to an array of indices *roll_indices*.
18
89
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _roll_vectorized(M, roll_indices, axis): assert axis in [0, 1] ndim = M.ndim assert ndim == 3 ndim_roll = roll_indices.ndim assert ndim_roll == 1 sh = M.shape r, c = sh[-2:] assert sh[0] == roll_indices.shape[0] vec_indices = np.arange(sh[0], dtype=np.int32) # Builds the rolled matrix M_roll = np.empty_like(M) if axis == 0: for ir in range(r): for ic in range(c): M_roll[:, ir, ic] = M[vec_indices, (-roll_indices+ir) % r, ic] else: # 1 for ir in range(r): for ic in range(c): M_roll[:, ir, ic] = M[vec_indices, ir, (-roll_indices+ic) % c] return M_roll ``` ###Assistant : Roll an array of matrices along *axis* (0: rows, 1: columns) according to an array of indices *roll_indices*.
401
def test_calibration_1_vs_all_vis_api(experiment_to_use): experiment = experiment_to_use probabilities = experiment.probabilities viz_outputs = ("pdf", "png") with TemporaryDirectory() as tmpvizdir: for viz_output in viz_outputs: vis_output_pattern_pdf = os.path.join(tmpvizdir, f"*.{viz_output}") visualize.calibration_1_vs_all( [probabilities, probabilities], experiment.ground_truth, experiment.ground_truth_metadata, experiment.output_feature_name, top_n_classes=[6], labels_limit=0, model_namess=["Model1", "Model2"], output_directory=tmpvizdir, file_format=viz_output, ) figure_cnt = glob.glob(vis_output_pattern_pdf) assert 7 == len(figure_cnt)
Ensure pdf and png figures can be saved via visualization API call. :param experiment_to_use: Object containing trained model and results to test visualization :return: None
25
44
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_calibration_1_vs_all_vis_api(experiment_to_use): experiment = experiment_to_use probabilities = experiment.probabilities viz_outputs = ("pdf", "png") with TemporaryDirectory() as tmpvizdir: for viz_output in viz_outputs: vis_output_pattern_pdf = os.path.join(tmpvizdir, f"*.{viz_output}") visualize.calibration_1_vs_all( [probabilities, probabilities], experiment.ground_truth, experiment.ground_truth_metadata, experiment.output_feature_name, top_n_classes=[6], labels_limit=0, model_namess=["Model1", "Model2"], output_directory=tmpvizdir, file_format=viz_output, ) figure_cnt = glob.glob(vis_output_pattern_pdf) assert 7 == len(figure_cnt) ``` ###Assistant : Ensure pdf and png figures can be saved via visualization API call. :param experiment_to_use: Object containing trained model and results to test visualization :return: None
402
def test_send_server_notice_delete_room(self) -> None: # user has no room memberships self._check_invite_and_join_status(self.other_user, 0, 0) # send first message channel = self.make_request( "POST", self.url, access_token=self.admin_user_tok, content={ "user_id": self.other_user, "content": {"msgtype": "m.text", "body": "test msg one"}, }, ) self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body) # user has one invite invited_rooms = self._check_invite_and_join_status(self.other_user, 1, 0) first_room_id = invited_rooms[0].room_id # user joins the room and is member now self.helper.join( room=first_room_id, user=self.other_user, tok=self.other_user_token ) self._check_invite_and_join_status(self.other_user, 0, 1) # get messages messages = self._sync_and_get_messages(first_room_id, self.other_user_token) self.assertEqual(len(messages), 1) self.assertEqual(messages[0]["content"]["body"], "test msg one") self.assertEqual(messages[0]["sender"], "@notices:test") # shut down and purge room self.get_success( self.room_shutdown_handler.shutdown_room(first_room_id, self.admin_user) ) self.get_success(self.pagination_handler.purge_room(first_room_id)) # user is not member anymore self._check_invite_and_join_status(self.other_user, 0, 0) # It doesn't really matter what API we use here, we just want to assert # that the room doesn't exist. summary = self.get_success(self.store.get_room_summary(first_room_id)) # The summary should be empty since the room doesn't exist. self.assertEqual(summary, {}) # invalidate cache of server notices room_ids # if server tries to send to a cached room_id it gives an error self.server_notices_manager.get_or_create_notice_room_for_user.invalidate_all() # send second message channel = self.make_request( "POST", self.url, access_token=self.admin_user_tok, content={ "user_id": self.other_user, "content": {"msgtype": "m.text", "body": "test msg two"}, }, ) self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body) # user has one invite invited_rooms = self._check_invite_and_join_status(self.other_user, 1, 0) second_room_id = invited_rooms[0].room_id # user joins the room and is member now self.helper.join( room=second_room_id, user=self.other_user, tok=self.other_user_token ) self._check_invite_and_join_status(self.other_user, 0, 1) # get message messages = self._sync_and_get_messages(second_room_id, self.other_user_token) self.assertEqual(len(messages), 1) self.assertEqual(messages[0]["content"]["body"], "test msg two") self.assertEqual(messages[0]["sender"], "@notices:test") # second room has new ID self.assertNotEqual(first_room_id, second_room_id)
Tests that the user get server notice in a new room after the first server notice room was deleted.
19
240
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_send_server_notice_delete_room(self) -> None: # user has no room memberships self._check_invite_and_join_status(self.other_user, 0, 0) # send first message channel = self.make_request( "POST", self.url, access_token=self.admin_user_tok, content={ "user_id": self.other_user, "content": {"msgtype": "m.text", "body": "test msg one"}, }, ) self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body) # user has one invite invited_rooms = self._check_invite_and_join_status(self.other_user, 1, 0) first_room_id = invited_rooms[0].room_id # user joins the room and is member now self.helper.join( room=first_room_id, user=self.other_user, tok=self.other_user_token ) self._check_invite_and_join_status(self.other_user, 0, 1) # get messages messages = self._sync_and_get_messages(first_room_id, self.other_user_token) self.assertEqual(len(messages), 1) self.assertEqual(messages[0]["content"]["body"], "test msg one") self.assertEqual(messages[0]["sender"], "@notices:test") # shut down and purge room self.get_success( self.room_shutdown_handler.shutdown_room(first_room_id, self.admin_user) ) self.get_success(self.pagination_handler.purge_room(first_room_id)) # user is not member anymore self._check_invite_and_join_status(self.other_user, 0, 0) # It doesn't really matter what API we use here, we just want to assert # that the room doesn't exist. summary = self.get_success(self.store.get_room_summary(first_room_id)) # The summary should be empty since the room doesn't exist. self.assertEqual(summary, {}) # invalidate cache of server notices room_ids # if server tries to send to a cached room_id it gives an error self.server_notices_manager.get_or_create_notice_room_for_user.invalidate_all() # send second message channel = self.make_request( "POST", self.url, access_token=self.admin_user_tok, content={ "user_id": self.other_user, "content": {"msgtype": "m.text", "body": "test msg two"}, }, ) self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body) # user has one invite invited_rooms = self._check_invite_and_join_status(self.other_user, 1, 0) second_room_id = invited_rooms[0].room_id # user joins the room and is member now self.helper.join( room=second_room_id, user=self.other_user, tok=self.other_user_token ) self._check_invite_and_join_status(self.other_user, 0, 1) # get message messages = self._sync_and_get_messages(second_room_id, self.other_user_token) self.assertEqual(len(messages), 1) self.assertEqual(messages[0]["content"]["body"], "test msg two") self.assertEqual(messages[0]["sender"], "@notices:test") # second room has new ID self.assertNotEqual(first_room_id, second_room_id) ``` ###Assistant : Tests that the user get server notice in a new room after the first server notice room was deleted.
403
def is_request_failed_response(resp): return len( resp.get('failures', []) ) > 0 or APIUtils.METASEQ_FAIL_MESSAGE_TEXT in resp.get('text', '')
Whether the requests to Metaseq worker have failed. It checks this based on the existences of the failure reasons as they get accumulated in `_make_request` functionn calls.
27
14
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def is_request_failed_response(resp): return len( resp.get('failures', []) ) > 0 or APIUtils.METASEQ_FAIL_MESSAGE_TEXT in resp.get('text', '') ``` ###Assistant : Whether the requests to Metaseq worker have failed. It checks this based on the existences of the failure reasons as they get accumulated in `_make_request` functionn calls.
404
def draw(self, renderer): if not self.get_visible(): return self._recompute_transform() width = self.convert_xunits(self.width) height = self.convert_yunits(self.height) # If the width and height of ellipse are not equal, take into account # stretching when calculating angles to draw between
Draw the arc to the given *renderer*. Notes ----- Ellipses are normally drawn using an approximation that uses eight cubic Bezier splines. The error of this approximation is 1.89818e-6, according to this unverified source: Lancaster, Don. *Approximating a Circle or an Ellipse Using Four Bezier Cubic Splines.* https://www.tinaja.com/glib/ellipse4.pdf There is a use case where very large ellipses must be drawn with very high accuracy, and it is too expensive to render the entire ellipse with enough segments (either splines or line segments). Therefore, in the case where either radius of the ellipse is large enough that the error of the spline approximation will be visible (greater than one pixel offset from the ideal), a different technique is used. In that case, only the visible parts of the ellipse are drawn, with each visible arc using a fixed number of spline segments (8). The algorithm proceeds as follows: 1. The points where the ellipse intersects the axes (or figure) bounding box are located. (This is done by performing an inverse transformation on the bbox such that it is relative to the unit circle -- this makes the intersection calculation much easier than doing rotated ellipse intersection directly.) This uses the "line intersecting a circle" algorithm from: Vince, John. *Geometry for Computer Graphics: Formulae, Examples & Proofs.* London: Springer-Verlag, 2005. 2. The angles of each of the intersection points are calculated. 3. Proceeding counterclockwise starting in the positive x-direction, each of the visible arc-segments between the pairs of vertices are drawn using the Bezier arc approximation technique implemented in `.Path.arc`.
258
36
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def draw(self, renderer): if not self.get_visible(): return self._recompute_transform() width = self.convert_xunits(self.width) height = self.convert_yunits(self.height) # If the width and height of ellipse are not equal, take into account # stretching when calculating angles to draw between ``` ###Assistant : Draw the arc to the given *renderer*. Notes ----- Ellipses are normally drawn using an approximation that uses eight cubic Bezier splines. The error of this approximation is 1.89818e-6, according to this unverified source: Lancaster, Don. *Approximating a Circle or an Ellipse Using Four Bezier Cubic Splines.* https://www.tinaja.com/glib/ellipse4.pdf There is a use case where very large ellipses must be drawn with very high accuracy, and it is too expensive to render the entire ellipse with enough segments (either splines or line segments). Therefore, in the case where either radius of the ellipse is large enough that the error of the spline approximation will be visible (greater than one pixel offset from the ideal), a different technique is used. In that case, only the visible parts of the ellipse are drawn, with each visible arc using a fixed number of spline segments (8). The algorithm proceeds as follows: 1. The points where the ellipse intersects the axes (or figure) bounding box are located. (This is done by performing an inverse transformation on the bbox such that it is relative to the unit circle -- this makes the intersection calculation much easier than doing rotated ellipse intersection directly.) This uses the "line intersecting a circle" algorithm from: Vince, John. *Geometry for Computer Graphics: Formulae, Examples & Proofs.* London: Springer-Verlag, 2005. 2. The angles of each of the intersection points are calculated. 3. Proceeding counterclockwise starting in the positive x-direction, each of the visible arc-segments between the pairs of vertices are drawn using the Bezier arc approximation technique implemented in `.Path.arc`.
405
def validate_parameter_constraints(parameter_constraints, params, caller_name): for param_name, param_val in params.items(): # We allow parameters to not have a constraint so that third party estimators # can inherit from sklearn estimators without having to necessarily use the # validation tools. if param_name not in parameter_constraints: continue constraints = parameter_constraints[param_name] if constraints == "no_validation": continue constraints = [make_constraint(constraint) for constraint in constraints] for constraint in constraints: if constraint.is_satisfied_by(param_val): # this constraint is satisfied, no need to check further. break else: # No constraint is satisfied, raise with an informative message. # Ignore constraints that we don't want to expose in the error message, # i.e. options that are for internal purpose or not officially supported. constraints = [ constraint for constraint in constraints if not constraint.hidden ] if len(constraints) == 1: constraints_str = f"{constraints[0]}" else: constraints_str = ( f"{', '.join([str(c) for c in constraints[:-1]])} or" f" {constraints[-1]}" ) raise ValueError( f"The {param_name!r} parameter of {caller_name} must be" f" {constraints_str}. Got {param_val!r} instead." )
Validate types and values of given parameters. Parameters ---------- parameter_constraints : dict or {"no_validation"} If "no_validation", validation is skipped for this parameter. If a dict, it must be a dictionary `param_name: list of constraints`. A parameter is valid if it satisfies one of the constraints from the list. Constraints can be: - an Interval object, representing a continuous or discrete range of numbers - the string "array-like" - the string "sparse matrix" - the string "random_state" - callable - None, meaning that None is a valid value for the parameter - any type, meaning that any instance of this type is valid - an Options object, representing a set of elements of a given type - a StrOptions object, representing a set of strings - the string "boolean" - the string "verbose" - the string "cv_object" - the string "missing_values" - a HasMethods object, representing method(s) an object must have - a Hidden object, representing a constraint not meant to be exposed to the user params : dict A dictionary `param_name: param_value`. The parameters to validate against the constraints. caller_name : str The name of the estimator or function or method that called this function.
195
160
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def validate_parameter_constraints(parameter_constraints, params, caller_name): for param_name, param_val in params.items(): # We allow parameters to not have a constraint so that third party estimators # can inherit from sklearn estimators without having to necessarily use the # validation tools. if param_name not in parameter_constraints: continue constraints = parameter_constraints[param_name] if constraints == "no_validation": continue constraints = [make_constraint(constraint) for constraint in constraints] for constraint in constraints: if constraint.is_satisfied_by(param_val): # this constraint is satisfied, no need to check further. break else: # No constraint is satisfied, raise with an informative message. # Ignore constraints that we don't want to expose in the error message, # i.e. options that are for internal purpose or not officially supported. constraints = [ constraint for constraint in constraints if not constraint.hidden ] if len(constraints) == 1: constraints_str = f"{constraints[0]}" else: constraints_str = ( f"{', '.join([str(c) for c in constraints[:-1]])} or" f" {constraints[-1]}" ) raise ValueError( f"The {param_name!r} parameter of {caller_name} must be" f" {constraints_str}. Got {param_val!r} instead." ) ``` ###Assistant : Validate types and values of given parameters. Parameters ---------- parameter_constraints : dict or {"no_validation"} If "no_validation", validation is skipped for this parameter. If a dict, it must be a dictionary `param_name: list of constraints`. A parameter is valid if it satisfies one of the constraints from the list. Constraints can be: - an Interval object, representing a continuous or discrete range of numbers - the string "array-like" - the string "sparse matrix" - the string "random_state" - callable - None, meaning that None is a valid value for the parameter - any type, meaning that any instance of this type is valid - an Options object, representing a set of elements of a given type - a StrOptions object, representing a set of strings - the string "boolean" - the string "verbose" - the string "cv_object" - the string "missing_values" - a HasMethods object, representing method(s) an object must have - a Hidden object, representing a constraint not meant to be exposed to the user params : dict A dictionary `param_name: param_value`. The parameters to validate against the constraints. caller_name : str The name of the estimator or function or method that called this function.
406
def _get_module_collection_mode(mode_dict, name): mode = 'pyc' # Default mode # No settings available - return default. if not mode_dict: return mode # Search the parent modules/packages in top-down fashion, and take the last given setting. This ensures that # a setting given for the top-level package is recursively propagated to all its subpackages and submodules, # but also allows individual sub-modules to override the setting again. name_parts = name.split('.') for i in range(len(name_parts)): modlevel = ".".join(name_parts[:i + 1]) modlevel_mode = mode_dict.get(modlevel, None) if modlevel_mode is not None: mode = modlevel_mode return mode
Determine the module/package collection mode for the given module name , based on the provided collection mode settings dictionary.
19
92
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _get_module_collection_mode(mode_dict, name): mode = 'pyc' # Default mode # No settings available - return default. if not mode_dict: return mode # Search the parent modules/packages in top-down fashion, and take the last given setting. This ensures that # a setting given for the top-level package is recursively propagated to all its subpackages and submodules, # but also allows individual sub-modules to override the setting again. name_parts = name.split('.') for i in range(len(name_parts)): modlevel = ".".join(name_parts[:i + 1]) modlevel_mode = mode_dict.get(modlevel, None) if modlevel_mode is not None: mode = modlevel_mode return mode ``` ###Assistant : Determine the module/package collection mode for the given module name , based on the provided collection mode settings dictionary.
407
def exact_gaussian_kernel(x, y, stddev): r x_aligned, y_aligned = _align_matrices(x, y) diff_squared_l2_norm = tf.reduce_sum( tf.math.squared_difference(x_aligned, y_aligned), 2 ) return tf.exp(-diff_squared_l2_norm / (2 * stddev * stddev))
Computes exact Gaussian kernel value(s) for tensors x and y and stddev. The Gaussian kernel for vectors u, v is defined as follows: K(u, v) = exp(-||u-v||^2 / (2* stddev^2)) where the norm is the l2-norm. x, y can be either vectors or matrices. If they are vectors, they must have the same dimension. If they are matrices, they must have the same number of columns. In the latter case, the method returns (as a matrix) K(u, v) values for all pairs (u, v) where u is a row from x and v is a row from y. Args: x: a tensor of rank 1 or 2. It's shape should be either [dim] or [m, dim]. y: a tensor of rank 1 or 2. It's shape should be either [dim] or [n, dim]. stddev: The width of the Gaussian kernel. Returns: A single value (scalar) with shape (1, 1) (if x, y are vectors) or a matrix of shape (m, n) with entries K(u, v) (where K is the Gaussian kernel) for all (u,v) pairs where u, v are rows from x and y respectively. Raises: ValueError: if the shapes of x, y are not compatible.
196
25
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def exact_gaussian_kernel(x, y, stddev): r x_aligned, y_aligned = _align_matrices(x, y) diff_squared_l2_norm = tf.reduce_sum( tf.math.squared_difference(x_aligned, y_aligned), 2 ) return tf.exp(-diff_squared_l2_norm / (2 * stddev * stddev)) ``` ###Assistant : Computes exact Gaussian kernel value(s) for tensors x and y and stddev. The Gaussian kernel for vectors u, v is defined as follows: K(u, v) = exp(-||u-v||^2 / (2* stddev^2)) where the norm is the l2-norm. x, y can be either vectors or matrices. If they are vectors, they must have the same dimension. If they are matrices, they must have the same number of columns. In the latter case, the method returns (as a matrix) K(u, v) values for all pairs (u, v) where u is a row from x and v is a row from y. Args: x: a tensor of rank 1 or 2. It's shape should be either [dim] or [m, dim]. y: a tensor of rank 1 or 2. It's shape should be either [dim] or [n, dim]. stddev: The width of the Gaussian kernel. Returns: A single value (scalar) with shape (1, 1) (if x, y are vectors) or a matrix of shape (m, n) with entries K(u, v) (where K is the Gaussian kernel) for all (u,v) pairs where u, v are rows from x and y respectively. Raises: ValueError: if the shapes of x, y are not compatible.
408
def enqueue_job(cls, func, name, obj_type, user, schedule_at=None, *args, **kwargs): job_result: JobResult = cls.objects.create( name=name, obj_type=obj_type, user=user, job_id=uuid.uuid4() ) queue = django_rq.get_queue("default") if schedule_at: job_result.status = JobResultStatusChoices.STATUS_SCHEDULED job_result.scheduled_time = schedule_at job_result.save() queue.enqueue_at(schedule_at, func, job_id=str(job_result.job_id), job_result=job_result, **kwargs) else: queue.enqueue(func, job_id=str(job_result.job_id), job_result=job_result, **kwargs) return job_result
Create a JobResult instance and enqueue a job using the given callable func: The callable object to be enqueued for execution name: Name for the JobResult instance obj_type: ContentType to link to the JobResult instance obj_type user: User object to link to the JobResult instance schedule_at: Schedule the job to be executed at the passed date and time args: additional args passed to the callable kwargs: additional kargs passed to the callable
72
42
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def enqueue_job(cls, func, name, obj_type, user, schedule_at=None, *args, **kwargs): job_result: JobResult = cls.objects.create( name=name, obj_type=obj_type, user=user, job_id=uuid.uuid4() ) queue = django_rq.get_queue("default") if schedule_at: job_result.status = JobResultStatusChoices.STATUS_SCHEDULED job_result.scheduled_time = schedule_at job_result.save() queue.enqueue_at(schedule_at, func, job_id=str(job_result.job_id), job_result=job_result, **kwargs) else: queue.enqueue(func, job_id=str(job_result.job_id), job_result=job_result, **kwargs) return job_result ``` ###Assistant : Create a JobResult instance and enqueue a job using the given callable func: The callable object to be enqueued for execution name: Name for the JobResult instance obj_type: ContentType to link to the JobResult instance obj_type user: User object to link to the JobResult instance schedule_at: Schedule the job to be executed at the passed date and time args: additional args passed to the callable kwargs: additional kargs passed to the callable
409
def text_style(self) -> Style: # TODO: Feels like there may be opportunity for caching here. style = Style() for node in reversed(self.ancestors): style += node.styles.text_style return style
Get the text style object. A widget's style is influenced by its parent. For instance if a widgets background has an alpha, then its parent's background color will show through. Additionally, widgets will inherit their parent's text style (i.e. bold, italic etc). Returns: Style: Rich Style object.
47
27
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def text_style(self) -> Style: # TODO: Feels like there may be opportunity for caching here. style = Style() for node in reversed(self.ancestors): style += node.styles.text_style return style ``` ###Assistant : Get the text style object. A widget's style is influenced by its parent. For instance if a widgets background has an alpha, then its parent's background color will show through. Additionally, widgets will inherit their parent's text style (i.e. bold, italic etc). Returns: Style: Rich Style object.
410
def get_app_list(self, request): app_dict = self._build_app_dict(request) # Sort the apps alphabetically. app_list = sorted(app_dict.values(), key=lambda x: x["name"].lower()) # Sort the models alphabetically within each app. for app in app_list: app["models"].sort(key=lambda x: x["name"]) return app_list
Return a sorted list of all the installed apps that have been registered in this site.
16
34
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_app_list(self, request): app_dict = self._build_app_dict(request) # Sort the apps alphabetically. app_list = sorted(app_dict.values(), key=lambda x: x["name"].lower()) # Sort the models alphabetically within each app. for app in app_list: app["models"].sort(key=lambda x: x["name"]) return app_list ``` ###Assistant : Return a sorted list of all the installed apps that have been registered in this site.
411
def find_library_file (self, dirs, lib, debug=0): raise NotImplementedError # -- Filename generation methods ----------------------------------- # The default implementation of the filename generating methods are # prejudiced towards the Unix/DOS/Windows view of the world: # * object files are named by replacing the source file extension # (eg. .c/.cpp -> .o/.obj) # * library files (shared or static) are named by plugging the # library name and extension into a format string, eg. # "lib%s.%s" % (lib_name, ".a") for Unix static libraries # * executables are named by appending an extension (possibly # empty) to the program name: eg. progname + ".exe" for # Windows # # To reduce redundant code, these methods expect to find # several attributes in the current object (presumably defined # as class attributes): # * src_extensions - # list of C/C++ source file extensions, eg. ['.c', '.cpp'] # * obj_extension - # object file extension, eg. '.o' or '.obj' # * static_lib_extension - # extension for static library files, eg. '.a' or '.lib' # * shared_lib_extension - # extension for shared library/object files, eg. '.so', '.dll' # * static_lib_format - # format string for generating static library filenames, # eg. 'lib%s.%s' or '%s.%s' # * shared_lib_format # format string for generating shared library filenames # (probably same as static_lib_format, since the extension # is one of the intended parameters to the format string) # * exe_extension - # extension for executable files, eg. '' or '.exe'
Search the specified list of directories for a static or shared library file 'lib' and return the full path to that file. If 'debug' true, look for a debugging version (if that makes sense on the current platform). Return None if 'lib' wasn't found in any of the specified directories.
50
241
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def find_library_file (self, dirs, lib, debug=0): raise NotImplementedError # -- Filename generation methods ----------------------------------- # The default implementation of the filename generating methods are # prejudiced towards the Unix/DOS/Windows view of the world: # * object files are named by replacing the source file extension # (eg. .c/.cpp -> .o/.obj) # * library files (shared or static) are named by plugging the # library name and extension into a format string, eg. # "lib%s.%s" % (lib_name, ".a") for Unix static libraries # * executables are named by appending an extension (possibly # empty) to the program name: eg. progname + ".exe" for # Windows # # To reduce redundant code, these methods expect to find # several attributes in the current object (presumably defined # as class attributes): # * src_extensions - # list of C/C++ source file extensions, eg. ['.c', '.cpp'] # * obj_extension - # object file extension, eg. '.o' or '.obj' # * static_lib_extension - # extension for static library files, eg. '.a' or '.lib' # * shared_lib_extension - # extension for shared library/object files, eg. '.so', '.dll' # * static_lib_format - # format string for generating static library filenames, # eg. 'lib%s.%s' or '%s.%s' # * shared_lib_format # format string for generating shared library filenames # (probably same as static_lib_format, since the extension # is one of the intended parameters to the format string) # * exe_extension - # extension for executable files, eg. '' or '.exe' ``` ###Assistant : Search the specified list of directories for a static or shared library file 'lib' and return the full path to that file. If 'debug' true, look for a debugging version (if that makes sense on the current platform). Return None if 'lib' wasn't found in any of the specified directories.
412
def test_simple_lock(self): # First to acquire this lock, so it should complete lock = self.get_success(self.store.try_acquire_lock("name", "key")) assert lock is not None # Enter the context manager self.get_success(lock.__aenter__()) # Attempting to acquire the lock again fails. lock2 = self.get_success(self.store.try_acquire_lock("name", "key")) self.assertIsNone(lock2) # Calling `is_still_valid` reports true. self.assertTrue(self.get_success(lock.is_still_valid())) # Drop the lock self.get_success(lock.__aexit__(None, None, None)) # We can now acquire the lock again. lock3 = self.get_success(self.store.try_acquire_lock("name", "key")) assert lock3 is not None self.get_success(lock3.__aenter__()) self.get_success(lock3.__aexit__(None, None, None))
Test that we can take out a lock and that while we hold it nobody else can take it out.
20
74
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_simple_lock(self): # First to acquire this lock, so it should complete lock = self.get_success(self.store.try_acquire_lock("name", "key")) assert lock is not None # Enter the context manager self.get_success(lock.__aenter__()) # Attempting to acquire the lock again fails. lock2 = self.get_success(self.store.try_acquire_lock("name", "key")) self.assertIsNone(lock2) # Calling `is_still_valid` reports true. self.assertTrue(self.get_success(lock.is_still_valid())) # Drop the lock self.get_success(lock.__aexit__(None, None, None)) # We can now acquire the lock again. lock3 = self.get_success(self.store.try_acquire_lock("name", "key")) assert lock3 is not None self.get_success(lock3.__aenter__()) self.get_success(lock3.__aexit__(None, None, None)) ``` ###Assistant : Test that we can take out a lock and that while we hold it nobody else can take it out.
413
def set_family(self, family): if family is None: family = mpl.rcParams['font.family'] if isinstance(family, str): family = [family] self._family = family
Change the font family. May be either an alias (generic name is CSS parlance), such as: 'serif', 'sans-serif', 'cursive', 'fantasy', or 'monospace', a real font name or a list of real font names. Real font names are not supported when :rc:`text.usetex` is `True`. Default: :rc:`font.family`
45
19
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def set_family(self, family): if family is None: family = mpl.rcParams['font.family'] if isinstance(family, str): family = [family] self._family = family ``` ###Assistant : Change the font family. May be either an alias (generic name is CSS parlance), such as: 'serif', 'sans-serif', 'cursive', 'fantasy', or 'monospace', a real font name or a list of real font names. Real font names are not supported when :rc:`text.usetex` is `True`. Default: :rc:`font.family`
414
def update_ema(biased_ema, value, decay): biased_ema = biased_ema * decay + (1 - decay) * value return biased_ema
calculate biased stat and unbiased stat in each step using exponential moving average method Parameters ---------- biased_ema : float previous stat value value : float current stat value decay : float the weight of previous stat value, larger means smoother curve Returns ------- float, float
45
17
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def update_ema(biased_ema, value, decay): biased_ema = biased_ema * decay + (1 - decay) * value return biased_ema ``` ###Assistant : calculate biased stat and unbiased stat in each step using exponential moving average method Parameters ---------- biased_ema : float previous stat value value : float current stat value decay : float the weight of previous stat value, larger means smoother curve Returns ------- float, float
415
def npartitions(n, verbose=False): n = int(n) if n < 0: return 0 if n <= 5: return [1, 1, 2, 3, 5, 7][n] if '_factor' not in globals(): _pre() # Estimate number of bits in p(n). This formula could be tidied pbits = int(( math.pi*(2*n/3.)**0.5 - math.log(4*n))/math.log(10) + 1) * \ math.log(10, 2) prec = p = int(pbits*1.1 + 100) s = fzero M = max(6, int(0.24*n**0.5 + 4)) if M > 10**5: raise ValueError("Input too big") # Corresponds to n > 1.7e11 sq23pi = mpf_mul(mpf_sqrt(from_rational(2, 3, p), p), mpf_pi(p), p) sqrt8 = mpf_sqrt(from_int(8), p) for q in range(1, M): a = _a(n, q, p) d = _d(n, q, p, sq23pi, sqrt8) s = mpf_add(s, mpf_mul(a, d), prec) if verbose: print("step", q, "of", M, to_str(a, 10), to_str(d, 10)) # On average, the terms decrease rapidly in magnitude. # Dynamically reducing the precision greatly improves # performance. p = bitcount(abs(to_int(d))) + 50 return int(to_int(mpf_add(s, fhalf, prec))) __all__ = ['npartitions']
Calculate the partition function P(n), i.e. the number of ways that n can be written as a sum of positive integers. P(n) is computed using the Hardy-Ramanujan-Rademacher formula [1]_. The correctness of this implementation has been tested through $10^10$. Examples ======== >>> from sympy.ntheory import npartitions >>> npartitions(25) 1958 References ========== .. [1] http://mathworld.wolfram.com/PartitionFunctionP.html
54
158
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def npartitions(n, verbose=False): n = int(n) if n < 0: return 0 if n <= 5: return [1, 1, 2, 3, 5, 7][n] if '_factor' not in globals(): _pre() # Estimate number of bits in p(n). This formula could be tidied pbits = int(( math.pi*(2*n/3.)**0.5 - math.log(4*n))/math.log(10) + 1) * \ math.log(10, 2) prec = p = int(pbits*1.1 + 100) s = fzero M = max(6, int(0.24*n**0.5 + 4)) if M > 10**5: raise ValueError("Input too big") # Corresponds to n > 1.7e11 sq23pi = mpf_mul(mpf_sqrt(from_rational(2, 3, p), p), mpf_pi(p), p) sqrt8 = mpf_sqrt(from_int(8), p) for q in range(1, M): a = _a(n, q, p) d = _d(n, q, p, sq23pi, sqrt8) s = mpf_add(s, mpf_mul(a, d), prec) if verbose: print("step", q, "of", M, to_str(a, 10), to_str(d, 10)) # On average, the terms decrease rapidly in magnitude. # Dynamically reducing the precision greatly improves # performance. p = bitcount(abs(to_int(d))) + 50 return int(to_int(mpf_add(s, fhalf, prec))) __all__ = ['npartitions'] ``` ###Assistant : Calculate the partition function P(n), i.e. the number of ways that n can be written as a sum of positive integers. P(n) is computed using the Hardy-Ramanujan-Rademacher formula [1]_. The correctness of this implementation has been tested through $10^10$. Examples ======== >>> from sympy.ntheory import npartitions >>> npartitions(25) 1958 References ========== .. [1] http://mathworld.wolfram.com/PartitionFunctionP.html
416
def build_sleep_command(self) -> list[str]: docker_pull(self.args, self.config.image) inspect = docker_image_inspect(self.args, self.config.image) return ['sh', '-c', f'sleep 60; exec {shlex.join(inspect.cmd)}']
Build and return the command to put the container to sleep. The sleep duration below was selected to: - Allow enough time to perform necessary operations in the container before waking it. - Make the delay obvious if the wake command doesn't run or succeed. - Avoid hanging indefinitely or for an unreasonably long time. NOTE: The container must have a POSIX-compliant default shell "sh" with a non-builtin "sleep" command.
70
17
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def build_sleep_command(self) -> list[str]: docker_pull(self.args, self.config.image) inspect = docker_image_inspect(self.args, self.config.image) return ['sh', '-c', f'sleep 60; exec {shlex.join(inspect.cmd)}'] ``` ###Assistant : Build and return the command to put the container to sleep. The sleep duration below was selected to: - Allow enough time to perform necessary operations in the container before waking it. - Make the delay obvious if the wake command doesn't run or succeed. - Avoid hanging indefinitely or for an unreasonably long time. NOTE: The container must have a POSIX-compliant default shell "sh" with a non-builtin "sleep" command.
417
def test_crash_only_one_worker_during_sampling_but_ignore(self): config = ( pg.PGConfig() .rollouts( num_rollout_workers=2, num_envs_per_worker=3, # Ignore worker failures (continue with worker #2). ignore_worker_failures=True, ) .environment( env=CartPoleCrashing, env_config={ # Crash prob=80%. "p_crash": 0.8, # Only crash on worker with index 1. "crash_on_worker_indices": [1], # Make sure nothing happens during pre-checks. "skip_env_checking": True, }, ) .debugging(worker_cls=ForwardHealthCheckToEnvWorker) ) # Pre-checking disables, so building the Algorithm is save. algo = config.build() # Expect some errors being logged here, but in general, should continue # as we ignore worker failures. algo.train() # One worker has been removed -> Only one left. self.assertEqual(algo.workers.num_healthy_remote_workers(), 1) algo.stop()
Expect some sub-envs to fail (and not recover), but ignore.
10
94
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_crash_only_one_worker_during_sampling_but_ignore(self): config = ( pg.PGConfig() .rollouts( num_rollout_workers=2, num_envs_per_worker=3, # Ignore worker failures (continue with worker #2). ignore_worker_failures=True, ) .environment( env=CartPoleCrashing, env_config={ # Crash prob=80%. "p_crash": 0.8, # Only crash on worker with index 1. "crash_on_worker_indices": [1], # Make sure nothing happens during pre-checks. "skip_env_checking": True, }, ) .debugging(worker_cls=ForwardHealthCheckToEnvWorker) ) # Pre-checking disables, so building the Algorithm is save. algo = config.build() # Expect some errors being logged here, but in general, should continue # as we ignore worker failures. algo.train() # One worker has been removed -> Only one left. self.assertEqual(algo.workers.num_healthy_remote_workers(), 1) algo.stop() ``` ###Assistant : Expect some sub-envs to fail (and not recover), but ignore.
418
def test_ohe_infrequent_three_levels_drop_infrequent_errors(drop): X_train = np.array([["a"] * 5 + ["b"] * 20 + ["c"] * 10 + ["d"] * 3]).T ohe = OneHotEncoder( handle_unknown="infrequent_if_exist", sparse=False, max_categories=3, drop=drop ) msg = f"Unable to drop category {drop[0]!r} from feature 0 because it is infrequent" with pytest.raises(ValueError, match=msg): ohe.fit(X_train)
Test three levels and dropping the infrequent category.
8
45
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_ohe_infrequent_three_levels_drop_infrequent_errors(drop): X_train = np.array([["a"] * 5 + ["b"] * 20 + ["c"] * 10 + ["d"] * 3]).T ohe = OneHotEncoder( handle_unknown="infrequent_if_exist", sparse=False, max_categories=3, drop=drop ) msg = f"Unable to drop category {drop[0]!r} from feature 0 because it is infrequent" with pytest.raises(ValueError, match=msg): ohe.fit(X_train) ``` ###Assistant : Test three levels and dropping the infrequent category.
419
def is_a_private_model(model): if model in PRIVATE_MODELS: return True # Wrapper, Encoder and Decoder are all privates if model.endswith("Wrapper"): return True if model.endswith("Encoder"): return True if model.endswith("Decoder"): return True return False
Returns True if the model should not be in the main init.
12
30
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def is_a_private_model(model): if model in PRIVATE_MODELS: return True # Wrapper, Encoder and Decoder are all privates if model.endswith("Wrapper"): return True if model.endswith("Encoder"): return True if model.endswith("Decoder"): return True return False ``` ###Assistant : Returns True if the model should not be in the main init.
420
async def test_midnight_turnover_before_midnight_outside_period(hass): config = { "binary_sensor": [ {"platform": "tod", "name": "Night", "after": "22:00", "before": "5:00"} ] } await async_setup_component(hass, "binary_sensor", config) await hass.async_block_till_done() state = hass.states.get("binary_sensor.night") assert state.state == STATE_OFF @freeze_time("2019-01-10 10:00:00-08:00")
Test midnight turnover setting before midnight outside period.
8
33
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python async def test_midnight_turnover_before_midnight_outside_period(hass): config = { "binary_sensor": [ {"platform": "tod", "name": "Night", "after": "22:00", "before": "5:00"} ] } await async_setup_component(hass, "binary_sensor", config) await hass.async_block_till_done() state = hass.states.get("binary_sensor.night") assert state.state == STATE_OFF @freeze_time("2019-01-10 10:00:00-08:00") ``` ###Assistant : Test midnight turnover setting before midnight outside period.
421
def _check_if_cleared(self) -> None: if self._blocks is None: raise ValueError( "This Dataset's blocks have been moved, which means that you " "can no longer use this Dataset." )
Raise an error if this BlockList has been previously cleared.
10
28
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _check_if_cleared(self) -> None: if self._blocks is None: raise ValueError( "This Dataset's blocks have been moved, which means that you " "can no longer use this Dataset." ) ``` ###Assistant : Raise an error if this BlockList has been previously cleared.
422
def test_join_leave(self) -> None: channel = self.make_request("GET", "/sync", access_token=self.tok) self.assertEqual(channel.code, 200, channel.result) self.assertNotIn(self.excluded_room_id, channel.json_body["rooms"]["join"]) self.assertIn(self.included_room_id, channel.json_body["rooms"]["join"]) self.helper.leave(self.excluded_room_id, self.user_id, tok=self.tok) self.helper.leave(self.included_room_id, self.user_id, tok=self.tok) channel = self.make_request( "GET", "/sync?since=" + channel.json_body["next_batch"], access_token=self.tok, ) self.assertEqual(channel.code, 200, channel.result) self.assertNotIn(self.excluded_room_id, channel.json_body["rooms"]["leave"]) self.assertIn(self.included_room_id, channel.json_body["rooms"]["leave"])
Tests that rooms are correctly excluded from the 'join' and 'leave' sections of sync responses.
15
38
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_join_leave(self) -> None: channel = self.make_request("GET", "/sync", access_token=self.tok) self.assertEqual(channel.code, 200, channel.result) self.assertNotIn(self.excluded_room_id, channel.json_body["rooms"]["join"]) self.assertIn(self.included_room_id, channel.json_body["rooms"]["join"]) self.helper.leave(self.excluded_room_id, self.user_id, tok=self.tok) self.helper.leave(self.included_room_id, self.user_id, tok=self.tok) channel = self.make_request( "GET", "/sync?since=" + channel.json_body["next_batch"], access_token=self.tok, ) self.assertEqual(channel.code, 200, channel.result) self.assertNotIn(self.excluded_room_id, channel.json_body["rooms"]["leave"]) self.assertIn(self.included_room_id, channel.json_body["rooms"]["leave"]) ``` ###Assistant : Tests that rooms are correctly excluded from the 'join' and 'leave' sections of sync responses.
423
def test_short_description_is_used_as_field_label(self): response = self.client.get("/admin/modeladmintest/author/inspect/1/") self.assertContains(response, "Birth information") self.assertNotContains(response, "author_birth_string")
A custom field has been added to the inspect view's `inspect_view_fields` and since this field has a `short_description` we expect it to be used as the field's label, and not use the name of the function.
36
10
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_short_description_is_used_as_field_label(self): response = self.client.get("/admin/modeladmintest/author/inspect/1/") self.assertContains(response, "Birth information") self.assertNotContains(response, "author_birth_string") ``` ###Assistant : A custom field has been added to the inspect view's `inspect_view_fields` and since this field has a `short_description` we expect it to be used as the field's label, and not use the name of the function.
424
def check_stock_uom_with_bin(item, stock_uom): if stock_uom == frappe.db.get_value("Item", item, "stock_uom"): return ref_uom = frappe.db.get_value("Stock Ledger Entry", {"item_code": item}, "stock_uom") if ref_uom: if cstr(ref_uom) != cstr(stock_uom): frappe.throw( _( "Default Unit of Measure for Item {0} cannot be changed directly because you have already made some transaction(s) with another UOM. You will need to create a new Item to use a different Default UOM." ).format(item) ) bin_list = frappe.db.sql( , (item, stock_uom), as_dict=1, ) if bin_list: frappe.throw( _( "Default Unit of Measure for Item {0} cannot be changed directly because you have already made some transaction(s) with another UOM. You need to either cancel the linked documents or create a new Item." ).format(item) ) # No SLE or documents against item. Bin UOM can be changed safely. frappe.db.sql(, (stock_uom, item))
select * from tabBin where item_code = %s and (reserved_qty > 0 or ordered_qty > 0 or indented_qty > 0 or planned_qty > 0) and stock_uom != %s update tabBin set stock_uom=%s where item_code=%s
34
127
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def check_stock_uom_with_bin(item, stock_uom): if stock_uom == frappe.db.get_value("Item", item, "stock_uom"): return ref_uom = frappe.db.get_value("Stock Ledger Entry", {"item_code": item}, "stock_uom") if ref_uom: if cstr(ref_uom) != cstr(stock_uom): frappe.throw( _( "Default Unit of Measure for Item {0} cannot be changed directly because you have already made some transaction(s) with another UOM. You will need to create a new Item to use a different Default UOM." ).format(item) ) bin_list = frappe.db.sql( , (item, stock_uom), as_dict=1, ) if bin_list: frappe.throw( _( "Default Unit of Measure for Item {0} cannot be changed directly because you have already made some transaction(s) with another UOM. You need to either cancel the linked documents or create a new Item." ).format(item) ) # No SLE or documents against item. Bin UOM can be changed safely. frappe.db.sql(, (stock_uom, item)) ``` ###Assistant : select * from tabBin where item_code = %s and (reserved_qty > 0 or ordered_qty > 0 or indented_qty > 0 or planned_qty > 0) and stock_uom != %s update tabBin set stock_uom=%s where item_code=%s
425
def fix_group_counters(): from django.db import connection click.echo("Correcting Group.num_comments counter") cursor = connection.cursor() cursor.execute( , [ActivityType.NOTE.value], ) @click.command() @click.option( "--with-docs/--without-docs", default=False, help="Synchronize and repair embedded documentation. This " "is disabled by default.", ) @configuration
UPDATE sentry_groupedmessage SET num_comments = ( SELECT COUNT(*) from sentry_activity WHERE type = %s and group_id = sentry_groupedmessage.id )
19
33
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def fix_group_counters(): from django.db import connection click.echo("Correcting Group.num_comments counter") cursor = connection.cursor() cursor.execute( , [ActivityType.NOTE.value], ) @click.command() @click.option( "--with-docs/--without-docs", default=False, help="Synchronize and repair embedded documentation. This " "is disabled by default.", ) @configuration ``` ###Assistant : UPDATE sentry_groupedmessage SET num_comments = ( SELECT COUNT(*) from sentry_activity WHERE type = %s and group_id = sentry_groupedmessage.id )
426
def get_filter(query=None, params=None, parser_config_overrides=None): # NOTE: this function assumes project permissions check already happened parsed_terms = [] if query is not None: try: parsed_terms = parse_search_query( query, params=params, config_overrides=parser_config_overrides ) except ParseError as e: raise InvalidSearchQuery(f"Parse error: {e.expr.name} (column {e.column():d})") kwargs = { "start": None, "end": None, "conditions": [], "having": [], "user_id": None, "organization_id": None, "team_id": [], "project_ids": [], "group_ids": [], "condition_aggregates": [], "aliases": params.get("aliases", {}) if params is not None else {}, } projects_to_filter = [] if any( isinstance(term, ParenExpression) or SearchBoolean.is_operator(term) for term in parsed_terms ): ( condition, having, found_projects_to_filter, group_ids, ) = convert_search_boolean_to_snuba_query(parsed_terms, params) if condition: and_conditions = flatten_condition_tree(condition, SNUBA_AND) for func in and_conditions: kwargs["conditions"].append(convert_function_to_condition(func)) if having: kwargs["condition_aggregates"] = [ term.key.name for term in parsed_terms if isinstance(term, AggregateFilter) ] and_having = flatten_condition_tree(having, SNUBA_AND) for func in and_having: kwargs["having"].append(convert_function_to_condition(func)) if found_projects_to_filter: projects_to_filter = list(set(found_projects_to_filter)) if group_ids is not None: kwargs["group_ids"].extend(list(set(group_ids))) else: projects_to_filter = set() for term in parsed_terms: if isinstance(term, SearchFilter): conditions, found_projects_to_filter, group_ids = format_search_filter(term, params) if len(conditions) > 0: kwargs["conditions"].extend(conditions) if found_projects_to_filter: projects_to_filter.update(found_projects_to_filter) if group_ids is not None: kwargs["group_ids"].extend(group_ids) elif isinstance(term, AggregateFilter): converted_filter = convert_aggregate_filter_to_snuba_query(term, params) kwargs["condition_aggregates"].append(term.key.name) if converted_filter: kwargs["having"].append(converted_filter) projects_to_filter = list(projects_to_filter) # Keys included as url params take precedent if same key is included in search # They are also considered safe and to have had access rules applied unlike conditions # from the query string. if params: for key in ("start", "end"): kwargs[key] = params.get(key, None) if "user_id" in params: kwargs["user_id"] = params["user_id"] if "organization_id" in params: kwargs["organization_id"] = params["organization_id"] if "team_id" in params: kwargs["team_id"] = params["team_id"] # OrganizationEndpoint.get_filter() uses project_id, but eventstore.Filter uses project_ids if "project_id" in params: if projects_to_filter: kwargs["project_ids"] = projects_to_filter else: kwargs["project_ids"] = params["project_id"] if "environment" in params: term = SearchFilter(SearchKey("environment"), "=", SearchValue(params["environment"])) kwargs["conditions"].append(convert_search_filter_to_snuba_query(term)) if "group_ids" in params: kwargs["group_ids"] = to_list(params["group_ids"]) # Deprecated alias, use `group_ids` instead if ISSUE_ID_ALIAS in params: kwargs["group_ids"] = to_list(params["issue.id"]) return eventstore.Filter(**kwargs)
Returns an eventstore filter given the search text provided by the user and URL params
15
307
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_filter(query=None, params=None, parser_config_overrides=None): # NOTE: this function assumes project permissions check already happened parsed_terms = [] if query is not None: try: parsed_terms = parse_search_query( query, params=params, config_overrides=parser_config_overrides ) except ParseError as e: raise InvalidSearchQuery(f"Parse error: {e.expr.name} (column {e.column():d})") kwargs = { "start": None, "end": None, "conditions": [], "having": [], "user_id": None, "organization_id": None, "team_id": [], "project_ids": [], "group_ids": [], "condition_aggregates": [], "aliases": params.get("aliases", {}) if params is not None else {}, } projects_to_filter = [] if any( isinstance(term, ParenExpression) or SearchBoolean.is_operator(term) for term in parsed_terms ): ( condition, having, found_projects_to_filter, group_ids, ) = convert_search_boolean_to_snuba_query(parsed_terms, params) if condition: and_conditions = flatten_condition_tree(condition, SNUBA_AND) for func in and_conditions: kwargs["conditions"].append(convert_function_to_condition(func)) if having: kwargs["condition_aggregates"] = [ term.key.name for term in parsed_terms if isinstance(term, AggregateFilter) ] and_having = flatten_condition_tree(having, SNUBA_AND) for func in and_having: kwargs["having"].append(convert_function_to_condition(func)) if found_projects_to_filter: projects_to_filter = list(set(found_projects_to_filter)) if group_ids is not None: kwargs["group_ids"].extend(list(set(group_ids))) else: projects_to_filter = set() for term in parsed_terms: if isinstance(term, SearchFilter): conditions, found_projects_to_filter, group_ids = format_search_filter(term, params) if len(conditions) > 0: kwargs["conditions"].extend(conditions) if found_projects_to_filter: projects_to_filter.update(found_projects_to_filter) if group_ids is not None: kwargs["group_ids"].extend(group_ids) elif isinstance(term, AggregateFilter): converted_filter = convert_aggregate_filter_to_snuba_query(term, params) kwargs["condition_aggregates"].append(term.key.name) if converted_filter: kwargs["having"].append(converted_filter) projects_to_filter = list(projects_to_filter) # Keys included as url params take precedent if same key is included in search # They are also considered safe and to have had access rules applied unlike conditions # from the query string. if params: for key in ("start", "end"): kwargs[key] = params.get(key, None) if "user_id" in params: kwargs["user_id"] = params["user_id"] if "organization_id" in params: kwargs["organization_id"] = params["organization_id"] if "team_id" in params: kwargs["team_id"] = params["team_id"] # OrganizationEndpoint.get_filter() uses project_id, but eventstore.Filter uses project_ids if "project_id" in params: if projects_to_filter: kwargs["project_ids"] = projects_to_filter else: kwargs["project_ids"] = params["project_id"] if "environment" in params: term = SearchFilter(SearchKey("environment"), "=", SearchValue(params["environment"])) kwargs["conditions"].append(convert_search_filter_to_snuba_query(term)) if "group_ids" in params: kwargs["group_ids"] = to_list(params["group_ids"]) # Deprecated alias, use `group_ids` instead if ISSUE_ID_ALIAS in params: kwargs["group_ids"] = to_list(params["issue.id"]) return eventstore.Filter(**kwargs) ``` ###Assistant : Returns an eventstore filter given the search text provided by the user and URL params
427
def reset(self): self.result = {"encoding": None, "confidence": 0.0, "language": None} self.done = False self._got_data = False self._has_win_bytes = False self._input_state = InputState.PURE_ASCII self._last_char = b"" if self._esc_charset_prober: self._esc_charset_prober.reset() if self._utf1632_prober: self._utf1632_prober.reset() for prober in self._charset_probers: prober.reset()
Reset the UniversalDetector and all of its probers back to their initial states. This is called by ``__init__``, so you only need to call this directly in between analyses of different documents.
32
36
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def reset(self): self.result = {"encoding": None, "confidence": 0.0, "language": None} self.done = False self._got_data = False self._has_win_bytes = False self._input_state = InputState.PURE_ASCII self._last_char = b"" if self._esc_charset_prober: self._esc_charset_prober.reset() if self._utf1632_prober: self._utf1632_prober.reset() for prober in self._charset_probers: prober.reset() ``` ###Assistant : Reset the UniversalDetector and all of its probers back to their initial states. This is called by ``__init__``, so you only need to call this directly in between analyses of different documents.
428
def test_redis_socket_parsing(self): for input, expected in [ (None, ("redis://localhost:6379", "redis://localhost:6379")), ( "redis+socket:///run/redis/redis.sock", ( "redis+socket:///run/redis/redis.sock", "unix:///run/redis/redis.sock", ), ), ( "unix:///run/redis/redis.sock", ( "redis+socket:///run/redis/redis.sock", "unix:///run/redis/redis.sock", ), ), ]: result = _parse_redis_url(input) self.assertTupleEqual(expected, result)
GIVEN: - Various Redis connection URI formats WHEN: - The URI is parsed THEN: - Socket based URIs are translated - Non-socket URIs are unchanged - None provided uses default
30
30
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_redis_socket_parsing(self): for input, expected in [ (None, ("redis://localhost:6379", "redis://localhost:6379")), ( "redis+socket:///run/redis/redis.sock", ( "redis+socket:///run/redis/redis.sock", "unix:///run/redis/redis.sock", ), ), ( "unix:///run/redis/redis.sock", ( "redis+socket:///run/redis/redis.sock", "unix:///run/redis/redis.sock", ), ), ]: result = _parse_redis_url(input) self.assertTupleEqual(expected, result) ``` ###Assistant : GIVEN: - Various Redis connection URI formats WHEN: - The URI is parsed THEN: - Socket based URIs are translated - Non-socket URIs are unchanged - None provided uses default
429
def path_components(self) -> tuple[str, ...]: path = urllib.parse.urlparse(self.url).path # This needs to be a tuple so that it's immutable. # Otherwise, this would fail silently: # request.path_components.append("foo") return tuple(url.unquote(i) for i in path.split("/") if i)
The URL's path components as a tuple of strings. Components are unquoted.
12
35
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def path_components(self) -> tuple[str, ...]: path = urllib.parse.urlparse(self.url).path # This needs to be a tuple so that it's immutable. # Otherwise, this would fail silently: # request.path_components.append("foo") return tuple(url.unquote(i) for i in path.split("/") if i) ``` ###Assistant : The URL's path components as a tuple of strings. Components are unquoted.
430
def gen_batches(n, batch_size, *, min_batch_size=0): if not isinstance(batch_size, numbers.Integral): raise TypeError( "gen_batches got batch_size=%s, must be an integer" % batch_size ) if batch_size <= 0: raise ValueError("gen_batches got batch_size=%s, must be positive" % batch_size) start = 0 for _ in range(int(n // batch_size)): end = start + batch_size if end + min_batch_size > n: continue yield slice(start, end) start = end if start < n: yield slice(start, n)
Generator to create slices containing `batch_size` elements from 0 to `n`. The last slice may contain less than `batch_size` elements, when `batch_size` does not divide `n`. Parameters ---------- n : int Size of the sequence. batch_size : int Number of elements in each batch. min_batch_size : int, default=0 Minimum number of elements in each batch. Yields ------ slice of `batch_size` elements See Also -------- gen_even_slices: Generator to create n_packs slices going up to n. Examples -------- >>> from sklearn.utils import gen_batches >>> list(gen_batches(7, 3)) [slice(0, 3, None), slice(3, 6, None), slice(6, 7, None)] >>> list(gen_batches(6, 3)) [slice(0, 3, None), slice(3, 6, None)] >>> list(gen_batches(2, 3)) [slice(0, 2, None)] >>> list(gen_batches(7, 3, min_batch_size=0)) [slice(0, 3, None), slice(3, 6, None), slice(6, 7, None)] >>> list(gen_batches(7, 3, min_batch_size=2)) [slice(0, 3, None), slice(3, 7, None)]
131
68
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def gen_batches(n, batch_size, *, min_batch_size=0): if not isinstance(batch_size, numbers.Integral): raise TypeError( "gen_batches got batch_size=%s, must be an integer" % batch_size ) if batch_size <= 0: raise ValueError("gen_batches got batch_size=%s, must be positive" % batch_size) start = 0 for _ in range(int(n // batch_size)): end = start + batch_size if end + min_batch_size > n: continue yield slice(start, end) start = end if start < n: yield slice(start, n) ``` ###Assistant : Generator to create slices containing `batch_size` elements from 0 to `n`. The last slice may contain less than `batch_size` elements, when `batch_size` does not divide `n`. Parameters ---------- n : int Size of the sequence. batch_size : int Number of elements in each batch. min_batch_size : int, default=0 Minimum number of elements in each batch. Yields ------ slice of `batch_size` elements See Also -------- gen_even_slices: Generator to create n_packs slices going up to n. Examples -------- >>> from sklearn.utils import gen_batches >>> list(gen_batches(7, 3)) [slice(0, 3, None), slice(3, 6, None), slice(6, 7, None)] >>> list(gen_batches(6, 3)) [slice(0, 3, None), slice(3, 6, None)] >>> list(gen_batches(2, 3)) [slice(0, 2, None)] >>> list(gen_batches(7, 3, min_batch_size=0)) [slice(0, 3, None), slice(3, 6, None), slice(6, 7, None)] >>> list(gen_batches(7, 3, min_batch_size=2)) [slice(0, 3, None), slice(3, 7, None)]
431
def test_condinst_maskhead_loss(self): s = 256 img_metas = [{ 'img_shape': (s, s, 3), 'pad_shape': (s, s, 3), 'scale_factor': 1, }] condinst_bboxhead = CondInstBboxHead( num_classes=4, in_channels=1, feat_channels=1, stacked_convs=1, norm_cfg=None) mask_feature_head = _fake_mask_feature_head() condinst_maskhead = CondInstMaskHead( mask_feature_head=mask_feature_head, loss_mask=dict( type='DiceLoss', use_sigmoid=True, activate=True, eps=5e-6, loss_weight=1.0)) # Fcos head expects a multiple levels of features per image feats = [] for i in range(len(condinst_bboxhead.strides)): feats.append( torch.rand(1, 1, s // (2**(i + 3)), s // (2**(i + 3)))) feats = tuple(feats) cls_scores, bbox_preds, centernesses, param_preds =\ condinst_bboxhead.forward(feats) # Test that empty ground truth encourages the network to # predict background gt_instances = InstanceData() gt_instances.bboxes = torch.empty((0, 4)) gt_instances.labels = torch.LongTensor([]) gt_instances.masks = _rand_masks(0, gt_instances.bboxes.numpy(), s, s) _ = condinst_bboxhead.loss_by_feat(cls_scores, bbox_preds, centernesses, param_preds, [gt_instances], img_metas) # When truth is empty then all mask loss # should be zero for random inputs positive_infos = condinst_bboxhead.get_positive_infos() mask_outs = condinst_maskhead.forward(feats, positive_infos) empty_gt_mask_losses = condinst_maskhead.loss_by_feat( *mask_outs, [gt_instances], img_metas, positive_infos) loss_mask = empty_gt_mask_losses['loss_mask'] self.assertEqual(loss_mask, 0, 'mask loss should be zero') # When truth is non-empty then all cls, box loss and centerness loss # should be nonzero for random inputs gt_instances = InstanceData() gt_instances.bboxes = torch.Tensor( [[23.6667, 23.8757, 238.6326, 151.8874]]) gt_instances.labels = torch.LongTensor([2]) gt_instances.masks = _rand_masks(1, gt_instances.bboxes.numpy(), s, s) _ = condinst_bboxhead.loss_by_feat(cls_scores, bbox_preds, centernesses, param_preds, [gt_instances], img_metas) positive_infos = condinst_bboxhead.get_positive_infos() mask_outs = condinst_maskhead.forward(feats, positive_infos) one_gt_mask_losses = condinst_maskhead.loss_by_feat( *mask_outs, [gt_instances], img_metas, positive_infos) loss_mask = one_gt_mask_losses['loss_mask'] self.assertGreater(loss_mask, 0, 'mask loss should be nonzero')
Tests condinst maskhead loss when truth is empty and non-empty.
10
228
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_condinst_maskhead_loss(self): s = 256 img_metas = [{ 'img_shape': (s, s, 3), 'pad_shape': (s, s, 3), 'scale_factor': 1, }] condinst_bboxhead = CondInstBboxHead( num_classes=4, in_channels=1, feat_channels=1, stacked_convs=1, norm_cfg=None) mask_feature_head = _fake_mask_feature_head() condinst_maskhead = CondInstMaskHead( mask_feature_head=mask_feature_head, loss_mask=dict( type='DiceLoss', use_sigmoid=True, activate=True, eps=5e-6, loss_weight=1.0)) # Fcos head expects a multiple levels of features per image feats = [] for i in range(len(condinst_bboxhead.strides)): feats.append( torch.rand(1, 1, s // (2**(i + 3)), s // (2**(i + 3)))) feats = tuple(feats) cls_scores, bbox_preds, centernesses, param_preds =\ condinst_bboxhead.forward(feats) # Test that empty ground truth encourages the network to # predict background gt_instances = InstanceData() gt_instances.bboxes = torch.empty((0, 4)) gt_instances.labels = torch.LongTensor([]) gt_instances.masks = _rand_masks(0, gt_instances.bboxes.numpy(), s, s) _ = condinst_bboxhead.loss_by_feat(cls_scores, bbox_preds, centernesses, param_preds, [gt_instances], img_metas) # When truth is empty then all mask loss # should be zero for random inputs positive_infos = condinst_bboxhead.get_positive_infos() mask_outs = condinst_maskhead.forward(feats, positive_infos) empty_gt_mask_losses = condinst_maskhead.loss_by_feat( *mask_outs, [gt_instances], img_metas, positive_infos) loss_mask = empty_gt_mask_losses['loss_mask'] self.assertEqual(loss_mask, 0, 'mask loss should be zero') # When truth is non-empty then all cls, box loss and centerness loss # should be nonzero for random inputs gt_instances = InstanceData() gt_instances.bboxes = torch.Tensor( [[23.6667, 23.8757, 238.6326, 151.8874]]) gt_instances.labels = torch.LongTensor([2]) gt_instances.masks = _rand_masks(1, gt_instances.bboxes.numpy(), s, s) _ = condinst_bboxhead.loss_by_feat(cls_scores, bbox_preds, centernesses, param_preds, [gt_instances], img_metas) positive_infos = condinst_bboxhead.get_positive_infos() mask_outs = condinst_maskhead.forward(feats, positive_infos) one_gt_mask_losses = condinst_maskhead.loss_by_feat( *mask_outs, [gt_instances], img_metas, positive_infos) loss_mask = one_gt_mask_losses['loss_mask'] self.assertGreater(loss_mask, 0, 'mask loss should be nonzero') ``` ###Assistant : Tests condinst maskhead loss when truth is empty and non-empty.
432
def test_ContinuousSelector_2(): cs = ContinuousSelector(threshold=5, svd_solver='randomized') X_transformed = cs.transform(iris_data[0:16, :]) assert_equal(X_transformed.shape[1],3)
Assert that ContinuousSelector works as expected with threshold=5.
8
11
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_ContinuousSelector_2(): cs = ContinuousSelector(threshold=5, svd_solver='randomized') X_transformed = cs.transform(iris_data[0:16, :]) assert_equal(X_transformed.shape[1],3) ``` ###Assistant : Assert that ContinuousSelector works as expected with threshold=5.
433
def test_add_view(self): add_dict = { "title": "Døm ikke", "content": "<p>great article</p>", "date_0": "2008-03-18", "date_1": "10:54:39", "section": self.s1.pk, } # Change User should not have access to add articles self.client.force_login(self.changeuser) # make sure the view removes test cookie self.assertIs(self.client.session.test_cookie_worked(), False) response = self.client.get(reverse("admin:admin_views_article_add")) self.assertEqual(response.status_code, 403) # Try POST just to make sure post = self.client.post(reverse("admin:admin_views_article_add"), add_dict) self.assertEqual(post.status_code, 403) self.assertEqual(Article.objects.count(), 3) self.client.get(reverse("admin:logout")) # View User should not have access to add articles self.client.force_login(self.viewuser) response = self.client.get(reverse("admin:admin_views_article_add")) self.assertEqual(response.status_code, 403) # Try POST just to make sure post = self.client.post(reverse("admin:admin_views_article_add"), add_dict) self.assertEqual(post.status_code, 403) self.assertEqual(Article.objects.count(), 3) # Now give the user permission to add but not change. self.viewuser.user_permissions.add( get_perm(Article, get_permission_codename("add", Article._meta)) ) response = self.client.get(reverse("admin:admin_views_article_add")) self.assertEqual(response.context["title"], "Add article") self.assertContains(response, "<title>Add article | Django site admin</title>") self.assertContains( response, '<input type="submit" value="Save and view" name="_continue">' ) post = self.client.post( reverse("admin:admin_views_article_add"), add_dict, follow=False ) self.assertEqual(post.status_code, 302) self.assertEqual(Article.objects.count(), 4) article = Article.objects.latest("pk") response = self.client.get( reverse("admin:admin_views_article_change", args=(article.pk,)) ) self.assertContains( response, '<li class="success">The article “Døm ikke” was added successfully.</li>', ) article.delete() self.client.get(reverse("admin:logout")) # Add user may login and POST to add view, then redirect to admin root self.client.force_login(self.adduser) addpage = self.client.get(reverse("admin:admin_views_article_add")) change_list_link = '&rsaquo; <a href="%s">Articles</a>' % reverse( "admin:admin_views_article_changelist" ) self.assertNotContains( addpage, change_list_link, msg_prefix="User restricted to add permission is given link to change list view in breadcrumbs.", ) post = self.client.post(reverse("admin:admin_views_article_add"), add_dict) self.assertRedirects(post, self.index_url) self.assertEqual(Article.objects.count(), 4) self.assertEqual(len(mail.outbox), 2) self.assertEqual(mail.outbox[0].subject, "Greetings from a created object") self.client.get(reverse("admin:logout")) # The addition was logged correctly addition_log = LogEntry.objects.all()[0] new_article = Article.objects.last() article_ct = ContentType.objects.get_for_model(Article) self.assertEqual(addition_log.user_id, self.adduser.pk) self.assertEqual(addition_log.content_type_id, article_ct.pk) self.assertEqual(addition_log.object_id, str(new_article.pk)) self.assertEqual(addition_log.object_repr, "Døm ikke") self.assertEqual(addition_log.action_flag, ADDITION) self.assertEqual(addition_log.get_change_message(), "Added.") # Super can add too, but is redirected to the change list view self.client.force_login(self.superuser) addpage = self.client.get(reverse("admin:admin_views_article_add")) self.assertContains( addpage, change_list_link, msg_prefix="Unrestricted user is not given link to change list view in breadcrumbs.", ) post = self.client.post(reverse("admin:admin_views_article_add"), add_dict) self.assertRedirects(post, reverse("admin:admin_views_article_changelist")) self.assertEqual(Article.objects.count(), 5) self.client.get(reverse("admin:logout")) # 8509 - if a normal user is already logged in, it is possible # to change user into the superuser without error self.client.force_login(self.joepublicuser) # Check and make sure that if user expires, data still persists self.client.force_login(self.superuser) # make sure the view removes test cookie self.assertIs(self.client.session.test_cookie_worked(), False)
Test add view restricts access and actually adds items.
9
342
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_add_view(self): add_dict = { "title": "Døm ikke", "content": "<p>great article</p>", "date_0": "2008-03-18", "date_1": "10:54:39", "section": self.s1.pk, } # Change User should not have access to add articles self.client.force_login(self.changeuser) # make sure the view removes test cookie self.assertIs(self.client.session.test_cookie_worked(), False) response = self.client.get(reverse("admin:admin_views_article_add")) self.assertEqual(response.status_code, 403) # Try POST just to make sure post = self.client.post(reverse("admin:admin_views_article_add"), add_dict) self.assertEqual(post.status_code, 403) self.assertEqual(Article.objects.count(), 3) self.client.get(reverse("admin:logout")) # View User should not have access to add articles self.client.force_login(self.viewuser) response = self.client.get(reverse("admin:admin_views_article_add")) self.assertEqual(response.status_code, 403) # Try POST just to make sure post = self.client.post(reverse("admin:admin_views_article_add"), add_dict) self.assertEqual(post.status_code, 403) self.assertEqual(Article.objects.count(), 3) # Now give the user permission to add but not change. self.viewuser.user_permissions.add( get_perm(Article, get_permission_codename("add", Article._meta)) ) response = self.client.get(reverse("admin:admin_views_article_add")) self.assertEqual(response.context["title"], "Add article") self.assertContains(response, "<title>Add article | Django site admin</title>") self.assertContains( response, '<input type="submit" value="Save and view" name="_continue">' ) post = self.client.post( reverse("admin:admin_views_article_add"), add_dict, follow=False ) self.assertEqual(post.status_code, 302) self.assertEqual(Article.objects.count(), 4) article = Article.objects.latest("pk") response = self.client.get( reverse("admin:admin_views_article_change", args=(article.pk,)) ) self.assertContains( response, '<li class="success">The article “Døm ikke” was added successfully.</li>', ) article.delete() self.client.get(reverse("admin:logout")) # Add user may login and POST to add view, then redirect to admin root self.client.force_login(self.adduser) addpage = self.client.get(reverse("admin:admin_views_article_add")) change_list_link = '&rsaquo; <a href="%s">Articles</a>' % reverse( "admin:admin_views_article_changelist" ) self.assertNotContains( addpage, change_list_link, msg_prefix="User restricted to add permission is given link to change list view in breadcrumbs.", ) post = self.client.post(reverse("admin:admin_views_article_add"), add_dict) self.assertRedirects(post, self.index_url) self.assertEqual(Article.objects.count(), 4) self.assertEqual(len(mail.outbox), 2) self.assertEqual(mail.outbox[0].subject, "Greetings from a created object") self.client.get(reverse("admin:logout")) # The addition was logged correctly addition_log = LogEntry.objects.all()[0] new_article = Article.objects.last() article_ct = ContentType.objects.get_for_model(Article) self.assertEqual(addition_log.user_id, self.adduser.pk) self.assertEqual(addition_log.content_type_id, article_ct.pk) self.assertEqual(addition_log.object_id, str(new_article.pk)) self.assertEqual(addition_log.object_repr, "Døm ikke") self.assertEqual(addition_log.action_flag, ADDITION) self.assertEqual(addition_log.get_change_message(), "Added.") # Super can add too, but is redirected to the change list view self.client.force_login(self.superuser) addpage = self.client.get(reverse("admin:admin_views_article_add")) self.assertContains( addpage, change_list_link, msg_prefix="Unrestricted user is not given link to change list view in breadcrumbs.", ) post = self.client.post(reverse("admin:admin_views_article_add"), add_dict) self.assertRedirects(post, reverse("admin:admin_views_article_changelist")) self.assertEqual(Article.objects.count(), 5) self.client.get(reverse("admin:logout")) # 8509 - if a normal user is already logged in, it is possible # to change user into the superuser without error self.client.force_login(self.joepublicuser) # Check and make sure that if user expires, data still persists self.client.force_login(self.superuser) # make sure the view removes test cookie self.assertIs(self.client.session.test_cookie_worked(), False) ``` ###Assistant : Test add view restricts access and actually adds items.
434
def install(collection, path, artifacts_manager): # FIXME: mv to dataclasses? # type: (Candidate, str, ConcreteArtifactsManager) -> None b_artifact_path = ( artifacts_manager.get_artifact_path if collection.is_concrete_artifact else artifacts_manager.get_galaxy_artifact_path )(collection) collection_path = os.path.join(path, collection.namespace, collection.name) b_collection_path = to_bytes(collection_path, errors='surrogate_or_strict') display.display( u"Installing '{coll!s}' to '{path!s}'". format(coll=to_text(collection), path=collection_path), ) if os.path.exists(b_collection_path): shutil.rmtree(b_collection_path) if collection.is_dir: install_src(collection, b_artifact_path, b_collection_path, artifacts_manager) else: install_artifact( b_artifact_path, b_collection_path, artifacts_manager._b_working_directory, collection.signatures, artifacts_manager.keyring ) if (collection.is_online_index_pointer and isinstance(collection.src, GalaxyAPI)): write_source_metadata( collection, b_collection_path, artifacts_manager ) display.display( '{coll!s} was installed successfully'. format(coll=to_text(collection)), )
Install a collection under a given path. :param collection: Collection to be installed. :param path: Collection dirs layout path. :param artifacts_manager: Artifacts manager.
23
76
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def install(collection, path, artifacts_manager): # FIXME: mv to dataclasses? # type: (Candidate, str, ConcreteArtifactsManager) -> None b_artifact_path = ( artifacts_manager.get_artifact_path if collection.is_concrete_artifact else artifacts_manager.get_galaxy_artifact_path )(collection) collection_path = os.path.join(path, collection.namespace, collection.name) b_collection_path = to_bytes(collection_path, errors='surrogate_or_strict') display.display( u"Installing '{coll!s}' to '{path!s}'". format(coll=to_text(collection), path=collection_path), ) if os.path.exists(b_collection_path): shutil.rmtree(b_collection_path) if collection.is_dir: install_src(collection, b_artifact_path, b_collection_path, artifacts_manager) else: install_artifact( b_artifact_path, b_collection_path, artifacts_manager._b_working_directory, collection.signatures, artifacts_manager.keyring ) if (collection.is_online_index_pointer and isinstance(collection.src, GalaxyAPI)): write_source_metadata( collection, b_collection_path, artifacts_manager ) display.display( '{coll!s} was installed successfully'. format(coll=to_text(collection)), ) ``` ###Assistant : Install a collection under a given path. :param collection: Collection to be installed. :param path: Collection dirs layout path. :param artifacts_manager: Artifacts manager.
435
def edit(self, parameter_s='',last_call=['','']): opts,args = self.parse_options(parameter_s,'prxn:') try: filename, lineno, is_temp = self._find_edit_target(self.shell, args, opts, last_call) except MacroToEdit as e: self._edit_macro(args, e.args[0]) return except InteractivelyDefined as e: print("Editing In[%i]" % e.index) args = str(e.index) filename, lineno, is_temp = self._find_edit_target(self.shell, args, opts, last_call) if filename is None: # nothing was found, warnings have already been issued, # just give up. return if is_temp: self._knowntemps.add(filename) elif (filename in self._knowntemps): is_temp = True # do actual editing here print('Editing...', end=' ') sys.stdout.flush() filepath = Path(filename) try: # Quote filenames that may have spaces in them when opening # the editor quoted = filename = str(filepath.absolute()) if " " in quoted: quoted = "'%s'" % quoted self.shell.hooks.editor(quoted, lineno) except TryNext: warn('Could not open editor') return # XXX TODO: should this be generalized for all string vars? # For now, this is special-cased to blocks created by cpaste if args.strip() == "pasted_block": self.shell.user_ns["pasted_block"] = filepath.read_text(encoding='utf-8') if 'x' in opts: # -x prevents actual execution print() else: print('done. Executing edited code...') with preserve_keys(self.shell.user_ns, '__file__'): if not is_temp: self.shell.user_ns['__file__'] = filename if 'r' in opts: # Untranslated IPython code source = filepath.read_text(encoding='utf-8') self.shell.run_cell(source, store_history=False) else: self.shell.safe_execfile(filename, self.shell.user_ns, self.shell.user_ns) if is_temp: try: return filepath.read_text(encoding='utf-8') except IOError as msg: if Path(msg.filename) == filepath: warn('File not found. Did you forget to save?') return else: self.shell.showtraceback()
Bring up an editor and execute the resulting code. Usage: %edit [options] [args] %edit runs IPython's editor hook. The default version of this hook is set to call the editor specified by your $EDITOR environment variable. If this isn't found, it will default to vi under Linux/Unix and to notepad under Windows. See the end of this docstring for how to change the editor hook. You can also set the value of this editor via the ``TerminalInteractiveShell.editor`` option in your configuration file. This is useful if you wish to use a different editor from your typical default with IPython (and for Windows users who typically don't set environment variables). This command allows you to conveniently edit multi-line code right in your IPython session. If called without arguments, %edit opens up an empty editor with a temporary file and will execute the contents of this file when you close it (don't forget to save it!). Options: -n <number>: open the editor at a specified line number. By default, the IPython editor hook uses the unix syntax 'editor +N filename', but you can configure this by providing your own modified hook if your favorite editor supports line-number specifications with a different syntax. -p: this will call the editor with the same data as the previous time it was used, regardless of how long ago (in your current session) it was. -r: use 'raw' input. This option only applies to input taken from the user's history. By default, the 'processed' history is used, so that magics are loaded in their transformed version to valid Python. If this option is given, the raw input as typed as the command line is used instead. When you exit the editor, it will be executed by IPython's own processor. -x: do not execute the edited code immediately upon exit. This is mainly useful if you are editing programs which need to be called with command line arguments, which you can then do using %run. Arguments: If arguments are given, the following possibilities exist: - If the argument is a filename, IPython will load that into the editor. It will execute its contents with execfile() when you exit, loading any code in the file into your interactive namespace. - The arguments are ranges of input history, e.g. "7 ~1/4-6". The syntax is the same as in the %history magic. - If the argument is a string variable, its contents are loaded into the editor. You can thus edit any string which contains python code (including the result of previous edits). - If the argument is the name of an object (other than a string), IPython will try to locate the file where it was defined and open the editor at the point where it is defined. You can use `%edit function` to load an editor exactly at the point where 'function' is defined, edit it and have the file be executed automatically. - If the object is a macro (see %macro for details), this opens up your specified editor with a temporary file containing the macro's data. Upon exit, the macro is reloaded with the contents of the file. Note: opening at an exact line is only supported under Unix, and some editors (like kedit and gedit up to Gnome 2.8) do not understand the '+NUMBER' parameter necessary for this feature. Good editors like (X)Emacs, vi, jed, pico and joe all do. After executing your code, %edit will return as output the code you typed in the editor (except when it was an existing file). This way you can reload the code in further invocations of %edit as a variable, via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of the output. Note that %edit is also available through the alias %ed. This is an example of creating a simple function inside the editor and then modifying it. First, start up the editor:: In [1]: edit Editing... done. Executing edited code... Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n' We can then call the function foo():: In [2]: foo() foo() was defined in an editing session Now we edit foo. IPython automatically loads the editor with the (temporary) file where foo() was previously defined:: In [3]: edit foo Editing... done. Executing edited code... And if we call foo() again we get the modified version:: In [4]: foo() foo() has now been changed! Here is an example of how to edit a code snippet successive times. First we call the editor:: In [5]: edit Editing... done. Executing edited code... hello Out[5]: "print 'hello'\\n" Now we call it again with the previous output (stored in _):: In [6]: edit _ Editing... done. Executing edited code... hello world Out[6]: "print 'hello world'\\n" Now we call it with the output #8 (stored in _8, also as Out[8]):: In [7]: edit _8 Editing... done. Executing edited code... hello again Out[7]: "print 'hello again'\\n" Changing the default editor hook: If you wish to write your own editor hook, you can put it in a configuration file which you load at startup time. The default hook is defined in the IPython.core.hooks module, and you can use that as a starting example for further modifications. That file also has general instructions on how to set a new hook for use once you've defined it.
882
214
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def edit(self, parameter_s='',last_call=['','']): opts,args = self.parse_options(parameter_s,'prxn:') try: filename, lineno, is_temp = self._find_edit_target(self.shell, args, opts, last_call) except MacroToEdit as e: self._edit_macro(args, e.args[0]) return except InteractivelyDefined as e: print("Editing In[%i]" % e.index) args = str(e.index) filename, lineno, is_temp = self._find_edit_target(self.shell, args, opts, last_call) if filename is None: # nothing was found, warnings have already been issued, # just give up. return if is_temp: self._knowntemps.add(filename) elif (filename in self._knowntemps): is_temp = True # do actual editing here print('Editing...', end=' ') sys.stdout.flush() filepath = Path(filename) try: # Quote filenames that may have spaces in them when opening # the editor quoted = filename = str(filepath.absolute()) if " " in quoted: quoted = "'%s'" % quoted self.shell.hooks.editor(quoted, lineno) except TryNext: warn('Could not open editor') return # XXX TODO: should this be generalized for all string vars? # For now, this is special-cased to blocks created by cpaste if args.strip() == "pasted_block": self.shell.user_ns["pasted_block"] = filepath.read_text(encoding='utf-8') if 'x' in opts: # -x prevents actual execution print() else: print('done. Executing edited code...') with preserve_keys(self.shell.user_ns, '__file__'): if not is_temp: self.shell.user_ns['__file__'] = filename if 'r' in opts: # Untranslated IPython code source = filepath.read_text(encoding='utf-8') self.shell.run_cell(source, store_history=False) else: self.shell.safe_execfile(filename, self.shell.user_ns, self.shell.user_ns) if is_temp: try: return filepath.read_text(encoding='utf-8') except IOError as msg: if Path(msg.filename) == filepath: warn('File not found. Did you forget to save?') return else: self.shell.showtraceback() ``` ###Assistant : Bring up an editor and execute the resulting code. Usage: %edit [options] [args] %edit runs IPython's editor hook. The default version of this hook is set to call the editor specified by your $EDITOR environment variable. If this isn't found, it will default to vi under Linux/Unix and to notepad under Windows. See the end of this docstring for how to change the editor hook. You can also set the value of this editor via the ``TerminalInteractiveShell.editor`` option in your configuration file. This is useful if you wish to use a different editor from your typical default with IPython (and for Windows users who typically don't set environment variables). This command allows you to conveniently edit multi-line code right in your IPython session. If called without arguments, %edit opens up an empty editor with a temporary file and will execute the contents of this file when you close it (don't forget to save it!). Options: -n <number>: open the editor at a specified line number. By default, the IPython editor hook uses the unix syntax 'editor +N filename', but you can configure this by providing your own modified hook if your favorite editor supports line-number specifications with a different syntax. -p: this will call the editor with the same data as the previous time it was used, regardless of how long ago (in your current session) it was. -r: use 'raw' input. This option only applies to input taken from the user's history. By default, the 'processed' history is used, so that magics are loaded in their transformed version to valid Python. If this option is given, the raw input as typed as the command line is used instead. When you exit the editor, it will be executed by IPython's own processor. -x: do not execute the edited code immediately upon exit. This is mainly useful if you are editing programs which need to be called with command line arguments, which you can then do using %run. Arguments: If arguments are given, the following possibilities exist: - If the argument is a filename, IPython will load that into the editor. It will execute its contents with execfile() when you exit, loading any code in the file into your interactive namespace. - The arguments are ranges of input history, e.g. "7 ~1/4-6". The syntax is the same as in the %history magic. - If the argument is a string variable, its contents are loaded into the editor. You can thus edit any string which contains python code (including the result of previous edits). - If the argument is the name of an object (other than a string), IPython will try to locate the file where it was defined and open the editor at the point where it is defined. You can use `%edit function` to load an editor exactly at the point where 'function' is defined, edit it and have the file be executed automatically. - If the object is a macro (see %macro for details), this opens up your specified editor with a temporary file containing the macro's data. Upon exit, the macro is reloaded with the contents of the file. Note: opening at an exact line is only supported under Unix, and some editors (like kedit and gedit up to Gnome 2.8) do not understand the '+NUMBER' parameter necessary for this feature. Good editors like (X)Emacs, vi, jed, pico and joe all do. After executing your code, %edit will return as output the code you typed in the editor (except when it was an existing file). This way you can reload the code in further invocations of %edit as a variable, via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of the output. Note that %edit is also available through the alias %ed. This is an example of creating a simple function inside the editor and then modifying it. First, start up the editor:: In [1]: edit Editing... done. Executing edited code... Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n' We can then call the function foo():: In [2]: foo() foo() was defined in an editing session Now we edit foo. IPython automatically loads the editor with the (temporary) file where foo() was previously defined:: In [3]: edit foo Editing... done. Executing edited code... And if we call foo() again we get the modified version:: In [4]: foo() foo() has now been changed! Here is an example of how to edit a code snippet successive times. First we call the editor:: In [5]: edit Editing... done. Executing edited code... hello Out[5]: "print 'hello'\\n" Now we call it again with the previous output (stored in _):: In [6]: edit _ Editing... done. Executing edited code... hello world Out[6]: "print 'hello world'\\n" Now we call it with the output #8 (stored in _8, also as Out[8]):: In [7]: edit _8 Editing... done. Executing edited code... hello again Out[7]: "print 'hello again'\\n" Changing the default editor hook: If you wish to write your own editor hook, you can put it in a configuration file which you load at startup time. The default hook is defined in the IPython.core.hooks module, and you can use that as a starting example for further modifications. That file also has general instructions on how to set a new hook for use once you've defined it.
436
def cell_length(self) -> int: # Done on demand and cached, as this is an O(n) operation if self._cell_length is None: self._cell_length = Segment.get_line_length(self._segments) return self._cell_length
Get the number of cells required to render this object.
10
25
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def cell_length(self) -> int: # Done on demand and cached, as this is an O(n) operation if self._cell_length is None: self._cell_length = Segment.get_line_length(self._segments) return self._cell_length ``` ###Assistant : Get the number of cells required to render this object.
437
def test_show_message_twice(view): view.show_message(message.MessageInfo(usertypes.MessageLevel.info, 'test')) view.show_message(message.MessageInfo(usertypes.MessageLevel.info, 'test')) assert len(view._messages) == 1
Show the same message twice -> only one should be shown.
11
10
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_show_message_twice(view): view.show_message(message.MessageInfo(usertypes.MessageLevel.info, 'test')) view.show_message(message.MessageInfo(usertypes.MessageLevel.info, 'test')) assert len(view._messages) == 1 ``` ###Assistant : Show the same message twice -> only one should be shown.
438
def create_default_plugins(request, placeholders, template, lang): from cms.api import add_plugin
Create all default plugins for the given ``placeholders`` if they have a "default_plugins" configuration value in settings. return all plugins, children, grandchildren (etc.) created
24
9
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def create_default_plugins(request, placeholders, template, lang): from cms.api import add_plugin ``` ###Assistant : Create all default plugins for the given ``placeholders`` if they have a "default_plugins" configuration value in settings. return all plugins, children, grandchildren (etc.) created
439
def _parse_jp2_header(fp): # Find the JP2 header box reader = BoxReader(fp) header = None mimetype = None while reader.has_next_box(): tbox = reader.next_box_type() if tbox == b"jp2h": header = reader.read_boxes() break elif tbox == b"ftyp": if reader.read_fields(">4s")[0] == b"jpx ": mimetype = "image/jpx" size = None mode = None bpc = None nc = None dpi = None # 2-tuple of DPI info, or None while header.has_next_box(): tbox = header.next_box_type() if tbox == b"ihdr": height, width, nc, bpc = header.read_fields(">IIHB") size = (width, height) if nc == 1 and (bpc & 0x7F) > 8: mode = "I;16" elif nc == 1: mode = "L" elif nc == 2: mode = "LA" elif nc == 3: mode = "RGB" elif nc == 4: mode = "RGBA" elif tbox == b"res ": res = header.read_boxes() while res.has_next_box(): tres = res.next_box_type() if tres == b"resc": vrcn, vrcd, hrcn, hrcd, vrce, hrce = res.read_fields(">HHHHBB") hres = _res_to_dpi(hrcn, hrcd, hrce) vres = _res_to_dpi(vrcn, vrcd, vrce) if hres is not None and vres is not None: dpi = (hres, vres) break if size is None or mode is None: raise SyntaxError("Malformed JP2 header") return size, mode, mimetype, dpi ## # Image plugin for JPEG2000 images.
Parse the JP2 header box to extract size, component count, color space information, and optionally DPI information, returning a (size, mode, mimetype, dpi) tuple.
24
198
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _parse_jp2_header(fp): # Find the JP2 header box reader = BoxReader(fp) header = None mimetype = None while reader.has_next_box(): tbox = reader.next_box_type() if tbox == b"jp2h": header = reader.read_boxes() break elif tbox == b"ftyp": if reader.read_fields(">4s")[0] == b"jpx ": mimetype = "image/jpx" size = None mode = None bpc = None nc = None dpi = None # 2-tuple of DPI info, or None while header.has_next_box(): tbox = header.next_box_type() if tbox == b"ihdr": height, width, nc, bpc = header.read_fields(">IIHB") size = (width, height) if nc == 1 and (bpc & 0x7F) > 8: mode = "I;16" elif nc == 1: mode = "L" elif nc == 2: mode = "LA" elif nc == 3: mode = "RGB" elif nc == 4: mode = "RGBA" elif tbox == b"res ": res = header.read_boxes() while res.has_next_box(): tres = res.next_box_type() if tres == b"resc": vrcn, vrcd, hrcn, hrcd, vrce, hrce = res.read_fields(">HHHHBB") hres = _res_to_dpi(hrcn, hrcd, hrce) vres = _res_to_dpi(vrcn, vrcd, vrce) if hres is not None and vres is not None: dpi = (hres, vres) break if size is None or mode is None: raise SyntaxError("Malformed JP2 header") return size, mode, mimetype, dpi ## # Image plugin for JPEG2000 images. ``` ###Assistant : Parse the JP2 header box to extract size, component count, color space information, and optionally DPI information, returning a (size, mode, mimetype, dpi) tuple.
440
def _populate_events(self) -> None: self.get_success( self.store.db_pool.simple_upsert( "rooms", {"room_id": self.room_id}, {"room_version": RoomVersions.V4.identifier}, ) ) self.event_ids: List[str] = [] for idx in range(20): event_json = { "type": f"test {idx}", "room_id": self.room_id, } event = make_event_from_dict(event_json, room_version=RoomVersions.V4) event_id = event.event_id self.get_success( self.store.db_pool.simple_upsert( "events", {"event_id": event_id}, { "event_id": event_id, "room_id": self.room_id, "topological_ordering": idx, "stream_ordering": idx, "type": event.type, "processed": True, "outlier": False, }, ) ) self.get_success( self.store.db_pool.simple_upsert( "event_json", {"event_id": event_id}, { "room_id": self.room_id, "json": json.dumps(event_json), "internal_metadata": "{}", "format_version": EventFormatVersions.V3, }, ) ) self.event_ids.append(event_id)
Ensure that there are test events in the database. When testing with the in-memory SQLite database, all the events are lost during the simulated outage. To ensure consistency between `room_id`s and `event_id`s before and after the outage, rows are built and inserted manually. Upserts are used to handle the non-SQLite case where events are not lost.
56
78
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _populate_events(self) -> None: self.get_success( self.store.db_pool.simple_upsert( "rooms", {"room_id": self.room_id}, {"room_version": RoomVersions.V4.identifier}, ) ) self.event_ids: List[str] = [] for idx in range(20): event_json = { "type": f"test {idx}", "room_id": self.room_id, } event = make_event_from_dict(event_json, room_version=RoomVersions.V4) event_id = event.event_id self.get_success( self.store.db_pool.simple_upsert( "events", {"event_id": event_id}, { "event_id": event_id, "room_id": self.room_id, "topological_ordering": idx, "stream_ordering": idx, "type": event.type, "processed": True, "outlier": False, }, ) ) self.get_success( self.store.db_pool.simple_upsert( "event_json", {"event_id": event_id}, { "room_id": self.room_id, "json": json.dumps(event_json), "internal_metadata": "{}", "format_version": EventFormatVersions.V3, }, ) ) self.event_ids.append(event_id) ``` ###Assistant : Ensure that there are test events in the database. When testing with the in-memory SQLite database, all the events are lost during the simulated outage. To ensure consistency between `room_id`s and `event_id`s before and after the outage, rows are built and inserted manually. Upserts are used to handle the non-SQLite case where events are not lost.
441
def check_if_ctx_is_empty(ctx): return all(check_if_project_is_empty(project_ctx) for project_ctx in ctx.projects.values()) # The entry point. This task is scheduled to run every week. @instrumented_task( name="sentry.tasks.weekly_reports.schedule_organizations", queue="reports.prepare", max_retries=5, acks_late=True, )
Check if the context is empty. If it is, we don't want to send an email.
16
26
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def check_if_ctx_is_empty(ctx): return all(check_if_project_is_empty(project_ctx) for project_ctx in ctx.projects.values()) # The entry point. This task is scheduled to run every week. @instrumented_task( name="sentry.tasks.weekly_reports.schedule_organizations", queue="reports.prepare", max_retries=5, acks_late=True, ) ``` ###Assistant : Check if the context is empty. If it is, we don't want to send an email.
442
def __delitem__(self, name): name = name.lower() newheaders = [] for k, v in self._headers: if k.lower() != name: newheaders.append((k, v)) self._headers = newheaders
Delete all occurrences of a header, if present. Does not raise an exception if the header is missing.
18
23
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def __delitem__(self, name): name = name.lower() newheaders = [] for k, v in self._headers: if k.lower() != name: newheaders.append((k, v)) self._headers = newheaders ``` ###Assistant : Delete all occurrences of a header, if present. Does not raise an exception if the header is missing.
443
def update_status(self): self.cleanup() ready = True while ready: # Use a loop as `ready` might return futures one by one ready, _ = ray.wait(list(self._staging_futures.keys()), timeout=0) for ready_fut in ready: self.handle_ready_future(ready_fut)
Update placement group status. Moves ready placement groups from `self._staging` to `self._ready`.
12
30
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def update_status(self): self.cleanup() ready = True while ready: # Use a loop as `ready` might return futures one by one ready, _ = ray.wait(list(self._staging_futures.keys()), timeout=0) for ready_fut in ready: self.handle_ready_future(ready_fut) ``` ###Assistant : Update placement group status. Moves ready placement groups from `self._staging` to `self._ready`.
444
def execute(): broken_sles = frappe.db.sql(, ( " %", # leading whitespace "% ", # trailing whitespace "%\n %", # leading whitespace on newline "% \n%", # trailing whitespace on newline ), as_dict=True, ) frappe.db.MAX_WRITES_PER_TRANSACTION += len(broken_sles) if not broken_sles: return broken_serial_nos = set() for sle in broken_sles: serial_no_list = get_serial_nos(sle.serial_no) correct_sr_no = "\n".join(serial_no_list) if correct_sr_no == sle.serial_no: continue frappe.db.set_value("Stock Ledger Entry", sle.name, "serial_no", correct_sr_no, update_modified=False) broken_serial_nos.update(serial_no_list) if not broken_serial_nos: return broken_sr_no_records = [sr[0] for sr in frappe.db.sql(, (list(broken_serial_nos),) )] frappe.db.MAX_WRITES_PER_TRANSACTION += len(broken_sr_no_records) patch_savepoint = "serial_no_patch" for serial_no in broken_sr_no_records: try: frappe.db.savepoint(patch_savepoint) sn = frappe.get_doc("Serial No", serial_no) sn.update_serial_no_reference() sn.db_update() except Exception: frappe.db.rollback(save_point=patch_savepoint)
select name, serial_no from `tabStock Ledger Entry` where is_cancelled = 0 and (serial_no like %s or serial_no like %s or serial_no like %s or serial_no like %s) select name from `tabSerial No` where status='Active' and coalesce(purchase_document_type, '') = '' and name in %s
43
101
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def execute(): broken_sles = frappe.db.sql(, ( " %", # leading whitespace "% ", # trailing whitespace "%\n %", # leading whitespace on newline "% \n%", # trailing whitespace on newline ), as_dict=True, ) frappe.db.MAX_WRITES_PER_TRANSACTION += len(broken_sles) if not broken_sles: return broken_serial_nos = set() for sle in broken_sles: serial_no_list = get_serial_nos(sle.serial_no) correct_sr_no = "\n".join(serial_no_list) if correct_sr_no == sle.serial_no: continue frappe.db.set_value("Stock Ledger Entry", sle.name, "serial_no", correct_sr_no, update_modified=False) broken_serial_nos.update(serial_no_list) if not broken_serial_nos: return broken_sr_no_records = [sr[0] for sr in frappe.db.sql(, (list(broken_serial_nos),) )] frappe.db.MAX_WRITES_PER_TRANSACTION += len(broken_sr_no_records) patch_savepoint = "serial_no_patch" for serial_no in broken_sr_no_records: try: frappe.db.savepoint(patch_savepoint) sn = frappe.get_doc("Serial No", serial_no) sn.update_serial_no_reference() sn.db_update() except Exception: frappe.db.rollback(save_point=patch_savepoint) ``` ###Assistant : select name, serial_no from `tabStock Ledger Entry` where is_cancelled = 0 and (serial_no like %s or serial_no like %s or serial_no like %s or serial_no like %s) select name from `tabSerial No` where status='Active' and coalesce(purchase_document_type, '') = '' and name in %s
445
def test_individual_caches_from_environ(self): config = {} self.config._environ = { "SYNAPSE_CACHE_FACTOR_SOMETHING_OR_OTHER": "2", "SYNAPSE_NOT_CACHE": "BLAH", } self.config.read_config(config, config_dir_path="", data_dir_path="") self.config.resize_all_caches() self.assertEqual(dict(self.config.cache_factors), {"something_or_other": 2.0})
Individual cache factors will be loaded from the environment.
9
20
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_individual_caches_from_environ(self): config = {} self.config._environ = { "SYNAPSE_CACHE_FACTOR_SOMETHING_OR_OTHER": "2", "SYNAPSE_NOT_CACHE": "BLAH", } self.config.read_config(config, config_dir_path="", data_dir_path="") self.config.resize_all_caches() self.assertEqual(dict(self.config.cache_factors), {"something_or_other": 2.0}) ``` ###Assistant : Individual cache factors will be loaded from the environment.
446
def test_already_checked_on_success(self): pod_name = "test-" + str(random.randint(0, 1000000)) k = KubernetesPodOperator( namespace='default', image="ubuntu:16.04", cmds=["bash", "-cx"], arguments=["echo 10"], labels={"foo": "bar"}, name=pod_name, task_id="task" + self.get_current_task_name(), in_cluster=False, do_xcom_push=False, is_delete_operator_pod=False, ) context = create_context(k) k.execute(context) actual_pod = k.find_pod('default', context, exclude_checked=False) actual_pod = self.api_client.sanitize_for_serialization(actual_pod) assert actual_pod['metadata']['labels']['already_checked'] == 'True'
When ``is_delete_operator_pod=False``, pod should have 'already_checked' label, whether pod is successful or not.
13
43
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_already_checked_on_success(self): pod_name = "test-" + str(random.randint(0, 1000000)) k = KubernetesPodOperator( namespace='default', image="ubuntu:16.04", cmds=["bash", "-cx"], arguments=["echo 10"], labels={"foo": "bar"}, name=pod_name, task_id="task" + self.get_current_task_name(), in_cluster=False, do_xcom_push=False, is_delete_operator_pod=False, ) context = create_context(k) k.execute(context) actual_pod = k.find_pod('default', context, exclude_checked=False) actual_pod = self.api_client.sanitize_for_serialization(actual_pod) assert actual_pod['metadata']['labels']['already_checked'] == 'True' ``` ###Assistant : When ``is_delete_operator_pod=False``, pod should have 'already_checked' label, whether pod is successful or not.
447
def get_invoice_cc_wh_map(invoice_list): si_items = frappe.db.sql( % ", ".join(["%s"] * len(invoice_list)), tuple(inv.name for inv in invoice_list), as_dict=1, ) invoice_cc_wh_map = {} for d in si_items: if d.cost_center: invoice_cc_wh_map.setdefault(d.parent, frappe._dict()).setdefault("cost_center", []).append( d.cost_center ) if d.warehouse: invoice_cc_wh_map.setdefault(d.parent, frappe._dict()).setdefault("warehouse", []).append( d.warehouse ) return invoice_cc_wh_map
select parent, cost_center, warehouse from `tabSales Invoice Item` where parent in (%s) and (ifnull(cost_center, '') != '' or ifnull(warehouse, '') != '')
22
40
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_invoice_cc_wh_map(invoice_list): si_items = frappe.db.sql( % ", ".join(["%s"] * len(invoice_list)), tuple(inv.name for inv in invoice_list), as_dict=1, ) invoice_cc_wh_map = {} for d in si_items: if d.cost_center: invoice_cc_wh_map.setdefault(d.parent, frappe._dict()).setdefault("cost_center", []).append( d.cost_center ) if d.warehouse: invoice_cc_wh_map.setdefault(d.parent, frappe._dict()).setdefault("warehouse", []).append( d.warehouse ) return invoice_cc_wh_map ``` ###Assistant : select parent, cost_center, warehouse from `tabSales Invoice Item` where parent in (%s) and (ifnull(cost_center, '') != '' or ifnull(warehouse, '') != '')
448
def parseSqliteTableSchema(value): retVal = False value = extractRegexResult(r"(?s)\((?P<result>.+)\)", value) if value: table = {} columns = OrderedDict() value = re.sub(r"\(.+?\)", "", value).strip() for match in re.finditer(r"(?:\A|,)\s*(([\"'`]).+?\2|\w+)(?:\s+(INT|INTEGER|TINYINT|SMALLINT|MEDIUMINT|BIGINT|UNSIGNED BIG INT|INT2|INT8|INTEGER|CHARACTER|VARCHAR|VARYING CHARACTER|NCHAR|NATIVE CHARACTER|NVARCHAR|TEXT|CLOB|LONGTEXT|BLOB|NONE|REAL|DOUBLE|DOUBLE PRECISION|FLOAT|REAL|NUMERIC|DECIMAL|BOOLEAN|DATE|DATETIME|NUMERIC)\b)?", decodeStringEscape(value), re.I): column = match.group(1).strip(match.group(2) or "") if re.search(r"(?i)\A(CONSTRAINT|PRIMARY|UNIQUE|CHECK|FOREIGN)\b", column.strip()): continue retVal = True columns[column] = match.group(3) or "TEXT" table[safeSQLIdentificatorNaming(conf.tbl, True)] = columns kb.data.cachedColumns[conf.db] = table return retVal
Parses table column names and types from specified SQLite table schema >>> kb.data.cachedColumns = {} >>> parseSqliteTableSchema("CREATE TABLE users(\\n\\t\\tid INTEGER,\\n\\t\\tname TEXT\\n);") True >>> tuple(kb.data.cachedColumns[conf.db][conf.tbl].items()) == (('id', 'INTEGER'), ('name', 'TEXT')) True >>> parseSqliteTableSchema("CREATE TABLE dummy(`foo bar` BIGINT, \\"foo\\" VARCHAR, 'bar' TEXT)"); True >>> tuple(kb.data.cachedColumns[conf.db][conf.tbl].items()) == (('foo bar', 'BIGINT'), ('foo', 'VARCHAR'), ('bar', 'TEXT')) True >>> parseSqliteTableSchema("CREATE TABLE suppliers(\\n\\tsupplier_id INTEGER PRIMARY KEY DESC,\\n\\tname TEXT NOT NULL\\n);"); True >>> tuple(kb.data.cachedColumns[conf.db][conf.tbl].items()) == (('supplier_id', 'INTEGER'), ('name', 'TEXT')) True >>> parseSqliteTableSchema("CREATE TABLE country_languages (\\n\\tcountry_id INTEGER NOT NULL,\\n\\tlanguage_id INTEGER NOT NULL,\\n\\tPRIMARY KEY (country_id, language_id),\\n\\tFOREIGN KEY (country_id) REFERENCES countries (country_id) ON DELETE CASCADE ON UPDATE NO ACTION,\\tFOREIGN KEY (language_id) REFERENCES languages (language_id) ON DELETE CASCADE ON UPDATE NO ACTION);"); True >>> tuple(kb.data.cachedColumns[conf.db][conf.tbl].items()) == (('country_id', 'INTEGER'), ('language_id', 'INTEGER')) True
119
59
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def parseSqliteTableSchema(value): retVal = False value = extractRegexResult(r"(?s)\((?P<result>.+)\)", value) if value: table = {} columns = OrderedDict() value = re.sub(r"\(.+?\)", "", value).strip() for match in re.finditer(r"(?:\A|,)\s*(([\"'`]).+?\2|\w+)(?:\s+(INT|INTEGER|TINYINT|SMALLINT|MEDIUMINT|BIGINT|UNSIGNED BIG INT|INT2|INT8|INTEGER|CHARACTER|VARCHAR|VARYING CHARACTER|NCHAR|NATIVE CHARACTER|NVARCHAR|TEXT|CLOB|LONGTEXT|BLOB|NONE|REAL|DOUBLE|DOUBLE PRECISION|FLOAT|REAL|NUMERIC|DECIMAL|BOOLEAN|DATE|DATETIME|NUMERIC)\b)?", decodeStringEscape(value), re.I): column = match.group(1).strip(match.group(2) or "") if re.search(r"(?i)\A(CONSTRAINT|PRIMARY|UNIQUE|CHECK|FOREIGN)\b", column.strip()): continue retVal = True columns[column] = match.group(3) or "TEXT" table[safeSQLIdentificatorNaming(conf.tbl, True)] = columns kb.data.cachedColumns[conf.db] = table return retVal ``` ###Assistant : Parses table column names and types from specified SQLite table schema >>> kb.data.cachedColumns = {} >>> parseSqliteTableSchema("CREATE TABLE users(\\n\\t\\tid INTEGER,\\n\\t\\tname TEXT\\n);") True >>> tuple(kb.data.cachedColumns[conf.db][conf.tbl].items()) == (('id', 'INTEGER'), ('name', 'TEXT')) True >>> parseSqliteTableSchema("CREATE TABLE dummy(`foo bar` BIGINT, \\"foo\\" VARCHAR, 'bar' TEXT)"); True >>> tuple(kb.data.cachedColumns[conf.db][conf.tbl].items()) == (('foo bar', 'BIGINT'), ('foo', 'VARCHAR'), ('bar', 'TEXT')) True >>> parseSqliteTableSchema("CREATE TABLE suppliers(\\n\\tsupplier_id INTEGER PRIMARY KEY DESC,\\n\\tname TEXT NOT NULL\\n);"); True >>> tuple(kb.data.cachedColumns[conf.db][conf.tbl].items()) == (('supplier_id', 'INTEGER'), ('name', 'TEXT')) True >>> parseSqliteTableSchema("CREATE TABLE country_languages (\\n\\tcountry_id INTEGER NOT NULL,\\n\\tlanguage_id INTEGER NOT NULL,\\n\\tPRIMARY KEY (country_id, language_id),\\n\\tFOREIGN KEY (country_id) REFERENCES countries (country_id) ON DELETE CASCADE ON UPDATE NO ACTION,\\tFOREIGN KEY (language_id) REFERENCES languages (language_id) ON DELETE CASCADE ON UPDATE NO ACTION);"); True >>> tuple(kb.data.cachedColumns[conf.db][conf.tbl].items()) == (('country_id', 'INTEGER'), ('language_id', 'INTEGER')) True
449
def get_phrase(value): phrase = Phrase() try: token, value = get_word(value) phrase.append(token) except errors.HeaderParseError: phrase.defects.append(errors.InvalidHeaderDefect( "phrase does not start with word")) while value and value[0] not in PHRASE_ENDS: if value[0]=='.': phrase.append(DOT) phrase.defects.append(errors.ObsoleteHeaderDefect( "period in 'phrase'")) value = value[1:] else: try: token, value = get_word(value) except errors.HeaderParseError: if value[0] in CFWS_LEADER: token, value = get_cfws(value) phrase.defects.append(errors.ObsoleteHeaderDefect( "comment found without atom")) else: raise phrase.append(token) return phrase, value
phrase = 1*word / obs-phrase obs-phrase = word *(word / "." / CFWS) This means a phrase can be a sequence of words, periods, and CFWS in any order as long as it starts with at least one word. If anything other than words is detected, an ObsoleteHeaderDefect is added to the token's defect list. We also accept a phrase that starts with CFWS followed by a dot; this is registered as an InvalidHeaderDefect, since it is not supported by even the obsolete grammar.
84
64
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_phrase(value): phrase = Phrase() try: token, value = get_word(value) phrase.append(token) except errors.HeaderParseError: phrase.defects.append(errors.InvalidHeaderDefect( "phrase does not start with word")) while value and value[0] not in PHRASE_ENDS: if value[0]=='.': phrase.append(DOT) phrase.defects.append(errors.ObsoleteHeaderDefect( "period in 'phrase'")) value = value[1:] else: try: token, value = get_word(value) except errors.HeaderParseError: if value[0] in CFWS_LEADER: token, value = get_cfws(value) phrase.defects.append(errors.ObsoleteHeaderDefect( "comment found without atom")) else: raise phrase.append(token) return phrase, value ``` ###Assistant : phrase = 1*word / obs-phrase obs-phrase = word *(word / "." / CFWS) This means a phrase can be a sequence of words, periods, and CFWS in any order as long as it starts with at least one word. If anything other than words is detected, an ObsoleteHeaderDefect is added to the token's defect list. We also accept a phrase that starts with CFWS followed by a dot; this is registered as an InvalidHeaderDefect, since it is not supported by even the obsolete grammar.
450
async def test_group_media_states(hass, mz_mock): entity_id = "media_player.speaker" reg = er.async_get(hass) info = get_fake_chromecast_info() chromecast, _ = await async_setup_media_player_cast(hass, info) _, conn_status_cb, media_status_cb, group_media_status_cb = get_status_callbacks( chromecast, mz_mock ) connection_status = MagicMock() connection_status.status = "CONNECTED" conn_status_cb(connection_status) await hass.async_block_till_done() state = hass.states.get(entity_id) assert state is not None assert state.name == "Speaker" assert state.state == "off" assert entity_id == reg.async_get_entity_id("media_player", "cast", str(info.uuid)) group_media_status = MagicMock(images=None) player_media_status = MagicMock(images=None) # Player has no state, group is buffering -> Should report 'buffering' group_media_status.player_state = "BUFFERING" group_media_status_cb(str(FakeGroupUUID), group_media_status) await hass.async_block_till_done() state = hass.states.get(entity_id) assert state.state == "buffering" # Player has no state, group is playing -> Should report 'playing' group_media_status.player_state = "PLAYING" group_media_status_cb(str(FakeGroupUUID), group_media_status) await hass.async_block_till_done() state = hass.states.get(entity_id) assert state.state == "playing" # Player is paused, group is playing -> Should report 'paused' player_media_status.player_state = None player_media_status.player_is_paused = True media_status_cb(player_media_status) await hass.async_block_till_done() await hass.async_block_till_done() state = hass.states.get(entity_id) assert state.state == "paused" # Player is in unknown state, group is playing -> Should report 'playing' player_media_status.player_state = "UNKNOWN" media_status_cb(player_media_status) await hass.async_block_till_done() state = hass.states.get(entity_id) assert state.state == "playing"
Test media states are read from group if entity has no state.
12
172
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python async def test_group_media_states(hass, mz_mock): entity_id = "media_player.speaker" reg = er.async_get(hass) info = get_fake_chromecast_info() chromecast, _ = await async_setup_media_player_cast(hass, info) _, conn_status_cb, media_status_cb, group_media_status_cb = get_status_callbacks( chromecast, mz_mock ) connection_status = MagicMock() connection_status.status = "CONNECTED" conn_status_cb(connection_status) await hass.async_block_till_done() state = hass.states.get(entity_id) assert state is not None assert state.name == "Speaker" assert state.state == "off" assert entity_id == reg.async_get_entity_id("media_player", "cast", str(info.uuid)) group_media_status = MagicMock(images=None) player_media_status = MagicMock(images=None) # Player has no state, group is buffering -> Should report 'buffering' group_media_status.player_state = "BUFFERING" group_media_status_cb(str(FakeGroupUUID), group_media_status) await hass.async_block_till_done() state = hass.states.get(entity_id) assert state.state == "buffering" # Player has no state, group is playing -> Should report 'playing' group_media_status.player_state = "PLAYING" group_media_status_cb(str(FakeGroupUUID), group_media_status) await hass.async_block_till_done() state = hass.states.get(entity_id) assert state.state == "playing" # Player is paused, group is playing -> Should report 'paused' player_media_status.player_state = None player_media_status.player_is_paused = True media_status_cb(player_media_status) await hass.async_block_till_done() await hass.async_block_till_done() state = hass.states.get(entity_id) assert state.state == "paused" # Player is in unknown state, group is playing -> Should report 'playing' player_media_status.player_state = "UNKNOWN" media_status_cb(player_media_status) await hass.async_block_till_done() state = hass.states.get(entity_id) assert state.state == "playing" ``` ###Assistant : Test media states are read from group if entity has no state.
451
def test_deserialize(self): block = blocks.PageChooserBlock() christmas_page = Page.objects.get(slug='christmas') self.assertEqual(block.to_python(christmas_page.id), christmas_page) # None should deserialize to None self.assertIsNone(block.to_python(None))
The serialized value of a PageChooserBlock (an ID) should deserialize to a Page object
14
17
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_deserialize(self): block = blocks.PageChooserBlock() christmas_page = Page.objects.get(slug='christmas') self.assertEqual(block.to_python(christmas_page.id), christmas_page) # None should deserialize to None self.assertIsNone(block.to_python(None)) ``` ###Assistant : The serialized value of a PageChooserBlock (an ID) should deserialize to a Page object
452
def _is_current_explicit_device(device_type): device_type = device_type.upper() if device_type not in ["CPU", "GPU"]: raise ValueError('`device_type` should be either "CPU" or "GPU".') device = _get_current_tf_device() return device is not None and device.device_type == device_type.upper()
Check if the current device is explicitly set on the device type specified. Args: device_type: A string containing `GPU` or `CPU` (case-insensitive). Returns: A boolean indicating if the current device scope is explicitly set on the device type. Raises: ValueError: If the `device_type` string indicates an unsupported device.
48
31
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _is_current_explicit_device(device_type): device_type = device_type.upper() if device_type not in ["CPU", "GPU"]: raise ValueError('`device_type` should be either "CPU" or "GPU".') device = _get_current_tf_device() return device is not None and device.device_type == device_type.upper() ``` ###Assistant : Check if the current device is explicitly set on the device type specified. Args: device_type: A string containing `GPU` or `CPU` (case-insensitive). Returns: A boolean indicating if the current device scope is explicitly set on the device type. Raises: ValueError: If the `device_type` string indicates an unsupported device.
453
def _return_datastructure_name(obj): if isinstance(obj, (text_type, binary_type)): if obj: yield to_native(obj, errors='surrogate_or_strict') return elif isinstance(obj, Mapping): for element in obj.items(): for subelement in _return_datastructure_name(element[1]): yield subelement elif is_iterable(obj): for element in obj: for subelement in _return_datastructure_name(element): yield subelement elif obj is None or isinstance(obj, bool): # This must come before int because bools are also ints return elif isinstance(obj, tuple(list(integer_types) + [float])): yield to_native(obj, nonstring='simplerepr') else: raise TypeError('Unknown parameter type: %s' % (type(obj)))
Return native stringified values from datastructures. For use with removing sensitive values pre-jsonification.
13
72
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _return_datastructure_name(obj): if isinstance(obj, (text_type, binary_type)): if obj: yield to_native(obj, errors='surrogate_or_strict') return elif isinstance(obj, Mapping): for element in obj.items(): for subelement in _return_datastructure_name(element[1]): yield subelement elif is_iterable(obj): for element in obj: for subelement in _return_datastructure_name(element): yield subelement elif obj is None or isinstance(obj, bool): # This must come before int because bools are also ints return elif isinstance(obj, tuple(list(integer_types) + [float])): yield to_native(obj, nonstring='simplerepr') else: raise TypeError('Unknown parameter type: %s' % (type(obj))) ``` ###Assistant : Return native stringified values from datastructures. For use with removing sensitive values pre-jsonification.
454
async def __aiter__(self): waiter = self._waiter while True: # Shield the future from being cancelled by a task waiting on it message, ts, waiter = await asyncio.shield(waiter) yield message, ts
Iterate over the messages in the message stream
8
30
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python async def __aiter__(self): waiter = self._waiter while True: # Shield the future from being cancelled by a task waiting on it message, ts, waiter = await asyncio.shield(waiter) yield message, ts ``` ###Assistant : Iterate over the messages in the message stream
455
def get_gridspec(self): return self._subplotspec.get_gridspec() if self._subplotspec else None
Return the `.GridSpec` associated with the subplot, or None.
9
8
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_gridspec(self): return self._subplotspec.get_gridspec() if self._subplotspec else None ``` ###Assistant : Return the `.GridSpec` associated with the subplot, or None.
456
def ESNet_x0_5(pretrained=False, use_ssld=False, **kwargs): model = ESNet(scale=0.5, stages_pattern=MODEL_STAGES_PATTERN["ESNet"], **kwargs) return model
ESNet_x0_5 Args: pretrained: bool=False or str. If `True` load pretrained parameters, `False` otherwise. If str, means the path of the pretrained model. use_ssld: bool=False. Whether using distillation pretrained model when pretrained=True. Returns: model: nn.Layer. Specific `ESNet_x0_5` model depends on args.
40
11
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def ESNet_x0_5(pretrained=False, use_ssld=False, **kwargs): model = ESNet(scale=0.5, stages_pattern=MODEL_STAGES_PATTERN["ESNet"], **kwargs) return model ``` ###Assistant : ESNet_x0_5 Args: pretrained: bool=False or str. If `True` load pretrained parameters, `False` otherwise. If str, means the path of the pretrained model. use_ssld: bool=False. Whether using distillation pretrained model when pretrained=True. Returns: model: nn.Layer. Specific `ESNet_x0_5` model depends on args.
457
def require_rjieba(test_case): return unittest.skipUnless(is_rjieba_available(), "test requires rjieba")(test_case)
Decorator marking a test that requires rjieba. These tests are skipped when rjieba isn't installed.
15
7
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def require_rjieba(test_case): return unittest.skipUnless(is_rjieba_available(), "test requires rjieba")(test_case) ``` ###Assistant : Decorator marking a test that requires rjieba. These tests are skipped when rjieba isn't installed.
458
def get_yaxis(self): return self.yaxis get_xgridlines = _axis_method_wrapper("xaxis", "get_gridlines") get_xticklines = _axis_method_wrapper("xaxis", "get_ticklines") get_ygridlines = _axis_method_wrapper("yaxis", "get_gridlines") get_yticklines = _axis_method_wrapper("yaxis", "get_ticklines") # Adding and tracking artists
[*Discouraged*] Return the YAxis instance. .. admonition:: Discouraged The use of this function is discouraged. You should instead directly access the attribute ``ax.yaxis``.
23
25
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_yaxis(self): return self.yaxis get_xgridlines = _axis_method_wrapper("xaxis", "get_gridlines") get_xticklines = _axis_method_wrapper("xaxis", "get_ticklines") get_ygridlines = _axis_method_wrapper("yaxis", "get_gridlines") get_yticklines = _axis_method_wrapper("yaxis", "get_ticklines") # Adding and tracking artists ``` ###Assistant : [*Discouraged*] Return the YAxis instance. .. admonition:: Discouraged The use of this function is discouraged. You should instead directly access the attribute ``ax.yaxis``.
459
def disable_tf_random_generator(): global _USE_GENERATOR_FOR_RNG _USE_GENERATOR_FOR_RNG = False
Disable the `tf.random.Generator` as the RNG for Keras. See `tf.keras.backend.experimental.is_tf_random_generator_enabled` for more details.
13
7
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def disable_tf_random_generator(): global _USE_GENERATOR_FOR_RNG _USE_GENERATOR_FOR_RNG = False ``` ###Assistant : Disable the `tf.random.Generator` as the RNG for Keras. See `tf.keras.backend.experimental.is_tf_random_generator_enabled` for more details.
460
def test_parse_timezone(all_parsers): # see gh-22256 parser = all_parsers data = result = parser.read_csv(StringIO(data), parse_dates=["dt"]) dti = DatetimeIndex( list( date_range( start="2018-01-04 09:01:00", end="2018-01-04 09:05:00", freq="1min", tz=timezone(timedelta(minutes=540)), ) ), freq=None, ) expected_data = {"dt": dti, "val": [23350, 23400, 23400, 23400, 23400]} expected = DataFrame(expected_data) tm.assert_frame_equal(result, expected) @skip_pyarrow @pytest.mark.parametrize( "date_string", ["32/32/2019", "02/30/2019", "13/13/2019", "13/2019", "a3/11/2018", "10/11/2o17"], )
dt,val 2018-01-04 09:01:00+09:00,23350 2018-01-04 09:02:00+09:00,23400 2018-01-04 09:03:00+09:00,23400 2018-01-04 09:04:00+09:00,23400 2018-01-04 09:05:00+09:00,23400
11
54
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_parse_timezone(all_parsers): # see gh-22256 parser = all_parsers data = result = parser.read_csv(StringIO(data), parse_dates=["dt"]) dti = DatetimeIndex( list( date_range( start="2018-01-04 09:01:00", end="2018-01-04 09:05:00", freq="1min", tz=timezone(timedelta(minutes=540)), ) ), freq=None, ) expected_data = {"dt": dti, "val": [23350, 23400, 23400, 23400, 23400]} expected = DataFrame(expected_data) tm.assert_frame_equal(result, expected) @skip_pyarrow @pytest.mark.parametrize( "date_string", ["32/32/2019", "02/30/2019", "13/13/2019", "13/2019", "a3/11/2018", "10/11/2o17"], ) ``` ###Assistant : dt,val 2018-01-04 09:01:00+09:00,23350 2018-01-04 09:02:00+09:00,23400 2018-01-04 09:03:00+09:00,23400 2018-01-04 09:04:00+09:00,23400 2018-01-04 09:05:00+09:00,23400
461
def alpn_proto_negotiated(self) -> Optional[bytes]: # pragma: no cover warnings.warn( "Connection.alpn_proto_negotiated is deprecated, use Connection.alpn instead.", DeprecationWarning, ) return self.alpn
*Deprecated:* An outdated alias for Connection.alpn.
6
19
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def alpn_proto_negotiated(self) -> Optional[bytes]: # pragma: no cover warnings.warn( "Connection.alpn_proto_negotiated is deprecated, use Connection.alpn instead.", DeprecationWarning, ) return self.alpn ``` ###Assistant : *Deprecated:* An outdated alias for Connection.alpn.
462
def device_class(self) -> CoverDeviceClass: if isinstance(self.node, Awning): return CoverDeviceClass.AWNING if isinstance(self.node, Blind): return CoverDeviceClass.BLIND if isinstance(self.node, GarageDoor): return CoverDeviceClass.GARAGE if isinstance(self.node, Gate): return CoverDeviceClass.GATE if isinstance(self.node, RollerShutter): return CoverDeviceClass.SHUTTER if isinstance(self.node, Window): return CoverDeviceClass.WINDOW return CoverDeviceClass.WINDOW
Define this cover as either awning, blind, garage, gate, shutter or window.
12
36
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def device_class(self) -> CoverDeviceClass: if isinstance(self.node, Awning): return CoverDeviceClass.AWNING if isinstance(self.node, Blind): return CoverDeviceClass.BLIND if isinstance(self.node, GarageDoor): return CoverDeviceClass.GARAGE if isinstance(self.node, Gate): return CoverDeviceClass.GATE if isinstance(self.node, RollerShutter): return CoverDeviceClass.SHUTTER if isinstance(self.node, Window): return CoverDeviceClass.WINDOW return CoverDeviceClass.WINDOW ``` ###Assistant : Define this cover as either awning, blind, garage, gate, shutter or window.
463
def get_yieldcurve(country) -> pd.DataFrame: data = investpy.bonds.get_bonds_overview(country) data.drop(columns=data.columns[0], axis=1, inplace=True) data.rename( columns={ "name": "Tenor", "last": "Current", "last_close": "Previous", "high": "High", "low": "Low", "change": "Change", "change_percentage": "% Change", }, inplace=True, ) return data
Get country yield curve [Source: Investing.com] Returns ------- pd.DataFrame Country yield curve
12
32
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_yieldcurve(country) -> pd.DataFrame: data = investpy.bonds.get_bonds_overview(country) data.drop(columns=data.columns[0], axis=1, inplace=True) data.rename( columns={ "name": "Tenor", "last": "Current", "last_close": "Previous", "high": "High", "low": "Low", "change": "Change", "change_percentage": "% Change", }, inplace=True, ) return data ``` ###Assistant : Get country yield curve [Source: Investing.com] Returns ------- pd.DataFrame Country yield curve
464
async def test_report_humidifier_humidity_state(hass): hass.states.async_set( "humidifier.dry", "on", { "friendly_name": "Humidifier dry", "supported_features": 0, "humidity": 25, "min_humidity": 20, "max_humidity": 90, }, ) hass.states.async_set( "humidifier.wet", "on", { "friendly_name": "Humidifier wet", "supported_features": 0, "humidity": 80, "min_humidity": 20, "max_humidity": 90, }, ) properties = await reported_properties(hass, "humidifier.dry") properties.assert_equal("Alexa.RangeController", "rangeValue", 25) properties = await reported_properties(hass, "humidifier.wet") properties.assert_equal("Alexa.RangeController", "rangeValue", 80)
Test PercentageController, PowerLevelController reports humidifier humidity correctly.
7
53
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python async def test_report_humidifier_humidity_state(hass): hass.states.async_set( "humidifier.dry", "on", { "friendly_name": "Humidifier dry", "supported_features": 0, "humidity": 25, "min_humidity": 20, "max_humidity": 90, }, ) hass.states.async_set( "humidifier.wet", "on", { "friendly_name": "Humidifier wet", "supported_features": 0, "humidity": 80, "min_humidity": 20, "max_humidity": 90, }, ) properties = await reported_properties(hass, "humidifier.dry") properties.assert_equal("Alexa.RangeController", "rangeValue", 25) properties = await reported_properties(hass, "humidifier.wet") properties.assert_equal("Alexa.RangeController", "rangeValue", 80) ``` ###Assistant : Test PercentageController, PowerLevelController reports humidifier humidity correctly.
465
def serialize(self, value): if self.type == CustomFieldTypeChoices.TYPE_OBJECT and value is not None: return value.pk return value
Prepare a value for storage as JSON data.
8
16
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def serialize(self, value): if self.type == CustomFieldTypeChoices.TYPE_OBJECT and value is not None: return value.pk return value ``` ###Assistant : Prepare a value for storage as JSON data.
466
def revert_to_saved(self, frame_index): if frame_index not in self._updated_frame_indices: logger.debug("Alignments not amended. Returning") return logger.verbose("Reverting alignments for frame_index %s", frame_index) print(frame_index) print(len(self._sorted_frame_names)) alignments = self._alignments.data[self._sorted_frame_names[frame_index]]["faces"] faces = self._frame_faces[frame_index] reset_grid = self._add_remove_faces(alignments, faces) for detected_face, face in zip(faces, alignments): detected_face.from_alignment(face, with_thumb=True) detected_face.load_aligned(None, force=True) _ = detected_face.aligned.average_distance # cache the distances self._updated_frame_indices.remove(frame_index) if not self._updated_frame_indices: self._tk_unsaved.set(False) if reset_grid: self._tk_face_count_changed.set(True) else: self._tk_edited.set(True) self._globals.tk_update.set(True)
Revert the frame's alignments to their saved version for the given frame index. Parameters ---------- frame_index: int The frame that should have their faces reverted to their saved version
29
59
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def revert_to_saved(self, frame_index): if frame_index not in self._updated_frame_indices: logger.debug("Alignments not amended. Returning") return logger.verbose("Reverting alignments for frame_index %s", frame_index) print(frame_index) print(len(self._sorted_frame_names)) alignments = self._alignments.data[self._sorted_frame_names[frame_index]]["faces"] faces = self._frame_faces[frame_index] reset_grid = self._add_remove_faces(alignments, faces) for detected_face, face in zip(faces, alignments): detected_face.from_alignment(face, with_thumb=True) detected_face.load_aligned(None, force=True) _ = detected_face.aligned.average_distance # cache the distances self._updated_frame_indices.remove(frame_index) if not self._updated_frame_indices: self._tk_unsaved.set(False) if reset_grid: self._tk_face_count_changed.set(True) else: self._tk_edited.set(True) self._globals.tk_update.set(True) ``` ###Assistant : Revert the frame's alignments to their saved version for the given frame index. Parameters ---------- frame_index: int The frame that should have their faces reverted to their saved version
467
def parse_args(args): # Use the file's docstring for the help text and don't let argparse reformat it. parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('--css', type=str, required=True, help='hostname of code signing server') group = parser.add_mutually_exclusive_group() # We use 'store_false' and a destination related to the other type of # artifact to cause the flag being set to disable publishing of the other # artifact. This makes using the parsed arguments later on a little simpler # and cleaner. group.add_argument('--snaps-only', action='store_false', dest='publish_windows', help='Skip publishing other artifacts and only publish the snaps') group.add_argument('--windows-only', action='store_false', dest='publish_snaps', help='Skip publishing other artifacts and only publish the Windows installer') return parser.parse_args(args)
Parse command line arguments. :param args: command line arguments with the program name removed. This is usually taken from sys.argv[1:]. :type args: `list` of `str` :returns: parsed arguments :rtype: argparse.Namespace
30
102
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def parse_args(args): # Use the file's docstring for the help text and don't let argparse reformat it. parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('--css', type=str, required=True, help='hostname of code signing server') group = parser.add_mutually_exclusive_group() # We use 'store_false' and a destination related to the other type of # artifact to cause the flag being set to disable publishing of the other # artifact. This makes using the parsed arguments later on a little simpler # and cleaner. group.add_argument('--snaps-only', action='store_false', dest='publish_windows', help='Skip publishing other artifacts and only publish the snaps') group.add_argument('--windows-only', action='store_false', dest='publish_snaps', help='Skip publishing other artifacts and only publish the Windows installer') return parser.parse_args(args) ``` ###Assistant : Parse command line arguments. :param args: command line arguments with the program name removed. This is usually taken from sys.argv[1:]. :type args: `list` of `str` :returns: parsed arguments :rtype: argparse.Namespace
468
def is_conservative(field): # Field is conservative irrespective of frame # Take the first frame in the result of the separate method of Vector if field == Vector(0): return True frame = list(field.separate())[0] return curl(field, frame).simplify() == Vector(0)
Checks if a field is conservative. Parameters ========== field : Vector The field to check for conservative property Examples ======== >>> from sympy.physics.vector import ReferenceFrame >>> from sympy.physics.vector import is_conservative >>> R = ReferenceFrame('R') >>> is_conservative(R[1]*R[2]*R.x + R[0]*R[2]*R.y + R[0]*R[1]*R.z) True >>> is_conservative(R[2] * R.y) False
46
37
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def is_conservative(field): # Field is conservative irrespective of frame # Take the first frame in the result of the separate method of Vector if field == Vector(0): return True frame = list(field.separate())[0] return curl(field, frame).simplify() == Vector(0) ``` ###Assistant : Checks if a field is conservative. Parameters ========== field : Vector The field to check for conservative property Examples ======== >>> from sympy.physics.vector import ReferenceFrame >>> from sympy.physics.vector import is_conservative >>> R = ReferenceFrame('R') >>> is_conservative(R[1]*R[2]*R.x + R[0]*R[2]*R.y + R[0]*R[1]*R.z) True >>> is_conservative(R[2] * R.y) False
469
def fixup_build_ext(cmd): if os.name == 'nt': cmd.debug = sys.executable.endswith('_d.exe') elif sysconfig.get_config_var('Py_ENABLE_SHARED'): # To further add to the shared builds fun on Unix, we can't just add # library_dirs to the Extension() instance because that doesn't get # plumbed through to the final compiler command. runshared = sysconfig.get_config_var('RUNSHARED') if runshared is None: cmd.library_dirs = ['.'] else: if sys.platform == 'darwin': cmd.library_dirs = [] else: name, equals, value = runshared.partition('=') cmd.library_dirs = [d for d in value.split(os.pathsep) if d]
Function needed to make build_ext tests pass. When Python was built with --enable-shared on Unix, -L. is not enough to find libpython<blah>.so, because regrtest runs in a tempdir, not in the source directory where the .so lives. When Python was built with in debug mode on Windows, build_ext commands need their debug attribute set, and it is not done automatically for some reason. This function handles both of these things. Example use: cmd = build_ext(dist) support.fixup_build_ext(cmd) cmd.ensure_finalized() Unlike most other Unix platforms, Mac OS X embeds absolute paths to shared libraries into executables, so the fixup is not needed there.
100
77
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def fixup_build_ext(cmd): if os.name == 'nt': cmd.debug = sys.executable.endswith('_d.exe') elif sysconfig.get_config_var('Py_ENABLE_SHARED'): # To further add to the shared builds fun on Unix, we can't just add # library_dirs to the Extension() instance because that doesn't get # plumbed through to the final compiler command. runshared = sysconfig.get_config_var('RUNSHARED') if runshared is None: cmd.library_dirs = ['.'] else: if sys.platform == 'darwin': cmd.library_dirs = [] else: name, equals, value = runshared.partition('=') cmd.library_dirs = [d for d in value.split(os.pathsep) if d] ``` ###Assistant : Function needed to make build_ext tests pass. When Python was built with --enable-shared on Unix, -L. is not enough to find libpython<blah>.so, because regrtest runs in a tempdir, not in the source directory where the .so lives. When Python was built with in debug mode on Windows, build_ext commands need their debug attribute set, and it is not done automatically for some reason. This function handles both of these things. Example use: cmd = build_ext(dist) support.fixup_build_ext(cmd) cmd.ensure_finalized() Unlike most other Unix platforms, Mac OS X embeds absolute paths to shared libraries into executables, so the fixup is not needed there.
470
def batch_uses_naming_series(): use_naming_series = cint(frappe.db.get_single_value("Stock Settings", "use_naming_series")) return bool(use_naming_series)
Verify if the Batch is to be named using a naming series :return: bool
14
9
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def batch_uses_naming_series(): use_naming_series = cint(frappe.db.get_single_value("Stock Settings", "use_naming_series")) return bool(use_naming_series) ``` ###Assistant : Verify if the Batch is to be named using a naming series :return: bool
471
def mixin_http_gateway_parser(parser=None): gp = add_arg_group(parser, title='HTTP Gateway') gp.add_argument( '--title', type=str, help='The title of this HTTP server. It will be used in automatics docs such as Swagger UI.', ) gp.add_argument( '--description', type=str, help='The description of this HTTP server. It will be used in automatics docs such as Swagger UI.', ) gp.add_argument( '--cors', action='store_true', default=False, help=, ) gp.add_argument( '--no-debug-endpoints', action='store_true', default=False, help='If set, `/status` `/post` endpoints are removed from HTTP interface. ', ) gp.add_argument( '--no-crud-endpoints', action='store_true', default=False, help=, ) gp.add_argument( '--expose-endpoints', type=str, help=, ) gp.add_argument( '--uvicorn-kwargs', action=KVAppendAction, metavar='KEY: VALUE', nargs='*', help=, ) gp.add_argument( '--grpc-server-kwargs', action=KVAppendAction, metavar='KEY: VALUE', nargs='*', help=, ) gp.add_argument( '--ssl-certfile', type=str, help=, dest='ssl_certfile', ) gp.add_argument( '--ssl-keyfile', type=str, help=, dest='ssl_keyfile', )
Add the options to rest server :param parser: the parser If set, a CORS middleware is added to FastAPI frontend to allow cross-origin access. If set, `/index`, `/search`, `/update`, `/delete` endpoints are removed from HTTP interface. Any executor that has `@requests(on=...)` bind with those values will receive data requests. A JSON string that represents a map from executor endpoints (`@requests(on=...)`) to HTTP endpoints. Dictionary of kwargs arguments that will be passed to Uvicorn server when starting the server More details can be found in Uvicorn docs: https://www.uvicorn.org/settings/ Dictionary of kwargs arguments that will be passed to the grpc server when starting the server # todo update the path to the certificate file the path to the key file
118
110
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def mixin_http_gateway_parser(parser=None): gp = add_arg_group(parser, title='HTTP Gateway') gp.add_argument( '--title', type=str, help='The title of this HTTP server. It will be used in automatics docs such as Swagger UI.', ) gp.add_argument( '--description', type=str, help='The description of this HTTP server. It will be used in automatics docs such as Swagger UI.', ) gp.add_argument( '--cors', action='store_true', default=False, help=, ) gp.add_argument( '--no-debug-endpoints', action='store_true', default=False, help='If set, `/status` `/post` endpoints are removed from HTTP interface. ', ) gp.add_argument( '--no-crud-endpoints', action='store_true', default=False, help=, ) gp.add_argument( '--expose-endpoints', type=str, help=, ) gp.add_argument( '--uvicorn-kwargs', action=KVAppendAction, metavar='KEY: VALUE', nargs='*', help=, ) gp.add_argument( '--grpc-server-kwargs', action=KVAppendAction, metavar='KEY: VALUE', nargs='*', help=, ) gp.add_argument( '--ssl-certfile', type=str, help=, dest='ssl_certfile', ) gp.add_argument( '--ssl-keyfile', type=str, help=, dest='ssl_keyfile', ) ``` ###Assistant : Add the options to rest server :param parser: the parser If set, a CORS middleware is added to FastAPI frontend to allow cross-origin access. If set, `/index`, `/search`, `/update`, `/delete` endpoints are removed from HTTP interface. Any executor that has `@requests(on=...)` bind with those values will receive data requests. A JSON string that represents a map from executor endpoints (`@requests(on=...)`) to HTTP endpoints. Dictionary of kwargs arguments that will be passed to Uvicorn server when starting the server More details can be found in Uvicorn docs: https://www.uvicorn.org/settings/ Dictionary of kwargs arguments that will be passed to the grpc server when starting the server # todo update the path to the certificate file the path to the key file
472
def test_image_crafter_index(encoder_doc_array, tmpdir): create_test_img(path=str(tmpdir), file_name='1.jpg') with Flow().add(uses=ImageCrafter) as f: res = f.index(inputs=encoder_doc_array) assert len(res) == 1 doc = res[0] assert doc.mime_type == 'image/jpeg' assert doc.tensor is not None
In this test, we input one ``DocumentArray`` with one ``Document``, and the `craft` method in the ``ImageCrafter`` returns chunks. In the ``ImageCrafter``, we filtered out all the modalities and only kept `image/jpeg`. So the 2 chunks should left only 1 chunk. And the tensor value of the ``Document`` is not empty once we finished crafting since we converted image uri/datauri to tensor.
62
28
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_image_crafter_index(encoder_doc_array, tmpdir): create_test_img(path=str(tmpdir), file_name='1.jpg') with Flow().add(uses=ImageCrafter) as f: res = f.index(inputs=encoder_doc_array) assert len(res) == 1 doc = res[0] assert doc.mime_type == 'image/jpeg' assert doc.tensor is not None ``` ###Assistant : In this test, we input one ``DocumentArray`` with one ``Document``, and the `craft` method in the ``ImageCrafter`` returns chunks. In the ``ImageCrafter``, we filtered out all the modalities and only kept `image/jpeg`. So the 2 chunks should left only 1 chunk. And the tensor value of the ``Document`` is not empty once we finished crafting since we converted image uri/datauri to tensor.
473
def find_file(path, saltenv="base", **kwargs): actual_saltenv = saltenv if "env" in kwargs: # "env" is not supported; Use "saltenv". kwargs.pop("env") path = os.path.normpath(path) fnd = {"path": "", "rel": ""} if os.path.isabs(path): return fnd if saltenv not in __opts__["file_roots"]: if "__env__" in __opts__["file_roots"]: log.debug( "salt environment '%s' maps to __env__ file_roots directory", saltenv ) saltenv = "__env__" else: return fnd
Search the environment for the relative path.
7
58
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def find_file(path, saltenv="base", **kwargs): actual_saltenv = saltenv if "env" in kwargs: # "env" is not supported; Use "saltenv". kwargs.pop("env") path = os.path.normpath(path) fnd = {"path": "", "rel": ""} if os.path.isabs(path): return fnd if saltenv not in __opts__["file_roots"]: if "__env__" in __opts__["file_roots"]: log.debug( "salt environment '%s' maps to __env__ file_roots directory", saltenv ) saltenv = "__env__" else: return fnd ``` ###Assistant : Search the environment for the relative path.
474
def get_prompt_templates(cls) -> List[PromptTemplate]: return list(cls.prompt_templates.values())
Returns the list of supported prompt templates. :return: List of supported prompt templates.
13
6
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_prompt_templates(cls) -> List[PromptTemplate]: return list(cls.prompt_templates.values()) ``` ###Assistant : Returns the list of supported prompt templates. :return: List of supported prompt templates.
475
def test_views(self, postgres_db): query = for cid, char in [(CID_A, 'a'), (CID_B, 'b')]: self.sql_via_http( query.format(f'test_view_{char}', char), company_id=cid, expected_resp_type=RESPONSE_TYPE.OK ) tables = self.get_tables_in('mindsdb', cid) self.assert_list( tables, { 'models', 'models_versions', f'test_view_{char}' } ) for cid, char in [(CID_A, 'a'), (CID_B, 'b')]: response = self.sql_via_http( f"select * from mindsdb.test_view_{char}", company_id=cid, expected_resp_type=RESPONSE_TYPE.TABLE ) assert len(response['data']) == 50 response = self.sql_via_http( f"DROP VIEW mindsdb.test_view_{char}", company_id=cid, expected_resp_type=RESPONSE_TYPE.OK ) tables = self.get_tables_in('mindsdb', cid) self.assert_list( tables, { 'models', 'models_versions' } ) self.sql_via_http( f"select * from mindsdb.test_view_{char}", company_id=cid, expected_resp_type=RESPONSE_TYPE.ERROR )
CREATE VIEW mindsdb.{} FROM test_integration_{} ( select * from rentals limit 50 )
13
81
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_views(self, postgres_db): query = for cid, char in [(CID_A, 'a'), (CID_B, 'b')]: self.sql_via_http( query.format(f'test_view_{char}', char), company_id=cid, expected_resp_type=RESPONSE_TYPE.OK ) tables = self.get_tables_in('mindsdb', cid) self.assert_list( tables, { 'models', 'models_versions', f'test_view_{char}' } ) for cid, char in [(CID_A, 'a'), (CID_B, 'b')]: response = self.sql_via_http( f"select * from mindsdb.test_view_{char}", company_id=cid, expected_resp_type=RESPONSE_TYPE.TABLE ) assert len(response['data']) == 50 response = self.sql_via_http( f"DROP VIEW mindsdb.test_view_{char}", company_id=cid, expected_resp_type=RESPONSE_TYPE.OK ) tables = self.get_tables_in('mindsdb', cid) self.assert_list( tables, { 'models', 'models_versions' } ) self.sql_via_http( f"select * from mindsdb.test_view_{char}", company_id=cid, expected_resp_type=RESPONSE_TYPE.ERROR ) ``` ###Assistant : CREATE VIEW mindsdb.{} FROM test_integration_{} ( select * from rentals limit 50 )
476
def convert(filename, cache): path = Path(filename) if not path.exists(): raise IOError(f"{path} does not exist") if path.suffix[1:] not in converter: import pytest pytest.skip(f"Don't know how to convert {path.suffix} files to png") newpath = path.parent / f"{path.stem}_{path.suffix[1:]}.png" # Only convert the file if the destination doesn't already exist or # is out of date. if not newpath.exists() or newpath.stat().st_mtime < path.stat().st_mtime: cache_dir = _get_cache_path() if cache else None if cache_dir is not None: _register_conversion_cache_cleaner_once() hash_value = get_file_hash(path) cached_path = cache_dir / (hash_value + newpath.suffix) if cached_path.exists(): _log.debug("For %s: reusing cached conversion.", filename) shutil.copyfile(cached_path, newpath) return str(newpath) _log.debug("For %s: converting to png.", filename) convert = converter[path.suffix[1:]] if path.suffix == ".svg": contents = path.read_text() if 'style="font:' in contents: # for svg.fonttype = none, we explicitly patch the font search # path so that fonts shipped by Matplotlib are found. convert = _svg_with_matplotlib_fonts_converter convert(path, newpath) if cache_dir is not None: _log.debug("For %s: caching conversion result.", filename) shutil.copyfile(newpath, cached_path) return str(newpath)
Convert the named file to png; return the name of the created file. If *cache* is True, the result of the conversion is cached in `matplotlib.get_cachedir() + '/test_cache/'`. The caching is based on a hash of the exact contents of the input file. Old cache entries are automatically deleted as needed to keep the size of the cache capped to twice the size of all baseline images.
67
155
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def convert(filename, cache): path = Path(filename) if not path.exists(): raise IOError(f"{path} does not exist") if path.suffix[1:] not in converter: import pytest pytest.skip(f"Don't know how to convert {path.suffix} files to png") newpath = path.parent / f"{path.stem}_{path.suffix[1:]}.png" # Only convert the file if the destination doesn't already exist or # is out of date. if not newpath.exists() or newpath.stat().st_mtime < path.stat().st_mtime: cache_dir = _get_cache_path() if cache else None if cache_dir is not None: _register_conversion_cache_cleaner_once() hash_value = get_file_hash(path) cached_path = cache_dir / (hash_value + newpath.suffix) if cached_path.exists(): _log.debug("For %s: reusing cached conversion.", filename) shutil.copyfile(cached_path, newpath) return str(newpath) _log.debug("For %s: converting to png.", filename) convert = converter[path.suffix[1:]] if path.suffix == ".svg": contents = path.read_text() if 'style="font:' in contents: # for svg.fonttype = none, we explicitly patch the font search # path so that fonts shipped by Matplotlib are found. convert = _svg_with_matplotlib_fonts_converter convert(path, newpath) if cache_dir is not None: _log.debug("For %s: caching conversion result.", filename) shutil.copyfile(newpath, cached_path) return str(newpath) ``` ###Assistant : Convert the named file to png; return the name of the created file. If *cache* is True, the result of the conversion is cached in `matplotlib.get_cachedir() + '/test_cache/'`. The caching is based on a hash of the exact contents of the input file. Old cache entries are automatically deleted as needed to keep the size of the cache capped to twice the size of all baseline images.
477
def resize(self, size, resample=None, box=None, reducing_gap=None): if resample is None: type_special = ";" in self.mode resample = Resampling.NEAREST if type_special else Resampling.BICUBIC elif resample not in ( Resampling.NEAREST, Resampling.BILINEAR, Resampling.BICUBIC, Resampling.LANCZOS, Resampling.BOX, Resampling.HAMMING, ): message = f"Unknown resampling filter ({resample})." filters = [ f"{filter[1]} ({filter[0]})" for filter in ( (Resampling.NEAREST, "Image.Resampling.NEAREST"), (Resampling.LANCZOS, "Image.Resampling.LANCZOS"), (Resampling.BILINEAR, "Image.Resampling.BILINEAR"), (Resampling.BICUBIC, "Image.Resampling.BICUBIC"), (Resampling.BOX, "Image.Resampling.BOX"), (Resampling.HAMMING, "Image.Resampling.HAMMING"), ) ] raise ValueError( message + " Use " + ", ".join(filters[:-1]) + " or " + filters[-1] ) if reducing_gap is not None and reducing_gap < 1.0: raise ValueError("reducing_gap must be 1.0 or greater") size = tuple(size) if box is None: box = (0, 0) + self.size else: box = tuple(box) if self.size == size and box == (0, 0) + self.size: return self.copy() if self.mode in ("1", "P"): resample = Resampling.NEAREST if self.mode in ["LA", "RGBA"] and resample != Resampling.NEAREST: im = self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) im = im.resize(size, resample, box) return im.convert(self.mode) self.load() if reducing_gap is not None and resample != Resampling.NEAREST: factor_x = int((box[2] - box[0]) / size[0] / reducing_gap) or 1 factor_y = int((box[3] - box[1]) / size[1] / reducing_gap) or 1 if factor_x > 1 or factor_y > 1: reduce_box = self._get_safe_box(size, resample, box) factor = (factor_x, factor_y) if callable(self.reduce): self = self.reduce(factor, box=reduce_box) else: self = Image.reduce(self, factor, box=reduce_box) box = ( (box[0] - reduce_box[0]) / factor_x, (box[1] - reduce_box[1]) / factor_y, (box[2] - reduce_box[0]) / factor_x, (box[3] - reduce_box[1]) / factor_y, ) return self._new(self.im.resize(size, resample, box))
Returns a resized copy of this image. :param size: The requested size in pixels, as a 2-tuple: (width, height). :param resample: An optional resampling filter. This can be one of :py:data:`PIL.Image.Resampling.NEAREST`, :py:data:`PIL.Image.Resampling.BOX`, :py:data:`PIL.Image.Resampling.BILINEAR`, :py:data:`PIL.Image.Resampling.HAMMING`, :py:data:`PIL.Image.Resampling.BICUBIC` or :py:data:`PIL.Image.Resampling.LANCZOS`. If the image has mode "1" or "P", it is always set to :py:data:`PIL.Image.Resampling.NEAREST`. If the image mode specifies a number of bits, such as "I;16", then the default filter is :py:data:`PIL.Image.Resampling.NEAREST`. Otherwise, the default filter is :py:data:`PIL.Image.Resampling.BICUBIC`. See: :ref:`concept-filters`. :param box: An optional 4-tuple of floats providing the source image region to be scaled. The values must be within (0, 0, width, height) rectangle. If omitted or None, the entire source is used. :param reducing_gap: Apply optimization by resizing the image in two steps. First, reducing the image by integer times using :py:meth:`~PIL.Image.Image.reduce`. Second, resizing using regular resampling. The last step changes size no less than by ``reducing_gap`` times. ``reducing_gap`` may be None (no first step is performed) or should be greater than 1.0. The bigger ``reducing_gap``, the closer the result to the fair resampling. The smaller ``reducing_gap``, the faster resizing. With ``reducing_gap`` greater or equal to 3.0, the result is indistinguishable from fair resampling in most cases. The default value is None (no optimization). :returns: An :py:class:`~PIL.Image.Image` object.
207
245
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def resize(self, size, resample=None, box=None, reducing_gap=None): if resample is None: type_special = ";" in self.mode resample = Resampling.NEAREST if type_special else Resampling.BICUBIC elif resample not in ( Resampling.NEAREST, Resampling.BILINEAR, Resampling.BICUBIC, Resampling.LANCZOS, Resampling.BOX, Resampling.HAMMING, ): message = f"Unknown resampling filter ({resample})." filters = [ f"{filter[1]} ({filter[0]})" for filter in ( (Resampling.NEAREST, "Image.Resampling.NEAREST"), (Resampling.LANCZOS, "Image.Resampling.LANCZOS"), (Resampling.BILINEAR, "Image.Resampling.BILINEAR"), (Resampling.BICUBIC, "Image.Resampling.BICUBIC"), (Resampling.BOX, "Image.Resampling.BOX"), (Resampling.HAMMING, "Image.Resampling.HAMMING"), ) ] raise ValueError( message + " Use " + ", ".join(filters[:-1]) + " or " + filters[-1] ) if reducing_gap is not None and reducing_gap < 1.0: raise ValueError("reducing_gap must be 1.0 or greater") size = tuple(size) if box is None: box = (0, 0) + self.size else: box = tuple(box) if self.size == size and box == (0, 0) + self.size: return self.copy() if self.mode in ("1", "P"): resample = Resampling.NEAREST if self.mode in ["LA", "RGBA"] and resample != Resampling.NEAREST: im = self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) im = im.resize(size, resample, box) return im.convert(self.mode) self.load() if reducing_gap is not None and resample != Resampling.NEAREST: factor_x = int((box[2] - box[0]) / size[0] / reducing_gap) or 1 factor_y = int((box[3] - box[1]) / size[1] / reducing_gap) or 1 if factor_x > 1 or factor_y > 1: reduce_box = self._get_safe_box(size, resample, box) factor = (factor_x, factor_y) if callable(self.reduce): self = self.reduce(factor, box=reduce_box) else: self = Image.reduce(self, factor, box=reduce_box) box = ( (box[0] - reduce_box[0]) / factor_x, (box[1] - reduce_box[1]) / factor_y, (box[2] - reduce_box[0]) / factor_x, (box[3] - reduce_box[1]) / factor_y, ) return self._new(self.im.resize(size, resample, box)) ``` ###Assistant : Returns a resized copy of this image. :param size: The requested size in pixels, as a 2-tuple: (width, height). :param resample: An optional resampling filter. This can be one of :py:data:`PIL.Image.Resampling.NEAREST`, :py:data:`PIL.Image.Resampling.BOX`, :py:data:`PIL.Image.Resampling.BILINEAR`, :py:data:`PIL.Image.Resampling.HAMMING`, :py:data:`PIL.Image.Resampling.BICUBIC` or :py:data:`PIL.Image.Resampling.LANCZOS`. If the image has mode "1" or "P", it is always set to :py:data:`PIL.Image.Resampling.NEAREST`. If the image mode specifies a number of bits, such as "I;16", then the default filter is :py:data:`PIL.Image.Resampling.NEAREST`. Otherwise, the default filter is :py:data:`PIL.Image.Resampling.BICUBIC`. See: :ref:`concept-filters`. :param box: An optional 4-tuple of floats providing the source image region to be scaled. The values must be within (0, 0, width, height) rectangle. If omitted or None, the entire source is used. :param reducing_gap: Apply optimization by resizing the image in two steps. First, reducing the image by integer times using :py:meth:`~PIL.Image.Image.reduce`. Second, resizing using regular resampling. The last step changes size no less than by ``reducing_gap`` times. ``reducing_gap`` may be None (no first step is performed) or should be greater than 1.0. The bigger ``reducing_gap``, the closer the result to the fair resampling. The smaller ``reducing_gap``, the faster resizing. With ``reducing_gap`` greater or equal to 3.0, the result is indistinguishable from fair resampling in most cases. The default value is None (no optimization). :returns: An :py:class:`~PIL.Image.Image` object.
478
def test_unrecognized_key(self) -> None: yaml_str = output_error = self.get_errors_from_gen_backend_stubs(yaml_str) self.assertExpectedInline(output_error, ) # noqa: B950 # if use_out_as_primary is provided, it must be a bool
\ backend: XLA cpp_namespace: torch_xla supported: - abs invalid_key: invalid_val contains unexpected keys: invalid_key. Only the following keys are supported: backend, cpp_namespace, extra_headers, supported, autograd, full_codegen
26
24
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_unrecognized_key(self) -> None: yaml_str = output_error = self.get_errors_from_gen_backend_stubs(yaml_str) self.assertExpectedInline(output_error, ) # noqa: B950 # if use_out_as_primary is provided, it must be a bool ``` ###Assistant : \ backend: XLA cpp_namespace: torch_xla supported: - abs invalid_key: invalid_val contains unexpected keys: invalid_key. Only the following keys are supported: backend, cpp_namespace, extra_headers, supported, autograd, full_codegen
479
def f2cexpr(expr): # TODO: support Fortran `len` function with optional kind parameter expr = re.sub(r'\blen\b', 'f2py_slen', expr) return expr
Rewrite Fortran expression as f2py supported C expression. Due to the lack of a proper expression parser in f2py, this function uses a heuristic approach that assumes that Fortran arithmetic expressions are valid C arithmetic expressions when mapping Fortran function calls to the corresponding C function/CPP macros calls.
48
19
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def f2cexpr(expr): # TODO: support Fortran `len` function with optional kind parameter expr = re.sub(r'\blen\b', 'f2py_slen', expr) return expr ``` ###Assistant : Rewrite Fortran expression as f2py supported C expression. Due to the lack of a proper expression parser in f2py, this function uses a heuristic approach that assumes that Fortran arithmetic expressions are valid C arithmetic expressions when mapping Fortran function calls to the corresponding C function/CPP macros calls.
480
def build_args(self, category, command=None, generate=False): logger.debug("Build cli arguments: (category: %s, command: %s, generate: %s)", category, command, generate) command = self.command if not command else command script = f"{category}.py" pathexecscript = os.path.join(self.pathscript, script) args = [sys.executable] if generate else [sys.executable, "-u"] args.extend([pathexecscript, command]) cli_opts = get_config().cli_opts for cliopt in cli_opts.gen_cli_arguments(command): args.extend(cliopt) if command == "train" and not generate: self._get_training_session_info(cliopt) if not generate: args.append("-gui") # Indicate to Faceswap that we are running the GUI if generate: # Delimit args with spaces args = [f'"{arg}"' if " " in arg and not arg.startswith(("[", "(")) and not arg.endswith(("]", ")")) else arg for arg in args] logger.debug("Built cli arguments: (%s)", args) return args
Build the faceswap command and arguments list. If training, pass the model folder and name to the training :class:`lib.gui.analysis.Session` for the GUI.
22
108
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def build_args(self, category, command=None, generate=False): logger.debug("Build cli arguments: (category: %s, command: %s, generate: %s)", category, command, generate) command = self.command if not command else command script = f"{category}.py" pathexecscript = os.path.join(self.pathscript, script) args = [sys.executable] if generate else [sys.executable, "-u"] args.extend([pathexecscript, command]) cli_opts = get_config().cli_opts for cliopt in cli_opts.gen_cli_arguments(command): args.extend(cliopt) if command == "train" and not generate: self._get_training_session_info(cliopt) if not generate: args.append("-gui") # Indicate to Faceswap that we are running the GUI if generate: # Delimit args with spaces args = [f'"{arg}"' if " " in arg and not arg.startswith(("[", "(")) and not arg.endswith(("]", ")")) else arg for arg in args] logger.debug("Built cli arguments: (%s)", args) return args ``` ###Assistant : Build the faceswap command and arguments list. If training, pass the model folder and name to the training :class:`lib.gui.analysis.Session` for the GUI.
481
def describe_v_switches(self, vpc_id=None): request = DescribeVSwitchesRequest() if vpc_id is not None: request.set_VpcId(vpc_id) response = self._send_request(request) if response is not None: return response.get("VSwitches").get("VSwitch") else: logging.error("Describe VSwitches Failed.") return None
Queries one or more VSwitches. :param vpc_id: The ID of the VPC to which the VSwitch belongs. :return: VSwitch list.
20
28
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def describe_v_switches(self, vpc_id=None): request = DescribeVSwitchesRequest() if vpc_id is not None: request.set_VpcId(vpc_id) response = self._send_request(request) if response is not None: return response.get("VSwitches").get("VSwitch") else: logging.error("Describe VSwitches Failed.") return None ``` ###Assistant : Queries one or more VSwitches. :param vpc_id: The ID of the VPC to which the VSwitch belongs. :return: VSwitch list.
482
def line(self, Y, X=None, win=None, env=None, opts=None, update=None, name=None): if update is not None: if update == "remove": return self.scatter( X=None, Y=None, opts=opts, win=win, env=env, update=update, name=name, ) else: assert X is not None, "must specify x-values for line update" assert Y.ndim == 1 or Y.ndim == 2, "Y should have 1 or 2 dim" assert Y.shape[-1] > 0, "must plot one line at least" if X is not None: assert X.ndim == 1 or X.ndim == 2, "X should have 1 or 2 dim" else: X = np.linspace(0, 1, Y.shape[0]) if Y.ndim == 2 and X.ndim == 1: X = np.tile(X, (Y.shape[1], 1)).transpose() assert X.shape == Y.shape, "X and Y should be the same shape" opts = {} if opts is None else opts opts["markers"] = opts.get("markers", False) opts["fillarea"] = opts.get("fillarea", False) opts["mode"] = "lines+markers" if opts.get("markers") else "lines" _title2str(opts) _assert_opts(opts) if Y.ndim == 1: linedata = np.column_stack((X, Y)) else: linedata = np.column_stack((X.ravel(order="F"), Y.ravel(order="F"))) labels = None if Y.ndim == 2: labels = np.arange(1, Y.shape[1] + 1) labels = np.tile(labels, (Y.shape[0], 1)).ravel(order="F") return self.scatter( X=linedata, Y=labels, opts=opts, win=win, env=env, update=update, name=name )
This function draws a line plot. It takes in an `N` or `NxM` tensor `Y` that specifies the values of the `M` lines (that connect `N` points) to plot. It also takes an optional `X` tensor that specifies the corresponding x-axis values; `X` can be an `N` tensor (in which case all lines will share the same x-axis values) or have the same size as `Y`. `update` can be used to efficiently update the data of an existing line. Use 'append' to append data, 'replace' to use new data, and 'remove' to delete the trace that is specified in `name`. If updating a single trace, use `name` to specify the name of the trace to be updated. Update data that is all NaN is ignored (can be used for masking update). Using `update='append'` will create a plot if it doesn't exist and append to the existing plot otherwise. The following `opts` are supported: - `opts.fillarea` : fill area below line (`boolean`) - `opts.markers` : show markers (`boolean`; default = `false`) - `opts.markersymbol`: marker symbol (`string`; default = `'dot'`) - `opts.markersize` : marker size (`number`; default = `'10'`) - `opts.linecolor` : line colors (`np.array`; default = None) - `opts.dash` : line dash type (`np.array`; default = None) - `opts.legend` : `list` or `tuple` containing legend names If `update` is specified, the figure will be updated without creating a new plot -- this can be used for efficient updating.
237
183
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def line(self, Y, X=None, win=None, env=None, opts=None, update=None, name=None): if update is not None: if update == "remove": return self.scatter( X=None, Y=None, opts=opts, win=win, env=env, update=update, name=name, ) else: assert X is not None, "must specify x-values for line update" assert Y.ndim == 1 or Y.ndim == 2, "Y should have 1 or 2 dim" assert Y.shape[-1] > 0, "must plot one line at least" if X is not None: assert X.ndim == 1 or X.ndim == 2, "X should have 1 or 2 dim" else: X = np.linspace(0, 1, Y.shape[0]) if Y.ndim == 2 and X.ndim == 1: X = np.tile(X, (Y.shape[1], 1)).transpose() assert X.shape == Y.shape, "X and Y should be the same shape" opts = {} if opts is None else opts opts["markers"] = opts.get("markers", False) opts["fillarea"] = opts.get("fillarea", False) opts["mode"] = "lines+markers" if opts.get("markers") else "lines" _title2str(opts) _assert_opts(opts) if Y.ndim == 1: linedata = np.column_stack((X, Y)) else: linedata = np.column_stack((X.ravel(order="F"), Y.ravel(order="F"))) labels = None if Y.ndim == 2: labels = np.arange(1, Y.shape[1] + 1) labels = np.tile(labels, (Y.shape[0], 1)).ravel(order="F") return self.scatter( X=linedata, Y=labels, opts=opts, win=win, env=env, update=update, name=name ) ``` ###Assistant : This function draws a line plot. It takes in an `N` or `NxM` tensor `Y` that specifies the values of the `M` lines (that connect `N` points) to plot. It also takes an optional `X` tensor that specifies the corresponding x-axis values; `X` can be an `N` tensor (in which case all lines will share the same x-axis values) or have the same size as `Y`. `update` can be used to efficiently update the data of an existing line. Use 'append' to append data, 'replace' to use new data, and 'remove' to delete the trace that is specified in `name`. If updating a single trace, use `name` to specify the name of the trace to be updated. Update data that is all NaN is ignored (can be used for masking update). Using `update='append'` will create a plot if it doesn't exist and append to the existing plot otherwise. The following `opts` are supported: - `opts.fillarea` : fill area below line (`boolean`) - `opts.markers` : show markers (`boolean`; default = `false`) - `opts.markersymbol`: marker symbol (`string`; default = `'dot'`) - `opts.markersize` : marker size (`number`; default = `'10'`) - `opts.linecolor` : line colors (`np.array`; default = None) - `opts.dash` : line dash type (`np.array`; default = None) - `opts.legend` : `list` or `tuple` containing legend names If `update` is specified, the figure will be updated without creating a new plot -- this can be used for efficient updating.
483
def test_delete_with_id(self, db_mock_class): op = DatabricksReposDeleteOperator(task_id=TASK_ID, repo_id="123") db_mock = db_mock_class.return_value db_mock.delete_repo.return_value = None op.execute(None) db_mock_class.assert_called_once_with( DEFAULT_CONN_ID, retry_limit=op.databricks_retry_limit, retry_delay=op.databricks_retry_delay ) db_mock.delete_repo.assert_called_once_with('123')
Test the execute function using Repo ID.
7
20
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_delete_with_id(self, db_mock_class): op = DatabricksReposDeleteOperator(task_id=TASK_ID, repo_id="123") db_mock = db_mock_class.return_value db_mock.delete_repo.return_value = None op.execute(None) db_mock_class.assert_called_once_with( DEFAULT_CONN_ID, retry_limit=op.databricks_retry_limit, retry_delay=op.databricks_retry_delay ) db_mock.delete_repo.assert_called_once_with('123') ``` ###Assistant : Test the execute function using Repo ID.
484
def test_user_rate_reached(self): for i in range(5): group = self.store_event( data={ "fingerprint": ["group1"], "timestamp": iso_format(before_now(minutes=5 + i)), "tags": {"sentry:user": i}, }, project_id=self.project.id, ).group snooze = GroupSnooze.objects.create(group=group, user_count=5, user_window=60) assert not snooze.is_valid(test_rates=True)
Test that ignoring an error issue until it's hit by 10 users in an hour works.
16
30
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_user_rate_reached(self): for i in range(5): group = self.store_event( data={ "fingerprint": ["group1"], "timestamp": iso_format(before_now(minutes=5 + i)), "tags": {"sentry:user": i}, }, project_id=self.project.id, ).group snooze = GroupSnooze.objects.create(group=group, user_count=5, user_window=60) assert not snooze.is_valid(test_rates=True) ``` ###Assistant : Test that ignoring an error issue until it's hit by 10 users in an hour works.
485
def make_zipfile(base_name, base_dir, verbose=0, dry_run=0): zip_filename = base_name + ".zip" mkpath(os.path.dirname(zip_filename), dry_run=dry_run) # If zipfile module is not available, try spawning an external # 'zip' command. if zipfile is None: if verbose: zipoptions = "-r" else: zipoptions = "-rq" try: spawn(["zip", zipoptions, zip_filename, base_dir], dry_run=dry_run) except DistutilsExecError: # XXX really should distinguish between "couldn't find # external 'zip' command" and "zip failed". raise DistutilsExecError(("unable to create zip file '%s': " "could neither import the 'zipfile' module nor " "find a standalone zip utility") % zip_filename) else: log.info("creating '%s' and adding '%s' to it", zip_filename, base_dir) if not dry_run: try: zip = zipfile.ZipFile(zip_filename, "w", compression=zipfile.ZIP_DEFLATED) except RuntimeError: zip = zipfile.ZipFile(zip_filename, "w", compression=zipfile.ZIP_STORED) with zip: if base_dir != os.curdir: path = os.path.normpath(os.path.join(base_dir, '')) zip.write(path, path) log.info("adding '%s'", path) for dirpath, dirnames, filenames in os.walk(base_dir): for name in dirnames: path = os.path.normpath(os.path.join(dirpath, name, '')) zip.write(path, path) log.info("adding '%s'", path) for name in filenames: path = os.path.normpath(os.path.join(dirpath, name)) if os.path.isfile(path): zip.write(path, path) log.info("adding '%s'", path) return zip_filename ARCHIVE_FORMATS = { 'gztar': (make_tarball, [('compress', 'gzip')], "gzip'ed tar-file"), 'bztar': (make_tarball, [('compress', 'bzip2')], "bzip2'ed tar-file"), 'xztar': (make_tarball, [('compress', 'xz')], "xz'ed tar-file"), 'ztar': (make_tarball, [('compress', 'compress')], "compressed tar file"), 'tar': (make_tarball, [('compress', None)], "uncompressed tar file"), 'zip': (make_zipfile, [],"ZIP file") }
Create a zip file from all the files under 'base_dir'. The output zip file will be named 'base_name' + ".zip". Uses either the "zipfile" Python module (if available) or the InfoZIP "zip" utility (if installed and found on the default search path). If neither tool is available, raises DistutilsExecError. Returns the name of the output zip file.
57
203
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def make_zipfile(base_name, base_dir, verbose=0, dry_run=0): zip_filename = base_name + ".zip" mkpath(os.path.dirname(zip_filename), dry_run=dry_run) # If zipfile module is not available, try spawning an external # 'zip' command. if zipfile is None: if verbose: zipoptions = "-r" else: zipoptions = "-rq" try: spawn(["zip", zipoptions, zip_filename, base_dir], dry_run=dry_run) except DistutilsExecError: # XXX really should distinguish between "couldn't find # external 'zip' command" and "zip failed". raise DistutilsExecError(("unable to create zip file '%s': " "could neither import the 'zipfile' module nor " "find a standalone zip utility") % zip_filename) else: log.info("creating '%s' and adding '%s' to it", zip_filename, base_dir) if not dry_run: try: zip = zipfile.ZipFile(zip_filename, "w", compression=zipfile.ZIP_DEFLATED) except RuntimeError: zip = zipfile.ZipFile(zip_filename, "w", compression=zipfile.ZIP_STORED) with zip: if base_dir != os.curdir: path = os.path.normpath(os.path.join(base_dir, '')) zip.write(path, path) log.info("adding '%s'", path) for dirpath, dirnames, filenames in os.walk(base_dir): for name in dirnames: path = os.path.normpath(os.path.join(dirpath, name, '')) zip.write(path, path) log.info("adding '%s'", path) for name in filenames: path = os.path.normpath(os.path.join(dirpath, name)) if os.path.isfile(path): zip.write(path, path) log.info("adding '%s'", path) return zip_filename ARCHIVE_FORMATS = { 'gztar': (make_tarball, [('compress', 'gzip')], "gzip'ed tar-file"), 'bztar': (make_tarball, [('compress', 'bzip2')], "bzip2'ed tar-file"), 'xztar': (make_tarball, [('compress', 'xz')], "xz'ed tar-file"), 'ztar': (make_tarball, [('compress', 'compress')], "compressed tar file"), 'tar': (make_tarball, [('compress', None)], "uncompressed tar file"), 'zip': (make_zipfile, [],"ZIP file") } ``` ###Assistant : Create a zip file from all the files under 'base_dir'. The output zip file will be named 'base_name' + ".zip". Uses either the "zipfile" Python module (if available) or the InfoZIP "zip" utility (if installed and found on the default search path). If neither tool is available, raises DistutilsExecError. Returns the name of the output zip file.
486
def test_power_levels_user_default(self): # The other user doesn't have the proper power level. channel = self._upgrade_room(self.other_token) self.assertEqual(403, channel.code, channel.result) # Increase the power levels so that this user can upgrade. power_levels = self.helper.get_state( self.room_id, "m.room.power_levels", tok=self.creator_token, ) power_levels["users_default"] = 100 self.helper.send_state( self.room_id, "m.room.power_levels", body=power_levels, tok=self.creator_token, ) # The upgrade should succeed! channel = self._upgrade_room(self.other_token) self.assertEqual(200, channel.code, channel.result)
Another user can upgrade the room if the default power level for users is increased.
15
56
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_power_levels_user_default(self): # The other user doesn't have the proper power level. channel = self._upgrade_room(self.other_token) self.assertEqual(403, channel.code, channel.result) # Increase the power levels so that this user can upgrade. power_levels = self.helper.get_state( self.room_id, "m.room.power_levels", tok=self.creator_token, ) power_levels["users_default"] = 100 self.helper.send_state( self.room_id, "m.room.power_levels", body=power_levels, tok=self.creator_token, ) # The upgrade should succeed! channel = self._upgrade_room(self.other_token) self.assertEqual(200, channel.code, channel.result) ``` ###Assistant : Another user can upgrade the room if the default power level for users is increased.
487
def get_exempt_total(filters): conditions = get_conditions(filters) try: return ( frappe.db.sql( .format( where_conditions=conditions ), filters, )[0][0] or 0 ) except (IndexError, TypeError): return 0
Returns the sum of each Sales Invoice Item Amount which is Vat Exempt. select sum(i.base_amount) as total from `tabSales Invoice Item` i inner join `tabSales Invoice` s on i.parent = s.name where s.docstatus = 1 and i.is_exempt = 1 {where_conditions} ;
41
22
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_exempt_total(filters): conditions = get_conditions(filters) try: return ( frappe.db.sql( .format( where_conditions=conditions ), filters, )[0][0] or 0 ) except (IndexError, TypeError): return 0 ``` ###Assistant : Returns the sum of each Sales Invoice Item Amount which is Vat Exempt. select sum(i.base_amount) as total from `tabSales Invoice Item` i inner join `tabSales Invoice` s on i.parent = s.name where s.docstatus = 1 and i.is_exempt = 1 {where_conditions} ;
488
def encrypt(self, key, text, confounder=None, key_usage_number=None): if key_usage_number is None: key_usage_number = self.get_usage()[0] self.cipher = key.encrypt(key_usage_number, text, confounder=confounder) EncryptionKey = lambda **kwargs: ASN1F_SEQUENCE( Int32("keytype", 0, explicit_tag=0x0), ASN1F_STRING("keyvalue", "", explicit_tag=0x1), **kwargs ) KerberosFlags = ASN1F_FLAGS _PADATA_TYPES = { 1: "PA-TGS-REQ", 2: "PA-ENC-TIMESTAMP", 3: "PA-PW-SALT", 11: "PA-ETYPE-INFO", 14: "PA-PK-AS-REQ-OLD", 15: "PA-PK-AS-REP-OLD", 16: "PA-PK-AS-REQ", 17: "PA-PK-AS-REP", 19: "PA-ETYPE-INFO2", 20: "PA-SVR-REFERRAL-INFO", 128: "PA-PAC-REQUEST", 133: "PA-FX-COOKIE", 134: "PA-AUTHENTICATION-SET", 135: "PA-AUTH-SET-SELECTED", 136: "PA-FX-FAST", 137: "PA-FX-ERROR", 165: "PA-SUPPORTED-ENCTYPES", 167: "PA-PAC-OPTIONS", } _PADATA_CLASSES = { # Filled elsewhere in this file } # RFC4120
Encrypt text and set it into cipher. :param key: the key to use for encryption :param text: the bytes value to encode :param confounder: (optional) specify the confounder bytes. Random otherwise :param key_usage_number: (optional) specify the key usage number. Guessed otherwise
41
86
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def encrypt(self, key, text, confounder=None, key_usage_number=None): if key_usage_number is None: key_usage_number = self.get_usage()[0] self.cipher = key.encrypt(key_usage_number, text, confounder=confounder) EncryptionKey = lambda **kwargs: ASN1F_SEQUENCE( Int32("keytype", 0, explicit_tag=0x0), ASN1F_STRING("keyvalue", "", explicit_tag=0x1), **kwargs ) KerberosFlags = ASN1F_FLAGS _PADATA_TYPES = { 1: "PA-TGS-REQ", 2: "PA-ENC-TIMESTAMP", 3: "PA-PW-SALT", 11: "PA-ETYPE-INFO", 14: "PA-PK-AS-REQ-OLD", 15: "PA-PK-AS-REP-OLD", 16: "PA-PK-AS-REQ", 17: "PA-PK-AS-REP", 19: "PA-ETYPE-INFO2", 20: "PA-SVR-REFERRAL-INFO", 128: "PA-PAC-REQUEST", 133: "PA-FX-COOKIE", 134: "PA-AUTHENTICATION-SET", 135: "PA-AUTH-SET-SELECTED", 136: "PA-FX-FAST", 137: "PA-FX-ERROR", 165: "PA-SUPPORTED-ENCTYPES", 167: "PA-PAC-OPTIONS", } _PADATA_CLASSES = { # Filled elsewhere in this file } # RFC4120 ``` ###Assistant : Encrypt text and set it into cipher. :param key: the key to use for encryption :param text: the bytes value to encode :param confounder: (optional) specify the confounder bytes. Random otherwise :param key_usage_number: (optional) specify the key usage number. Guessed otherwise
489
def create_v_switch(self, vpc_id, zone_id, cidr_block): request = CreateVSwitchRequest() request.set_ZoneId(zone_id) request.set_VpcId(vpc_id) request.set_CidrBlock(cidr_block) response = self._send_request(request) if response is not None: return response.get("VSwitchId") else: logging.error("create_v_switch vpc_id %s failed.", vpc_id) return None
Create vSwitches to divide the VPC into one or more subnets :param vpc_id: The ID of the VPC to which the VSwitch belongs. :param zone_id: The ID of the zone to which the target VSwitch belongs. :param cidr_block: The CIDR block of the VSwitch. :return:
45
29
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def create_v_switch(self, vpc_id, zone_id, cidr_block): request = CreateVSwitchRequest() request.set_ZoneId(zone_id) request.set_VpcId(vpc_id) request.set_CidrBlock(cidr_block) response = self._send_request(request) if response is not None: return response.get("VSwitchId") else: logging.error("create_v_switch vpc_id %s failed.", vpc_id) return None ``` ###Assistant : Create vSwitches to divide the VPC into one or more subnets :param vpc_id: The ID of the VPC to which the VSwitch belongs. :param zone_id: The ID of the zone to which the target VSwitch belongs. :param cidr_block: The CIDR block of the VSwitch. :return:
490
def transparent_background(self) -> bool: return self.bgcolor is None or self.bgcolor.is_default
Check if the style specified a transparent background.
8
10
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def transparent_background(self) -> bool: return self.bgcolor is None or self.bgcolor.is_default ``` ###Assistant : Check if the style specified a transparent background.
491
def isPerfectNumber(number): # precondition assert isinstance(number, int) and ( number > 1 ), "'number' must been an int and >= 1" divisors = getDivisors(number) # precondition assert ( isinstance(divisors, list) and (divisors[0] == 1) and (divisors[len(divisors) - 1] == number) ), "Error in help-function getDivisiors(...)" # summed all divisors up to 'number' (exclusive), hence [:-1] return sum(divisors[:-1]) == number # ------------------------------------------------------------
input: positive integer 'number' > 1 returns true if 'number' is a perfect number otherwise false.
16
61
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def isPerfectNumber(number): # precondition assert isinstance(number, int) and ( number > 1 ), "'number' must been an int and >= 1" divisors = getDivisors(number) # precondition assert ( isinstance(divisors, list) and (divisors[0] == 1) and (divisors[len(divisors) - 1] == number) ), "Error in help-function getDivisiors(...)" # summed all divisors up to 'number' (exclusive), hence [:-1] return sum(divisors[:-1]) == number # ------------------------------------------------------------ ``` ###Assistant : input: positive integer 'number' > 1 returns true if 'number' is a perfect number otherwise false.
492
def _get_cmap(name=None, lut=None): if name is None: name = mpl.rcParams['image.cmap'] if isinstance(name, colors.Colormap): return name _api.check_in_list(sorted(_colormaps), name=name) if lut is None: return _colormaps[name] else: return _colormaps[name].resampled(lut) # do it in two steps like this so we can have an un-deprecated version in # pyplot. get_cmap = _api.deprecated( '3.6', pending=True, alternative="``matplotlib.colormaps[name]``" )(_get_cmap) @_api.deprecated( '3.6', pending=True, alternative="``matplotlib.colormaps.unregister_cmap(name)``" )
Get a colormap instance, defaulting to rc values if *name* is None. Colormaps added with :func:`register_cmap` take precedence over built-in colormaps. Parameters ---------- name : `matplotlib.colors.Colormap` or str or None, default: None If a `.Colormap` instance, it will be returned. Otherwise, the name of a colormap known to Matplotlib, which will be resampled by *lut*. The default, None, means :rc:`image.cmap`. lut : int or None, default: None If *name* is not already a Colormap instance and *lut* is not None, the colormap will be resampled to have *lut* entries in the lookup table. Returns ------- Colormap
96
56
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _get_cmap(name=None, lut=None): if name is None: name = mpl.rcParams['image.cmap'] if isinstance(name, colors.Colormap): return name _api.check_in_list(sorted(_colormaps), name=name) if lut is None: return _colormaps[name] else: return _colormaps[name].resampled(lut) # do it in two steps like this so we can have an un-deprecated version in # pyplot. get_cmap = _api.deprecated( '3.6', pending=True, alternative="``matplotlib.colormaps[name]``" )(_get_cmap) @_api.deprecated( '3.6', pending=True, alternative="``matplotlib.colormaps.unregister_cmap(name)``" ) ``` ###Assistant : Get a colormap instance, defaulting to rc values if *name* is None. Colormaps added with :func:`register_cmap` take precedence over built-in colormaps. Parameters ---------- name : `matplotlib.colors.Colormap` or str or None, default: None If a `.Colormap` instance, it will be returned. Otherwise, the name of a colormap known to Matplotlib, which will be resampled by *lut*. The default, None, means :rc:`image.cmap`. lut : int or None, default: None If *name* is not already a Colormap instance and *lut* is not None, the colormap will be resampled to have *lut* entries in the lookup table. Returns ------- Colormap
493
def cancel(self): with self._condition: if self._state in [RUNNING, FINISHED]: return False if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]: return True self._state = CANCELLED self._condition.notify_all() self._invoke_callbacks() return True
Cancel the future if possible. Returns True if the future was cancelled, False otherwise. A future cannot be cancelled if it is running or has already completed.
27
25
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def cancel(self): with self._condition: if self._state in [RUNNING, FINISHED]: return False if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]: return True self._state = CANCELLED self._condition.notify_all() self._invoke_callbacks() return True ``` ###Assistant : Cancel the future if possible. Returns True if the future was cancelled, False otherwise. A future cannot be cancelled if it is running or has already completed.
494
def get_hub_metadata(url, token=None): if token is None: token = HfFolder.get_token() headers = {"user-agent": http_user_agent()} headers["authorization"] = f"Bearer {token}" r = huggingface_hub.file_download._request_with_retry( method="HEAD", url=url, headers=headers, allow_redirects=False ) huggingface_hub.file_download._raise_for_status(r) commit_hash = r.headers.get(HUGGINGFACE_HEADER_X_REPO_COMMIT) etag = r.headers.get(HUGGINGFACE_HEADER_X_LINKED_ETAG) or r.headers.get("ETag") if etag is not None: etag = huggingface_hub.file_download._normalize_etag(etag) return etag, commit_hash
Returns the commit hash and associated etag for a given url.
11
46
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_hub_metadata(url, token=None): if token is None: token = HfFolder.get_token() headers = {"user-agent": http_user_agent()} headers["authorization"] = f"Bearer {token}" r = huggingface_hub.file_download._request_with_retry( method="HEAD", url=url, headers=headers, allow_redirects=False ) huggingface_hub.file_download._raise_for_status(r) commit_hash = r.headers.get(HUGGINGFACE_HEADER_X_REPO_COMMIT) etag = r.headers.get(HUGGINGFACE_HEADER_X_LINKED_ETAG) or r.headers.get("ETag") if etag is not None: etag = huggingface_hub.file_download._normalize_etag(etag) return etag, commit_hash ``` ###Assistant : Returns the commit hash and associated etag for a given url.
495
def aug_test(self, aug_batch_feats, aug_batch_img_metas, rescale=False): return self.aug_test_bboxes( aug_batch_feats, aug_batch_img_metas, rescale=rescale)
Test function with test time augmentation. Args: aug_batch_feats (list[Tensor]): the outer list indicates test-time augmentations and inner Tensor should have a shape NxCxHxW, which contains features for all images in the batch. aug_batch_img_metas (list[list[dict]]): the outer list indicates test-time augs (multiscale, flip, etc.) and the inner list indicates images in a batch. each dict has image information. rescale (bool, optional): Whether to rescale the results. Defaults to False. Returns: list[ndarray]: bbox results of each class
75
10
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def aug_test(self, aug_batch_feats, aug_batch_img_metas, rescale=False): return self.aug_test_bboxes( aug_batch_feats, aug_batch_img_metas, rescale=rescale) ``` ###Assistant : Test function with test time augmentation. Args: aug_batch_feats (list[Tensor]): the outer list indicates test-time augmentations and inner Tensor should have a shape NxCxHxW, which contains features for all images in the batch. aug_batch_img_metas (list[list[dict]]): the outer list indicates test-time augs (multiscale, flip, etc.) and the inner list indicates images in a batch. each dict has image information. rescale (bool, optional): Whether to rescale the results. Defaults to False. Returns: list[ndarray]: bbox results of each class
496
def ensure_schema_for_first_block(self) -> Optional[Union["pyarrow.Schema", type]]: get_schema = cached_remote_fn(_get_schema) try: block = next(self.iter_blocks()) except (StopIteration, ValueError): # Dataset is empty (no blocks) or was manually cleared. return None schema = ray.get(get_schema.remote(block)) # Set the schema. self._metadata[0].schema = schema return schema
Ensure that the schema is set for the first block. Returns None if the block list is empty.
18
39
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def ensure_schema_for_first_block(self) -> Optional[Union["pyarrow.Schema", type]]: get_schema = cached_remote_fn(_get_schema) try: block = next(self.iter_blocks()) except (StopIteration, ValueError): # Dataset is empty (no blocks) or was manually cleared. return None schema = ray.get(get_schema.remote(block)) # Set the schema. self._metadata[0].schema = schema return schema ``` ###Assistant : Ensure that the schema is set for the first block. Returns None if the block list is empty.
497
def get_local_am_pm(): am_local = time(1).strftime("%p") pm_local = time(13).strftime("%p") return am_local, pm_local @pytest.fixture(params=["string", "pathlike", "buffer"])
Return the AM and PM strings returned by strftime in current locale.
12
14
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_local_am_pm(): am_local = time(1).strftime("%p") pm_local = time(13).strftime("%p") return am_local, pm_local @pytest.fixture(params=["string", "pathlike", "buffer"]) ``` ###Assistant : Return the AM and PM strings returned by strftime in current locale.
498
def validate_pages_layout(module, page): try: getattr(page, "layout") except AttributeError: raise exceptions.NoLayoutException( f )
No layout found in {module + ".py"} A variable or a function named "layout" is required.
16
12
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def validate_pages_layout(module, page): try: getattr(page, "layout") except AttributeError: raise exceptions.NoLayoutException( f ) ``` ###Assistant : No layout found in {module + ".py"} A variable or a function named "layout" is required.
499
def test_upscale_downscale_delay(): upscale_delay_s = 30.0 downscale_delay_s = 600.0 config = AutoscalingConfig( min_replicas=1, max_replicas=2, target_num_ongoing_requests_per_replica=1, upscale_delay_s=30.0, downscale_delay_s=600.0, ) policy = BasicAutoscalingPolicy(config) upscale_wait_periods = int(upscale_delay_s / CONTROL_LOOP_PERIOD_S) downscale_wait_periods = int(downscale_delay_s / CONTROL_LOOP_PERIOD_S) overload_requests = [100] # We should scale up only after enough consecutive scale-up decisions. for i in range(upscale_wait_periods): new_num_replicas = policy.get_decision_num_replicas( current_num_ongoing_requests=overload_requests, curr_target_num_replicas=1 ) assert new_num_replicas == 1, i new_num_replicas = policy.get_decision_num_replicas( current_num_ongoing_requests=overload_requests, curr_target_num_replicas=1 ) assert new_num_replicas == 2 no_requests = [0, 0] # We should scale down only after enough consecutive scale-down decisions. for i in range(downscale_wait_periods): new_num_replicas = policy.get_decision_num_replicas( current_num_ongoing_requests=no_requests, curr_target_num_replicas=2 ) assert new_num_replicas == 2, i new_num_replicas = policy.get_decision_num_replicas( current_num_ongoing_requests=no_requests, curr_target_num_replicas=2 ) assert new_num_replicas == 1 # Get some scale-up decisions, but not enough to trigger a scale up. for i in range(int(upscale_wait_periods / 2)): new_num_replicas = policy.get_decision_num_replicas( current_num_ongoing_requests=overload_requests, curr_target_num_replicas=1 ) assert new_num_replicas == 1, i # Interrupt with a scale-down decision. policy.get_decision_num_replicas( current_num_ongoing_requests=[0], curr_target_num_replicas=1 ) # The counter should be reset, so it should require `upscale_wait_periods` # more periods before we actually scale up. for i in range(upscale_wait_periods): new_num_replicas = policy.get_decision_num_replicas( current_num_ongoing_requests=overload_requests, curr_target_num_replicas=1 ) assert new_num_replicas == 1, i new_num_replicas = policy.get_decision_num_replicas( current_num_ongoing_requests=overload_requests, curr_target_num_replicas=1 ) assert new_num_replicas == 2 # Get some scale-down decisions, but not enough to trigger a scale down. for i in range(int(downscale_wait_periods / 2)): new_num_replicas = policy.get_decision_num_replicas( current_num_ongoing_requests=no_requests, curr_target_num_replicas=2 ) assert new_num_replicas == 2, i # Interrupt with a scale-up decision. policy.get_decision_num_replicas( current_num_ongoing_requests=[100, 100], curr_target_num_replicas=2 ) # The counter should be reset so it should require `downscale_wait_periods` # more periods before we actually scale down. for i in range(downscale_wait_periods): new_num_replicas = policy.get_decision_num_replicas( current_num_ongoing_requests=no_requests, curr_target_num_replicas=2 ) assert new_num_replicas == 2, i new_num_replicas = policy.get_decision_num_replicas( current_num_ongoing_requests=no_requests, curr_target_num_replicas=2 ) assert new_num_replicas == 1
Unit test for upscale_delay_s and downscale_delay_s.
6
278
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_upscale_downscale_delay(): upscale_delay_s = 30.0 downscale_delay_s = 600.0 config = AutoscalingConfig( min_replicas=1, max_replicas=2, target_num_ongoing_requests_per_replica=1, upscale_delay_s=30.0, downscale_delay_s=600.0, ) policy = BasicAutoscalingPolicy(config) upscale_wait_periods = int(upscale_delay_s / CONTROL_LOOP_PERIOD_S) downscale_wait_periods = int(downscale_delay_s / CONTROL_LOOP_PERIOD_S) overload_requests = [100] # We should scale up only after enough consecutive scale-up decisions. for i in range(upscale_wait_periods): new_num_replicas = policy.get_decision_num_replicas( current_num_ongoing_requests=overload_requests, curr_target_num_replicas=1 ) assert new_num_replicas == 1, i new_num_replicas = policy.get_decision_num_replicas( current_num_ongoing_requests=overload_requests, curr_target_num_replicas=1 ) assert new_num_replicas == 2 no_requests = [0, 0] # We should scale down only after enough consecutive scale-down decisions. for i in range(downscale_wait_periods): new_num_replicas = policy.get_decision_num_replicas( current_num_ongoing_requests=no_requests, curr_target_num_replicas=2 ) assert new_num_replicas == 2, i new_num_replicas = policy.get_decision_num_replicas( current_num_ongoing_requests=no_requests, curr_target_num_replicas=2 ) assert new_num_replicas == 1 # Get some scale-up decisions, but not enough to trigger a scale up. for i in range(int(upscale_wait_periods / 2)): new_num_replicas = policy.get_decision_num_replicas( current_num_ongoing_requests=overload_requests, curr_target_num_replicas=1 ) assert new_num_replicas == 1, i # Interrupt with a scale-down decision. policy.get_decision_num_replicas( current_num_ongoing_requests=[0], curr_target_num_replicas=1 ) # The counter should be reset, so it should require `upscale_wait_periods` # more periods before we actually scale up. for i in range(upscale_wait_periods): new_num_replicas = policy.get_decision_num_replicas( current_num_ongoing_requests=overload_requests, curr_target_num_replicas=1 ) assert new_num_replicas == 1, i new_num_replicas = policy.get_decision_num_replicas( current_num_ongoing_requests=overload_requests, curr_target_num_replicas=1 ) assert new_num_replicas == 2 # Get some scale-down decisions, but not enough to trigger a scale down. for i in range(int(downscale_wait_periods / 2)): new_num_replicas = policy.get_decision_num_replicas( current_num_ongoing_requests=no_requests, curr_target_num_replicas=2 ) assert new_num_replicas == 2, i # Interrupt with a scale-up decision. policy.get_decision_num_replicas( current_num_ongoing_requests=[100, 100], curr_target_num_replicas=2 ) # The counter should be reset so it should require `downscale_wait_periods` # more periods before we actually scale down. for i in range(downscale_wait_periods): new_num_replicas = policy.get_decision_num_replicas( current_num_ongoing_requests=no_requests, curr_target_num_replicas=2 ) assert new_num_replicas == 2, i new_num_replicas = policy.get_decision_num_replicas( current_num_ongoing_requests=no_requests, curr_target_num_replicas=2 ) assert new_num_replicas == 1 ``` ###Assistant : Unit test for upscale_delay_s and downscale_delay_s.