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
100
def _tune_legacy_checkpoint_score_attr(self) -> Optional[str]: if self.checkpoint_score_attribute is None: return self.checkpoint_score_attribute prefix = "" if self.checkpoint_score_order == MIN: prefix = "min-" return f"{prefix}{self.checkpoint_score_at...
Same as ``checkpoint_score_attr`` in ``tune.run``. Only used for Legacy API compatibility.
11
49
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _tune_legacy_checkpoint_score_attr(self) -> Optional[str]: if self.checkpoint_score_attribute is None: return self.checkpoint_score_attribute prefix ...
101
def test_dynamic_sampling_bias_activation(self): project = self.project # force creation project.update_option( "sentry:dynamic_sampling_biases", [ {"id": "boostEnvironments", "active": False}, ], ) self.login_as(self.user) ...
Tests that when sending a request to enable a dynamic sampling bias, the bias will be successfully enabled and the audit log 'SAMPLING_BIAS_ENABLED' will be triggered
26
59
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_dynamic_sampling_bias_activation(self): project = self.project # force creation project.update_option( "sentry:dynamic_sampling_biases", ...
102
def call(self, inputs, *args, **kwargs): input_shape = K.int_shape(inputs) if len(input_shape) != 4: raise ValueError('Inputs should have rank ' + str(4) + '; Received input shape:', str(input_shape)) if self.data_fo...
This is where the layer's logic lives. Parameters ---------- inputs: tensor Input tensor, or list/tuple of input tensors args: tuple Additional standard keras Layer arguments kwargs: dict Additional standard keras Layer keyword arguments ...
42
152
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def call(self, inputs, *args, **kwargs): input_shape = K.int_shape(inputs) if len(input_shape) != 4: raise ValueError('Inputs should have rank ' + ...
103
def to_native_types(self, slicer=None, **kwargs) -> np.ndarray: warnings.warn( "The 'to_native_types' method is deprecated and will be removed in " "a future version. Use 'astype(str)' instead.", FutureWarning, stacklevel=find_stack_level(inspect.currentf...
Format specified values of `self` and return them. .. deprecated:: 1.2.0 Parameters ---------- slicer : int, array-like An indexer into `self` that specifies which values are used in the formatting process. kwargs : dict Options for ...
93
40
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def to_native_types(self, slicer=None, **kwargs) -> np.ndarray: warnings.warn( "The 'to_native_types' method is deprecated and will be removed in " "...
104
def periphery(G, e=None, usebounds=False, weight=None): if usebounds is True and e is None and not G.is_directed(): return _extrema_bounding(G, compute="periphery", weight=weight) if e is None: e = eccentricity(G, weight=weight) diameter = max(e.values()) p = [v for v in e if e[v] =...
Returns the periphery of the graph G. The periphery is the set of nodes with eccentricity equal to the diameter. Parameters ---------- G : NetworkX graph A graph e : eccentricity dictionary, optional A precomputed dictionary of eccentricities. weight : string, function, or None ...
212
44
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def periphery(G, e=None, usebounds=False, weight=None): if usebounds is True and e is None and not G.is_directed(): return _extrema_bounding(G, compute="periphery", weight=w...
105
def _current_mode_setpoint_enums(self) -> list[ThermostatSetpointType | None]: if self._current_mode is None: # Thermostat(valve) with no support for setting a mode is considered heating-only return [ThermostatSetpointType.HEATING] return THERMOSTAT_MODE_SETPOINT_MAP.get...
Return the list of enums that are relevant to the current thermostat mode.
13
30
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _current_mode_setpoint_enums(self) -> list[ThermostatSetpointType | None]: if self._current_mode is None: # Thermostat(valve) with no support for setting a m...
106
def line(loc, strg): lastCR = strg.rfind("\n", 0, loc) nextCR = strg.find("\n", loc) if nextCR >= 0: return strg[lastCR + 1:nextCR] else: return strg[lastCR + 1:]
Returns the line of text containing loc within a string, counting newlines as line separators.
15
25
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def line(loc, strg): lastCR = strg.rfind("\n", 0, loc) nextCR = strg.find("\n", loc) if nextCR >= 0: return strg[lastCR + 1:nextCR] else: return strg[las...
107
def _parse_configs(self, config_files): formatted = "" for cfile in config_files: fname = os.path.basename(cfile) ext = os.path.splitext(cfile)[1] formatted += f"\n--------- {fname} ---------\n" if ext == ".ini": formatted += self....
Parse the given list of config files into a human readable format. Parameters ---------- config_files: list A list of paths to the faceswap config files Returns ------- str The current configuration in the config files formatted in a human reada...
41
37
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _parse_configs(self, config_files): formatted = "" for cfile in config_files: fname = os.path.basename(cfile) ext = os.path.splitext(cfil...
108
def parent(self) -> DOMNode: if self._parent is None: raise NoParent(f"{self} has no parent") assert isinstance(self._parent, DOMNode) return self._parent
Get the parent node. Raises: NoParent: If this is the root node. Returns: DOMNode: The node which is the direct parent of this node.
24
18
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def parent(self) -> DOMNode: if self._parent is None: raise NoParent(f"{self} has no parent") assert isinstance(self._parent, DOMNode) return sel...
109
def user_documents_dir(self) -> str: documents_dir = _get_user_dirs_folder("XDG_DOCUMENTS_DIR") if documents_dir is None: documents_dir = os.environ.get("XDG_DOCUMENTS_DIR", "").strip() if not documents_dir: documents_dir = os.path.expanduser("~/Documents...
:return: documents directory tied to the user, e.g. ``~/Documents``
9
23
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def user_documents_dir(self) -> str: documents_dir = _get_user_dirs_folder("XDG_DOCUMENTS_DIR") if documents_dir is None: documents_dir = os.environ.get(...
110
def test_iforest_sparse(global_random_seed): rng = check_random_state(global_random_seed) X_train, X_test = train_test_split(diabetes.data[:50], random_state=rng) grid = ParameterGrid({"max_samples": [0.5, 1.0], "bootstrap": [True, False]}) for sparse_format in [csc_matrix, csr_matrix]: X_...
Check IForest for various parameter settings on sparse input.
9
65
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_iforest_sparse(global_random_seed): rng = check_random_state(global_random_seed) X_train, X_test = train_test_split(diabetes.data[:50], random_state=rng) grid = Par...
111
def get_scorer_names(): return sorted(_SCORERS.keys()) for name, metric in [ ("precision", precision_score), ("recall", recall_score), ("f1", f1_score), ("jaccard", jaccard_score), ]: _SCORERS[name] = make_scorer(metric, average="binary") for average in ["macro", "micro", "samples", "...
Get the names of all available scorers. These names can be passed to :func:`~sklearn.metrics.get_scorer` to retrieve the scorer object. Returns ------- list of str Names of all available scorers.
29
41
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_scorer_names(): return sorted(_SCORERS.keys()) for name, metric in [ ("precision", precision_score), ("recall", recall_score), ("f1", f1_score), ("jaccard"...
112
def _split_generators(self, dl_manager): # Download extract and return path of data file. dl_dir = dl_manager.download_and_extract(_URL) # Use swda/ folder. data_dir = os.path.join(dl_dir, "swda") # Handle partitions files: download extract and return paths of split fil...
Returns SplitGenerators. This method is tasked with downloading/extracting the data and defining the splits. Args: dl_manager (:obj:`datasets.utils.download_manager.DownloadManager`): Download manager to download and extract data files from urls. Returns: ...
34
95
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _split_generators(self, dl_manager): # Download extract and return path of data file. dl_dir = dl_manager.download_and_extract(_URL) # Use swda/ folder....
113
def print_help(self): help_text = console.print(text=help_text, menu="Stocks - Discovery")
Print help[cmds] [src][Geek of Wall St][/src] rtearn realtime earnings from and expected moves [src][Finnhub][/src] pipo past IPOs dates fipo future IPOs dates [src][Yahoo Finance][/src] gainers show latest top gainers losers show latest top losers ugs ...
142
8
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def print_help(self): help_text = console.print(text=help_text, menu="Stocks - Discovery") ``` ###Assistant : Print help[cmds] [src][Geek of Wall St][/...
114
def handle_fk_field(self, obj, field): self._start_relational_field(field) related_att = getattr(obj, field.get_attname()) if related_att is not None: if self.use_natural_foreign_keys and hasattr( field.remote_field.model, "natural_key" ): ...
Handle a ForeignKey (they need to be treated slightly differently from regular fields).
13
60
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def handle_fk_field(self, obj, field): self._start_relational_field(field) related_att = getattr(obj, field.get_attname()) if related_att is not None: ...
115
def test_metrics_folder(): with _ray_start(include_dashboard=True) as context: session_dir = context["session_dir"] assert os.path.exists( f"{session_dir}/metrics/grafana/provisioning/dashboards/default.yml" ) assert os.path.exists( f"{session_dir}/metric...
Tests that the default dashboard files get created.
8
24
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_metrics_folder(): with _ray_start(include_dashboard=True) as context: session_dir = context["session_dir"] assert os.path.exists( f"{session_dir...
116
def state_dict(self): state_dict = {} state_dict['dynamic_loss_scale'] = self.dynamic_loss_scale state_dict['cur_scale'] = self.cur_scale state_dict['cur_iter'] = self.cur_iter if state_dict['dynamic_loss_scale']: state_dict['last_overflow_iter'] = self.last_...
Returns a dict containing the current state of this :class:`FP16_Optimizer` instance. This dict contains attributes of :class:`FP16_Optimizer`, as well as the state_dict of the contained Pytorch optimizer. Example:: checkpoint = {} checkpoint['model'] = model.sta...
39
44
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def state_dict(self): state_dict = {} state_dict['dynamic_loss_scale'] = self.dynamic_loss_scale state_dict['cur_scale'] = self.cur_scale state_dict[...
117
def _update_mean_variance(n_past, mu, var, X, sample_weight=None): if X.shape[0] == 0: return mu, var # Compute (potentially weighted) mean and variance of new datapoints if sample_weight is not None: n_new = float(sample_weight.sum()) if np.isclose(...
Compute online update of Gaussian mean and variance. Given starting sample count, mean, and variance, a new set of points X, and optionally sample weights, return the updated mean and variance. (NB - each dimension (column) in X is treated as independent -- you get variance, not covaria...
191
162
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _update_mean_variance(n_past, mu, var, X, sample_weight=None): if X.shape[0] == 0: return mu, var # Compute (potentially weighted) mean and variance...
118
def is_prime(n): sympy_deprecation_warning( , deprecated_since_version="1.11", active_deprecations_target='deprecated-carmichael-static-methods', ) return isprime(n)
is_prime is just a wrapper around sympy.ntheory.primetest.isprime so use that directly instead.
12
9
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def is_prime(n): sympy_deprecation_warning( , deprecated_since_version="1.11", active_deprecations_target='deprecated-carmichael-static-methods', ) ...
119
def standard_b64decode(s): return b64decode(s) _urlsafe_encode_translation = bytes.maketrans(b'+/', b'-_') _urlsafe_decode_translation = bytes.maketrans(b'-_', b'+/')
Decode bytes encoded with the standard Base64 alphabet. Argument s is a bytes-like object or ASCII string to decode. The result is returned as a bytes object. A binascii.Error is raised if the input is incorrectly padded. Characters that are not in the standard alphabet are discarded prior to the pa...
52
12
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def standard_b64decode(s): return b64decode(s) _urlsafe_encode_translation = bytes.maketrans(b'+/', b'-_') _urlsafe_decode_translation = bytes.maketrans(b'-_', b'+/') ```...
120
def inception_score(self, imgs, batch_size=32, splits=1): N = len(imgs) dataloader = torch.utils.data.DataLoader(imgs, batch_size=batch_size) up = nn.Upsample( size=(28, 28), mode="bilinear", align_corners=False, # This is to reduce user warnings fro...
Calculate the inception score of the generated images.
8
29
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def inception_score(self, imgs, batch_size=32, splits=1): N = len(imgs) dataloader = torch.utils.data.DataLoader(imgs, batch_size=batch_size) up = nn.Upsampl...
121
def execute(): frappe.reload_doc("stock", "doctype", "shipment") # update submitted status frappe.db.sql( ) # update cancelled status frappe.db.sql( )
UPDATE `tabShipment` SET status = "Submitted" WHERE status = "Draft" AND docstatus = 1UPDATE `tabShipment` SET status = "Cancelled" WHERE status = "Draft" AND docstatus = 2
27
17
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def execute(): frappe.reload_doc("stock", "doctype", "shipment") # update submitted status frappe.db.sql( ) # update cancelled status frappe.db.sql( ) ``` ###Assi...
122
def url(self, name): raise NotImplementedError("subclasses of Storage must provide a url() method")
Return an absolute URL where the file's contents can be accessed directly by a web browser.
16
12
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def url(self, name): raise NotImplementedError("subclasses of Storage must provide a url() method") ``` ###Assistant : Return an absolute URL where the...
123
def load_attributes_from_hdf5_group(group, name): if name in group.attrs: data = [ n.decode("utf8") if hasattr(n, "decode") else n for n in group.attrs[name] ] else: data = [] chunk_id = 0 while "%s%d" % (name, chunk_id) in group.attrs: ...
Loads attributes of the specified name from the HDF5 group. This method deals with an inherent problem of HDF5 file which is not able to store data larger than HDF5_OBJECT_HEADER_LIMIT bytes. Args: group: A pointer to a HDF5 group. name: A name of the attributes to load. Returns: ...
51
57
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def load_attributes_from_hdf5_group(group, name): if name in group.attrs: data = [ n.decode("utf8") if hasattr(n, "decode") else n for n in group.att...
124
def _find_root_block_schema(block_schemas_with_references): return next( ( block_schema for ( block_schema, _, parent_block_schema_id, ) in block_schemas_with_references if parent_block_schema_id is None ...
Attempts to find the root block schema from a list of block schemas with references. Returns None if a root block schema is not found. Returns only the first potential root block schema if multiple are found.
37
21
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _find_root_block_schema(block_schemas_with_references): return next( ( block_schema for ( block_schema, _, ...
125
def feature_embedding(input_feats, out_feat_len): assert input_feats.ndim == 2 assert isinstance(out_feat_len, int) assert out_feat_len >= input_feats.shape[1] num_nodes = input_feats.shape[0] feat_dim = input_feats.shape[1] feat_repeat_times = out_feat_len // feat_dim residue_dim = ou...
Embed features. This code was partially adapted from https://github.com/GXYM/DRRG licensed under the MIT license. Args: input_feats (ndarray): The input features of shape (N, d), where N is the number of nodes in graph, d is the input feature vector length. out_feat_len (int): The l...
54
162
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def feature_embedding(input_feats, out_feat_len): assert input_feats.ndim == 2 assert isinstance(out_feat_len, int) assert out_feat_len >= input_feats.shape[1] num_node...
126
def decision_function(self, X): check_is_fitted(self) xp, _ = get_namespace(X) X = self._validate_data(X, accept_sparse="csr", reset=False) scores = safe_sparse_dot(X, self.coef_.T, dense_output=True) + self.intercept_ return xp.reshape(scores, -1) if scores.shape[1] ==...
Predict confidence scores for samples. The confidence score for a sample is proportional to the signed distance of that sample to the hyperplane. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The data matrix for whic...
79
29
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def decision_function(self, X): check_is_fitted(self) xp, _ = get_namespace(X) X = self._validate_data(X, accept_sparse="csr", reset=False) scores =...
127
def get_ranking(pairs): if len(pairs) == 1: return list(pairs[0]) w = get_winner(pairs) # now remove the winner from the list of pairs p_new = np.array([(a, b) for a, b in pairs if a != w]) return [w] + get_ranking(p_new)
Abuses concordance property to get a (not necessarily unqiue) ranking. The lack of uniqueness is due to the potential existance of multiple equally ranked winners. We have to pick one, which is where the non-uniqueness comes from
37
38
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_ranking(pairs): if len(pairs) == 1: return list(pairs[0]) w = get_winner(pairs) # now remove the winner from the list of pairs p_new = np.array([(a, b) f...
128
def backup_dir(dir, ext=".bak"): # type: (str, str) -> str n = 1 extension = ext while os.path.exists(dir + extension): n += 1 extension = ext + str(n) return dir + extension
Figure out the name of a directory to back up the given dir to (adding .bak, .bak2, etc)
18
31
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def backup_dir(dir, ext=".bak"): # type: (str, str) -> str n = 1 extension = ext while os.path.exists(dir + extension): n += 1 extension = ext + str(n) ...
129
def synchronize(local_filters, remotes, update_remote=True): remote_filters = ray.get( [r.get_filters.remote(flush_after=True) for r in remotes] ) for rf in remote_filters: for k in local_filters: local_filters[k].apply_changes(rf[k], with_buffer=...
Aggregates all filters from remote evaluators. Local copy is updated and then broadcasted to all remote evaluators. Args: local_filters: Filters to be synchronized. remotes: Remote evaluators with filters. update_remote: Whether to push updates to remote filters. ...
36
42
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def synchronize(local_filters, remotes, update_remote=True): remote_filters = ray.get( [r.get_filters.remote(flush_after=True) for r in remotes] ) ...
130
def test_estimator_empty_instance_dict(estimator): state = estimator.__getstate__() expected = {"_sklearn_version": sklearn.__version__} assert state == expected # this should not raise pickle.loads(pickle.dumps(BaseEstimator()))
Check that ``__getstate__`` returns an empty ``dict`` with an empty instance. Python 3.11+ changed behaviour by returning ``None`` instead of raising an ``AttributeError``. Non-regression test for gh-25188.
27
19
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_estimator_empty_instance_dict(estimator): state = estimator.__getstate__() expected = {"_sklearn_version": sklearn.__version__} assert state == expected # this...
131
def test_with_variables(self): context = Context({"name": "jonathan wells"}) template = expected = self.assertHTMLEqual(expected, Template(template).render(context))
{% load wagtailadmin_tags %} {% fragment as my_fragment %} <p>Hello, {{ name|title }}</p> {% endfragment %} Text coming after: {{ my_fragment }} Text coming after: <p>Hello, Jonathan Wells</p>
28
13
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_with_variables(self): context = Context({"name": "jonathan wells"}) template = expected = self.assertHTMLEqual(expected, Template(template).rend...
132
def _extract_interpreter(b_module_data): interpreter = None args = [] b_lines = b_module_data.split(b"\n", 1) if b_lines[0].startswith(b"#!"): b_shebang = b_lines[0].strip() # shlex.split on python-2.6 needs bytes. On python-3.x it needs text cli_split = shlex.split(to_na...
Used to extract shebang expression from binary module data and return a text string with the shebang, or None if no shebang is detected.
24
54
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _extract_interpreter(b_module_data): interpreter = None args = [] b_lines = b_module_data.split(b"\n", 1) if b_lines[0].startswith(b"#!"): b_shebang = b_lin...
133
def test_resource_exhausted_info(self): # generate some random data to be captured implicitly in training func. from sklearn.datasets import fetch_olivetti_faces a_large_array = [] for i in range(50): a_large_array.append(fetch_olivetti_faces())
This is to test if helpful information is displayed when the objects captured in trainable/training function are too large and RESOURCES_EXHAUSTED error of gRPC is triggered.
26
26
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_resource_exhausted_info(self): # generate some random data to be captured implicitly in training func. from sklearn.datasets import fetch_olivetti_faces ...
134
def testing_session_settings(): with tempfile.TemporaryDirectory() as tmpdir: profile = prefect.settings.Profile( name="test-session", settings={ # Set PREFECT_HOME to a temporary directory to avoid clobbering # environments and settings ...
Creates a fixture for the scope of the test session that modifies setting defaults. This ensures that tests are isolated from existing settings, databases, etc.
25
77
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def testing_session_settings(): with tempfile.TemporaryDirectory() as tmpdir: profile = prefect.settings.Profile( name="test-session", settings={ ...
135
def bot_start(self, **kwargs) -> None: self.buy_rsi = IntParameter([0, 50], default=30, space='buy')
Parameters can also be defined here ...
7
11
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def bot_start(self, **kwargs) -> None: self.buy_rsi = IntParameter([0, 50], default=30, space='buy') ``` ###Assistant : Parameters can also be defined ...
136
def getvalue(self): if callable(getattr(self.stream, "getvalue", None)): return self.stream.getvalue()
Return the fully serialized queryset (or None if the output stream is not seekable).
14
8
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def getvalue(self): if callable(getattr(self.stream, "getvalue", None)): return self.stream.getvalue() ``` ###Assistant : Return the fully...
137
def boxplot(self, X, win=None, env=None, opts=None): X = np.squeeze(X) assert X.ndim == 1 or X.ndim == 2, "X should be one or two-dimensional" if X.ndim == 1: X = X[:, None] opts = {} if opts is None else opts _title2str(opts) _assert_opts(opts) ...
This function draws boxplots of the specified data. It takes as input an `N` or an `NxM` tensor `X` that specifies the `N` data values of which to construct the `M` boxplots. The following plot-specific `opts` are currently supported: - `opts.legend`: labels for each of the col...
49
106
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def boxplot(self, X, win=None, env=None, opts=None): X = np.squeeze(X) assert X.ndim == 1 or X.ndim == 2, "X should be one or two-dimensional" if X.ndim == ...
138
def test_body_after_POST_multipart_related(self): # Ticket #9054 # There are cases in which the multipart data is related instead of # being a binary upload, in which case it should still be accessible # via body. payload_data = b"\r\n".join([ b'--boundary', ...
Reading body after parsing multipart that isn't form-data is allowed
10
65
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_body_after_POST_multipart_related(self): # Ticket #9054 # There are cases in which the multipart data is related instead of # being a binary upload,...
139
def query(self, query, **kwargs) -> Result: try: if self.db_conn: result = self.db_conn.aql.execute(query, **kwargs) return result else: raise AirflowException( f"Failed to execute AQLQuery, error connecting to ...
Function to create a arangodb session and execute the AQL query in the session. :param query: AQL query :return: Result
20
39
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def query(self, query, **kwargs) -> Result: try: if self.db_conn: result = self.db_conn.aql.execute(query, **kwargs) return resul...
140
def test_post_process_frame(feature_names, target_names): pd = pytest.importorskip("pandas") X_original = pd.DataFrame( { "col_int_as_integer": [1, 2, 3], "col_int_as_numeric": [1, 2, 3], "col_float_as_real": [1.0, 2.0, 3.0], "col_float_as_numeric": ...
Check the behaviour of the post-processing function for splitting a dataframe.
11
64
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_post_process_frame(feature_names, target_names): pd = pytest.importorskip("pandas") X_original = pd.DataFrame( { "col_int_as_integer": [1, 2, 3], ...
141
def cleanse_setting(self, key, value): try: is_sensitive = self.hidden_settings.search(key) except TypeError: is_sensitive = False if is_sensitive: cleansed = self.cleansed_substitute elif isinstance(value, dict): cleansed = {k: s...
Cleanse an individual setting key/value of sensitive content. If the value is a dictionary, recursively cleanse the keys in that dictionary.
21
64
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def cleanse_setting(self, key, value): try: is_sensitive = self.hidden_settings.search(key) except TypeError: is_sensitive = False i...
142
def func_dump(func): if os.name == "nt": raw_code = marshal.dumps(func.__code__).replace(b"\\", b"/") code = codecs.encode(raw_code, "base64").decode("ascii") else: raw_code = marshal.dumps(func.__code__) code = codecs.encode(raw_code, "base64").decode("ascii") defaults ...
Serializes a user defined function. Args: func: the function to serialize. Returns: A tuple `(code, defaults, closure)`.
17
42
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def func_dump(func): if os.name == "nt": raw_code = marshal.dumps(func.__code__).replace(b"\\", b"/") code = codecs.encode(raw_code, "base64").decode("ascii") el...
143
def cauchy_upper_bound(f): if not f.lev: return dup_cauchy_upper_bound(f.rep, f.dom) else: raise ValueError('univariate polynomial expected')
Computes the Cauchy upper bound on the roots of ``f``.
10
13
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def cauchy_upper_bound(f): if not f.lev: return dup_cauchy_upper_bound(f.rep, f.dom) else: raise ValueError('univariate polynomial expected')...
144
def kernS(s): hit = False quoted = '"' in s or "'" in s if '(' in s and not quoted: if s.count('(') != s.count(")"): raise SympifyError('unmatched left parenthesis') # strip all space from s s = ''.join(s.split()) olds = s # now use space to represen...
Use a hack to try keep autosimplification from distributing a a number into an Add; this modification does not prevent the 2-arg Mul from becoming an Add, however. Examples ======== >>> from sympy.core.sympify import kernS >>> from sympy.abc import x, y The 2-arg Mul distributes a number ...
121
288
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def kernS(s): hit = False quoted = '"' in s or "'" in s if '(' in s and not quoted: if s.count('(') != s.count(")"): raise SympifyError('unmatched left p...
145
def test_load_corrupt_file(self, patched_pickle_load): # First load is the schema version patched_pickle_load.side_effect = [DocumentClassifier.FORMAT_VERSION, OSError()] with self.assertRaises(ClassifierModelCorruptError): self.classifier.load()
GIVEN: - Corrupted classifier pickle file WHEN: - An attempt is made to load the classifier THEN: - The ClassifierModelCorruptError is raised
22
17
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_load_corrupt_file(self, patched_pickle_load): # First load is the schema version patched_pickle_load.side_effect = [DocumentClassifier.FORMAT_VERSION, OSErr...
146
def current_option(self) -> str: return self.device[self.entity_description.current_option_key]
Return the selected entity option to represent the entity state.
10
6
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def current_option(self) -> str: return self.device[self.entity_description.current_option_key] ``` ###Assistant : Return the selected entity option to represen...
147
def gen_html(img): html_code = img['html']['structure']['tokens'].copy() to_insert = [i for i, tag in enumerate(html_code) if tag in ('<td>', '>')] for i, cell in zip(to_insert[::-1], img['html']['cells'][::-1]): if cell['tokens']: text = ''.join(cell['tokens']) # skip e...
Formats HTML code from tokenized annotation of img
8
63
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def gen_html(img): html_code = img['html']['structure']['tokens'].copy() to_insert = [i for i, tag in enumerate(html_code) if tag in ('<td>', '>')] for i, cell in zip(to_ins...
148
def key_aliases(self) -> Iterable[str]: for alias in _get_key_aliases(self.key): yield _normalize_key(alias)
Get the aliases for the key, including the key itself
10
10
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def key_aliases(self) -> Iterable[str]: for alias in _get_key_aliases(self.key): yield _normalize_key(alias) ``` ###Assistant : Get the aliases for ...
149
def test_create_single_available_ip(self): vrf = VRF.objects.create(name='VRF 1') prefix = Prefix.objects.create(prefix=IPNetwork('192.0.2.0/30'), vrf=vrf, is_pool=True) url = reverse('ipam-api:prefix-available-ips', kwargs={'pk': prefix.pk}) self.add_permissions('ipam.view_pref...
Test retrieval of the first available IP address within a parent prefix.
12
69
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_create_single_available_ip(self): vrf = VRF.objects.create(name='VRF 1') prefix = Prefix.objects.create(prefix=IPNetwork('192.0.2.0/30'), vrf=vrf, is_pool=T...
150
def climate_adc_t3000_missing_setpoint_fixture(client, climate_adc_t3000_state): data = copy.deepcopy(climate_adc_t3000_state) data["name"] = f"{data['name']} missing setpoint" for value in data["values"][:]: if ( value["commandClassName"] == "Humidity Control Setpoint" ...
Mock a climate ADC-T3000 node with missing de-humidify setpoint.
9
38
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def climate_adc_t3000_missing_setpoint_fixture(client, climate_adc_t3000_state): data = copy.deepcopy(climate_adc_t3000_state) data["name"] = f"{data['name']} missing setpoint" ...
151
def classify_ode(eq, func=None, dict=False, ics=None, *, prep=True, xi=None, eta=None, n=None, **kwargs): r
Returns a tuple of possible :py:meth:`~sympy.solvers.ode.dsolve` classifications for an ODE. The tuple is ordered so that first item is the classification that :py:meth:`~sympy.solvers.ode.dsolve` uses to solve the ODE by default. In general, classifications at the near the beginning of the list ...
184
12
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def classify_ode(eq, func=None, dict=False, ics=None, *, prep=True, xi=None, eta=None, n=None, **kwargs): r ``` ###Assistant : Returns a tuple of possible :py:meth:`~sym...
152
def mode(a, axis=0, nan_policy='propagate'): a, axis = _chk_asarray(a, axis) if a.size == 0: return ModeResult(np.array([]), np.array([])) contains_nan, nan_policy = _contains_nan(a, nan_policy) if contains_nan and nan_policy == 'omit': a = ma.masked_invalid(a) return msta...
Return an array of the modal (most common) value in the passed array. If there is more than one such value, only the smallest is returned. The bin-count for the modal bins is also returned. Parameters ---------- a : array_like n-dimensional array of which to find mode(s). axis : int or...
183
108
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def mode(a, axis=0, nan_policy='propagate'): a, axis = _chk_asarray(a, axis) if a.size == 0: return ModeResult(np.array([]), np.array([])) contains_nan, nan_policy ...
153
def wait_for_instance(self) -> AnsibleCoreCI: core_ci = self.get_instance() core_ci.wait() return core_ci
Wait for an AnsibleCoreCI VM instance to become ready.
9
10
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def wait_for_instance(self) -> AnsibleCoreCI: core_ci = self.get_instance() core_ci.wait() return core_ci ``` ###Assistant : Wait for an Ansibl...
154
def spherical_bessel_fn(n, x=None, polys=False): if n < 0: dup = dup_spherical_bessel_fn_minus(-int(n), ZZ) else: dup = dup_spherical_bessel_fn(int(n), ZZ) poly = DMP(dup, ZZ) if x is not None: poly = Poly.new(poly, 1/x) else: poly = PurePoly.new(poly, 1/Dummy...
Coefficients for the spherical Bessel functions. Those are only needed in the jn() function. The coefficients are calculated from: fn(0, z) = 1/z fn(1, z) = 1/z**2 fn(n-1, z) + fn(n+1, z) == (2*n+1)/z * fn(n, z) Parameters ========== n : int `n` decides the degree of po...
107
41
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def spherical_bessel_fn(n, x=None, polys=False): if n < 0: dup = dup_spherical_bessel_fn_minus(-int(n), ZZ) else: dup = dup_spherical_bessel_fn(int(n), ZZ) ...
155
def raft_large(*, pretrained=False, progress=True, **kwargs): return _raft( arch="raft_large", pretrained=pretrained, progress=progress, # Feature encoder feature_encoder_layers=(64, 64, 96, 128, 256), feature_encoder_block=ResidualBlock, feature_encoder...
RAFT model from `RAFT: Recurrent All Pairs Field Transforms for Optical Flow <https://arxiv.org/abs/2003.12039>`_. Args: pretrained (bool): Whether to use weights that have been pre-trained on :class:`~torchvsion.datasets.FlyingChairs` + :class:`~torchvsion.datasets.FlyingThings3D` ...
68
65
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def raft_large(*, pretrained=False, progress=True, **kwargs): return _raft( arch="raft_large", pretrained=pretrained, progress=progress, # Feature e...
156
def _get_prettyprint_usage(self, console, executor_name, usage_kind=None): from rich.panel import Panel from rich.syntax import Syntax flow_plain = f flow_docker = f flow_sandbox = f panels = [ Panel( Syntax( p[0], ...
from jina import Flow f = Flow().add(uses='jinahub://{executor_name}') from jina import Flow f = Flow().add(uses='jinahub+docker://{executor_name}') from jina import Flow f = Flow().add(uses='jinahub+sandbox://{executor_name}')
21
66
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _get_prettyprint_usage(self, console, executor_name, usage_kind=None): from rich.panel import Panel from rich.syntax import Syntax flow_plain = f flow_d...
157
def encoding(self, val): self._encoding = val if hasattr(self, "GET"): del self.GET if hasattr(self, "_post"): del self._post
Set the encoding used for GET/POST accesses. If the GET or POST dictionary has already been created, remove and recreate it on the next access (so that it is decoded correctly).
31
16
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def encoding(self, val): self._encoding = val if hasattr(self, "GET"): del self.GET if hasattr(self, "_post"): del self._post ...
158
def scale(self, factor, scale_tips=False, **kwargs): r if self.get_length() == 0: return self if scale_tips: super().scale(factor, **kwargs) self._set_stroke_width_from_length() return self has_tip = self.has_tip() has_start_tip =...
Scale an arrow, but keep stroke width and arrow tip size fixed. See Also -------- :meth:`~.Mobject.scale` Examples -------- :: >>> arrow = Arrow(np.array([-1, -1, 0]), np.array([1, 1, 0]), buff=0) >>> scaled_arrow = arrow.scale(2) >>...
85
44
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def scale(self, factor, scale_tips=False, **kwargs): r if self.get_length() == 0: return self if scale_tips: super().scale(factor, **kwargs) ...
159
def effective(file, line, frame): possibles = Breakpoint.bplist[file, line] for b in possibles: if not b.enabled: continue if not checkfuncname(b, frame): continue # Count every hit when bp is enabled b.hits += 1 if not b.cond: # I...
Determine which breakpoint for this file:line is to be acted upon. Called only if we know there is a breakpoint at this location. Return the breakpoint that was triggered and a boolean that indicates if it is ok to delete a temporary breakpoint. Return (None, None) if there is no matching breakpoint....
52
151
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def effective(file, line, frame): possibles = Breakpoint.bplist[file, line] for b in possibles: if not b.enabled: continue if not checkfuncname(b, fr...
160
def _log_gauss_mass(a, b): a, b = jnp.array(a), jnp.array(b) a, b = jnp.broadcast_arrays(a, b) # Note: Docstring carried over from scipy # Calculations in right tail are inaccurate, so we'll exploit the # symmetry and work only in the left tail case_left = b <= 0 case_right = a > 0 case_central = ~(...
Log of Gaussian probability mass within an interval
8
172
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _log_gauss_mass(a, b): a, b = jnp.array(a), jnp.array(b) a, b = jnp.broadcast_arrays(a, b) # Note: Docstring carried over from scipy # Calculations in right tail are inaccura...
161
def test_fx_validator_integration(tmpdir): not_supported = { None: "`self.trainer` reference is not registered", "on_before_accelerator_backend_setup": "You can't", "setup": "You can't", "configure_sharded_model": "You can't", "on_configure_sharded_model": "You can't", ...
Tries to log inside all `LightningModule` and `Callback` hooks to check any expected errors.
14
249
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_fx_validator_integration(tmpdir): not_supported = { None: "`self.trainer` reference is not registered", "on_before_accelerator_backend_setup": "You can't", ...
162
def enable_application_mode() -> Callable[[], None]: terminal_in = sys.stdin terminal_out = sys.stdout current_console_mode_in = _get_console_mode(terminal_in) current_console_mode_out = _get_console_mode(terminal_out)
Enable application mode. Returns: Callable[[], None]: A callable that will restore terminal to previous state.
15
17
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def enable_application_mode() -> Callable[[], None]: terminal_in = sys.stdin terminal_out = sys.stdout current_console_mode_in = _get_console_mode(terminal_in) current...
163
def get_attributes(self) -> dict[str, str]: return _attributes( message=self.message, type=self.type, )
Return a dictionary of attributes for this instance.
8
10
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_attributes(self) -> dict[str, str]: return _attributes( message=self.message, type=self.type, ) ``` ###Assistant : Retur...
164
def check_handle_timedout(self) -> None: for trade in Trade.get_open_order_trades(): try: if not trade.open_order_id: continue order = self.exchange.fetch_order(trade.open_order_id, trade.pair) except (ExchangeError): ...
Check if any orders are timed out and cancel if necessary :param timeoutvalue: Number of minutes until order is considered timed out :return: None
24
125
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def check_handle_timedout(self) -> None: for trade in Trade.get_open_order_trades(): try: if not trade.open_order_id: contin...
165
def test_user_misery_denominator(self): ProjectTransactionThreshold.objects.create( project=self.project, organization=self.project.organization, threshold=600, metric=TransactionMetric.LCP.value, ) lcps = [ 400, 40...
This is to test against a bug where the denominator of misery(total unique users) was wrong This is because the total unique users for a LCP misery should only count users that have had a txn with lcp, and not count all transactions (ie. uniq_if(transaction has lcp) not just uniq())
50
119
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_user_misery_denominator(self): ProjectTransactionThreshold.objects.create( project=self.project, organization=self.project.organization, ...
166
def _determine_base_url(document, page_url): # type: (HTMLElement, str) -> str for base in document.findall(".//base"): href = base.get("href") if href is not None: return href return page_url
Determine the HTML document's base URL. This looks for a ``<base>`` tag in the HTML document. If present, its href attribute denotes the base URL of anchor tags in the document. If there is no such tag (or if it does not have a valid href attribute), the HTML file's URL is used as the base URL. :p...
79
25
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _determine_base_url(document, page_url): # type: (HTMLElement, str) -> str for base in document.findall(".//base"): href = base.get("href") if href is not No...
167
def pairwise_distances(self, U, V): return self._distance_block.eval(feed_dict={self._features_batch1: U, self._features_batch2: V}) #----------------------------------------------------------------------------
Evaluate pairwise distances between two batches of feature vectors.
9
10
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def pairwise_distances(self, U, V): return self._distance_block.eval(feed_dict={self._features_batch1: U, self._features_batch2: V}) #--------------------------------------...
168
def upgrade(): op.create_table( 'project', sa.Column('id', sa.Integer(), nullable=False), sa.Column('created_at', sa.DateTime(), nullable=True), sa.Column('updated_at', sa.DateTime(), nullable=True), sa.Column('deleted_at', sa.DateTime(), nullable=True), sa.Column('na...
update predictor set project_id = :project_id update view set project_id = :project_id select id, name from view where exists (select 1 from predictor where view.name = predictor.name) update view set name = :name where id =...
37
110
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def upgrade(): op.create_table( 'project', sa.Column('id', sa.Integer(), nullable=False), sa.Column('created_at', sa.DateTime(), nullable=True), sa.Column...
169
def clear(self) -> None: self._patterns: List[PatternType] = [] self.matcher: Matcher = Matcher(self.nlp.vocab, validate=self.validate) self.phrase_matcher: PhraseMatcher = PhraseMatcher( self.nlp.vocab, attr=self.phrase_matcher_attr, validate=self.va...
Reset all patterns. RETURNS: None DOCS: https://spacy.io/api/spanruler#clear
7
21
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def clear(self) -> None: self._patterns: List[PatternType] = [] self.matcher: Matcher = Matcher(self.nlp.vocab, validate=self.validate) self.phrase_matcher: ...
170
def _from_module(self, module, object): if module is None: return True elif inspect.getmodule(object) is not None: return module is inspect.getmodule(object) elif inspect.isfunction(object): return module.__dict__ is object.__globals__ elif in...
Return true if the given object is defined in the given module.
12
88
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _from_module(self, module, object): if module is None: return True elif inspect.getmodule(object) is not None: return module is inspect.g...
171
def cut_ansi_string_into_parts(string_with_ansi_codes): color_codes_english = ['Black', 'Red', 'Green', 'Yellow', 'Blue', 'Magenta', 'Cyan', 'White', 'Reset'] color_codes = ["30m", "31m", "32m", "33m", "34m", "35m", "36m", "37m", "0m"] effect_codes_english = ['Italic', 'Underline', 'Slow Blink', 'Rapid...
Converts a string with ambedded ANSI Color Codes and parses it to create a list of tuples describing pieces of the input string. :param string_with_ansi_codes: :return: [(sty, str, str, str), ...] A list of tuples. Each tuple has format: (text, text color, background color, effects)
45
258
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def cut_ansi_string_into_parts(string_with_ansi_codes): color_codes_english = ['Black', 'Red', 'Green', 'Yellow', 'Blue', 'Magenta', 'Cyan', 'White', 'Reset'] color_codes = ["30...
172
def interpolate(self, f=None, f_step=DEFAULT_STEP, pol_order=1, f_min=DEFAULT_F_MIN, f_max=DEFAULT_F_MAX): # Remove None values i = 0 while i < len(self.raw): if self.raw[i] is None: self.raw = np.delete(self.raw, i) self.frequency = np.delete...
Interpolates missing values from previous and next value. Resets all but raw data.
13
147
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def interpolate(self, f=None, f_step=DEFAULT_STEP, pol_order=1, f_min=DEFAULT_F_MIN, f_max=DEFAULT_F_MAX): # Remove None values i = 0 while i < len(self.raw)...
173
def step(self, closure=None): loss = None if closure is not None: with torch.enable_grad(): loss = closure() device = self.param_groups[0]['params'][0].device one_tensor = torch.tensor(1.0, device=device) # because torch.where doesn't handle scalars...
Performs a single optimization step. Args: closure (callable, optional): A closure that reevaluates the model and returns the loss.
19
182
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def step(self, closure=None): loss = None if closure is not None: with torch.enable_grad(): loss = closure() device = self.param...
174
async def _async_force_resync(self, *_): self._forced_resync = None await self._async_force_refresh_state()
Force a resync after an update since the hub may have stale state.
13
9
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python async def _async_force_resync(self, *_): self._forced_resync = None await self._async_force_refresh_state() ``` ###Assistant : Force a resync after an u...
175
def set_color_codes(palette="deep"): if palette == "reset": colors = [ (0., 0., 1.), (0., .5, 0.), (1., 0., 0.), (.75, 0., .75), (.75, .75, 0.), (0., .75, .75), (0., 0., 0.) ] elif not isinstance(palette, st...
Change how matplotlib color shorthands are interpreted. Calling this will change how shorthand codes like "b" or "g" are interpreted by matplotlib in subsequent plots. Parameters ---------- palette : {deep, muted, pastel, dark, bright, colorblind} Named seaborn palette to use as the source...
78
90
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def set_color_codes(palette="deep"): if palette == "reset": colors = [ (0., 0., 1.), (0., .5, 0.), (1., 0., 0.), (.75, 0., .7...
176
def test_mapped_literal_length_increase_at_runtime_adds_additional_tis(dag_maker, session): from airflow.models import Variable Variable.set(key='arg1', value=[1, 2, 3])
Test that when the length of mapped literal increases at runtime, additional ti is added
15
11
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_mapped_literal_length_increase_at_runtime_adds_additional_tis(dag_maker, session): from airflow.models import Variable Variable.set(key='arg1', value=[1, 2, 3]) ...
177
def create_png_thumbnail_file(self, thumb_dir): thumb_file = Path(thumb_dir) / Path(f"{self.doc.pk:07}.png") thumb_file.write_text("this is a dummy png file") return thumb_file
Creates a dummy PNG thumbnail file in the given directory, based on the database Document
15
16
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def create_png_thumbnail_file(self, thumb_dir): thumb_file = Path(thumb_dir) / Path(f"{self.doc.pk:07}.png") thumb_file.write_text("this is a dummy png file") ...
178
def test_parse_html(self): assert validate(parse_html(), '<!DOCTYPE html><body>&quot;perfectly&quot;<a>valid<div>HTML').tag == "html" with self.assertRaises(ValueError) as cm: validate(parse_html(), None) assert_validationerror(cm.exception, )
ValidationError: Unable to parse HTML: can only parse strings (None)
10
16
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_parse_html(self): assert validate(parse_html(), '<!DOCTYPE html><body>&quot;perfectly&quot;<a>valid<div>HTML').tag == "html" with self.assertRaises(ValueError) as cm...
179
def _check_feature_names_in(estimator, input_features=None, *, generate_names=True): feature_names_in_ = getattr(estimator, "feature_names_in_", None) n_features_in_ = getattr(estimator, "n_features_in_", None) if input_features is not None: input_features = np.asarray(input_features, dtype=o...
Check `input_features` and generate names if needed. Commonly used in :term:`get_feature_names_out`. Parameters ---------- input_features : array-like of str or None, default=None Input features. - If `input_features` is `None`, then `feature_names_in_` is used as feature ...
110
107
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _check_feature_names_in(estimator, input_features=None, *, generate_names=True): feature_names_in_ = getattr(estimator, "feature_names_in_", None) n_features_in_ = getattr(...
180
def all_pairs_bellman_ford_path(G, weight="weight"): path = single_source_bellman_ford_path # TODO This can be trivially parallelized. for n in G: yield (n, path(G, n, weight=weight))
Compute shortest paths between all nodes in a weighted graph. Parameters ---------- G : NetworkX graph weight : string or function (default="weight") If this is a string, then edge weights will be accessed via the edge attribute with this key (that is, the weight of the edge jo...
170
22
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def all_pairs_bellman_ford_path(G, weight="weight"): path = single_source_bellman_ford_path # TODO This can be trivially parallelized. for n in G: yield (n, path(G, ...
181
def update_cost_in_all_boms_in_test(): log = enqueue_update_cost() # create BOM Update Log while log.status != "Completed": resume_bom_cost_update_jobs() # run cron job until complete log.reload() return log
Utility to run 'Update Cost' job in tests without Cron job until fully complete.
14
24
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def update_cost_in_all_boms_in_test(): log = enqueue_update_cost() # create BOM Update Log while log.status != "Completed": resume_bom_cost_update_jobs() # run cron job until comple...
182
def clear(self) -> None: self.row_count = 0 self._clear_caches() self._y_offsets.clear() self.data.clear() self.rows.clear() self._line_no = 0 self._require_update_dimensions = True self.refresh()
Clear the table. Args: columns (bool, optional): Also clear the columns. Defaults to False.
14
18
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def clear(self) -> None: self.row_count = 0 self._clear_caches() self._y_offsets.clear() self.data.clear() self.rows.clear() self._li...
183
def copyFile(source_path, dest_path): while 1: try: shutil.copyfile(source_path, dest_path) except PermissionError as e: if e.errno != errno.EACCES: raise general.warning("Problem copying file %s:" % e) try: repl...
Improved version of shutil.copy This handles errors with a chance to correct them, e.g. on Windows, files might be locked by running program or virus checkers.
26
43
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def copyFile(source_path, dest_path): while 1: try: shutil.copyfile(source_path, dest_path) except PermissionError as e: if e.errno != errno...
184
def test_iforest(global_random_seed): X_train = np.array([[0, 1], [1, 2]]) X_test = np.array([[2, 1], [1, 1]]) grid = ParameterGrid( {"n_estimators": [3], "max_samples": [0.5, 1.0, 3], "bootstrap": [True, False]} ) with ignore_warnings(): for params in grid: Isolat...
Check Isolation Forest for various parameter settings.
7
37
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_iforest(global_random_seed): X_train = np.array([[0, 1], [1, 2]]) X_test = np.array([[2, 1], [1, 1]]) grid = ParameterGrid( {"n_estimators": [3], "max_samp...
185
def invalidate_caches(self): _register(MetaPathFinder, machinery.BuiltinImporter, machinery.FrozenImporter, machinery.PathFinder, machinery.WindowsRegistryFinder)
An optional method for clearing the finder's cache, if any. This method is used by importlib.invalidate_caches().
16
7
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def invalidate_caches(self): _register(MetaPathFinder, machinery.BuiltinImporter, machinery.FrozenImporter, machinery.PathFinder, machinery.WindowsRegistryFinder) ...
186
def reap(instance=None, status='failed', excluded_uuids=[]): me = instance if me is None: try: me = Instance.objects.me() except RuntimeError as e: logger.warning(f'Local instance is not registered, not running reaper: {e}') return workflow_ctype_id =...
Reap all jobs in running for this instance.
8
49
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def reap(instance=None, status='failed', excluded_uuids=[]): me = instance if me is None: try: me = Instance.objects.me() except RuntimeError as e: ...
187
def closure(self, rel, depth=-1): from nltk.util import acyclic_breadth_first for synset in acyclic_breadth_first(self, rel, depth): if synset != self: yield synset from nltk.util import acyclic_depth_first as acyclic_tree from nltk.util import unweighted_...
Return the transitive closure of source under the rel relationship, breadth-first, discarding cycles: >>> from nltk.corpus import wordnet as wn >>> computer = wn.synset('computer.n.01') >>> topic = lambda s:s.topic_domains() >>> print(list(computer.closure(topic))) ...
88
44
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def closure(self, rel, depth=-1): from nltk.util import acyclic_breadth_first for synset in acyclic_breadth_first(self, rel, depth): if synset != self:...
188
def _get_save_args(self) -> Tuple[int, ...]: filetype = self.config["format"] args: Tuple[int, ...] = tuple() if filetype == "jpg" and self.config["jpg_quality"] > 0: args = (cv2.IMWRITE_JPEG_QUALITY, # pylint: disable=no-member self.config["jpg_quality"...
Obtain the save parameters for the file format. Returns ------- tuple The OpenCV specific arguments for the selected file format
20
46
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _get_save_args(self) -> Tuple[int, ...]: filetype = self.config["format"] args: Tuple[int, ...] = tuple() if filetype == "jpg" and self.config["jpg_quali...
189
def set_constrained_layout_pads(self, **kwargs): if isinstance(self.get_layout_engine(), ConstrainedLayoutEngine): self.get_layout_engine().set(**kwargs)
Set padding for ``constrained_layout``. Tip: The parameters can be passed from a dictionary by using ``fig.set_constrained_layout(**pad_dict)``. See :doc:`/tutorials/intermediate/constrainedlayout_guide`. Parameters ---------- w_pad : float, default: :rc:`figu...
122
7
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def set_constrained_layout_pads(self, **kwargs): if isinstance(self.get_layout_engine(), ConstrainedLayoutEngine): self.get_layout_engine().set(**kwargs) ...
190
def track_current_candle(self): if self.dd.current_candle > self.current_candle: self.get_corr_dataframes = True self.pair_it = 0 self.current_candle = self.dd.current_candle # Following methods which are overridden by user made prediction models. # See freq...
Checks if the latest candle appended by the datadrawer is equivalent to the latest candle seen by FreqAI. If not, it asks to refresh the cached corr_dfs, and resets the pair counter.
32
32
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def track_current_candle(self): if self.dd.current_candle > self.current_candle: self.get_corr_dataframes = True self.pair_it = 0 self.cu...
191
def find(self, req): dist = self.by_key.get(req.key) if dist is not None and dist not in req: # XXX add more info raise VersionConflict(dist, req) return dist
Find a distribution matching requirement `req` If there is an active distribution for the requested project, this returns it as long as it meets the version requirement specified by `req`. But, if there is an active distribution for the project and it does *not* meet the `req` requirem...
64
26
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def find(self, req): dist = self.by_key.get(req.key) if dist is not None and dist not in req: # XXX add more info raise VersionConflict(dist,...
192
def current() -> dict | None: try: ContextStack.top(_FROZEN_CONTEXT_KEY) sample: Sample = {} for ctx in ContextStack.stack(_FROZEN_CONTEXT_KEY): if not isinstance(ctx, dict): raise TypeError(f'Expect architecture to be a dict, foun...
Retrieve the current frozen context. If multiple layers have been found, they would be merged from bottom to top. Returns ------- The sample in frozen context. If no sample is found, return none.
33
36
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def current() -> dict | None: try: ContextStack.top(_FROZEN_CONTEXT_KEY) sample: Sample = {} for ctx in ContextStack.stack(_FROZEN_CONTEX...
193
def test_rept_child() -> None: rows = 10_000 cols = 7 rept_row_count = 5 # these times and sizes are based on the above constants # and Madhavas MacBook Pro 2019 expected_rept_mem_size = 4.010650634765625 expected_rept_ser_size = 7.4926300048828125 macbook_pro_2019_ser_time = 0.187...
We need to benchmark both the size and time to serialize and deserialize REPTs
14
230
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_rept_child() -> None: rows = 10_000 cols = 7 rept_row_count = 5 # these times and sizes are based on the above constants # and Madhavas MacBook Pro 2019 ...
194
def _ecm_one_factor(n, B1=10000, B2=100000, max_curve=200): n = as_int(n) if B1 % 2 != 0 or B2 % 2 != 0: raise ValueError("The Bounds should be an even integer") sieve.extend(B2) if isprime(n): return n from sympy.functions.elementary.miscellaneous import sqrt from sympy.p...
Returns one factor of n using Lenstra's 2 Stage Elliptic curve Factorization with Suyama's Parameterization. Here Montgomery arithmetic is used for fast computation of addition and doubling of points in elliptic curve. This ECM method considers elliptic curves in Montgomery form (E : b*y**2*z =...
303
319
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _ecm_one_factor(n, B1=10000, B2=100000, max_curve=200): n = as_int(n) if B1 % 2 != 0 or B2 % 2 != 0: raise ValueError("The Bounds should be an even integer") sie...
195
async def test_unique_id(hass): await setup_test_entity( hass, { "unique": { "command_open": "echo open", "command_close": "echo close", "command_stop": "echo stop", "unique_id": "unique", }, "no...
Test unique_id option and if it only creates one cover per id.
12
78
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python async def test_unique_id(hass): await setup_test_entity( hass, { "unique": { "command_open": "echo open", "command_close"...
196
def mock_ssl_context(): with patch( "homeassistant.components.mqtt.config_flow.SSLContext" ) as mock_context, patch( "homeassistant.components.mqtt.config_flow.load_pem_private_key" ) as mock_key_check, patch( "homeassistant.components.mqtt.config_flow.load_pem_x509_certificate"...
Mock the SSL context used to load the cert chain and to load verify locations.
15
28
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def mock_ssl_context(): with patch( "homeassistant.components.mqtt.config_flow.SSLContext" ) as mock_context, patch( "homeassistant.components.mqtt.config_flow.l...
197
def test_task_states_for_dag_run_when_dag_run_not_exists(self): with pytest.raises(DagRunNotFound): default_date2 = timezone.datetime(2016, 1, 9) task_command.task_states_for_dag_run( self.parser.parse_args( [ 'tasks', ...
task_states_for_dag_run should return an AirflowException when invalid dag id is passed
11
21
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_task_states_for_dag_run_when_dag_run_not_exists(self): with pytest.raises(DagRunNotFound): default_date2 = timezone.datetime(2016, 1, 9) tas...
198
def test_title_present(self): response = self.get(4) self.assertContains(response, "Christmas", 3)
The page title should appear three times. Once in the header, and two times in the field listing (as the actual title and as the draft title)
27
8
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_title_present(self): response = self.get(4) self.assertContains(response, "Christmas", 3) ``` ###Assistant : The page title should app...
199
def _set_position(self, pos, which='both'): if not isinstance(pos, mtransforms.BboxBase): pos = mtransforms.Bbox.from_bounds(*pos) for ax in self._twinned_axes.get_siblings(self): if which in ('both', 'active'): ax._position.set(pos) if which ...
Private version of set_position. Call this internally to get the same functionality of `set_position`, but not to take the axis out of the constrained_layout hierarchy.
25
30
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _set_position(self, pos, which='both'): if not isinstance(pos, mtransforms.BboxBase): pos = mtransforms.Bbox.from_bounds(*pos) for ax in self._twinne...