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 th...
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.shap...
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, ...
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 Tempo...
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_t...
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...
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', '') `...
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 # stretc...
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 C...
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 ...
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 # valida...
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 sati...
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 s...
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...
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...
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 dimensio...
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_alig...
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") ...
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 instan...
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=...
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: S...
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): ...
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["model...
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:...
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: # * objec...
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 impl...
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 t...
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 lo...
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:...
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] s...
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 R...
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...
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.l...
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 sym...
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() ...
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 hangi...
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 ['...
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_fa...
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, ...
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...
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_un...
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 ...
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()...
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", "befo...
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 " ...
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.jso...
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) se...
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 i...
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 ...
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": i...
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=...
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( , ...
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=pars...
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...
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: ...
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 =...
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", ...
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...
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("...
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, thi...
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...
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. ...
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...
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_ch...
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, ...
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.sh...
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 s...
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...
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 )(collecti...
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_m...
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: ...
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...
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_t...
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_lin...
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,...
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 ``pla...
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": ...
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_bo...
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] = [] f...
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. ...
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}, ...
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_retr...
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 ...
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.appe...
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_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, _ = ...
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: ...
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, '') = '' ...
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 w...
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.re...
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_...
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"}, ...
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', ...
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"...
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_m...
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+(...
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'...
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(...
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: ...
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...
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.appe...
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( ...
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 a...
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...
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 ...
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 "C...
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(elemen...
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 ...
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, wa...
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 sub...
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.Lay...
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 ``` ###Ass...
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 th...
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_tic...
[*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...
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...
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", ...
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( ...
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 inste...
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...
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): ...
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": "...
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( ...
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, ...
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", ...
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 ``` ###As...
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._s...
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 ...
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, h...
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__, ...
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') ...
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): ...
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 ...
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 ...
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 t...
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 ...
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', ...
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=...)`...
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 th...
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 ...
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...
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(inpu...
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 __...
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 ...
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 prom...
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 = sel...
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}', ...
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}_{pa...
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 n...
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...
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.B...
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`, ...
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.NEARE...
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...
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 functi...
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 ``` ###Assistan...
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" pathexecscr...
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, c...
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:...
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...
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, ...
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 ...
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.scatt...
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_CON...
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...
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}, }, ...
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"], ...
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 =...
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 DistutilsExecErr...
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...
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 = s...
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.assertEqu...
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...
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", ...
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. ...
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 = k...
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 res...
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) reques...
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 b...
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(d...
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(numb...
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].resamp...
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 returne...
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(s...
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() ...
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_...
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_redir...
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...
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[...
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) ...
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. ...
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.ite...
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...
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 ) ``` ...
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 = BasicA...
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, ta...