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
200
def hvac_modes(self) -> list[HVACMode]: hvac_state = HVAC_MODES_MAPPING[self._climate.get_hvac_state()] return [HVACMode.AUTO, hvac_state]
Return the list of available hvac operation modes. HEAT and COOL mode are exclusive. End user has to enable a mode manually within the Somfy application. So only one mode can be displayed. Auto mode is a scheduler.
38
10
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def hvac_modes(self) -> list[HVACMode]: hvac_state = HVAC_MODES_MAPPING[self._climate.get_hvac_state()] return [HVACMode.AUTO, hvac_state] ``` ###Assist...
201
def _assert_expected_task_states(self, dagrun, expected_states): tis = dagrun.get_task_instances() for ti in tis: try: expected_state = expected_states[ti.task_id] except KeyError: raise ValueError(f"Invalid task id {ti.task_id} found!") ...
Helper function that asserts `TaskInstances` of a given `task_id` are in a given state.
14
46
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _assert_expected_task_states(self, dagrun, expected_states): tis = dagrun.get_task_instances() for ti in tis: try: expected_state = ...
202
def set_customer_info(fieldname, customer, value=""): if fieldname == "loyalty_program": frappe.db.set_value("Customer", customer, "loyalty_program", value) contact = frappe.get_cached_value("Customer", customer, "customer_primary_contact") if not contact: contact = frappe.db.sql( , (customer), as_dict...
SELECT parent FROM `tabDynamic Link` WHERE parenttype = 'Contact' AND parentfield = 'links' AND link_doctype = 'Customer' AND link_name = %s
21
91
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def set_customer_info(fieldname, customer, value=""): if fieldname == "loyalty_program": frappe.db.set_value("Customer", customer, "loyalty_program", value) contact = frappe.get_cached_...
203
def test_unpublish_not_include_children_view_post(self): # Post to the unpublish page response = self.client.post( reverse("wagtailadmin_pages:unpublish", args=(self.test_page.id,)), {} ) # Should be redirected to explorer page self.assertRedirects( ...
This posts to the unpublish view and checks that the page was unpublished but its descendants were not
18
46
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_unpublish_not_include_children_view_post(self): # Post to the unpublish page response = self.client.post( reverse("wagtailadmin_pages:unpublish"...
204
def _get_data_from_filepath(self, filepath_or_buffer): # if it is a string but the file does not exist, it might be a JSON string filepath_or_buffer = stringify_path(filepath_or_buffer) if ( not isinstance(filepath_or_buffer, str) or is_url(filepath_or_buffer) ...
The function read_json accepts three input types: 1. filepath (string-like) 2. file-like object (e.g. open file object, StringIO) 3. JSON string This method turns (1) into (2) to simplify the rest of the processing. It returns input types (2) and (3) unchang...
64
75
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _get_data_from_filepath(self, filepath_or_buffer): # if it is a string but the file does not exist, it might be a JSON string filepath_or_buffer = stringify_path...
205
def _run_pip(args, additional_paths=None): # Run the bootstraping in a subprocess to avoid leaking any state that happens # after pip has executed. Particulary, this avoids the case when pip holds onto # the files in *additional_paths*, preventing us to remove them at the end of the # invocation. co...
import runpy import sys sys.path = {additional_paths or []} + sys.path sys.argv[1:] = {args} runpy.run_module("pip", run_name="__main__", alter_sys=True)
17
58
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _run_pip(args, additional_paths=None): # Run the bootstraping in a subprocess to avoid leaking any state that happens # after pip has executed. Particulary, this avoids the case ...
206
def test_pprint_heap_allocated_type(): module_name = "xxlimited" if sys.version_info < (3, 10) else "xxlimited_35" expected_output = ( "xxlimited.Null" if sys.version_info < (3, 11) else "xxlimited_35.Null" ) xxlimited = pytest.importorskip(module_name) output = pretty.pretty(xxlimited....
Test that pprint works for heap allocated types.
8
34
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_pprint_heap_allocated_type(): module_name = "xxlimited" if sys.version_info < (3, 10) else "xxlimited_35" expected_output = ( "xxlimited.Null" if sys.version_in...
207
def test_orderby_percentile_with_many_fields_transactions_unsupported_fields(self): response = self.get_response( self.organization.slug, field=[ "p50(sentry.transactions.measurements.lcp)", "sum(user_misery)", ], statsPeri...
Test that contains a field in the `select` that is performance related but currently not supported should return a 400
20
37
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_orderby_percentile_with_many_fields_transactions_unsupported_fields(self): response = self.get_response( self.organization.slug, field=[ ...
208
def generate_dependency_map(integration_targets): # type: (t.List[IntegrationTarget]) -> t.Dict[str, t.Set[IntegrationTarget]] targets_dict = dict((target.name, target) for target in integration_targets) target_dependencies = analyze_integration_target_dependencies(integration_targets) dependency_map ...
Analyze the given list of integration test targets and return a dictionary expressing target names and the targets on which they depend.
22
67
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def generate_dependency_map(integration_targets): # type: (t.List[IntegrationTarget]) -> t.Dict[str, t.Set[IntegrationTarget]] targets_dict = dict((target.name, target) for target ...
209
def text(self) -> str: if self.error is None: return str(self) return self.error.databaseText()
Get a short text description of the error. This is a string suitable to show to the user as error message.
21
12
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def text(self) -> str: if self.error is None: return str(self) return self.error.databaseText() ``` ###Assistant : Get a short text descrip...
210
def test_recover_start_from_replica_actor_names(serve_instance): # Test failed to deploy with total of 2 replicas, # but first constructor call fails.
Test controller is able to recover starting -> running replicas from actor names.
13
18
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_recover_start_from_replica_actor_names(serve_instance): # Test failed to deploy with total of 2 replicas, # but first constructor call fails. ``` ###Assista...
211
def associated_entities(self) -> list[dict[str, Any]]: ha_entity_registry = self.device.gateway.ha_entity_registry zha_device_registry = self.device.gateway.device_registry return [ GroupEntityReference( ha_entity_registry.async_get(entity_ref.reference_id).n...
Return the list of entities that were derived from this endpoint.
11
29
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def associated_entities(self) -> list[dict[str, Any]]: ha_entity_registry = self.device.gateway.ha_entity_registry zha_device_registry = self.device.gateway.device_r...
212
def getheader(self, name, default=None): if self.headers is None: raise ResponseNotReady() headers = self.headers.get_all(name) or default if isinstance(headers, str) or not hasattr(headers, '__iter__'): return headers else: return ', '.join(h...
Returns the value of the header matching *name*. If there are multiple matching headers, the values are combined into a single string separated by commas and spaces. If no matching header is found, returns *default* or None if the *default* is not specified. If the headers are...
50
28
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def getheader(self, name, default=None): if self.headers is None: raise ResponseNotReady() headers = self.headers.get_all(name) or default if isi...
213
def test_generate_pipeline_code_2(): pipeline = [ 'KNeighborsClassifier', [ 'CombineDFs', [ 'GradientBoostingClassifier', 'input_matrix', 38.0, 5, 5, 5, 0.05,...
Assert that generate_pipeline_code() returns the correct code given a specific pipeline with two CombineDFs.make_pipeline( make_union( StackingEstimator(estimator=GradientBoostingClassifier(learning_rate=38.0, max_depth=5, max_features=5, min_samples_leaf=5, min_samples_split=0.05, n_estimators=0.5)), ...
33
42
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_generate_pipeline_code_2(): pipeline = [ 'KNeighborsClassifier', [ 'CombineDFs', [ 'GradientBoostingClassifier', ...
214
def _script_names(dist, script_name, is_gui): # type: (Distribution, str, bool) -> List[str] if dist_in_usersite(dist): bin_dir = get_bin_user() else: bin_dir = get_bin_prefix() exe_name = os.path.join(bin_dir, script_name) paths_to_remove = [exe_name] if WINDOWS: pa...
Create the fully qualified name of the files created by {console,gui}_scripts for the given ``dist``. Returns the list of file names
21
46
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _script_names(dist, script_name, is_gui): # type: (Distribution, str, bool) -> List[str] if dist_in_usersite(dist): bin_dir = get_bin_user() else: bin_di...
215
def bbox_center(boxes): boxes_cx = (boxes[..., 0] + boxes[..., 2]) / 2 boxes_cy = (boxes[..., 1] + boxes[..., 3]) / 2 return paddle.stack([boxes_cx, boxes_cy], axis=-1)
Get bbox centers from boxes. Args: boxes (Tensor): boxes with shape (..., 4), "xmin, ymin, xmax, ymax" format. Returns: Tensor: boxes centers with shape (..., 2), "cx, cy" format.
29
24
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def bbox_center(boxes): boxes_cx = (boxes[..., 0] + boxes[..., 2]) / 2 boxes_cy = (boxes[..., 1] + boxes[..., 3]) / 2 return paddle.stack([boxes_cx, boxes_cy], axis=-1) ...
216
def predict(self, input): input_names = self.predictor.get_input_names() input_tensor = self.predictor.get_input_handle(input_names[0]) output_names = self.predictor.get_output_names() output_tensor = self.predictor.get_output_handle(output_names[0]) # preprocess ...
Args: input (str) or (list): video file path or image data list Returns: results (dict):
15
58
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def predict(self, input): input_names = self.predictor.get_input_names() input_tensor = self.predictor.get_input_handle(input_names[0]) output_names = self...
217
def deep_deconstruct(self, obj): if isinstance(obj, list): return [self.deep_deconstruct(value) for value in obj] elif isinstance(obj, tuple): return tuple(self.deep_deconstruct(value) for value in obj) elif isinstance(obj, dict): return {key: self.de...
Recursive deconstruction for a field and its arguments. Used for full comparison for rename/alter; sometimes a single-level deconstruction will not compare correctly.
22
121
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def deep_deconstruct(self, obj): if isinstance(obj, list): return [self.deep_deconstruct(value) for value in obj] elif isinstance(obj, tuple): ...
218
def test_cancellation(self): deferred: "Deferred[str]" = Deferred() wrapper_deferred = stop_cancellation(deferred) # Cancel the new `Deferred`. wrapper_deferred.cancel() self.assertTrue(wrapper_deferred.called) self.failureResultOf(wrapper_deferred, CancelledErr...
Test that cancellation of the new `Deferred` leaves the original running.
11
54
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_cancellation(self): deferred: "Deferred[str]" = Deferred() wrapper_deferred = stop_cancellation(deferred) # Cancel the new `Deferred`. wrap...
219
def getgeneratorlocals(generator): if not isgenerator(generator): raise TypeError("{!r} is not a Python generator".format(generator)) frame = getattr(generator, "gi_frame", None) if frame is not None: return generator.gi_frame.f_locals else: return {} # -----------------...
Get the mapping of generator local variables to their current values. A dict is returned, with the keys the local variable names and values the bound values.
27
43
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def getgeneratorlocals(generator): if not isgenerator(generator): raise TypeError("{!r} is not a Python generator".format(generator)) frame = getattr(generator, "gi_fr...
220
async def test_last_bin_contains_end_date(client, route): response = await client.post( f"/{route}/history", json=dict( history_start=str(dt), history_end=str(dt.add(days=1, minutes=30)), history_interval_seconds=timedelta(days=1).total_seconds(), ), ...
The last bin contains the end date, so its own end could be after the history end
17
44
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python async def test_last_bin_contains_end_date(client, route): response = await client.post( f"/{route}/history", json=dict( history_start=str(dt), ...
221
def _validate_attributes(self): # Run config if not isinstance(self.run_config, RunConfig): raise ValueError( f"`run_config` should be an instance of `ray.air.RunConfig`, " f"found {type(self.run_config)} with value `{self.run_config}`." )...
Called on __init()__ to validate trainer attributes.
7
168
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _validate_attributes(self): # Run config if not isinstance(self.run_config, RunConfig): raise ValueError( f"`run_config` should be an...
222
def longitude(self) -> float | None: if ( self.extra_state_attributes is not None and ATTR_LONGITUDE in self.extra_state_attributes ): longitude: float = self.extra_state_attributes[ATTR_LONGITUDE] return longitude return None
Return longitude if provided in extra_state_attributes or None.
8
25
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def longitude(self) -> float | None: if ( self.extra_state_attributes is not None and ATTR_LONGITUDE in self.extra_state_attributes ): ...
223
def user_cache_dir(self) -> str: path = os.path.normpath(get_win_folder("CSIDL_LOCAL_APPDATA")) return self._append_parts(path, opinion_value="Cache")
:return: cache directory tied to the user (if opinionated with ``Cache`` folder within ``$appname``) e.g. ``%USERPROFILE%\\AppData\\Local\\$appauthor\\$appname\\Cache\\$version``
16
10
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def user_cache_dir(self) -> str: path = os.path.normpath(get_win_folder("CSIDL_LOCAL_APPDATA")) return self._append_parts(path, opinion_value="Cache") ``` ...
224
def get_project_config(project, full_config=True, project_keys=None): with sentry_sdk.push_scope() as scope: scope.set_tag("project", project.id) with metrics.timer("relay.config.get_project_config.duration"): return _get_project_config(project, full_config=full_config, project_keys...
Constructs the ProjectConfig information. :param project: The project to load configuration for. Ensure that organization is bound on this object; otherwise it will be loaded from the database. :param full_config: True if only the full config is required, False if only the restricted (fo...
97
16
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_project_config(project, full_config=True, project_keys=None): with sentry_sdk.push_scope() as scope: scope.set_tag("project", project.id) with metrics.timer(...
225
def _query_kg(self, sparql_query): try: response = self.knowledge_graph.query(sparql_query=sparql_query) # unpack different answer styles if isinstance(response, list): if len(response) == 0: result = "" else: ...
Execute a single SPARQL query on the knowledge graph to retrieve an answer and unpack different answer styles for boolean queries, count queries, and list queries. :param sparql_query: SPARQL query that shall be executed on the knowledge graph
38
61
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _query_kg(self, sparql_query): try: response = self.knowledge_graph.query(sparql_query=sparql_query) # unpack different answer styles ...
226
def _path_importer_cache(cls, path): if path == '': try: path = _os.getcwd() except FileNotFoundError: # Don't cache the failure as the cwd can easily change to # a valid directory later on. return None try:...
Get the finder for the path entry from sys.path_importer_cache. If the path entry is not in the cache, find the appropriate finder and cache it. If no finder is available, store None.
32
47
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _path_importer_cache(cls, path): if path == '': try: path = _os.getcwd() except FileNotFoundError: # Don't cache ...
227
def test_publish_parts(self): import docutils self.assertNotEqual( docutils.parsers.rst.roles.DEFAULT_INTERPRETED_ROLE, "cmsreference" ) source = "reST, `interpreted text`, default role." markup = "<p>reST, <cite>interpreted text</cite>, default role.</p>\n"...
Django shouldn't break the default role for interpreted text when ``publish_parts`` is used directly, by setting it to ``cmsreference`` (#6681).
20
28
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_publish_parts(self): import docutils self.assertNotEqual( docutils.parsers.rst.roles.DEFAULT_INTERPRETED_ROLE, "cmsreference" ) ...
228
def test_get_backfill_points_in_room(self): setup_info = self._setup_room_for_backfill_tests() room_id = setup_info.room_id depth_map = setup_info.depth_map # Try at "B" backfill_points = self.get_success( self.store.get_backfill_points_in_room(room_id, dept...
Test to make sure only backfill points that are older and come before the `current_depth` are returned.
17
88
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_get_backfill_points_in_room(self): setup_info = self._setup_room_for_backfill_tests() room_id = setup_info.room_id depth_map = setup_info.depth_map ...
229
def theano_code(expr, cache=None, **kwargs): sympy_deprecation_warning( , deprecated_since_version="1.8", active_deprecations_target='theanocode-deprecated') if not theano: raise ImportError("theano is required for theano_code") if cache is None: cache = global_cac...
Convert a SymPy expression into a Theano graph variable. .. deprecated:: 1.8 ``sympy.printing.theanocode`` is deprecated. Theano has been renamed to Aesara. Use ``sympy.printing.aesaracode`` instead. See :ref:`theanocode-deprecated` for more information. Parameters ========== ...
94
28
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def theano_code(expr, cache=None, **kwargs): sympy_deprecation_warning( , deprecated_since_version="1.8", active_deprecations_target='theanocode-deprecated') ...
230
def _validate_axes_lengths(self): if self._row_lengths_cache is not None and len(self.index) > 0: # An empty frame can have 0 rows but a nonempty index. If the frame # does have rows, the number of rows must equal the size of the # index. num_rows = sum(s...
Validate that labels are split correctly if split is known.
10
147
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _validate_axes_lengths(self): if self._row_lengths_cache is not None and len(self.index) > 0: # An empty frame can have 0 rows but a nonempty index. If the f...
231
def test_get_name_capability_sid(): cap_sid = "S-1-15-3-1024-1065365936-1281604716-3511738428-1654721687-432734479-3232135806-4053264122-3456934681" sid_obj = win32security.ConvertStringSidToSid(cap_sid) assert salt.utils.win_dacl.get_name(sid_obj) is None
Test get_name with a compatibility SID. Should return `None` as we want to ignore these SIDs
16
12
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_get_name_capability_sid(): cap_sid = "S-1-15-3-1024-1065365936-1281604716-3511738428-1654721687-432734479-3232135806-4053264122-3456934681" sid_obj = win32security.Conv...
232
def entry_points(group=None): eps = importlib.metadata.entry_points() if group: try: return eps.select(group=group) except AttributeError: return eps.get(group, []) return eps
Returns an iterable of entrypoints. For compatibility with Python 3.8/3.9. In 3.10 the return type changed from a dict to an ``importlib.metadata.EntryPoints``. This compatibility utility can be removed once Python 3.10 is the minimum.
34
17
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def entry_points(group=None): eps = importlib.metadata.entry_points() if group: try: return eps.select(group=group) except AttributeError: ...
233
def elliptic_curve(self) -> Optional[str]: key = self._private_key() if isinstance(key, EllipticCurvePrivateKey): return key.curve.name return None
:returns: If the private key is an elliptic key, the name of its curve. :rtype: str
16
14
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def elliptic_curve(self) -> Optional[str]: key = self._private_key() if isinstance(key, EllipticCurvePrivateKey): return key.curve.name return No...
234
def page_type_display_name(self): if not self.specific_class or self.is_root(): return "" else: return self.specific_class.get_verbose_name()
A human-readable version of this page's type
7
12
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def page_type_display_name(self): if not self.specific_class or self.is_root(): return "" else: return self.specific_class.get_verbose_name()...
235
def save(self, fname, **kwargs) -> Plot: # TODO expose important keyword arugments in our signature? self.plot().save(fname, **kwargs) return self
Render the plot and write it to a buffer or file on disk. Parameters ---------- fname : str, path, or buffer Location on disk to save the figure, or a buffer to write into. Other keyword arguments are passed to :meth:`matplotlib.figure.Figure.savefig`.
41
19
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def save(self, fname, **kwargs) -> Plot: # TODO expose important keyword arugments in our signature? self.plot().save(fname, **kwargs) return self `...
236
def get_install_candidate(self, link_evaluator, link): # type: (LinkEvaluator, Link) -> Optional[InstallationCandidate] is_candidate, result = link_evaluator.evaluate_link(link) if not is_candidate: if result: self._log_skipped_link(link, reason=result) ...
If the link is a candidate for install, convert it to an InstallationCandidate and return it. Otherwise, return None.
19
29
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_install_candidate(self, link_evaluator, link): # type: (LinkEvaluator, Link) -> Optional[InstallationCandidate] is_candidate, result = link_evaluator.evaluat...
237
def bar(self, x=None, y=None, **kwargs) -> PlotAccessor: return self(kind="bar", x=x, y=y, **kwargs)
Vertical bar plot. A bar plot is a plot that presents categorical data with rectangular bars with lengths proportional to the values that they represent. A bar plot shows comparisons among discrete categories. One axis of the plot shows the specific categories being compared, a...
52
12
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def bar(self, x=None, y=None, **kwargs) -> PlotAccessor: return self(kind="bar", x=x, y=y, **kwargs) ``` ###Assistant : Vertical bar plot. A b...
238
def ctc_decode(y_pred, input_length, greedy=True, beam_width=100, top_paths=1): input_shape = shape(y_pred) num_samples, num_steps = input_shape[0], input_shape[1] y_pred = tf.math.log( tf.compat.v1.transpose(y_pred, perm=[1, 0, 2]) + epsilon() ) input_length = tf.cast(input_length, tf....
Decodes the output of a softmax. Can use either greedy search (also known as best path) or a constrained dictionary search. Args: y_pred: tensor `(samples, time_steps, num_categories)` containing the prediction, or output of the softmax. input_length: tensor `(samples, )` conta...
149
71
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def ctc_decode(y_pred, input_length, greedy=True, beam_width=100, top_paths=1): input_shape = shape(y_pred) num_samples, num_steps = input_shape[0], input_shape[1] y_pred = ...
239
def display_time_updates(bar): threading.Thread(target=_show_time_updates, args=(bar,)).start()
Start displaying the progress `bar` in a notebook. Parameters ---------- bar : tqdm.tqdm The progress bar wrapper to display in a notebook cell.
23
4
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def display_time_updates(bar): threading.Thread(target=_show_time_updates, args=(bar,)).start() ``` ###Assistant : Start displaying the progress `bar` in a notebo...
240
def remove(name=None, pkgs=None, **kwargs): targets = salt.utils.args.split_input(pkgs) if pkgs else [name] if not targets: return {} if pkgs: log.debug("Removing these fileset(s)/rpm package(s) %s: %s", name, targets) errors = [] # Get a list of the currently installed pkgs....
Remove specified fileset(s)/rpm package(s). name The name of the fileset or rpm package to be deleted. .. versionadded:: 3005 preference to install rpm packages are to use in the following order: /opt/freeware/bin/dnf /opt/freeware/bin/yum /usr/bin/yum...
101
157
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def remove(name=None, pkgs=None, **kwargs): targets = salt.utils.args.split_input(pkgs) if pkgs else [name] if not targets: return {} if pkgs: log.debug("Re...
241
def _from_ordinalf(x, tz=None): tz = _get_tzinfo(tz) dt = (np.datetime64(get_epoch()) + np.timedelta64(int(np.round(x * MUSECONDS_PER_DAY)), 'us')) if dt < np.datetime64('0001-01-01') or dt >= np.datetime64('10000-01-01'): raise ValueError(f'Date ordinal {x} converts to {dt} (using ...
Convert Gregorian float of the date, preserving hours, minutes, seconds and microseconds. Return value is a `.datetime`. The input date *x* is a float in ordinal days at UTC, and the output will be the specified `.datetime` object corresponding to that time in timezone *tz*, or if *tz* is ``None`...
56
156
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _from_ordinalf(x, tz=None): tz = _get_tzinfo(tz) dt = (np.datetime64(get_epoch()) + np.timedelta64(int(np.round(x * MUSECONDS_PER_DAY)), 'us')) if dt < np.da...
242
def getdoc(object): try: doc = object.__doc__ except AttributeError: return None if doc is None: try: doc = _finddoc(object) except (AttributeError, TypeError): return None if not isinstance(doc, str): return None return cleandoc(d...
Get the documentation string for an object. All tabs are expanded to spaces. To clean up docstrings that are indented to line up with blocks of code, any whitespace than can be uniformly removed from the second line onwards is removed.
41
31
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def getdoc(object): try: doc = object.__doc__ except AttributeError: return None if doc is None: try: doc = _finddoc(object) exce...
243
def load_config_with_kwargs(cls, kwargs): assert_is_a_marshmallow_class(cls) schema = cls.Schema() fields = schema.fields.keys() return load_config(cls, **{k: v for k, v in kwargs.items() if k in fields}), { k: v for k, v in kwargs.items() if k not in fields }
Takes a marshmallow class and dict of parameter values and appropriately instantiantes the schema.
14
37
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def load_config_with_kwargs(cls, kwargs): assert_is_a_marshmallow_class(cls) schema = cls.Schema() fields = schema.fields.keys() return load_config(cls, **{k: v for k, v...
244
def test_payment_refund_or_void_refund_called_txn_exist(refund_mock, payment): # given payment.charge_status = ChargeStatus.FULLY_CHARGED payment.save(update_fields=["charge_status"]) assert payment.can_refund() is True payment.captured_amount = payment.total payment.save(update_fields=["ca...
Ensure that the refund method is called when the refund process is already ongoing but not covered full payment captured amount.
21
43
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_payment_refund_or_void_refund_called_txn_exist(refund_mock, payment): # given payment.charge_status = ChargeStatus.FULLY_CHARGED payment.save(update_fields=["charge...
245
def _all(self): groups = super(Deprecated, self).values() return EntryPoints(itertools.chain.from_iterable(groups))
Reconstruct a list of all entrypoints from the groups.
9
8
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _all(self): groups = super(Deprecated, self).values() return EntryPoints(itertools.chain.from_iterable(groups)) ``` ###Assistant : Reconstr...
246
def readlines(self, sizehint=None, keepends=True): data = self.read() return data.splitlines(keepends)
Read all lines available on the input stream and return them as a list. Line breaks are implemented using the codec's decoder method and are included in the list entries. sizehint, if given, is ignored since there is no efficient way to finding the true end...
46
9
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def readlines(self, sizehint=None, keepends=True): data = self.read() return data.splitlines(keepends) ``` ###Assistant : Read all lines available on ...
247
async def notify_clients(cls) -> None: while not cls.STOP: await asyncio.sleep(cls.UPDATE_INTERVALS) if cls.EVENT_QUEUE: await cls.broadcast_estimations()
Notify clients about events statuses in the queue periodically.
9
14
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python async def notify_clients(cls) -> None: while not cls.STOP: await asyncio.sleep(cls.UPDATE_INTERVALS) if cls.EVENT_QUEUE: await cls.br...
248
def _readPyPIFile(self): # Complex stuff, pylint: disable=too-many-branches,too-many-statements if self.used_modules is None: pyi_filename = self.getPyIFilename() if os.path.exists(pyi_filename): pyi_deps = OrderedSet() # Flag signallin...
Read the .pyi file if present and scan for dependencies.
10
244
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _readPyPIFile(self): # Complex stuff, pylint: disable=too-many-branches,too-many-statements if self.used_modules is None: pyi_filename = self.getPyI...
249
def topological_sort(self): result = [] # Make a shallow copy of the adjacency list alist = {} for k, v in self.adjacency_list.items(): alist[k] = v[:] while True: # See what we can remove in this run to_remove = [] for k, ...
Perform a topological sort of the graph. :return: A tuple, the first element of which is a topologically sorted list of distributions, and the second element of which is a list of distributions that cannot be sorted because they have circular dependenc...
47
108
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def topological_sort(self): result = [] # Make a shallow copy of the adjacency list alist = {} for k, v in self.adjacency_list.items(): a...
250
def soft_reset(self) -> None: self.length = 0 self.episode_id = random.randrange(int(2e9)) self.total_reward = 0.0 self.agent_rewards = defaultdict(float) self._agent_reward_history = defaultdict(list)
Clears rewards and metrics, but retains RNN and other state. This is used to carry state across multiple logical episodes in the same env (i.e., if `soft_horizon` is set).
29
19
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def soft_reset(self) -> None: self.length = 0 self.episode_id = random.randrange(int(2e9)) self.total_reward = 0.0 self.agent_rewards = defaultdict(f...
251
def get_ordering_field(self, field_name): try: field = self.opts.get_field(field_name) return field.name except FieldDoesNotExist: # See whether field_name is a name of a non-field # that allows sorting. if callable(field_name): ...
Returns the proper model field name corresponding to the given field_name to use for ordering. field_name may either be the name of a proper model field or the name of a method (on the admin or model) or a callable with the 'admin_order_field' attribute. Returns None if no prope...
55
46
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_ordering_field(self, field_name): try: field = self.opts.get_field(field_name) return field.name except FieldDoesNotExist: ...
252
def _check_ordering(self, obj): # ordering = None if obj.ordering is None: # The default value is None return [] elif not isinstance(obj.ordering, (list, tuple)): return must_be( "a list or tuple", option="ordering", obj=obj, id="admin.E031" ...
Check that ordering refers to existing fields or is random.
10
50
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _check_ordering(self, obj): # ordering = None if obj.ordering is None: # The default value is None return [] elif not isinstance(obj.orderi...
253
def parsing_hooks(cls) -> Tuple[Type["Block"], Type["Sentence"], Type["Statements"]]: return Block, Sentence, Statements
Returns object types that this class should be able to `parse` recusrively. The order of the objects indicates the order in which the parser should try to parse each subitem. :returns: A list of Parsable classes. :rtype list:
38
10
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def parsing_hooks(cls) -> Tuple[Type["Block"], Type["Sentence"], Type["Statements"]]: return Block, Sentence, Statements ``` ###Assistant : Returns object types...
254
def _cast_inplace(terms, acceptable_dtypes, dtype) -> None: dt = np.dtype(dtype) for term in terms: if term.type in acceptable_dtypes: continue try: new_value = term.value.astype(dt) except AttributeError: new_value = dt.type(term.value) ...
Cast an expression inplace. Parameters ---------- terms : Op The expression that should cast. acceptable_dtypes : list of acceptable numpy.dtype Will not cast if term's dtype in this list. dtype : str or numpy.dtype The dtype to cast to.
39
28
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _cast_inplace(terms, acceptable_dtypes, dtype) -> None: dt = np.dtype(dtype) for term in terms: if term.type in acceptable_dtypes: continue try:...
255
def _deployment_created(self, external_id, request): payload = request.data["payload"] vercel_project_id = ( payload["projectId"] if payload.get("projectId") else payload["project"]["id"] ) # Only create releases for production deploys for now if payload["target"] != ...
Steps: 1. Find all org integrations that match the external id 2. Search the configs to find one that matches the vercel project of the webhook 3. Look up the Sentry project that matches 4. Look up the connected internal integration 5. Find the token ...
77
360
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _deployment_created(self, external_id, request): payload = request.data["payload"] vercel_project_id = ( payload["projectId"] if payload.get("projectId") else...
256
def _app_user(self) -> User | None: return self.user if isinstance(self.user, User) else None
The user, if they are represented persistently in our app.
10
13
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _app_user(self) -> User | None: return self.user if isinstance(self.user, User) else None ``` ###Assistant : The user, if they are represented persistently ...
257
def new_locator(self, nx, nx1=None): return AxesLocator(self, nx, 0, nx1 if nx1 is not None else nx + 1, 1)
Create a new `.AxesLocator` for the specified cell. Parameters ---------- nx, nx1 : int Integers specifying the column-position of the cell. When *nx1* is None, a single *nx*-th column is specified. Otherwise, location of columns spanning between *nx...
46
19
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def new_locator(self, nx, nx1=None): return AxesLocator(self, nx, 0, nx1 if nx1 is not None else nx + 1, 1) ``` ###Assistant : Create a new `.AxesLocat...
258
def test_edit_cases(self) -> None: self.login("hamlet") hamlet = self.example_user("hamlet") msg_id = self.send_stream_message( self.example_user("hamlet"), "Denmark", topic_name="topic 1", content="content 1" ) result = self.client_patch( f"/json...
This test verifies the accuracy of construction of Zulip's edit history data structures.
13
310
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_edit_cases(self) -> None: self.login("hamlet") hamlet = self.example_user("hamlet") msg_id = self.send_stream_message( self.example_user...
259
def get_project_name(doctype, txt, searchfield, start, page_len, filters): doctype = "Project" cond = "" if filters and filters.get("customer"): cond = % ( frappe.db.escape(filters.get("customer")) ) fields = get_fields(doctype, ["name", "project_name"]) searchfields = frappe.get_meta(doctype).get_search_...
(`tabProject`.customer = %s or ifnull(`tabProject`.customer,"")="") andselect {fields} from `tabProject` where `tabProject`.status not in ('Completed', 'Cancelled') and {cond} {scond} {match_cond} order by (case when locate(%(_txt)s, `tabProject`.name) > 0 then locate(%(_txt)s, `tabProject`.name) else 9...
41
69
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_project_name(doctype, txt, searchfield, start, page_len, filters): doctype = "Project" cond = "" if filters and filters.get("customer"): cond = % ( frappe.db.escape(filters....
260
def test_autosuggest_at_EOL(text, cursor, suggestion, called): event = make_event(text, cursor, suggestion) event.current_buffer.insert_text = Mock() _apply_autosuggest(event) if called: event.current_buffer.insert_text.assert_called() else: event.current_buffer.insert_text.ass...
test that autosuggest is only applied at end of line.
10
21
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_autosuggest_at_EOL(text, cursor, suggestion, called): event = make_event(text, cursor, suggestion) event.current_buffer.insert_text = Mock() _apply_autosuggest(eve...
261
def stack3(x, filters, blocks, stride1=2, groups=32, name=None): x = block3(x, filters, stride=stride1, groups=groups, name=name + "_block1") for i in range(2, blocks + 1): x = block3( x, filters, groups=groups, conv_shortcut=False, name=n...
A set of stacked residual blocks. Args: x: input tensor. filters: integer, filters of the bottleneck layer in a block. blocks: integer, blocks in the stacked blocks. stride1: default 2, stride of the first layer in the first block. groups: default 32, group size for grouped convolutio...
58
43
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def stack3(x, filters, blocks, stride1=2, groups=32, name=None): x = block3(x, filters, stride=stride1, groups=groups, name=name + "_block1") for i in range(2, blocks + 1): ...
262
def is_mixed(self) -> bool: warnings.warn( "Index.is_mixed is deprecated and will be removed in a future version. " "Check index.inferred_type directly instead.", FutureWarning, stacklevel=find_stack_level(inspect.currentframe()), ) return...
Check if the Index holds data with mixed data types. Returns ------- bool Whether or not the Index holds data with mixed data types. See Also -------- is_boolean : Check if the Index only consists of booleans. is_integer : Check if the Index...
118
28
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def is_mixed(self) -> bool: warnings.warn( "Index.is_mixed is deprecated and will be removed in a future version. " "Check index.inferred_type direct...
263
def responder(request): # Find an available port with socket.socket() as sock: sock.bind(("localhost", 0)) port = sock.getsockname()[1] server_process = multiprocessing.Process( target=process_server, args=(request.param, port) ) server_process.start() yield port ...
Fixture that starts a local http server in a separate process on localhost and returns the port. Running in a separate process instead of a thread to allow termination/killing of http server upon cleanup.
34
93
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def responder(request): # Find an available port with socket.socket() as sock: sock.bind(("localhost", 0)) port = sock.getsockname()[1] server_process = mul...
264
def _pre_setup(self): super()._pre_setup() if self.available_apps is not None: apps.set_available_apps(self.available_apps) setting_changed.send( sender=settings._wrapped.__class__, setting="INSTALLED_APPS", value=self.avai...
Perform pre-test setup: * If the class has an 'available_apps' attribute, restrict the app registry to these applications, then fire the post_migrate signal -- it must run with the correct set of applications for the test case. * If the class has a 'fixtures' attribute, inst...
48
72
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _pre_setup(self): super()._pre_setup() if self.available_apps is not None: apps.set_available_apps(self.available_apps) setting_changed.s...
265
def test_multiple_actions_form(self): action_data = { ACTION_CHECKBOX_NAME: [self.s1.pk], # Two different actions selected on the two forms... "action": ["external_mail", "delete_selected"], # ...but "go" was clicked on the top form. "index": ...
Actions come from the form whose submit button was pressed (#10618).
11
51
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_multiple_actions_form(self): action_data = { ACTION_CHECKBOX_NAME: [self.s1.pk], # Two different actions selected on the two forms... ...
266
def test_empty_message(self) -> None: self.login("hamlet") othello = self.example_user("othello") result = self.client_post( "/json/messages", {"type": "private", "content": " ", "to": othello.email}, ) self.assert_json_error(result, "Message must...
Sending a message that is empty or only whitespace should fail
11
26
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_empty_message(self) -> None: self.login("hamlet") othello = self.example_user("othello") result = self.client_post( "/json/messages", ...
267
def freqai_feature_engineering_generic(self, dataframe, **kwargs): dataframe["%-pct-change"] = dataframe["close"].pct_change() dataframe["%-raw_volume"] = dataframe["volume"] dataframe["%-raw_price"] = dataframe["close"] return dataframe
This optional function will be called for all include_timeframes (including corr_pairs). After that, the features will be shifted by the number of candles in the include_shifted_candles. :param df: strategy dataframe which will receive the features dataframe["%-pct-change"] = da...
38
15
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def freqai_feature_engineering_generic(self, dataframe, **kwargs): dataframe["%-pct-change"] = dataframe["close"].pct_change() dataframe["%-raw_volume"] = dataframe[...
268
def next_sample(uid): return next(_SHARED_SEQUENCES[uid]) @keras_export("keras.utils.GeneratorEnqueuer")
Gets the next value from the generator `uid`. To allow multiple generators to be used at the same time, we use `uid` to get a specific one. A single generator would cause the validation to overwrite the training generator. Args: uid: int, generator identifier Returns: The next val...
51
5
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def next_sample(uid): return next(_SHARED_SEQUENCES[uid]) @keras_export("keras.utils.GeneratorEnqueuer") ``` ###Assistant : Gets the next value from the generator `uid...
269
def check_settings(base_url=None): if base_url is None: base_url = settings.STATIC_URL if not base_url: raise ImproperlyConfigured( "You're using the staticfiles app " "without having set the required STATIC_URL setting.") if settings.MEDIA_URL == base_url: ...
Check if the staticfiles settings have sane values.
8
83
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def check_settings(base_url=None): if base_url is None: base_url = settings.STATIC_URL if not base_url: raise ImproperlyConfigured( "You're using the...
270
def kubernetes_dict(self, **kwargs) -> Dict: config = self.dict(**kwargs) for idx, deployment in enumerate(config["deployments"]): if isinstance(deployment.get("ray_actor_options"), dict): # JSON-serialize ray_actor_options' resources dictionary if...
Returns dictionary in Kubernetes format. Dictionary can be yaml-dumped to a Serve config file directly and then copy-pasted into a RayService Kubernetes config. Args: all kwargs are passed directly into schema's dict() function.
33
89
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def kubernetes_dict(self, **kwargs) -> Dict: config = self.dict(**kwargs) for idx, deployment in enumerate(config["deployments"]): if isinstance(deploy...
271
def reload_images(self, group_method, img_list): logger.info("Preparing to group...") if group_method == 'group_blur': filename_list, image_list = self._get_images() blurs = [self.estimate_blur(img) for img in image_list] temp_list = list(zip(filename_list, b...
Reloads the image list by replacing the comparative values with those that the chosen grouping method expects. :param group_method: str name of the grouping method that will be used. :param img_list: image list that has been sorted by one of the sort methods. :return: im...
56
135
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def reload_images(self, group_method, img_list): logger.info("Preparing to group...") if group_method == 'group_blur': filename_list, image_list = self._...
272
def get_sales_orders(quotations): if not quotations: return [] quotation_names = [q.name for q in quotations] return frappe.db.sql( .format( ", ".join(["%s"] * len(quotation_names)) ), tuple(quotation_names), as_dict=1, ) # nosec
SELECT so.`name`, so.`base_grand_total`, soi.prevdoc_docname as quotation FROM `tabSales Order` so, `tabSales Order Item` soi WHERE so.docstatus=1 AND so.name = soi.parent AND soi.prevdoc_docname in ({0})
24
27
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_sales_orders(quotations): if not quotations: return [] quotation_names = [q.name for q in quotations] return frappe.db.sql( .format( ", ".join(["%s"] * len(quotation_name...
273
def download_extract(name, folder=None): fname = download(name) base_dir = os.path.dirname(fname) data_dir, ext = os.path.splitext(fname) if ext == '.zip': fp = zipfile.ZipFile(fname, 'r') elif ext in ('.tar', '.gz'): fp = tarfile.open(fname, 'r') else: assert False,...
Download and extract a zip/tar file. Defined in :numref:`sec_utils`
9
47
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def download_extract(name, folder=None): fname = download(name) base_dir = os.path.dirname(fname) data_dir, ext = os.path.splitext(fname) if ext == '.zip': fp = ...
274
def sample_weights_mismatch(self): # If there is a mismatch between sample weight mode and the placeholders # created, then recompile the sub-graphs that depend on sample weights. return ( self.sample_weight_mode is not None and self.sample_weight is None ) or ( ...
Check if the sample weight and the mode match or not.
11
48
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def sample_weights_mismatch(self): # If there is a mismatch between sample weight mode and the placeholders # created, then recompile the sub-graphs that depend on s...
275
def shebang(self, line, cell): # Create the event loop in which to run script magics # this operates on a background thread if self.event_loop is None: if sys.platform == "win32": # don't override the current policy, # just create an event lo...
Run a cell via a shell command The `%%script` line is like the #! line of script, specifying a program (bash, perl, ruby, etc.) with which to run. The rest of the cell is run by that program. Examples -------- :: In [1]: %%script bash ...: f...
61
69
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def shebang(self, line, cell): # Create the event loop in which to run script magics # this operates on a background thread if self.event_loop is None: ...
276
def statistics(self): try: return self._local.statistics except AttributeError: self._local.statistics = {} return self._local.statistics
Return a dictionary of runtime statistics. This dictionary will be empty when the controller has never been ran. When it is running or has ran previously it should have (but may not) have useful and/or informational keys and values when running is underway and/or completed. .. ...
145
12
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def statistics(self): try: return self._local.statistics except AttributeError: self._local.statistics = {} return self._local.st...
277
def send(self, sender, **named): if ( not self.receivers or self.sender_receivers_cache.get(sender) is NO_RECEIVERS ): return [] return [ (receiver, receiver(signal=self, sender=sender, **named)) for receiver in self._live_rec...
Send signal from sender to all connected receivers. If any receiver raises an error, the error propagates back through send, terminating the dispatch loop. So it's possible that all receivers won't be called if an error is raised. Arguments: sender ...
70
26
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def send(self, sender, **named): if ( not self.receivers or self.sender_receivers_cache.get(sender) is NO_RECEIVERS ): return [] ...
278
def deploy_ray_func(func, *args): # pragma: no cover result = func(*args) ip = get_node_ip_address() if isinstance(result, pandas.DataFrame): return result, len(result), len(result.columns), ip elif all(isinstance(r, pandas.DataFrame) for r in result): return [i for r in result for...
Execute a function on an axis partition in a worker process. Parameters ---------- func : callable Function to be executed on an axis partition. *args : iterable Additional arguments that need to passed in ``func``. Returns ------- list The result of the functi...
61
55
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def deploy_ray_func(func, *args): # pragma: no cover result = func(*args) ip = get_node_ip_address() if isinstance(result, pandas.DataFrame): return result, len(res...
279
def _set_gradient_checkpointing(self, module, value=False): if isinstance(module, ViltEncoder): module.gradient_checkpointing = value VILT_START_DOCSTRING = r VILT_INPUTS_DOCSTRING = r VILT_IMAGES_AND_TEXT_CLASSIFICATION_INPUTS_DOCSTRING = r @add_start_docstrings( "The bare ViLT Model tran...
This model is a PyTorch `torch.nn.Module <https://pytorch.org/docs/stable/nn.html#torch.nn.Module>`_ subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`ViltConfig`]): Model configuratio...
802
36
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _set_gradient_checkpointing(self, module, value=False): if isinstance(module, ViltEncoder): module.gradient_checkpointing = value VILT_START_DOCSTRING = r VILT_INP...
280
def needs_document_end_workaround(self): if objects.backend == usertypes.Backend.QtWebKit: return False assert objects.backend == usertypes.Backend.QtWebEngine, objects.backend broken_scripts = [ ('http://userstyles.org', None), ('https://github.com...
Check whether to force @run-at document-end. This needs to be done on QtWebEngine for known-broken scripts. On Qt 5.12, accessing the DOM isn't possible with "@run-at document-start". It was documented to be impossible before, but seems to work fine. However, some scripts do D...
57
29
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def needs_document_end_workaround(self): if objects.backend == usertypes.Backend.QtWebKit: return False assert objects.backend == usertypes.Backend.QtWe...
281
def _temperature_unit(self) -> str: if ( weather_option_temperature_unit := self._weather_option_temperature_unit ) is not None: return weather_option_temperature_unit return self._default_temperature_unit
Return the converted unit of measurement for temperature. Should not be set by integrations.
14
17
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _temperature_unit(self) -> str: if ( weather_option_temperature_unit := self._weather_option_temperature_unit ) is not None: return weath...
282
def fontName(self, fontprop): if isinstance(fontprop, str): filenames = [fontprop] elif mpl.rcParams['pdf.use14corefonts']: filenames = _fontManager._find_fonts_by_props( fontprop, fontext='afm', directory=RendererPdf._afm_font_dir ) ...
Select a font based on fontprop and return a name suitable for Op.selectfont. If fontprop is a string, it will be interpreted as the filename of the font.
28
78
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def fontName(self, fontprop): if isinstance(fontprop, str): filenames = [fontprop] elif mpl.rcParams['pdf.use14corefonts']: filenames = _fon...
283
def center_to_corners_format(x): x_center, y_center, width, height = x.unbind(-1) boxes = [(x_center - 0.5 * width), (y_center - 0.5 * height), (x_center + 0.5 * width), (y_center + 0.5 * height)] return torch.stack(boxes, dim=-1)
Converts a PyTorch tensor of bounding boxes of center format (center_x, center_y, width, height) to corners format (left, top, right, bottom).
21
33
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def center_to_corners_format(x): x_center, y_center, width, height = x.unbind(-1) boxes = [(x_center - 0.5 * width), (y_center - 0.5 * height), (x_center + 0.5 * width), (y_cent...
284
def add(self, key, value, timeout=DEFAULT_TIMEOUT, version=None): raise NotImplementedError( "subclasses of BaseCache must provide an add() method" )
Set a value in the cache if the key does not already exist. If timeout is given, use that timeout for the key; otherwise use the default cache timeout. Return True if the value was stored, False otherwise.
38
17
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def add(self, key, value, timeout=DEFAULT_TIMEOUT, version=None): raise NotImplementedError( "subclasses of BaseCache must provide an add() method" ) ...
285
def normalized_laplacian_matrix(G, nodelist=None, weight="weight"): r import numpy as np import scipy as sp import scipy.sparse # call as sp.sparse if nodelist is None: nodelist = list(G) A = nx.to_scipy_sparse_array(G, nodelist=nodelist, weight=weight, format="csr") n, m = A.shape...
Returns the normalized Laplacian matrix of G. The normalized graph Laplacian is the matrix .. math:: N = D^{-1/2} L D^{-1/2} where `L` is the graph Laplacian and `D` is the diagonal matrix of node degrees [1]_. Parameters ---------- G : graph A NetworkX graph nodelis...
190
94
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def normalized_laplacian_matrix(G, nodelist=None, weight="weight"): r import numpy as np import scipy as sp import scipy.sparse # call as sp.sparse if nodelist is None:...
286
def extract_patches_2d(image, patch_size, *, max_patches=None, random_state=None): i_h, i_w = image.shape[:2] p_h, p_w = patch_size if p_h > i_h: raise ValueError( "Height of the patch should be less than the height of the image." ) if p_w > i_w: raise ValueErr...
Reshape a 2D image into a collection of patches. The resulting patches are allocated in a dedicated array. Read more in the :ref:`User Guide <image_feature_extraction>`. Parameters ---------- image : ndarray of shape (image_height, image_width) or \ (image_height, image_width, n_channels)...
266
136
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def extract_patches_2d(image, patch_size, *, max_patches=None, random_state=None): i_h, i_w = image.shape[:2] p_h, p_w = patch_size if p_h > i_h: raise ValueError( ...
287
def refresh_from_db(self, using=None, fields=None): if fields is None: self._prefetched_objects_cache = {} else: prefetched_objects_cache = getattr(self, "_prefetched_objects_cache", ()) for field in fields: if field in prefetched_objects_cach...
Reload field values from the database. By default, the reloading happens from the database this instance was loaded from, or by the read router if this instance wasn't loaded from any database. The using parameter will override the default. Fields can be used to specify which ...
85
165
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def refresh_from_db(self, using=None, fields=None): if fields is None: self._prefetched_objects_cache = {} else: prefetched_objects_cache = g...
288
def set_tunnel(self, host, port=None, headers=None): if self.sock: raise RuntimeError("Can't set up tunnel for established connection") self._tunnel_host, self._tunnel_port = self._get_hostport(host, port) if headers: self._tunnel_headers = headers else...
Set up host and port for HTTP CONNECT tunnelling. In a connection that uses HTTP CONNECT tunneling, the host passed to the constructor is used as a proxy server that relays all communication to the endpoint passed to `set_tunnel`. This done by sending an HTTP CONNECT request to the prox...
85
27
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def set_tunnel(self, host, port=None, headers=None): if self.sock: raise RuntimeError("Can't set up tunnel for established connection") self._tunnel_ho...
289
def explicit_device_get_scope() -> Iterator[None]: state = transfer_guard_lib.thread_local_state() prev = state.explicit_device_get state.explicit_device_get = True try: yield finally: state.explicit_device_get = prev
Indicates that the current context is an explicit device_get() call.
10
19
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def explicit_device_get_scope() -> Iterator[None]: state = transfer_guard_lib.thread_local_state() prev = state.explicit_device_get state.explicit_device_get = True try: yield...
290
def accessory_info(self) -> Service: return self.accessory.services.first( service_type=ServicesTypes.ACCESSORY_INFORMATION )
Information about the make and model of an accessory.
9
8
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def accessory_info(self) -> Service: return self.accessory.services.first( service_type=ServicesTypes.ACCESSORY_INFORMATION ) ``` ###Assista...
291
def _always_object(classes): if object not in classes: return classes + (object,) return classes
Ensure object appears in the mro even for old-style classes.
10
13
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _always_object(classes): if object not in classes: return classes + (object,) return classes ``` ###Assistant : Ensure object appears in the mro e...
292
def addIncludedDataFilesFromFileOptions(): for included_datafile in _addIncludedDataFilesFromFileOptions(): addIncludedDataFile(included_datafile)
Early data files, from user options that work with file system.
11
7
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def addIncludedDataFilesFromFileOptions(): for included_datafile in _addIncludedDataFilesFromFileOptions(): addIncludedDataFile(included_datafile) ``` ###Assi...
293
def _attributes(**kwargs) -> dict[str, str]: return {key: str(value) for key, value in kwargs.items() if value is not None}
Return the given kwargs as a dictionary with values converted to strings. Items with a value of None will be omitted.
21
18
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _attributes(**kwargs) -> dict[str, str]: return {key: str(value) for key, value in kwargs.items() if value is not None} ``` ###Assistant : Return the given kwargs ...
294
def test_charpp(self): dll = CDLL(_ctypes_test.__file__) func = dll._testfunc_c_p_p func.restype = c_char_p argv = (c_char_p * 2)() argc = c_int( 2 ) argv[0] = b'hello' argv[1] = b'world' result = func( byref(argc), argv ) self.assertEqual...
Test that a character pointer-to-pointer is correctly passed
8
35
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_charpp(self): dll = CDLL(_ctypes_test.__file__) func = dll._testfunc_c_p_p func.restype = c_char_p argv = (c_char_p * 2)() argc = c_...
295
def test_error_message_unsigned(self): # Ensure to test for potential overflow in the case of: # x - y # and # y - x x = np.asarray([0, 1, 8], dtype='uint8') y = np.asarray([4, 4, 4], dtype='uint8') with pytest.raises(AssertionError) as exc_...
Check the the message is formatted correctly when overflow can occur (gh21768)
12
50
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_error_message_unsigned(self): # Ensure to test for potential overflow in the case of: # x - y # and # y - x x = np.asa...
296
def _join_or_get_room(self, room_id_or_alias): rooms = self._client.get_rooms() if room_id_or_alias in rooms: _LOGGER.debug("Already in room %s", room_id_or_alias) return rooms[room_id_or_alias] for room in rooms.values(): if room.room_id not in self...
Join a room or get it, if we are already in the room. We can't just always call join_room(), since that seems to crash the client if we're already in the room.
32
64
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _join_or_get_room(self, room_id_or_alias): rooms = self._client.get_rooms() if room_id_or_alias in rooms: _LOGGER.debug("Already in room %s", room_id...
297
def _is_function_class_equation(func_class, f, symbol): if f.is_Mul or f.is_Add: return all(_is_function_class_equation(func_class, arg, symbol) for arg in f.args) if f.is_Pow: if not f.exp.has(symbol): return _is_function_class_equation(func_class, f.base, s...
Tests whether the equation is an equation of the given function class. The given equation belongs to the given function class if it is comprised of functions of the function class which are multiplied by or added to expressions independent of the symbol. In addition, the arguments of all such function...
123
52
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _is_function_class_equation(func_class, f, symbol): if f.is_Mul or f.is_Add: return all(_is_function_class_equation(func_class, arg, symbol) for arg i...
298
def get_feature_names_out(self, input_features=None): class_name = self.__class__.__name__.lower() return np.asarray([f"{class_name}0"], dtype=object)
Get output feature names for transformation. Parameters ---------- input_features : array-like of str or None, default=None Ignored. Returns ------- feature_names_out : ndarray of str objects An ndarray with one string i.e. ["isotonicregression0"...
32
9
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_feature_names_out(self, input_features=None): class_name = self.__class__.__name__.lower() return np.asarray([f"{class_name}0"], dtype=object) ``` ...
299
def get_distance(self, f, dist_val, lookup_type): # Getting the distance parameter value = dist_val[0] # Shorthand boolean flags. geodetic = f.geodetic(self.connection) geography = f.geography if isinstance(value, Distance): if geography: ...
Retrieve the distance parameters for the given geometry field, distance lookup value, and the distance lookup type. This is the most complex implementation of the spatial backends due to what is supported on geodetic geometry columns vs. what's available on projected geometry c...
55
80
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_distance(self, f, dist_val, lookup_type): # Getting the distance parameter value = dist_val[0] # Shorthand boolean flags. geodetic = f.geode...