Dataset Viewer
Auto-converted to Parquet Duplicate
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
0
def rolling(self, *args, **kwargs) -> RollingGroupby: from pandas.core.window import RollingGroupby return RollingGroupby( self._selected_obj, *args, _grouper=self.grouper, _as_index=self.as_index, **kwargs, )
Return a rolling grouper, providing rolling functionality per group.
9
18
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def rolling(self, *args, **kwargs) -> RollingGroupby: from pandas.core.window import RollingGroupby return RollingGroupby( self._selected_obj, ...
1
def expected_degree_graph(w, seed=None, selfloops=True): r n = len(w) G = nx.empty_graph(n) # If there are no nodes are no edges in the graph, return the empty graph. if n == 0 or max(w) == 0: return G rho = 1 / sum(w) # Sort the weights in decreasing order. The original order of t...
Returns a random graph with given expected degrees. Given a sequence of expected degrees $W=(w_0,w_1,\ldots,w_{n-1})$ of length $n$ this algorithm assigns an edge between node $u$ and node $v$ with probability .. math:: p_{uv} = \frac{w_u w_v}{\sum_k w_k} . Parameters ---------- w...
298
179
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def expected_degree_graph(w, seed=None, selfloops=True): r n = len(w) G = nx.empty_graph(n) # If there are no nodes are no edges in the graph, return the empty graph. if...
2
def save(self, path): os.makedirs(path, exist_ok=True) with open(os.path.join(path, "metrics.json"), "w") as fp: json.dump(self.metrics, fp) artifacts_metadata = { artifact_name: { "uri": artifact.uri, "class_name": _get_fully_qua...
Write the evaluation results to the specified local filesystem path
10
49
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def save(self, path): os.makedirs(path, exist_ok=True) with open(os.path.join(path, "metrics.json"), "w") as fp: json.dump(self.metrics, fp) art...
3
def test_build_group_generic_issue_attachment(self): event = self.store_event( data={"message": "Hello world", "level": "error"}, project_id=self.project.id ) event = event.for_group(event.groups[0]) occurrence = self.build_occurrence(level="info") occurrence...
Test that a generic issue type's Slack alert contains the expected values
12
51
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_build_group_generic_issue_attachment(self): event = self.store_event( data={"message": "Hello world", "level": "error"}, project_id=self.project.id ...
4
def apply(self, func, mask=None) -> 'ImageProcessor': img = orig_img = self._img img = func(img).astype(orig_img.dtype) if img.ndim != 4: raise Exception('func used in ImageProcessor.apply changed format of image') if mask is not None: mask = self._check...
apply your own function on internal image image has NHWC format. Do not change format, but dims can be changed. func callable (img) -> img example: .apply( lambda img: img-[102,127,63] )
31
45
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def apply(self, func, mask=None) -> 'ImageProcessor': img = orig_img = self._img img = func(img).astype(orig_img.dtype) if img.ndim != 4: raise E...
5
def predict(self, x): # start the timer self.timer.start() v_, _ = self.eval_out() # evaluate the ratings and the associated probabilities vp = self.sess.run(v_, feed_dict={self.vu: x}) # stop the timer self.timer.stop() log.info("Done infere...
Returns the inferred ratings. This method is similar to recommend_k_items() with the exceptions that it returns all the inferred ratings Basic mechanics: The method samples new ratings from the learned joint distribution, together with their probabilities. The input x must have the sam...
108
38
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def predict(self, x): # start the timer self.timer.start() v_, _ = self.eval_out() # evaluate the ratings and the associated probabilities vp = se...
6
def raw_decode(self, s, idx=0): try: obj, end = self.scan_once(s, idx) except StopIteration as err: raise JSONDecodeError("Expecting value", s, err.value) from None return obj, end
Decode a JSON document from ``s`` (a ``str`` beginning with a JSON document) and return a 2-tuple of the Python representation and the index in ``s`` where the document ended. This can be used to decode a JSON document from a string that may have extraneous data at the end.
50
24
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def raw_decode(self, s, idx=0): try: obj, end = self.scan_once(s, idx) except StopIteration as err: raise JSONDecodeError("Expecting value", ...
7
def has_bridges(G, root=None): try: next(bridges(G)) except StopIteration: return False else: return True @not_implemented_for("multigraph") @not_implemented_for("directed")
Decide whether a graph has any bridges. A *bridge* in a graph is an edge whose removal causes the number of connected components of the graph to increase. Parameters ---------- G : undirected graph root : node (optional) A node in the graph `G`. If specified, only the bridges in the ...
167
14
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def has_bridges(G, root=None): try: next(bridges(G)) except StopIteration: return False else: return True @not_implemented_for("multigraph") @not_i...
8
def wheel_metadata(source, dist_info_dir): # type: (ZipFile, str) -> Message path = f"{dist_info_dir}/WHEEL" # Zip file path separators must be / wheel_contents = read_wheel_metadata_file(source, path) try: wheel_text = wheel_contents.decode() except UnicodeDecodeError as e: ...
Return the WHEEL metadata of an extracted wheel, if possible. Otherwise, raise UnsupportedWheel.
13
65
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def wheel_metadata(source, dist_info_dir): # type: (ZipFile, str) -> Message path = f"{dist_info_dir}/WHEEL" # Zip file path separators must be / wheel_contents = read_w...
9
def remove_column(self, i, *args, **kwargs): table = self.table.remove_column(i, *args, **kwargs) name = self.table.column_names[i] blocks = [] for tables in self.blocks: blocks.append( [ t.remove_column(t.column_names.index(name),...
Create new Table with the indicated column removed. Args: i (:obj:`int`): Index of column to remove. Returns: :class:`datasets.table.Table`: New table without the column.
23
40
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def remove_column(self, i, *args, **kwargs): table = self.table.remove_column(i, *args, **kwargs) name = self.table.column_names[i] blocks = [] for t...
10
def test_cable_cannot_terminate_to_a_wireless_interface(self): wireless_interface = Interface(device=self.device1, name="W1", type=InterfaceTypeChoices.TYPE_80211A) cable = Cable(a_terminations=[self.interface2], b_terminations=[wireless_interface]) with self.assertRaises(ValidationErro...
A cable cannot terminate to a wireless interface
8
14
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_cable_cannot_terminate_to_a_wireless_interface(self): wireless_interface = Interface(device=self.device1, name="W1", type=InterfaceTypeChoices.TYPE_80211A) ...
11
def get_test_db_clone_settings(self, suffix): # When this function is called, the test database has been created # already and its name has been copied to settings_dict['NAME'] so # we don't need to call _get_test_db_name. orig_settings_dict = self.connection.settings_dict ...
Return a modified connection settings dict for the n-th clone of a DB.
13
43
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_test_db_clone_settings(self, suffix): # When this function is called, the test database has been created # already and its name has been copied to settings_d...
12
def open(self, host='', port=IMAP4_PORT, timeout=None): self.host = host self.port = port self.sock = self._create_socket(timeout) self.file = self.sock.makefile('rb')
Setup connection to remote server on "host:port" (default: localhost:standard IMAP4 port). This connection will be used by the routines: read, readline, send, shutdown.
23
17
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def open(self, host='', port=IMAP4_PORT, timeout=None): self.host = host self.port = port self.sock = self._create_socket(timeout) self.file = self.s...
13
def synchronized_output_end_sequence(self) -> str: if self.synchronised_output: return TERMINAL_MODES_ANSI_SEQUENCES[Mode.SynchronizedOutput]["end_sync"] return ""
Returns the ANSI sequence that we should send to the terminal to tell it that it should stop buffering the content we're about to send. If the terminal doesn't seem to support synchronised updates the string will be empty. Returns: str: the "synchronised output stop" ANSI s...
65
10
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def synchronized_output_end_sequence(self) -> str: if self.synchronised_output: return TERMINAL_MODES_ANSI_SEQUENCES[Mode.SynchronizedOutput]["end_sync"] ...
14
def _band_penalty_coefficients(self, fc, q, gain, filter_frs): ref_frs = biquad.digital_coeffs(self.frequency, 192e3, *biquad.peaking(fc, q, gain, fs=192e3)) est_sums = np.sum(filter_frs, axis=1) ref_sums = np.sum(ref_frs, axis=1) penalties = np.zeros((len(fc),)) mask = ...
Calculates penalty coefficients for filters if their transition bands extend beyond Nyquist frequency The calculation is based on ratio of frequency response integrals between 44.1 kHz and 192 kHz Args: fc: Filter center frequencies, 1-D array q: Filter qualities, 1-D array ...
65
42
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _band_penalty_coefficients(self, fc, q, gain, filter_frs): ref_frs = biquad.digital_coeffs(self.frequency, 192e3, *biquad.peaking(fc, q, gain, fs=192e3)) est_sum...
15
def test_predict_on_toy_problem(global_random_seed): clf1 = LogisticRegression(random_state=global_random_seed) clf2 = RandomForestClassifier(n_estimators=10, random_state=global_random_seed) clf3 = GaussianNB() X = np.array( [[-1.1, -1.5], [-1.2, -1.4], [-3.4, -2.2], [1.1, 1.2], [2.1, 1.4...
Manually check predicted class labels for toy dataset.
8
104
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_predict_on_toy_problem(global_random_seed): clf1 = LogisticRegression(random_state=global_random_seed) clf2 = RandomForestClassifier(n_estimators=10, random_state=globa...
16
def fit_transform(self, X, y=None): self._validate_params() return self._transform(X, fitting=True)
Learn a list of feature name -> indices mappings and transform X. Like fit(X) followed by transform(X), but does not require materializing X in memory. Parameters ---------- X : Mapping or iterable over Mappings Dict(s) or Mapping(s) from feature names (arbitrary Py...
78
8
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def fit_transform(self, X, y=None): self._validate_params() return self._transform(X, fitting=True) ``` ###Assistant : Learn a list of feature name -> i...
17
def _on_feature_permission_requested(self, url, feature): page = self._widget.page() grant_permission = functools.partial( page.setFeaturePermission, url, feature, QWebEnginePage.PermissionPolicy.PermissionGrantedByUser) deny_permission = functools.partial( ...
Ask the user for approval for geolocation/media/etc..
7
125
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _on_feature_permission_requested(self, url, feature): page = self._widget.page() grant_permission = functools.partial( page.setFeaturePermission, url...
18
def add_find_python(self): start = 402 for ver in self.versions: install_path = r"SOFTWARE\Python\PythonCore\%s\InstallPath" % ver machine_reg = "python.machine." + ver user_reg = "python.user." + ver machine_prop = "PYTHON.MACHINE." + ver ...
Adds code to the installer to compute the location of Python. Properties PYTHON.MACHINE.X.Y and PYTHON.USER.X.Y will be set from the registry for each version of Python. Properties TARGETDIRX.Y will be set from PYTHON.USER.X.Y if defined, else from PYTHON.MACHINE.X.Y. Properti...
45
167
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def add_find_python(self): start = 402 for ver in self.versions: install_path = r"SOFTWARE\Python\PythonCore\%s\InstallPath" % ver machine_r...
19
def write_exports(self, exports): rf = self.get_distinfo_file(EXPORTS_FILENAME) with open(rf, 'w') as f: write_exports(exports, f)
Write a dictionary of exports to a file in .ini format. :param exports: A dictionary of exports, mapping an export category to a list of :class:`ExportEntry` instances describing the individual export entries.
32
13
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def write_exports(self, exports): rf = self.get_distinfo_file(EXPORTS_FILENAME) with open(rf, 'w') as f: write_exports(exports, f) ``` ###As...
20
def _get_action_handler_with_module_context(self, connection, templar): module_collection, separator, module_name = self._task.action.rpartition(".") module_prefix = module_name.split('_')[0] if module_collection: # For network modules, which look for one action plugin per p...
Returns the correct action plugin to handle the requestion task action and the module context
15
191
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _get_action_handler_with_module_context(self, connection, templar): module_collection, separator, module_name = self._task.action.rpartition(".") module_prefix =...
21
def forward(self, y_hat, y, length): mask = sequence_mask(sequence_length=length, max_len=y.size(1)).unsqueeze(2) y_norm = sample_wise_min_max(y, mask) y_hat_norm = sample_wise_min_max(y_hat, mask) ssim_loss = self.loss_func((y_norm * mask).unsqueeze(1), (y_hat_norm * mask).unsq...
Args: y_hat (tensor): model prediction values. y (tensor): target values. length (tensor): length of each sample in a batch for masking. Shapes: y_hat: B x T X D y: B x T x D length: B Returns: loss: An avera...
50
61
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def forward(self, y_hat, y, length): mask = sequence_mask(sequence_length=length, max_len=y.size(1)).unsqueeze(2) y_norm = sample_wise_min_max(y, mask) y_hat...
22
def get_commands(): commands = {name: 'django.core' for name in find_commands(__path__[0])} if not settings.configured: return commands for app_config in reversed(apps.get_app_configs()): path = os.path.join(app_config.path, 'management') commands.update({name: app_config.name...
Return a dictionary mapping command names to their callback applications. Look for a management.commands package in django.core, and in each installed application -- if a commands package exists, register all commands in that package. Core commands are always included. If a settings module has be...
115
31
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_commands(): commands = {name: 'django.core' for name in find_commands(__path__[0])} if not settings.configured: return commands for app_config in reversed(...
23
def getphraselist(self): plist = [] while self.pos < len(self.field): if self.field[self.pos] in self.FWS: self.pos += 1 elif self.field[self.pos] == '"': plist.append(self.getquote()) elif self.field[self.pos] == '(': ...
Parse a sequence of RFC 2822 phrases. A phrase is a sequence of words, which are in turn either RFC 2822 atoms or quoted-strings. Phrases are canonicalized by squeezing all runs of continuous whitespace into one space.
37
35
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def getphraselist(self): plist = [] while self.pos < len(self.field): if self.field[self.pos] in self.FWS: self.pos += 1 eli...
24
def set_location(self, location): # This puts the rectangle into figure-relative coordinates. if isinstance(location, str): _api.check_in_list(self._locstrings, location=location) self._pos = 1. if location in ('top', 'right') else 0. elif isinstance(location, n...
Set the vertical or horizontal location of the axes in parent-normalized coordinates. Parameters ---------- location : {'top', 'bottom', 'left', 'right'} or float The position to put the secondary axis. Strings can be 'top' or 'bottom' for orientation='...
71
142
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def set_location(self, location): # This puts the rectangle into figure-relative coordinates. if isinstance(location, str): _api.check_in_list(self._loc...
25
def length(self): if self._length_cache is None: if len(self.call_queue): self.drain_call_queue() else: self._length_cache, self._width_cache = _get_index_and_columns.remote( self.oid ) if isinstance(sel...
Get the length of the object wrapped by this partition. Returns ------- int The length of the object.
18
24
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def length(self): if self._length_cache is None: if len(self.call_queue): self.drain_call_queue() else: self._length_...
26
def dmp_l2_norm_squared(f, u, K): if not u: return dup_l2_norm_squared(f, K) v = u - 1 return sum([ dmp_l2_norm_squared(c, v, K) for c in f ])
Returns squared l2 norm of a polynomial in ``K[X]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y = ring("x,y", ZZ) >>> R.dmp_l2_norm_squared(2*x*y - x - 3) 14
30
25
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def dmp_l2_norm_squared(f, u, K): if not u: return dup_l2_norm_squared(f, K) v = u - 1 return sum([ dmp_l2_norm_squared(c, v, K) for c in f ]) ``` ##...
27
def cloud_filter(args, targets): # type: (IntegrationConfig, t.Tuple[IntegrationTarget, ...]) -> t.List[str] if args.metadata.cloud_config is not None: return [] # cloud filter already performed prior to delegation exclude = [] # type: t.List[str] for provider in get_cloud_providers(args, ...
Return a list of target names to exclude based on the given targets.
13
40
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def cloud_filter(args, targets): # type: (IntegrationConfig, t.Tuple[IntegrationTarget, ...]) -> t.List[str] if args.metadata.cloud_config is not None: return [] # cloud f...
28
def test_upgrade_available_none(): chk_upgrade_out = ( "Last metadata expiration check: 22:5:48 ago on Mon Dec 6 19:26:36 EST 2021." ) dnf_call = MagicMock(return_value={"retcode": 100, "stdout": chk_upgrade_out}) version_mock = MagicMock(return_value="6.6-2") with patch("pathlib.Pat...
test upgrade available where a valid upgrade is not available
10
64
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_upgrade_available_none(): chk_upgrade_out = ( "Last metadata expiration check: 22:5:48 ago on Mon Dec 6 19:26:36 EST 2021." ) dnf_call = MagicMock(return...
29
def test_too_many_boosted_releases_do_not_boost_anymore(self): release_2 = Release.get_or_create(self.project, "2.0") release_3 = Release.get_or_create(self.project, "3.0") for release_id in (self.release.id, release_2.id): self.redis_client.set(f"ds::p:{self.project.id}:r:...
This test tests the case when we have already too many boosted releases, in this case we want to skip the boosting of anymore releases
25
56
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_too_many_boosted_releases_do_not_boost_anymore(self): release_2 = Release.get_or_create(self.project, "2.0") release_3 = Release.get_or_create(self.project,...
30
def hits(G, max_iter=100, tol=1.0e-8, nstart=None, normalized=True): import numpy as np import scipy as sp import scipy.sparse.linalg # call as sp.sparse.linalg if len(G) == 0: return {}, {} A = nx.adjacency_matrix(G, nodelist=list(G), dtype=float) if nstart is None: u, s...
Returns HITS hubs and authorities values for nodes. The HITS algorithm computes two numbers for a node. Authorities estimates the node value based on the incoming links. Hubs estimates the node value based on outgoing links. Parameters ---------- G : graph A NetworkX graph max_iter ...
248
90
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def hits(G, max_iter=100, tol=1.0e-8, nstart=None, normalized=True): import numpy as np import scipy as sp import scipy.sparse.linalg # call as sp.sparse.linalg if len...
31
def test_connection(self) -> Tuple[bool, str]: try: conn = self.get_conn() conn.pwd return True, "Connection successfully tested" except Exception as e: return False, str(e)
Test the FTP connection by calling path with directory
9
22
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_connection(self) -> Tuple[bool, str]: try: conn = self.get_conn() conn.pwd return True, "Connection successfully tested" ...
32
def call_price(self, other_args): parser = argparse.ArgumentParser( add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, prog="price", description=, ) parser.add_argument( "-s", "--symbol", ...
Process price commandDisplay price and interval of confidence in real-time. [Source: Pyth]
12
74
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def call_price(self, other_args): parser = argparse.ArgumentParser( add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, ...
33
def _single_map_nested(args): function, data_struct, types, rank, disable_tqdm, desc = args # Singleton first to spare some computation if not isinstance(data_struct, dict) and not isinstance(data_struct, types): return function(data_struct) # Reduce logging to keep things readable in mul...
Apply a function recursively to each element of a nested data struct.
12
182
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _single_map_nested(args): function, data_struct, types, rank, disable_tqdm, desc = args # Singleton first to spare some computation if not isinstance(data_struct, dict)...
34
def test_unified(self): self.write_settings("settings_to_diff.py", sdict={"FOO": '"bar"'}) args = ["diffsettings", "--settings=settings_to_diff", "--output=unified"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "+ FOO = 'bar'") ...
--output=unified emits settings diff in unified mode.
7
35
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_unified(self): self.write_settings("settings_to_diff.py", sdict={"FOO": '"bar"'}) args = ["diffsettings", "--settings=settings_to_diff", "--output=unified"]...
35
def runtime_env(self): return RuntimeEnv.deserialize(self._get_runtime_env_string())
Get the runtime env of the current job/worker. If this API is called in driver or ray client, returns the job level runtime env. If this API is called in workers/actors, returns the worker level runtime env. Returns: A new ray.runtime_env.RuntimeEnv instance. To me...
95
4
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def runtime_env(self): return RuntimeEnv.deserialize(self._get_runtime_env_string()) ``` ###Assistant : Get the runtime env of the current job/worker. ...
36
def sleeper(self, duration): s = time() yield time_to_sleep = duration - (time() - s) if time_to_sleep > 0: self.wait(time_to_sleep)
Do something and then wait for a given duration minus the time it took doing something
16
19
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def sleeper(self, duration): s = time() yield time_to_sleep = duration - (time() - s) if time_to_sleep > 0: self.wait(time_to_sleep) ...
37
def test_BoundaryNorm(): boundaries = [0, 1.1, 2.2] vals = [-1, 0, 1, 2, 2.2, 4] # Without interpolation expected = [-1, 0, 0, 1, 2, 2] ncolors = len(boundaries) - 1 bn = mcolors.BoundaryNorm(boundaries, ncolors) assert_array_equal(bn(vals), expected) # ncolors != len(boundaries)...
GitHub issue #1258: interpolation was failing with numpy 1.7 pre-release.
10
623
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_BoundaryNorm(): boundaries = [0, 1.1, 2.2] vals = [-1, 0, 1, 2, 2.2, 4] # Without interpolation expected = [-1, 0, 0, 1, 2, 2] ncolors = len(boundaries) -...
38
def _join_by_index(self, other_modin_frames, how, sort, ignore_index): if how == "outer": raise NotImplementedError("outer join is not supported in HDK engine") lhs = self._maybe_materialize_rowid() reset_index_names = False for rhs in other_modin_frames: ...
Perform equi-join operation for multiple frames by index columns. Parameters ---------- other_modin_frames : list of HdkOnNativeDataframe Frames to join with. how : str A type of join. sort : bool Sort the result by join keys. ...
55
171
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _join_by_index(self, other_modin_frames, how, sort, ignore_index): if how == "outer": raise NotImplementedError("outer join is not supported in HDK engine") ...
39
def _object2proto(self) -> RunFunctionOrConstructorAction_PB: return RunFunctionOrConstructorAction_PB( path=self.path, args=[serialize(x, to_bytes=True) for x in self.args], kwargs={k: serialize(v, to_bytes=True) for k, v in self.kwargs.items()}, id_at_l...
Returns a protobuf serialization of self. As a requirement of all objects which inherit from Serializable, this method transforms the current object into the corresponding Protobuf object so that it can be further serialized. :return: returns a protobuf object :rtype: RunFuncti...
68
25
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _object2proto(self) -> RunFunctionOrConstructorAction_PB: return RunFunctionOrConstructorAction_PB( path=self.path, args=[serialize(x, to_bytes=T...
40
def truncated_cube_graph(create_using=None): description = [ "adjacencylist", "Truncated Cube Graph", 24, [ [2, 3, 5], [12, 15], [4, 5], [7, 9], [6], [17, 19], [8, 9], [11, 13], ...
Returns the skeleton of the truncated cube. The truncated cube is an Archimedean solid with 14 regular faces (6 octagonal and 8 triangular), 36 edges and 24 nodes [1]_. The truncated cube is created by truncating (cutting off) the tips of the cube one third of the way into each edge [2]_. Par...
91
56
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def truncated_cube_graph(create_using=None): description = [ "adjacencylist", "Truncated Cube Graph", 24, [ [2, 3, 5], [12, 1...
41
def get_admin_urls_for_registration(self): urls = () for instance in self.modeladmin_instances: urls += instance.get_admin_urls_for_registration() return urls
Utilised by Wagtail's 'register_admin_urls' hook to register urls for used by any associated ModelAdmin instances
15
14
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_admin_urls_for_registration(self): urls = () for instance in self.modeladmin_instances: urls += instance.get_admin_urls_for_registration() ...
42
def setName(self, name): self.name = name self.errmsg = "Expected " + self.name if __diag__.enable_debug_on_named_expressions: self.setDebug() return self
Define name for this expression, makes debugging and exception messages clearer. Example:: Word(nums).parseString("ABC") # -> Exception: Expected W:(0123...) (at char 0), (line:1, col:1) Word(nums).setName("integer").parseString("ABC") # -> Exception: Expected integer (at ch...
34
17
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def setName(self, name): self.name = name self.errmsg = "Expected " + self.name if __diag__.enable_debug_on_named_expressions: self.setDebug() ...
43
def get_func(cls, key, **kwargs): if "agg_func" in kwargs: return cls.inplace_applyier_builder(key, kwargs["agg_func"]) elif "func_dict" in kwargs: return cls.inplace_applyier_builder(key, kwargs["func_dict"]) else: return cls.inplace_applyier_builder...
Extract aggregation function from groupby arguments. Parameters ---------- key : callable or str Default aggregation function. If aggregation function is not specified via groupby arguments, then `key` function is used. **kwargs : dict GroupB...
106
21
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_func(cls, key, **kwargs): if "agg_func" in kwargs: return cls.inplace_applyier_builder(key, kwargs["agg_func"]) elif "func_dict" in kwargs: ...
44
def update_scheduler(self, metric): self.worker_group.apply_all_operators( lambda op: [sched.step(metric) for sched in op._schedulers] )
Calls ``scheduler.step(metric)`` on all registered schedulers. This is useful for lr_schedulers such as ``ReduceLROnPlateau``.
14
12
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def update_scheduler(self, metric): self.worker_group.apply_all_operators( lambda op: [sched.step(metric) for sched in op._schedulers] ) ``` ...
45
def paired_cosine_distances(X, Y): X, Y = check_paired_arrays(X, Y) return 0.5 * row_norms(normalize(X) - normalize(Y), squared=True) PAIRED_DISTANCES = { "cosine": paired_cosine_distances, "euclidean": paired_euclidean_distances, "l2": paired_euclidean_distances, "l1": paired_manhattan_d...
Compute the paired cosine distances between X and Y. Read more in the :ref:`User Guide <metrics>`. Parameters ---------- X : array-like of shape (n_samples, n_features) An array where each row is a sample and each column is a feature. Y : array-like of shape (n_samples, n_features) ...
114
31
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def paired_cosine_distances(X, Y): X, Y = check_paired_arrays(X, Y) return 0.5 * row_norms(normalize(X) - normalize(Y), squared=True) PAIRED_DISTANCES = { "cosine": paired...
46
def torchdynamo_smart_context_manager(self): ctx_manager = contextlib.nullcontext() if is_torchdynamo_available(): import torchdynamo from torchdynamo.optimizations.training import aot_autograd_speedup_strategy if self.args.torchdynamo == "eager": ...
A helper wrapper that creates an appropriate context manager for `torchdynamo`.
11
29
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def torchdynamo_smart_context_manager(self): ctx_manager = contextlib.nullcontext() if is_torchdynamo_available(): import torchdynamo from to...
47
def check_aug_version(self) -> bool: self.aug.set("/test/path/testing/arg", "aRgUMeNT") try: matches = self.aug.match( "/test//*[self::arg=~regexp('argument', 'i')]") except RuntimeError: self.aug.remove("/test/path") return False ...
Checks that we have recent enough version of libaugeas. If augeas version is recent enough, it will support case insensitive regexp matching
22
20
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def check_aug_version(self) -> bool: self.aug.set("/test/path/testing/arg", "aRgUMeNT") try: matches = self.aug.match( "/test//*[self::a...
48
def resize_depth(depth, width, height): depth = torch.squeeze(depth[0, :, :, :]).to("cpu") depth_resized = cv2.resize( depth.numpy(), (width, height), interpolation=cv2.INTER_CUBIC ) return depth_resized
Resize depth map and bring to CPU (numpy). Args: depth (tensor): depth width (int): image width height (int): image height Returns: array: processed depth
24
20
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def resize_depth(depth, width, height): depth = torch.squeeze(depth[0, :, :, :]).to("cpu") depth_resized = cv2.resize( depth.numpy(), (width, height), interpolation=cv2...
49
def comp(z1, z2, tol=None): r if type(z2) is str: if not pure_complex(z1, or_real=True): raise ValueError('when z2 is a str z1 must be a Number') return str(z1) == z2 if not z1: z1, z2 = z2, z1 if not z1: return True if not tol: a, b = z1, z2 ...
Return a bool indicating whether the error between z1 and z2 is $\le$ ``tol``. Examples ======== If ``tol`` is ``None`` then ``True`` will be returned if :math:`|z1 - z2|\times 10^p \le 5` where $p$ is minimum value of the decimal precision of each value. >>> from sympy import comp, pi ...
217
213
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def comp(z1, z2, tol=None): r if type(z2) is str: if not pure_complex(z1, or_real=True): raise ValueError('when z2 is a str z1 must be a Number') return s...
50
def _parse_img_level_ann(self, image_level_ann_file): item_lists = defaultdict(list) with self.file_client.get_local_path( image_level_ann_file) as local_path: with open(local_path, 'r') as f: reader = csv.reader(f) i = -1 ...
Parse image level annotations from csv style ann_file. Args: image_level_ann_file (str): CSV style image level annotation file path. Returns: defaultdict[list[dict]]: Annotations where item of the defaultdict indicates an image, each of which has (n)...
51
58
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _parse_img_level_ann(self, image_level_ann_file): item_lists = defaultdict(list) with self.file_client.get_local_path( image_level_ann_file) as ...
51
def logical_and(self, a, b): a = _convert_other(a, raiseit=True) return a.logical_and(b, context=self)
Applies the logical operation 'and' between each operand's digits. The operands must be both logical numbers. >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0')) Decimal('0') >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1')) Decimal('0') >>> ExtendedCo...
52
11
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def logical_and(self, a, b): a = _convert_other(a, raiseit=True) return a.logical_and(b, context=self) ``` ###Assistant : Applies the logical operation ...
52
def decrement_part_small(self, part, ub): if self.lpart >= ub - 1: self.p1 += 1 # increment to keep track of usefulness of tests return False plen = len(part) for j in range(plen - 1, -1, -1): # Knuth's mod, (answer to problem 7.2.1.5.69) ...
Decrements part (a subrange of pstack), if possible, returning True iff the part was successfully decremented. Parameters ========== part part to be decremented (topmost part on the stack) ub the maximum number of parts allowed in a partition ...
319
182
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def decrement_part_small(self, part, ub): if self.lpart >= ub - 1: self.p1 += 1 # increment to keep track of usefulness of tests return False ...
53
def get_node_id(self) -> str: node_id = self.worker.current_node_id assert not node_id.is_nil() return node_id.hex()
Get current node ID for this worker or driver. Node ID is the id of a node that your driver, task, or actor runs. The ID will be in hex format. Returns: A node id in hex format for this worker or driver.
43
12
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_node_id(self) -> str: node_id = self.worker.current_node_id assert not node_id.is_nil() return node_id.hex() ``` ###Assistant : Get curr...
54
def list_option(*, info): return _option( info, "List options", lambda opt: (isinstance(info.config.get_obj(opt.name), list) and not opt.no_autoconfig) )
A CompletionModel filled with settings whose values are lists.
9
16
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def list_option(*, info): return _option( info, "List options", lambda opt: (isinstance(info.config.get_obj(opt.name), list) and not opt.no_autoc...
55
def get_instance_from_config_with_end_date(config, query): start_date = "2021-03-04" end_date = "2021-04-04" conversion_window_days = 14 google_api = GoogleAds(credentials=config["credentials"], customer_id=config["customer_id"]) instance = CustomQuery( api=google_api, conversion_wi...
SELecT campaign.id, campaign.name, campaign.status, metrics.impressions FROM campaign wheRe campaign.status = 'PAUSED' AND metrics.impressions > 100 order by campaign.status SELECT campaign.accessible_bidding_strategy, segments.ad_destination_type, campaign....
29
53
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_instance_from_config_with_end_date(config, query): start_date = "2021-03-04" end_date = "2021-04-04" conversion_window_days = 14 google_api = GoogleAds(credentials=co...
56
def node_degree_xy(G, x="out", y="in", weight=None, nodes=None): nodes = set(G) if nodes is None else set(nodes) if G.is_directed(): direction = {"out": G.out_degree, "in": G.in_degree} xdeg = direction[x] ydeg = direction[y] else: xdeg = ydeg = G.degree for u, degu...
Generate node degree-degree pairs for edges in G. Parameters ---------- G: NetworkX graph x: string ('in','out') The degree type for source node (directed graphs only). y: string ('in','out') The degree type for target node (directed graphs only). weight: string or None, option...
157
69
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def node_degree_xy(G, x="out", y="in", weight=None, nodes=None): nodes = set(G) if nodes is None else set(nodes) if G.is_directed(): direction = {"out": G.out_degree, "i...
57
def validate(self, num_steps=None, profile=False, reduce_results=True, info=None): worker_stats = self.worker_group.validate( num_steps=num_steps, profile=profile, info=info ) if reduce_results: return self._process_stats(worker_stats) else: ...
Evaluates the model on the validation data set. Args: num_steps (int): Number of batches to compute update steps on per worker. This corresponds also to the number of times ``TrainingOperator.validate_batch`` is called per worker. profile (bool): Returns ...
113
20
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def validate(self, num_steps=None, profile=False, reduce_results=True, info=None): worker_stats = self.worker_group.validate( num_steps=num_steps, profile=profil...
58
def set_raw_scale(self, in_, scale): self.__check_input(in_) self.raw_scale[in_] = scale
Set the scale of raw features s.t. the input blob = input * scale. While Python represents images in [0, 1], certain Caffe models like CaffeNet and AlexNet represent images in [0, 255] so the raw_scale of these models must be 255. Parameters ---------- in_ : whi...
57
8
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def set_raw_scale(self, in_, scale): self.__check_input(in_) self.raw_scale[in_] = scale ``` ###Assistant : Set the scale of raw features s.t. ...
59
def test_add_rule_to_best_shard(): # If we start with an empty list, then add to first shard shards: List[List[bazel_sharding.BazelRule]] = [list() for _ in range(4)] optimum = 600 rule = bazel_sharding.BazelRule("mock", "medium") bazel_sharding.add_rule_to_best_shard(rule, shards, optimum) ...
Test that the best shard in optimal strategy is chosen correctly.
11
151
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_add_rule_to_best_shard(): # If we start with an empty list, then add to first shard shards: List[List[bazel_sharding.BazelRule]] = [list() for _ in range(4)] optim...
60
def async_heartbeat(self) -> None: self._computed_state = False self._restart_timer() self.async_write_ha_state()
Mark the device as online, and restart the 25 hour timer. This gets called when the heartbeat node beats, but also when the parent sensor sends any events, as we can trust that to mean the device is online. This mitigates the risk of false positives due to a single missed heartbeat even...
53
9
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def async_heartbeat(self) -> None: self._computed_state = False self._restart_timer() self.async_write_ha_state() ``` ###Assistant : Mark the de...
61
def test_assert_series_equal_interval_dtype_mismatch(): # https://github.com/pandas-dev/pandas/issues/32747 left = Series([pd.Interval(0, 1, "right")], dtype="interval") right = left.astype(object) msg = tm.assert_series_equal(left, right, check_dtype=False) with pytest.raises(AssertionError...
Attributes of Series are different Attribute "dtype" are different \\[left\\]: interval\\[int64, right\\] \\[right\\]: object
14
24
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_assert_series_equal_interval_dtype_mismatch(): # https://github.com/pandas-dev/pandas/issues/32747 left = Series([pd.Interval(0, 1, "right")], dtype="interval") right = ...
62
def rc_file_defaults(): # Deprecation warnings were already handled when creating rcParamsOrig, no # need to reemit them here. with _api.suppress_matplotlib_deprecation_warning(): from .style.core import STYLE_BLACKLIST rcParams.update({k: rcParamsOrig[k] for k in rcParamsOrig ...
Restore the `.rcParams` from the original rc file loaded by Matplotlib. Style-blacklisted `.rcParams` (defined in ``matplotlib.style.core.STYLE_BLACKLIST``) are not updated.
19
35
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def rc_file_defaults(): # Deprecation warnings were already handled when creating rcParamsOrig, no # need to reemit them here. with _api.suppress_matplotlib_deprecation_warn...
63
def lexer(self) -> Optional[Lexer]: if isinstance(self._lexer, Lexer): return self._lexer try: return get_lexer_by_name( self._lexer, stripnl=False, ensurenl=True, tabsize=self.tab_size, ) ...
The lexer for this syntax, or None if no lexer was found. Tries to find the lexer by name if a string was passed to the constructor.
27
21
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def lexer(self) -> Optional[Lexer]: if isinstance(self._lexer, Lexer): return self._lexer try: return get_lexer_by_name( sel...
64
def test_numeric_repl(file, multiline_file): file.replace(multiline_file, r"Etiam", 123) assert "123" in multiline_file.read_text()
This test covers cases where the replacement string is numeric. The CLI parser yaml-fies it into a numeric type. If not converted back to a string type in file.replace, a TypeError occurs when the replace is attempted. See https://github.com/saltstack/salt/issues/9097 for more information.
42
10
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_numeric_repl(file, multiline_file): file.replace(multiline_file, r"Etiam", 123) assert "123" in multiline_file.read_text() ``` ###Assistant : This te...
65
def set_interpret_parameters(self, segments=16): self.interpretation_segments = segments return self
Calculates interpretation score of image subsections by splitting the image into subsections, then using a "leave one out" method to calculate the score of each subsection by whiting out the subsection and measuring the delta of the output value. Parameters: segments (int): Number of interpreta...
50
8
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def set_interpret_parameters(self, segments=16): self.interpretation_segments = segments return self ``` ###Assistant : Calculates interpretati...
66
def can_native_upsert(self) -> bool: return sqlite3.sqlite_version_info >= (3, 24, 0)
Do we support native UPSERTs? This requires SQLite3 3.24+, plus some more work we haven't done yet to tell what was inserted vs updated.
24
10
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def can_native_upsert(self) -> bool: return sqlite3.sqlite_version_info >= (3, 24, 0) ``` ###Assistant : Do we support native UPSERTs? This requires SQ...
67
async def get_actors(self) -> dict: reply = await self._client.get_all_actor_info(timeout=DEFAULT_RPC_TIMEOUT) result = {} for message in reply.actor_table_data: data = self._message_to_dict(message=message, fields_to_decode=["actor_id"]) data = filter_fields(dat...
List all actor information from the cluster. Returns: {actor_id -> actor_data_in_dict} actor_data_in_dict's schema is in ActorState
16
29
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python async def get_actors(self) -> dict: reply = await self._client.get_all_actor_info(timeout=DEFAULT_RPC_TIMEOUT) result = {} for message in reply.actor_table_d...
68
def insert_predictor_answer(self, insert): model_interface = self.session.model_interface data_store = self.session.data_store select_data_query = insert.get('select_data_query') if isinstance(select_data_query, str) is False or len(select_data_query) == 0: self.pac...
Start learn new predictor. Parameters: - insert - dict with keys as columns of mindsb.predictors table.
16
181
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def insert_predictor_answer(self, insert): model_interface = self.session.model_interface data_store = self.session.data_store select_data_query = insert.ge...
69
def populate_historical_trade_data(self): trade_data = self.__orderbook.pivot( index="Date", columns="Ticker", values=[ "Type", "Sector", "Industry", "Country", "Price", "...
Create a new dataframe to store historical prices by ticker
10
78
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def populate_historical_trade_data(self): trade_data = self.__orderbook.pivot( index="Date", columns="Ticker", values=[ "...
70
def test_fetch_openml_equivalence_array_dataframe(monkeypatch, parser): pytest.importorskip("pandas") data_id = 61 _monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response=True) bunch_as_frame_true = fetch_openml( data_id=data_id, as_frame=True, cache=False, ...
Check the equivalence of the dataset when using `as_frame=False` and `as_frame=True`.
11
47
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_fetch_openml_equivalence_array_dataframe(monkeypatch, parser): pytest.importorskip("pandas") data_id = 61 _monkey_patch_webbased_functions(monkeypatch, data_id, gz...
71
def wire_type(self): if hasattr(self, '_m_wire_type'): return self._m_wire_type self._m_wire_type = KaitaiStream.resolve_enum(GoogleProtobuf.Pair.WireTypes, (self.key.value & 7)) return getattr(self, '_m_wire_type', None)
"Wire type" is a part of the "key" that carries enough information to parse value from the wire, i.e. read correct amount of bytes, but there's not enough informaton to interprete in unambiguously. For example, one can't clearly distinguish 64-bit fixed-sized integers fro...
59
17
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def wire_type(self): if hasattr(self, '_m_wire_type'): return self._m_wire_type self._m_wire_type = KaitaiStream.resolve_enum(GoogleProt...
72
def address(self): # pragma: no cover warnings.warn( "Client.address is deprecated, use Client.peername instead.", DeprecationWarning, stacklevel=2, ) return self.peername
*Deprecated:* An outdated alias for Client.peername.
6
18
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def address(self): # pragma: no cover warnings.warn( "Client.address is deprecated, use Client.peername instead.", DeprecationWarning, s...
End of preview. Expand in Data Studio

YAML Metadata Warning:The task_categories "text2text-generation" is not in the official list: text-classification, token-classification, table-question-answering, question-answering, zero-shot-classification, translation, summarization, feature-extraction, text-generation, fill-mask, sentence-similarity, text-to-speech, text-to-audio, automatic-speech-recognition, audio-to-audio, audio-classification, audio-text-to-text, voice-activity-detection, depth-estimation, image-classification, object-detection, image-segmentation, text-to-image, image-to-text, image-to-image, image-to-video, unconditional-image-generation, video-classification, reinforcement-learning, robotics, tabular-classification, tabular-regression, tabular-to-text, table-to-text, multiple-choice, text-ranking, text-retrieval, time-series-forecasting, text-to-video, image-text-to-text, image-text-to-image, image-text-to-video, visual-question-answering, document-question-answering, zero-shot-image-classification, graph-ml, mask-generation, zero-shot-object-detection, text-to-3d, image-to-3d, image-feature-extraction, video-text-to-text, keypoint-detection, visual-document-retrieval, any-to-any, video-to-video, other

Dataset Card for Dataset Name

This dataset card aims to be a base template for creating python docs from methods. This is formatted from semeru/code-code-galeras-code-completion-from-docstring-3k-deduped

Dataset Description

  • Curated by: semeru/code-code-galeras-code-completion-from-docstring-3k-deduped
  • Language(s) (NLP): Python
  • License: [More Information Needed]

Dataset Sources [optional]

  • Repository: semeru/code-code-galeras-code-completion-from-docstring-3k-deduped

Uses

(use however you like)

Dataset Structure

Code - Method Doc - Documentation for the method Lang - Language Prompt - Prompt field for training

Downloads last month
6