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...
73
def jordan_block(kls, size=None, eigenvalue=None, *, band='upper', **kwargs): if 'rows' in kwargs or 'cols' in kwargs: msg = if 'rows' in kwargs and 'cols' in kwargs: msg += f
Returns a Jordan block Parameters ========== size : Integer, optional Specifies the shape of the Jordan block matrix. eigenvalue : Number or Symbol Specifies the value for the main diagonal of the matrix. .. note:: The keyword ``eig...
442
28
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def jordan_block(kls, size=None, eigenvalue=None, *, band='upper', **kwargs): if 'rows' in kwargs or 'cols' in kwargs: msg = if 'rows' in kwargs and...
74
def get_openapi_specs() -> dict: app = get_app() return get_openapi( title=app.title, version=app.version, openapi_version=app.openapi_version, description=app.description, routes=app.routes, servers=[{"url": "http://localhost:8000"}], )
Used to autogenerate OpenAPI specs file to use in the documentation. Returns `servers` to specify base URL for OpenAPI Playground (see https://swagger.io/docs/specification/api-host-and-base-path/) See `.github/utils/generate_openapi_specs.py`
24
17
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_openapi_specs() -> dict: app = get_app() return get_openapi( title=app.title, version=app.version, openapi_version=app.openapi_version, ...
75
def get_all_employee_emails(company): employee_list = frappe.get_all( "Employee", fields=["name", "employee_name"], filters={"status": "Active", "company": company} ) employee_emails = [] for employee in employee_list: if not employee: continue user, company_email, personal_email = frappe.db.get_value( ...
Returns list of employee emails either based on user_id or company_email
11
47
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_all_employee_emails(company): employee_list = frappe.get_all( "Employee", fields=["name", "employee_name"], filters={"status": "Active", "company": company} ) employee_emails ...
76
def test_in_non_semver_projects_resolved_in_next_release_is_equated_to_in_release(self): release_1 = self.create_release( date_added=timezone.now() - timedelta(minutes=45), version="foobar 1" ) release_2 = self.create_release(version="foobar 2") self.create_release(v...
Test that ensures that if we basically know the next release when clicking on Resolved In Next Release because that release exists, then we can short circuit setting GroupResolution to type "inNextRelease", and then having `clear_exrired_resolutions` run once a new release is created to...
75
81
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_in_non_semver_projects_resolved_in_next_release_is_equated_to_in_release(self): release_1 = self.create_release( date_added=timezone.now() - timedelta(m...
77
def subscription_order_updated_webhook(subscription_webhook): return subscription_webhook( ORDER_UPDATED_SUBSCRIPTION_QUERY, WebhookEventAsyncType.ORDER_UPDATED ) ORDER_CONFIRMED_SUBSCRIPTION_QUERY = @pytest.fixture
subscription{ event{ ...on OrderConfirmed{ order{ id } } } }
10
10
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def subscription_order_updated_webhook(subscription_webhook): return subscription_webhook( ORDER_UPDATED_SUBSCRIPTION_QUERY, WebhookEventAsyncType.ORDER_UPDATED ) ORDER_CON...
78
def cast_to_compatible_types(table): schema = table.schema new_schema = schema need_cast = False uint_to_int_cast = False new_cols = {} uint_to_int_map = { pa.uint8(): pa.int16(), pa.uint16(): pa.int32(), pa.uint32(): pa.int64(...
Cast PyArrow table to be fully compatible with OmniSci. Parameters ---------- table : pyarrow.Table Source table. Returns ------- pyarrow.Table Table with fully compatible types with OmniSci.
26
295
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def cast_to_compatible_types(table): schema = table.schema new_schema = schema need_cast = False uint_to_int_cast = False new_cols = {} ...
79
def data(self) -> 'DataRequest._DataContent': return DataRequest._DataContent(self.proto.data)
Get the data contaned in this data request :return: the data content as an instance of _DataContent wrapping docs and groundtruths
21
6
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def data(self) -> 'DataRequest._DataContent': return DataRequest._DataContent(self.proto.data) ``` ###Assistant : Get the data contaned in this data request ...
80
def model_from_json(json_string, custom_objects=None): from keras.layers import ( deserialize_from_json, ) # pylint: disable=g-import-not-at-top return deserialize_from_json(json_string, custom_objects=custom_objects)
Parses a JSON model configuration string and returns a model instance. Usage: >>> model = tf.keras.Sequential([ ... tf.keras.layers.Dense(5, input_shape=(3,)), ... tf.keras.layers.Softmax()]) >>> config = model.to_json() >>> loaded_model = tf.keras.models.model_from_json(config) A...
59
15
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def model_from_json(json_string, custom_objects=None): from keras.layers import ( deserialize_from_json, ) # pylint: disable=g-import-not-at-top return deserialize...
81
def test_do_nothing_if_converted(self, run_convert_mock): stdout, _ = self.call_command() run_convert_mock.assert_not_called() self.assertIn("Converting all PNG thumbnails to WebP", stdout)
GIVEN: - Document exists with default WebP thumbnail path WHEN: - Thumbnail conversion is attempted THEN: - Nothing is converted
20
15
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_do_nothing_if_converted(self, run_convert_mock): stdout, _ = self.call_command() run_convert_mock.assert_not_called() self.assertIn("Converting all...
82
def __ror__(self, other): if isinstance(other, str_type): other = self._literalStringClass(other) if not isinstance(other, ParserElement): raise TypeError( "Cannot combine element of type {} with ParserElement".format( type(other).__na...
Implementation of ``|`` operator when left operand is not a :class:`ParserElement`
11
30
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def __ror__(self, other): if isinstance(other, str_type): other = self._literalStringClass(other) if not isinstance(other, ParserElement): ra...
83
def shash(value): length = len(value) if length == 0: return 0 x = Hash.ordinal(value[0]) << 7 for c in value: x = (1000003 * x) ^ Hash.ordinal(c) x ^= length x &= 0xFFFFFFFFFFFFFFFF if x == -1: x = -2 # Co...
Returns a Python 2.7 hash for a string. Logic ported from the 2.7 Python branch: cpython/Objects/stringobject.c Method: static long string_hash(PyStringObject *a) Args: value: input string Returns: Python 2.7 hash
29
48
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def shash(value): length = len(value) if length == 0: return 0 x = Hash.ordinal(value[0]) << 7 for c in value: x = (100000...
84
def data_files_with_one_split_and_metadata(tmp_path, auto_text_file): data_dir = tmp_path / "autofolder_data_dir_with_metadata_one_split" data_dir.mkdir(parents=True, exist_ok=True) subdir = data_dir / "subdir" subdir.mkdir(parents=True, exist_ok=True) filename = data_dir / "file.txt" shutil.co...
\ {"file_name": "file.txt", "additional_feature": "Dummy file"} {"file_name": "file2.txt", "additional_feature": "Second dummy file"} {"file_name": "subdir/file3.txt", "additional_feature": "Third dummy file"}
18
74
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def data_files_with_one_split_and_metadata(tmp_path, auto_text_file): data_dir = tmp_path / "autofolder_data_dir_with_metadata_one_split" data_dir.mkdir(parents=True, exist_ok=True) ...
85
def test_upload_room_keys_wrong_version(self) -> None: version = self.get_success( self.handler.create_version( self.local_user, { "algorithm": "m.megolm_backup.v1", "auth_data": "first_version_auth_data", ...
Check that we get a 403 on uploading keys for an old version
13
47
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_upload_room_keys_wrong_version(self) -> None: version = self.get_success( self.handler.create_version( self.local_user, ...
86
def previewtrain(self) -> Dict[str, List[Union[Image.Image, ImageTk.PhotoImage, None, float]]]: return self._previewtrain
dict or ``None``: The training preview images. Dictionary key is the image name (`str`). Dictionary values are a `list` of the training image (:class:`PIL.Image`), the image formatted for tkinter display (:class:`PIL.ImageTK.PhotoImage`), the last modification time of the image (`float`). ...
58
10
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def previewtrain(self) -> Dict[str, List[Union[Image.Image, ImageTk.PhotoImage, None, float]]]: return self._previewtrain ``` ###Assistant : dict or ``None``: ...
87
def test_padding(self): n = coord_net_spec() ax, a, b = coord_map_from_to(n.deconv, n.data) pad = random.randint(0, 10) # conv padding n = coord_net_spec(pad=pad) _, a_pad, b_pad = coord_map_from_to(n.deconv, n.data) self.assertEquals(a, a_pad) se...
Padding conv adds offset while padding deconv subtracts offset.
9
71
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_padding(self): n = coord_net_spec() ax, a, b = coord_map_from_to(n.deconv, n.data) pad = random.randint(0, 10) # conv padding n = co...
88
def require_cuda(test_case): return unittest.skipUnless(torch.cuda.is_available(), "test requires a GPU")(test_case)
Decorator marking a test that requires CUDA. These tests are skipped when there are no GPU available.
17
8
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def require_cuda(test_case): return unittest.skipUnless(torch.cuda.is_available(), "test requires a GPU")(test_case) ``` ###Assistant : Decorator marking a test t...
89
def _flush_periodically(self) -> None: while self._active: # flush is thread-safe; it acquires and releases the lock internally self.flush() time.sleep(self._flush_period)
Whilst this handler is active, flush the handler periodically.
9
19
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _flush_periodically(self) -> None: while self._active: # flush is thread-safe; it acquires and releases the lock internally self.flush() ...
90
def save_flagged(self, dir, label, data, encryption_key) -> str | Dict: if "confidences" in data: return json.dumps( { example["label"]: example["confidence"] for example in data["confidences"] } ) e...
Returns: Either a string representing the main category label, or a dictionary with category keys mapping to confidence levels.
19
28
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def save_flagged(self, dir, label, data, encryption_key) -> str | Dict: if "confidences" in data: return json.dumps( { exampl...
91
def test_higher_rank_inputs_for_importance_weights(self): for fw in framework_iterator(frameworks=("torch", "tf"), session=True): vtrace = vtrace_tf if fw != "torch" else vtrace_torch if fw == "tf": inputs_ = { "log_rhos": tf1.placeholder( ...
Checks support for additional dimensions in inputs.
7
96
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_higher_rank_inputs_for_importance_weights(self): for fw in framework_iterator(frameworks=("torch", "tf"), session=True): vtrace = vtrace_tf if fw != "to...
92
def test_task_fail_duration(app, admin_client, dag_maker, session): with dag_maker() as dag: op1 = BashOperator(task_id='fail', bash_command='exit 1') op2 = BashOperator(task_id='success', bash_command='exit 0') with pytest.raises(AirflowException): op1.run() op2.run() op1...
Task duration page with a TaskFail entry should render without error.
11
104
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_task_fail_duration(app, admin_client, dag_maker, session): with dag_maker() as dag: op1 = BashOperator(task_id='fail', bash_command='exit 1') op2 = BashOper...
93
def test_all_users(self) -> None: self._create_users(2) channel = self.make_request( "GET", self.url + "?deactivated=true", {}, access_token=self.admin_user_tok, ) self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_bo...
List all users, including deactivated users.
6
30
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_all_users(self) -> None: self._create_users(2) channel = self.make_request( "GET", self.url + "?deactivated=true", {}, ...
94
def real_quick_ratio(self): la, lb = len(self.a), len(self.b) # can't have more matches than the number of elements in the # shorter sequence return _calculate_ratio(min(la, lb), la + lb) __class_getitem__ = classmethod(GenericAlias)
Return an upper bound on ratio() very quickly. This isn't defined beyond that it is an upper bound on .ratio(), and is faster to compute than either .ratio() or .quick_ratio().
30
31
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def real_quick_ratio(self): la, lb = len(self.a), len(self.b) # can't have more matches than the number of elements in the # shorter sequence return...
95
def test_unpublish_view_invalid_page_id(self): # Request confirm unpublish page but with illegal page id response = self.client.get( reverse( "wagtail_bulk_action", args=( "wagtailcore", "page", ...
This tests that the unpublish view returns an error if the page id is invalid
15
35
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_unpublish_view_invalid_page_id(self): # Request confirm unpublish page but with illegal page id response = self.client.get( reverse( ...
96
def test_warn_report(): fn = report with warnings.catch_warnings(record=True) as record: # Ignore Deprecation warnings. warnings.filterwarnings("ignore", category=DeprecationWarning) assert not fn(dict()) assert fn.__name__ in record[0].message.args[0] reset_log_once_wit...
Checks if calling session.report function outside of session raises warning.
10
23
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_warn_report(): fn = report with warnings.catch_warnings(record=True) as record: # Ignore Deprecation warnings. warnings.filterwarnings("ignore", categ...
97
def forward(self, feats, img_metas): batch_size = len(img_metas) mask_features, multi_scale_memorys = self.pixel_decoder(feats) # multi_scale_memorys (from low resolution to high resolution) decoder_inputs = [] decoder_positional_encodings = [] for i in range(sel...
Forward function. Args: feats (list[Tensor]): Multi scale Features from the upstream network, each is a 4D-tensor. img_metas (list[dict]): List of image information. Returns: tuple: A tuple contains two elements. - cls_pred_list (list[Te...
73
201
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def forward(self, feats, img_metas): batch_size = len(img_metas) mask_features, multi_scale_memorys = self.pixel_decoder(feats) # multi_scale_memorys (from l...
98
def formfield_for_manytomany(self, db_field, request, **kwargs): # If it uses an intermediary model that isn't auto created, don't show # a field in admin. if not db_field.remote_field.through._meta.auto_created: return None db = kwargs.get("using") if "widg...
Get a form Field for a ManyToManyField.
7
139
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def formfield_for_manytomany(self, db_field, request, **kwargs): # If it uses an intermediary model that isn't auto created, don't show # a field in admin. i...
99
def test_expiry_logic(self) -> None: self.event_creator_handler._rooms_to_exclude_from_dummy_event_insertion[ "1" ] = 100000 self.event_creator_handler._rooms_to_exclude_from_dummy_event_insertion[ "2" ] = 200000 self.event_creator_handler._rooms_...
Simple test to ensure that _expire_rooms_to_exclude_from_dummy_event_insertion() expires old entries correctly.
10
57
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_expiry_logic(self) -> None: self.event_creator_handler._rooms_to_exclude_from_dummy_event_insertion[ "1" ] = 100000 self.event_creator_h...