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
1,800
def enter_positions(self) -> int: trades_created = 0 whitelist = copy.deepcopy(self.active_pair_whitelist) if not whitelist: logger.info("Active pair whitelist is empty.") return trades_created # Remove pairs for currently opened trades from the whitelis...
Tries to execute entry orders for new trades (positions)
9
170
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def enter_positions(self) -> int: trades_created = 0 whitelist = copy.deepcopy(self.active_pair_whitelist) if not whitelist: logger.info("Active...
1,801
def validate_js_path(registered_paths, package_name, path_in_package_dist): if package_name not in registered_paths: raise exceptions.DependencyException( f ) if path_in_package_dist not in registered_paths[package_name]: raise exceptions.DependencyException( f ...
Error loading dependency. "{package_name}" is not a registered library. Registered libraries are: {list(registered_paths.keys())} "{package_name}" is registered but the path requested is not valid. The path requested: "{path_in_package_dist}" ...
32
22
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def validate_js_path(registered_paths, package_name, path_in_package_dist): if package_name not in registered_paths: raise exceptions.DependencyException( f )...
1,802
def get_all_node_ids() -> List[Tuple[str, str]]: node_ids = [] # Sort on NodeID to ensure the ordering is deterministic across the cluster. for node in sorted(ray.nodes(), key=lambda entry: entry["NodeID"]): # print(node) if node["Alive"]: node_ids.append((node["NodeID"], no...
Get IDs for all live nodes in the cluster. Returns a list of (node_id: str, ip_address: str). The node_id can be passed into the Ray SchedulingPolicy API.
27
36
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_all_node_ids() -> List[Tuple[str, str]]: node_ids = [] # Sort on NodeID to ensure the ordering is deterministic across the cluster. for node in sorted(ray.nodes(), k...
1,803
def _ignore_comments(self, block): comment_spans = False while True: comment_start = block.find(b"#") # look for next comment if comment_start == -1: # no comment found break comment_end = self._find_comment_end(block, comment_start) ...
Deletes comments from block. If comment does not end in this block, raises a flag.
15
70
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _ignore_comments(self, block): comment_spans = False while True: comment_start = block.find(b"#") # look for next comment if comment_st...
1,804
def test_torch_auto_gpu_to_cpu(ray_start_4_cpus_2_gpus): num_workers = 2 assert os.environ["CUDA_VISIBLE_DEVICES"] == ""
Tests if GPU tensors are auto converted to CPU on driver.
11
9
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_torch_auto_gpu_to_cpu(ray_start_4_cpus_2_gpus): num_workers = 2 assert os.environ["CUDA_VISIBLE_DEVICES"] == "" ``` ###Assistant : Tests if GPU tensors are...
1,805
def formatyear(self, theyear, width=3): v = [] a = v.append width = max(width, 1) a('<table border="0" cellpadding="0" cellspacing="0" class="%s">' % self.cssclass_year) a('\n') a('<tr><th colspan="%d" class="%s">%s</th></tr>' % ( width, sel...
Return a formatted year as a table of tables.
9
60
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def formatyear(self, theyear, width=3): v = [] a = v.append width = max(width, 1) a('<table border="0" cellpadding="0" cellspacing="0" class="%s">' %...
1,806
def predict(self, inputs): training = False user = inputs["user"] input_seq = inputs["input_seq"] candidate = inputs["candidate"] mask = tf.expand_dims(tf.cast(tf.not_equal(input_seq, 0), tf.float32), -1) seq_embeddings, positional_embeddings = self.embedding(in...
Model prediction for candidate (negative) items
6
198
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def predict(self, inputs): training = False user = inputs["user"] input_seq = inputs["input_seq"] candidate = inputs["candidate"] mask = tf....
1,807
def tobitmap(self, name="image"): self.load() if self.mode != "1": msg = "not a bitmap" raise ValueError(msg) data = self.tobytes("xbm") return b"".join( [ f"#define {name}_width {self.size[0]}\n".encode("ascii"), ...
Returns the image converted to an X11 bitmap. .. note:: This method only works for mode "1" images. :param name: The name prefix to use for the bitmap variables. :returns: A string containing an X11 bitmap. :raises ValueError: If the mode is not "1"
44
36
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def tobitmap(self, name="image"): self.load() if self.mode != "1": msg = "not a bitmap" raise ValueError(msg) data = self.tobytes("x...
1,808
def add_edges_from(self, ebunch_to_add, **attr): for e in ebunch_to_add: ne = len(e) if ne == 3: u, v, dd = e elif ne == 2: u, v = e dd = {} else: raise NetworkXError(f"Edge tuple {e} must be...
Add all the edges in ebunch_to_add. Parameters ---------- ebunch_to_add : container of edges Each edge given in the container will be added to the graph. The edges must be given as 2-tuples (u, v) or 3-tuples (u, v, d) where d is a dictionary containing edge ...
305
102
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def add_edges_from(self, ebunch_to_add, **attr): for e in ebunch_to_add: ne = len(e) if ne == 3: u, v, dd = e elif ne == ...
1,809
def _select_device(self) -> None: if os.path.exists(plaidml.settings.user_settings): # pylint:disable=no-member self._log("debug", "Setting PlaidML devices from user_settings") else: self._select_largest_gpu()
If the plaidml user configuration settings exist, then set the default GPU from the settings file, Otherwise set the GPU to be the one with most VRAM.
27
16
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _select_device(self) -> None: if os.path.exists(plaidml.settings.user_settings): # pylint:disable=no-member self._log("debug", "Setting PlaidML devices from...
1,810
def test_readlink_non_canonical(file, source): intermediate = source.parent / "intermediate.lnk" intermediate.symlink_to(source) target = source.parent / "symlink.lnk" target.symlink_to(intermediate) try: result = file.readlink(path=target) assert result == str(intermediate) ...
Test readlink where there are nested symlinks and canonicalize=False Should resolve to the first symlink
15
26
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_readlink_non_canonical(file, source): intermediate = source.parent / "intermediate.lnk" intermediate.symlink_to(source) target = source.parent / "symlink.lnk" t...
1,811
def select_proxy(url, proxies): proxies = proxies or {} urlparts = urlparse(url) if urlparts.hostname is None: return proxies.get(urlparts.scheme, proxies.get("all")) proxy_keys = [ urlparts.scheme + "://" + urlparts.hostname, urlparts.scheme, "all://" + urlparts.ho...
Select a proxy for the url, if applicable. :param url: The url being for the request :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs
29
49
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def select_proxy(url, proxies): proxies = proxies or {} urlparts = urlparse(url) if urlparts.hostname is None: return proxies.get(urlparts.scheme, proxies.get("all")...
1,812
def eof_received(self): try: if self._loop.get_debug(): logger.debug("%r received EOF", self) self._wakeup_waiter(ConnectionResetError) if not self._in_handshake: keep_open = self._app_protocol.eof_received() if keep_...
Called when the other end of the low-level stream is half-closed. If this returns a false value (including None), the transport will close itself. If it returns a true value, closing the transport is up to the protocol.
38
31
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def eof_received(self): try: if self._loop.get_debug(): logger.debug("%r received EOF", self) self._wakeup_waiter(ConnectionResetErr...
1,813
def url_result(url, ie=None, video_id=None, video_title=None, *, url_transparent=False, **kwargs): if ie is not None: kwargs['ie_key'] = ie if isinstance(ie, str) else ie.ie_key() if video_id is not None: kwargs['id'] = video_id if video_title is not None: ...
Returns a URL that points to a page that should be processed
12
49
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def url_result(url, ie=None, video_id=None, video_title=None, *, url_transparent=False, **kwargs): if ie is not None: kwargs['ie_key'] = ie if isinstance(ie, str...
1,814
def _shade_colors(color, normals, lightsource=None): if lightsource is None: # chosen for backwards-compatibility lightsource = mcolors.LightSource(azdeg=225, altdeg=19.4712) with np.errstate(invalid="ignore"): shade = ((normals / np.linalg.norm(normals, axis=1, keepdims=True)) ...
Shade *color* using normal vectors given by *normals*, assuming a *lightsource* (using default position if not given). *color* can also be an array of the same length as *normals*.
29
48
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _shade_colors(color, normals, lightsource=None): if lightsource is None: # chosen for backwards-compatibility lightsource = mcolors.LightSource(azdeg=225, altdeg...
1,815
def score(self, X, y, **fit_params): check_is_fitted(self) return self.estimator_.score(self.transform(X), y, **fit_params)
Reduce X to the selected features and return the score of the estimator. Parameters ---------- X : array of shape [n_samples, n_features] The input samples. y : array of shape [n_samples] The target values. **fit_params : dict Parameters to ...
72
10
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def score(self, X, y, **fit_params): check_is_fitted(self) return self.estimator_.score(self.transform(X), y, **fit_params) ``` ###Assistant : Reduce X ...
1,816
def reset(self, pos): self.value = pos self.velocity = 0 if self.history: val = self.history[-1][1] self.history = [(time(), val)]
(internal) Reset the value and the velocity to the `pos`. Mostly used when the bounds are checked.
17
18
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def reset(self, pos): self.value = pos self.velocity = 0 if self.history: val = self.history[-1][1] self.history = [(time(), val)] ...
1,817
def test_from_fan_speed(fan_speed, expected_result): assert _from_fan_speed(fan_speed) == expected_result @pytest.mark.parametrize( "percentage, expected_result", [ (1, 2), (100, 50), (50, 26), ], )
Test that we can convert fan speed to percentage value.
10
19
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_from_fan_speed(fan_speed, expected_result): assert _from_fan_speed(fan_speed) == expected_result @pytest.mark.parametrize( "percentage, expected_result", [ ...
1,818
def task_runner(): from sentry.testutils.helpers.task_runner import TaskRunner return TaskRunner @pytest.fixture
Context manager that ensures Celery tasks run directly inline where invoked. While this context manager is active any Celery tasks created will run immediately at the callsite rather than being sent to RabbitMQ and handled by a worker.
38
9
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def task_runner(): from sentry.testutils.helpers.task_runner import TaskRunner return TaskRunner @pytest.fixture ``` ###Assistant : Context manager that ensures C...
1,819
def get_random_string(length, allowed_chars=RANDOM_STRING_CHARS): return "".join(secrets.choice(allowed_chars) for i in range(length))
Return a securely generated random string. The bit length of the returned value can be calculated with the formula: log_2(len(allowed_chars)^length) For example, with default `allowed_chars` (26+26+10), this gives: * length: 12, bit length =~ 71 bits * length: 22, bit length =~ 131 bi...
44
9
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_random_string(length, allowed_chars=RANDOM_STRING_CHARS): return "".join(secrets.choice(allowed_chars) for i in range(length)) ``` ###Assistant : Return a...
1,820
def test_command_reply(tplaybook): tplaybook >> TEvent() tplaybook << TCommand() tplaybook >> tutils.reply() assert tplaybook assert tplaybook.actual[1] == tplaybook.actual[2].command
CommandReplies can use relative offsets to point to the matching command.
11
17
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_command_reply(tplaybook): tplaybook >> TEvent() tplaybook << TCommand() tplaybook >> tutils.reply() assert tplaybook assert tplaybook.actual[1] == tplaybook...
1,821
def _mirrored_cross_device_ops(all_reduce_alg, num_packs): if all_reduce_alg is None: return None mirrored_all_reduce_options = { "nccl": tf.distribute.NcclAllReduce, "hierarchical_copy": tf.distribute.HierarchicalCopyAllReduce, } if all_reduce_alg not in mirrored_all_reduce...
Return a CrossDeviceOps based on all_reduce_alg and num_packs. Args: all_reduce_alg: a string specifying which cross device op to pick, or None. num_packs: an integer specifying number of packs for the cross device op. Returns: tf.distribute.CrossDeviceOps object or None. Raises: ...
47
47
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _mirrored_cross_device_ops(all_reduce_alg, num_packs): if all_reduce_alg is None: return None mirrored_all_reduce_options = { "nccl": tf.distribute.NcclAllRe...
1,822
def test_delete_queue(self, mock_sb_admin_client): hook = AdminClientHook(azure_service_bus_conn_id=self.conn_id) hook.delete_queue(self.queue_name) expected_calls = [mock.call().__enter__().delete_queue(self.queue_name)] mock_sb_admin_client.assert_has_calls(expected_calls)
Test Delete queue functionality by passing queue name, assert the function with values, mock the azure service bus function `delete_queue`
20
11
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_delete_queue(self, mock_sb_admin_client): hook = AdminClientHook(azure_service_bus_conn_id=self.conn_id) hook.delete_queue(self.queue_name) expected...
1,823
def get_content_disposition(self): value = self.get('content-disposition') if value is None: return None c_d = _splitparam(value)[0].lower() return c_d # I.e. def walk(self): ... from email.iterators import walk
Return the message's content-disposition if it exists, or None. The return values can be either 'inline', 'attachment' or None according to the rfc2183.
23
25
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_content_disposition(self): value = self.get('content-disposition') if value is None: return None c_d = _splitparam(value)[0].lower() ...
1,824
def _get_or_create(self, s, name=None, dtype=None, broadcastable=None): # Defaults if name is None: name = s.name if dtype is None: dtype = 'floatX' if broadcastable is None: broadcastable = () key = self._get_key(s, name, dtype=dtyp...
Get the Aesara variable for a SymPy symbol from the cache, or create it if it does not exist.
19
51
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _get_or_create(self, s, name=None, dtype=None, broadcastable=None): # Defaults if name is None: name = s.name if dtype is None: ...
1,825
def defer(self, *fields): self._not_support_combined_queries("defer") if self._fields is not None: raise TypeError("Cannot call defer() after .values() or .values_list()") clone = self._chain() if fields == (None,): clone.query.clear_deferred_loading() ...
Defer the loading of data for certain fields until they are accessed. Add the set of deferred fields to any existing set of deferred fields. The only exception to this is if None is passed in as the only parameter, in which case removal all deferrals.
46
29
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def defer(self, *fields): self._not_support_combined_queries("defer") if self._fields is not None: raise TypeError("Cannot call defer() after .values() o...
1,826
def match_seq(self, nodes, results=None): if len(nodes) != 1: return False return self.match(nodes[0], results)
Does this pattern exactly match a sequence of nodes? Default implementation for non-wildcard patterns.
14
13
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def match_seq(self, nodes, results=None): if len(nodes) != 1: return False return self.match(nodes[0], results) ``` ###Assistant : ...
1,827
def team_ids_with_membership(self) -> FrozenSet[int]: return frozenset(team.id for team in self._team_memberships.keys())
Return the IDs of teams in which the user has actual membership. This represents the set of all teams for which `has_team_membership` returns true. Use that method where possible and use this property only when you need to iterate or query for all such teams. Compare to accessible_team...
69
10
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def team_ids_with_membership(self) -> FrozenSet[int]: return frozenset(team.id for team in self._team_memberships.keys()) ``` ###Assistant : Return the IDs of t...
1,828
def test_gumbel_softmax(self): for fw, sess in framework_iterator(frameworks=("tf2", "tf"), session=True): batch_size = 1000 num_categories = 5 input_space = Box(-1.0, 1.0, shape=(batch_size, num_categories)) input_space.seed(42) # Batch of s...
Tests the GumbelSoftmax ActionDistribution (tf + eager only).
8
99
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_gumbel_softmax(self): for fw, sess in framework_iterator(frameworks=("tf2", "tf"), session=True): batch_size = 1000 num_categories = 5 ...
1,829
def get_confusion_matrix(gt_label, pred_label, num_classes): index = (gt_label * num_classes + pred_label).astype('int32') label_count = np.bincount(index) confusion_matrix = np.zeros((num_classes, num_classes)) for i_label in range(num_classes): for i_pred_label in range(num_classes): ...
Calcute the confusion matrix by given label and pred :param gt_label: the ground truth label :param pred_label: the pred label :param num_classes: the nunber of class :return: the confusion matrix
30
43
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_confusion_matrix(gt_label, pred_label, num_classes): index = (gt_label * num_classes + pred_label).astype('int32') label_count = np.bincount(index) confusion_matrix ...
1,830
def make_pad_mask(lengths, xs=None, length_dim=-1): if length_dim == 0: raise ValueError('length_dim cannot be 0: {}'.format(length_dim)) if not isinstance(lengths, list): lengths = lengths.tolist() bs = int(len(lengths)) if xs is None: maxlen = int(max(lengths)) else: ...
Make mask tensor containing indices of padded part. Args: lengths (LongTensor or List): Batch of lengths (B,). xs (Tensor, optional): The reference tensor. If set, masks will be the same shape as this tensor. length_dim (int, optional): Dimension indicator of the above tensor. See the examp...
417
103
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def make_pad_mask(lengths, xs=None, length_dim=-1): if length_dim == 0: raise ValueError('length_dim cannot be 0: {}'.format(length_dim)) if not isinstance(lengths, lis...
1,831
def test_guess_content_type_from_filename(self) -> None: data, content_type = encode_multipart_formdata({"file": ("somefile", b"zulip!", None)}) result = self.api_post( self.example_user("hamlet"), "/api/v1/user_uploads", data, content_type=content_type ) self.assert...
Test coverage for files without content-type in the metadata; in which case we try to guess the content-type from the filename.
21
58
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_guess_content_type_from_filename(self) -> None: data, content_type = encode_multipart_formdata({"file": ("somefile", b"zulip!", None)}) result = self.api_po...
1,832
def get_member(name, members): # look first for a generic match - prepend lib and append .so expr = rf'lib{name}\.so' member = get_one_match(expr, members) if member: return member elif AIX_ABI == 64: expr = rf'lib{name}64\.so' member = get_one_match(expr, members) i...
Return an archive member matching the request in name. Name is the library name without any prefix like lib, suffix like .so, or version number. Given a list of members find and return the most appropriate result Priority is given to generic libXXX.so, then a versioned libXXX.so.a.b.c and final...
53
85
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_member(name, members): # look first for a generic match - prepend lib and append .so expr = rf'lib{name}\.so' member = get_one_match(expr, members) if member: ...
1,833
def check_original_docker_image(): if not os.path.isfile('/.dockerenv') or os.environ.get('PYTHON_BASE_IMAGE') is None: raise pytest.skip( )
Adding/removing a user as part of a test is very bad for host os (especially if the user already existed to begin with on the OS), therefore we check if we run inside a the official docker container and only allow to run the test there. This is done by checking /.dockerenv file (always present inside container) and che...
62
12
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def check_original_docker_image(): if not os.path.isfile('/.dockerenv') or os.environ.get('PYTHON_BASE_IMAGE') is None: raise pytest.skip( ) ``` ...
1,834
def _useWizardInterface(): if not conf.wizard: return logger.info("starting wizard interface") while not conf.url: message = "Please enter full target URL (-u): " conf.url = readInput(message, default=None) message = "%s data (--data) [Enter for None]: " % ((conf.method ...
Presents simple wizard interface for beginner users
7
253
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _useWizardInterface(): if not conf.wizard: return logger.info("starting wizard interface") while not conf.url: message = "Please enter full target URL...
1,835
async def run_migrations_online() -> None: engine = await db_interface.engine() versions_dir = context.get_x_argument(as_dictionary=True).get("versions_dir", None) if versions_dir is None: # if version dir is not explicitly provided determine versions location from dialect dialect = ...
Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context.
21
63
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python async def run_migrations_online() -> None: engine = await db_interface.engine() versions_dir = context.get_x_argument(as_dictionary=True).get("versions_dir", None) if ver...
1,836
def get_mop_query(doctype, txt, searchfield, start, page_len, filters): return frappe.db.sql( , {"parent": filters.get("parent"), "start": start, "page_len": page_len, "txt": "%%%s%%" % txt}, ) @frappe.whitelist() @frappe.validate_and_sanitize_search_inputs
select mode_of_payment from `tabPayment Order Reference` where parent = %(parent)s and mode_of_payment like %(txt)s limit %(start)s, %(page_len)s
17
23
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_mop_query(doctype, txt, searchfield, start, page_len, filters): return frappe.db.sql( , {"parent": filters.get("parent"), "start": start, "page_len": page_len, "txt": "%%%s%%" %...
1,837
def test_doc_pyplot_summary(): pyplot_docs = Path(__file__).parent / '../../../doc/api/pyplot_summary.rst' if not pyplot_docs.exists(): pytest.skip("Documentation sources not available") lines = pyplot_docs.read_text() m = re.search(r':nosignatures:\n\n(.*?)\n\n', lines, re.DOTALL) doc...
Test that pyplot_summary lists all the plot functions.
8
88
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_doc_pyplot_summary(): pyplot_docs = Path(__file__).parent / '../../../doc/api/pyplot_summary.rst' if not pyplot_docs.exists(): pytest.skip("Documentation source...
1,838
def validate_child_on_delete(row, parent): if parent.doctype == "Sales Order": if flt(row.delivered_qty): frappe.throw( _("Row #{0}: Cannot delete item {1} which has already been delivered").format( row.idx, row.item_code ) ) if flt(row.work_order_qty): frappe.throw( _("Row #{0}: Cannot...
Check if partially transacted item (row) is being deleted.
9
107
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def validate_child_on_delete(row, parent): if parent.doctype == "Sales Order": if flt(row.delivered_qty): frappe.throw( _("Row #{0}: Cannot delete item {1} which has already been...
1,839
def _get_items(self): postprocess_items = {} # Debug Landmarks if (hasattr(self._args, 'debug_landmarks') and self._args.debug_landmarks): postprocess_items["DebugLandmarks"] = None # Face Filter post processing if ((hasattr(self._args, "filter") and self._a...
Check the passed in command line arguments for requested actions, For any requested actions, add the item to the actions list along with any relevant arguments and keyword arguments. Returns ------- dict The name of the action to be performed as the key. Any action...
53
108
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _get_items(self): postprocess_items = {} # Debug Landmarks if (hasattr(self._args, 'debug_landmarks') and self._args.debug_landmarks): postpr...
1,840
def _collapse_addresses_internal(addresses): # First merge to_merge = list(addresses) subnets = {} while to_merge: net = to_merge.pop() supernet = net.supernet() existing = subnets.get(supernet) if existing is None: subnets[supernet] = net elif ex...
Loops through the addresses, collapsing concurrent netblocks. Example: ip1 = IPv4Network('192.0.2.0/26') ip2 = IPv4Network('192.0.2.64/26') ip3 = IPv4Network('192.0.2.128/26') ip4 = IPv4Network('192.0.2.192/26') _collapse_addresses_internal([ip1, ip2, ip3, ip4]) -> ...
57
83
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _collapse_addresses_internal(addresses): # First merge to_merge = list(addresses) subnets = {} while to_merge: net = to_merge.pop() supernet = net.su...
1,841
def inaxes(self, xy): axes_list = [a for a in self.figure.get_axes() if a.patch.contains_point(xy) and a.get_visible()] if axes_list: axes = cbook._topmost_artist(axes_list) else: axes = None return axes
Return the topmost visible `~.axes.Axes` containing the point *xy*. Parameters ---------- xy : (float, float) (x, y) pixel positions from left/bottom of the canvas. Returns ------- `~matplotlib.axes.Axes` or None The topmost visible Axes...
46
25
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def inaxes(self, xy): axes_list = [a for a in self.figure.get_axes() if a.patch.contains_point(xy) and a.get_visible()] if axes_list: ...
1,842
def upgrade(): conn = op.get_bind() is_sqlite = bool(conn.dialect.name == "sqlite") is_mssql = bool(conn.dialect.name == "mssql") if is_sqlite: op.execute("PRAGMA foreign_keys=off") with op.batch_alter_table('dag_run', schema=None) as batch_op: batch_op.add_column(sa.Column('l...
Apply Add ``scheduling_decision`` to ``DagRun`` and ``DAG`` UPDATE dag SET concurrency={concurrency}, has_task_concurrency_limits={1 if is_sqlite or is_mssql else sa.true()} where concurrency IS NULL
22
135
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def upgrade(): conn = op.get_bind() is_sqlite = bool(conn.dialect.name == "sqlite") is_mssql = bool(conn.dialect.name == "mssql") if is_sqlite: op.execute("PRAG...
1,843
def enrich_ledger_entries_with_event_data(self, ledger_entries): # Build up a list of the subset of ledger entries we are expected # to enrich with event metadata. event_id_to_ledger_entry = {} for entry in ledger_entries: maybe_event_id: Optional[str] = entry.get("e...
Enriches a list of ledger entries with event metadata (applies only to decrements that have an event_id property set, i.e. automated decrements to the ledger applied by Orb).
28
50
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def enrich_ledger_entries_with_event_data(self, ledger_entries): # Build up a list of the subset of ledger entries we are expected # to enrich with event metadata. ...
1,844
def test_cache() -> None: ledger_store = DictLedgerStore() user_key = b"1322" ledger = DataSubjectLedger.get_or_create(store=ledger_store, user_key=user_key) assert ( ledger._cache_constant2epsilon[0] == 0.05372712063485988 ), "The first value in the cache is incorrect" assert ( ...
Ensure the most up to date RDP-to-epsilon cache is being used.
11
81
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_cache() -> None: ledger_store = DictLedgerStore() user_key = b"1322" ledger = DataSubjectLedger.get_or_create(store=ledger_store, user_key=user_key) assert ( ...
1,845
def get_lexer_for_mimetype(_mime, **options): for modname, name, _, _, mimetypes in LEXERS.values(): if _mime in mimetypes: if name not in _lexer_cache: _load_lexers(modname) return _lexer_cache[name](**options) for cls in find_plugin_lexers(): if _mi...
Get a lexer for a mimetype. Raises ClassNotFound if not found.
11
42
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_lexer_for_mimetype(_mime, **options): for modname, name, _, _, mimetypes in LEXERS.values(): if _mime in mimetypes: if name not in _lexer_cache: ...
1,846
def test_glm_regression(solver, fit_intercept, glm_dataset): model, X, y, _, coef_with_intercept, coef_without_intercept, alpha = glm_dataset params = dict( alpha=alpha, fit_intercept=fit_intercept, # While _GeneralizedLinearRegressor exposes the solver parameter, public # e...
Test that GLM converges for all solvers to correct solution. We work with a simple constructed data set with known solution.
21
127
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_glm_regression(solver, fit_intercept, glm_dataset): model, X, y, _, coef_with_intercept, coef_without_intercept, alpha = glm_dataset params = dict( alpha=alpha,...
1,847
def _cuda_check(self): with Popen("nvcc -V", shell=True, stdout=PIPE, stderr=PIPE) as chk: stdout, stderr = chk.communicate() if not stderr: version = re.search(r".*release (?P<cuda>\d+\.\d+)", stdout.decode(locale.getpreferredencoding()))...
Obtain the location and version of Cuda and populate :attr:`cuda_version` and :attr:`cuda_path` Initially just calls `nvcc -V` to get the installed version of Cuda currently in use. If this fails, drills down to more OS specific checking methods.
38
81
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _cuda_check(self): with Popen("nvcc -V", shell=True, stdout=PIPE, stderr=PIPE) as chk: stdout, stderr = chk.communicate() if not stderr: ...
1,848
def test_map_product_same(self, dag_maker, session): outputs = [] with dag_maker(dag_id="product_same", session=session) as dag:
Test a mapped task can refer to the same source multiple times.
12
12
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_map_product_same(self, dag_maker, session): outputs = [] with dag_maker(dag_id="product_same", session=session) as dag: ``` ###Assistant : Tes...
1,849
def get_deepbooru_tags(pil_image, threshold=0.5): from modules import shared # prevents circular reference create_deepbooru_process(threshold) shared.deepbooru_process_return["value"] = -1 shared.deepbooru_process_queue.put(pil_image) while shared.deepbooru_process_return["value"] == -1: ...
This method is for running only one image at a time for simple use. Used to the img2img interrogate.
19
24
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_deepbooru_tags(pil_image, threshold=0.5): from modules import shared # prevents circular reference create_deepbooru_process(threshold) shared.deepbooru_process_retu...
1,850
def test_update_from_select(self, mock_handler): self.set_handler(mock_handler, name='pg', tables={'tasks': self.df}) # --- use predictor --- predictor = { 'name': 'task_model', 'predict': 'p', 'dtypes': { 'p': dtype.float, 'a'...
update pg.table2 set a1 = df.a, c1 = df.c from ( SELECT model.a as a, model.b as b, model.p as c FROM pg.tasks as t ...
57
101
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_update_from_select(self, mock_handler): self.set_handler(mock_handler, name='pg', tables={'tasks': self.df}) # --- use predictor --- predictor = { ...
1,851
def get_total_shipments(scorecard): supplier = frappe.get_doc("Supplier", scorecard.supplier) # Look up all PO Items with delivery dates between our dates data = frappe.db.sql( , {"supplier": supplier.name, "start_date": scorecard.start_date, "end_date": scorecard.end_date}, as_dict=0, )[0][0] if not dat...
Gets the total number of ordered shipments to arrive in the period (based on Purchase Receipts) SELECT COUNT(po_item.base_amount) FROM `tabPurchase Order Item` po_item, `tabPurchase Order` po WHERE po.supplier = %(supplier)s AND po_item.schedule_date BETWEEN %(start_date)s AND %(end_date)s ...
44
38
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_total_shipments(scorecard): supplier = frappe.get_doc("Supplier", scorecard.supplier) # Look up all PO Items with delivery dates between our dates data = frappe.db.sql( , {...
1,852
def source(object): print('In file: %s' % inspect.getsourcefile(object)) print(inspect.getsource(object))
Prints the source code of a given object. .. deprecated:: 1.3 The ``source()`` function is deprecated. Use ``inspect.getsource()`` or ``??`` in IPython/Jupyter instead.
23
8
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def source(object): print('In file: %s' % inspect.getsourcefile(object)) print(inspect.getsource(object)) ``` ###Assistant : Prints the source code of a given...
1,853
def validate_axis(axis, input_shape): input_shape = tf.TensorShape(input_shape) rank = input_shape.rank if not rank: raise ValueError( f"Input has undefined rank. Received: input_shape={input_shape}" ) # Convert axis to list and resolve negatives if isinstance(axis,...
Validate an axis value and returns its standardized form. Args: axis: Value to validate. Can be an integer or a list/tuple of integers. Integers may be negative. input_shape: Reference input shape that the axis/axes refer to. Returns: Normalized form of `axis`, i.e. a list with all-p...
47
98
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def validate_axis(axis, input_shape): input_shape = tf.TensorShape(input_shape) rank = input_shape.rank if not rank: raise ValueError( f"Input has undefi...
1,854
def _filter_to(self, it, pred): buf = '' idx = 0 for i, t, v in it: if pred(t): if buf: yield idx, None, buf buf = '' yield i, t, v else: if not buf: idx =...
Keep only the tokens that match `pred`, merge the others together
11
47
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _filter_to(self, it, pred): buf = '' idx = 0 for i, t, v in it: if pred(t): if buf: yield idx, None, buf ...
1,855
def entity_registry_enabled_default(self) -> bool: return bool(self._config[CONF_ENABLED_BY_DEFAULT])
Return if the entity should be enabled when first added to the entity registry.
14
6
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def entity_registry_enabled_default(self) -> bool: return bool(self._config[CONF_ENABLED_BY_DEFAULT]) ``` ###Assistant : Return if the entity should be enabled ...
1,856
def bisectors(self): # use lines containing sides so containment check during # intersection calculation can be avoided, thus reducing # the processing time for calculating the bisectors s = [Line(l) for l in self.sides] v = self.vertices c = self.incenter ...
The angle bisectors of the triangle. An angle bisector of a triangle is a straight line through a vertex which cuts the corresponding angle in half. Returns ======= bisectors : dict Each key is a vertex (Point) and each value is the corresponding bisect...
91
62
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def bisectors(self): # use lines containing sides so containment check during # intersection calculation can be avoided, thus reducing # the processing time ...
1,857
def query(query, filters={}, top_k_reader=5, top_k_retriever=5) -> Tuple[List[Dict[str, Any]], Dict[str, str]]: url = f"{API_ENDPOINT}/{DOC_REQUEST}" params = {"filters": filters, "Retriever": {"top_k": top_k_retriever}, "Reader": {"top_k": top_k_reader}} req = {"query": query, "params": params} r...
Send a query to the REST API and parse the answer. Returns both a ready-to-use representation of the results and the raw JSON.
23
124
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def query(query, filters={}, top_k_reader=5, top_k_retriever=5) -> Tuple[List[Dict[str, Any]], Dict[str, str]]: url = f"{API_ENDPOINT}/{DOC_REQUEST}" params = {"filters": filte...
1,858
def format_target_temperature(target_temperature): return str(round(float(target_temperature) * 2, 0) / 2).rstrip("0").rstrip(".")
Format target temperature to be sent to the Daikin unit, rounding to nearest half degree.
15
9
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def format_target_temperature(target_temperature): return str(round(float(target_temperature) * 2, 0) / 2).rstrip("0").rstrip(".") ``` ###Assistant : Format target tem...
1,859
def get_data(filters=None): data = [] emirates, amounts_by_emirate = append_vat_on_sales(data, filters) append_vat_on_expenses(data, filters) return data, emirates, amounts_by_emirate
Returns the list of dictionaries. Each dictionary is a row in the datatable and chart data.
16
16
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_data(filters=None): data = [] emirates, amounts_by_emirate = append_vat_on_sales(data, filters) append_vat_on_expenses(data, filters) return data, emirates, amounts_by_emirate ...
1,860
def dict(self, *args, **kwargs): kwargs.setdefault("exclude_none", True) return super().dict(*args, **kwargs)
Exclude `None` fields by default to comply with the OpenAPI spec.
11
9
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def dict(self, *args, **kwargs): kwargs.setdefault("exclude_none", True) return super().dict(*args, **kwargs) ``` ###Assistant : Exclude `None` fields ...
1,861
def extract_column_names(self) -> Dict[str, Tuple[str, str]]: fields = [] for field in self.properties.keys(): if not is_airbyte_column(field): fields.append(field) result = {} field_names = set() for field in fields: field_name = ...
Generate a mapping of JSON properties to normalized SQL Column names, handling collisions and avoid duplicate names The mapped value to a field property is a tuple where: - the first value is the normalized "raw" column name - the second value is the normalized quoted column name to ...
54
83
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def extract_column_names(self) -> Dict[str, Tuple[str, str]]: fields = [] for field in self.properties.keys(): if not is_airbyte_column(field): ...
1,862
def _build_paths_from_predecessors(sources, target, pred): if target not in pred: raise nx.NetworkXNoPath(f"Target {target} cannot be reached from given sources") seen = {target} stack = [[target, 0]] top = 0 while top >= 0: node, i = stack[top] if node in sources: ...
Compute all simple paths to target, given the predecessors found in pred, terminating when any source in sources is found. Parameters ---------- sources : set Starting nodes for path. target : node Ending node for path. pred : dict A dictionary of predecessor lists, keyed...
126
88
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _build_paths_from_predecessors(sources, target, pred): if target not in pred: raise nx.NetworkXNoPath(f"Target {target} cannot be reached from given sources") seen ...
1,863
def is_connected(self) -> bool: return self._backend is not None and self._backend.is_connected
Return True if the client is connected to a device.
10
11
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def is_connected(self) -> bool: return self._backend is not None and self._backend.is_connected ``` ###Assistant : Return True if the client is connected to a d...
1,864
def _create_gnu_long_header(cls, name, type, encoding, errors): name = name.encode(encoding, errors) + NUL info = {} info["name"] = "././@LongLink" info["type"] = type info["size"] = len(name) info["magic"] = GNU_MAGIC # create extended header + name bl...
Return a GNUTYPE_LONGNAME or GNUTYPE_LONGLINK sequence for name.
8
42
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _create_gnu_long_header(cls, name, type, encoding, errors): name = name.encode(encoding, errors) + NUL info = {} info["name"] = "././@LongLink" ...
1,865
def genocchi_poly(n, x=None, polys=False): if n < 0: raise ValueError("Cannot generate Genocchi polynomial of degree %s" % (n-1)) poly = DMP(dup_genocchi(int(n), ZZ), ZZ) if x is not None: poly = Poly.new(poly, x) else: poly = PurePoly.new(poly, Dummy('x')) return poly i...
Generates the Genocchi polynomial `\operatorname{G}_n(x)`. `\operatorname{G}_n(x)` is twice the difference between the plain and central Bernoulli polynomials, so has degree `n-1`: .. math :: \operatorname{G}_n(x) = 2 (\operatorname{B}_n(x) - \operatorname{B}_n^c(x)) The factor of 2 in th...
70
43
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def genocchi_poly(n, x=None, polys=False): if n < 0: raise ValueError("Cannot generate Genocchi polynomial of degree %s" % (n-1)) poly = DMP(dup_genocchi(int(n), ZZ), ZZ...
1,866
def _triage_segments(window, nperseg, input_length): # parse window; if array like, then set nperseg = win.shape if isinstance(window, (str, tuple)): # if nperseg not specified if nperseg is None: nperseg = 256 # then change to default if nperseg > input_length: warnings.warn(f'nperseg =...
Parses window and nperseg arguments for spectrogram and _spectral_helper. This is a helper function, not meant to be called externally. Parameters ---------- window : string, tuple, or ndarray If window is specified by a string or tuple and nperseg is not specified, nperseg is set to the default ...
182
118
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _triage_segments(window, nperseg, input_length): # parse window; if array like, then set nperseg = win.shape if isinstance(window, (str, tuple)): # if nperseg not specified ...
1,867
def register_for_auto_class(cls, auto_class="AutoModel"): if not isinstance(auto_class, str): auto_class = auto_class.__name__ import transformers.models.auto as auto_module if not hasattr(auto_module, auto_class): raise ValueError(f"{auto_class} is not a valid...
Register this class with a given auto class. This should only be used for custom models as the ones in the library are already mapped with an auto class. Args: auto_class (`str` or `type`, *optional*, defaults to `"AutoModel"`): The auto class to register this new m...
47
57
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def register_for_auto_class(cls, auto_class="AutoModel"): if not isinstance(auto_class, str): auto_class = auto_class.__name__ import transformers.model...
1,868
def is_accelerate_available(): return _accelerate_available # docstyle-ignore FLAX_IMPORT_ERROR = # docstyle-ignore INFLECT_IMPORT_ERROR = # docstyle-ignore PYTORCH_IMPORT_ERROR = # docstyle-ignore ONNX_IMPORT_ERROR = # docstyle-ignore SCIPY_IMPORT_ERROR = # docstyle-ignore TENSORFLOW_IMPORT_ERROR = #...
{0} requires the FLAX library but it was not found in your environment. Checkout the instructions on the installation page: https://github.com/google/flax and follow the ones that match your environment. {0} requires the inflect library but it was not found in your environment. You can install it with pip: `pip insta...
197
66
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def is_accelerate_available(): return _accelerate_available # docstyle-ignore FLAX_IMPORT_ERROR = # docstyle-ignore INFLECT_IMPORT_ERROR = # docstyle-ignore PYTORCH_IMPORT_ERROR = ...
1,869
def set_horizontalalignment(self, align): _api.check_in_list(['center', 'right', 'left'], align=align) self._horizontalalignment = align self.stale = True
Set the horizontal alignment relative to the anchor point. See also :doc:`/gallery/text_labels_and_annotations/text_alignment`. Parameters ---------- align : {'left', 'center', 'right'}
19
13
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def set_horizontalalignment(self, align): _api.check_in_list(['center', 'right', 'left'], align=align) self._horizontalalignment = align self.stale = True ...
1,870
def _wrap_awaitable(awaitable): return (yield from awaitable.__await__()) _wrap_awaitable._is_coroutine = _is_coroutine
Helper for asyncio.ensure_future(). Wraps awaitable (an object with __await__) into a coroutine that will later be wrapped in a Task by ensure_future().
22
9
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _wrap_awaitable(awaitable): return (yield from awaitable.__await__()) _wrap_awaitable._is_coroutine = _is_coroutine ``` ###Assistant : Helper for asyncio.ensure_f...
1,871
def normalize_file(file, separators=None): # Normalize path separators. if separators is None: separators = NORMALIZE_PATH_SEPS # Convert path object to string. norm_file = str(file) for sep in separators: norm_file = norm_file.replace(sep, posixpath.sep) # Remove current directory prefix. if norm_file....
Normalizes the file path to use the POSIX path separator (i.e., ``'/'``). *file* (:class:`str` or :class:`pathlib.PurePath`) is the file path. *separators* (:class:`~collections.abc.Collection` of :class:`str`; or :data:`None`) optionally contains the path separators to normalize. This does not need to include ...
75
43
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def normalize_file(file, separators=None): # Normalize path separators. if separators is None: separators = NORMALIZE_PATH_SEPS # Convert path object to string. norm_file = str(file...
1,872
def wildcard_types(self) -> List[str]: return [t for t, state_keys in self.types.items() if state_keys is None]
Returns a list of event types which require us to fetch all state keys. This will be empty unless `has_wildcards` returns True. Returns: A list of event types.
28
15
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def wildcard_types(self) -> List[str]: return [t for t, state_keys in self.types.items() if state_keys is None] ``` ###Assistant : Returns a list of event types...
1,873
def get_columns(self, table_name) -> Response: q = f"SHOW COLUMNS IN TABLE {table_name};" result = self.native_query(q) return result
List the columns in the tabels for which the user have access
12
17
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_columns(self, table_name) -> Response: q = f"SHOW COLUMNS IN TABLE {table_name};" result = self.native_query(q) return result ``` ###Ass...
1,874
def get_on_time_shipments(scorecard): supplier = frappe.get_doc("Supplier", scorecard.supplier) # Look up all PO Items with delivery dates between our dates total_items_delivered_on_time = frappe.db.sql( , {"supplier": supplier.name, "start_date": scorecard.start_date, "end_date": scorecard.end_date}, as_d...
Gets the number of late shipments (counting each item) in the period (based on Purchase Receipts vs POs) SELECT COUNT(pr_item.qty) FROM `tabPurchase Order Item` po_item, `tabPurchase Receipt Item` pr_item, `tabPurchase Order` po, `tabPurchase Receipt` pr WHERE po.supplier = %(supplier)s...
69
38
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_on_time_shipments(scorecard): supplier = frappe.get_doc("Supplier", scorecard.supplier) # Look up all PO Items with delivery dates between our dates total_items_delivered_on_t...
1,875
def test_commit_comment_deleted(self) -> None: expected_message = self.check_webhook("commit_comment_deleted", TOPIC, expected_message)
[hypro999](http://139.59.64.214:7990/users/hypro999) deleted their comment on [508d1b67f1f](http://139.59.64.214:7990/projects/SBOX/repos/sandbox/commits/508d1b67f1f8f3a25f543a030a7a178894aa9907):\n~~~ quote\n~~Just an arbitrary comment on a commit. Nothing to see here...~~\n~~~
17
9
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_commit_comment_deleted(self) -> None: expected_message = self.check_webhook("commit_comment_deleted", TOPIC, expected_message) ``` ###Assistant : [hypr...
1,876
async def get_work_queues(self) -> Optional[UUID]: work_queues = [] for name in self.work_queues: try: # support IDs and names if isinstance(name, UUID): work_queue = await self.client.read_work_queue(id=name) else:...
Loads the work queue objects corresponding to the agent's target work queues. If any of them don't exist, they are created.
21
42
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python async def get_work_queues(self) -> Optional[UUID]: work_queues = [] for name in self.work_queues: try: # support IDs and names ...
1,877
def test_read_nonexistent_stream_raises_exception(mocker): s1 = MockStream(name="s1") s2 = MockStream(name="this_stream_doesnt_exist_in_the_source") mocker.patch.object(MockStream, "get_json_schema", return_value={}) src = MockSource(streams=[s1]) catalog = ConfiguredAirbyteCatalog(streams=[_...
Tests that attempting to sync a stream which the source does not return from the `streams` method raises an exception
20
26
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_read_nonexistent_stream_raises_exception(mocker): s1 = MockStream(name="s1") s2 = MockStream(name="this_stream_doesnt_exist_in_the_source") mocker.patch.object(Moc...
1,878
def _should_queue(self, link, referrer, rel): scheme, netloc, path, _, _, _ = urlparse(link) if path.endswith(self.source_extensions + self.binary_extensions + self.excluded_extensions): result = False elif self.skip_externals and not link.startswith...
Determine whether a link URL from a referring page and with a particular "rel" attribute should be queued for scraping.
20
89
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _should_queue(self, link, referrer, rel): scheme, netloc, path, _, _, _ = urlparse(link) if path.endswith(self.source_extensions + self.binary_extensions + ...
1,879
def receive(): header = _in_file.read(16) _logger.debug('Received command, header: [%s]', header) if header is None or len(header) < 16: # Pipe EOF encountered _logger.debug('Pipe EOF encountered') return None, None length = int(header[2:]) data = _in_file.read(length) ...
Receive a command from Training Service. Returns a tuple of command (CommandType) and payload (str)
15
48
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def receive(): header = _in_file.read(16) _logger.debug('Received command, header: [%s]', header) if header is None or len(header) < 16: # Pipe EOF encountered ...
1,880
def bettertitle(value): return ' '.join([w[0].upper() + w[1:] for w in value.split()]) @register.filter()
Alternative to the builtin title(). Ensures that the first letter of each word is uppercase but retains the original case of all others.
23
12
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def bettertitle(value): return ' '.join([w[0].upper() + w[1:] for w in value.split()]) @register.filter() ``` ###Assistant : Alternative to the builtin title(). E...
1,881
def load_pascal_annotation(index, pascal_root): classes = ('__background__', # always index 0 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike', 'pers...
This code is borrowed from Ross Girshick's FAST-RCNN code (https://github.com/rbgirshick/fast-rcnn). It parses the PASCAL .xml metadata files. See publication for further details: (http://arxiv.org/abs/1504.08083). Thanks Ross!
25
45
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def load_pascal_annotation(index, pascal_root): classes = ('__background__', # always index 0 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus',...
1,882
def get(self): logger = get_logger() logger.debug(f"ENTER::Partition.get::{self._identity}") if len(self.call_queue): self.drain_call_queue() result = UnidistWrapper.materialize(self._data) logger.debug(f"EXIT::Partition.get::{self._identity}") return...
Get the object wrapped by this partition out of the object store. Returns ------- pandas.DataFrame The object from the object store.
21
15
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get(self): logger = get_logger() logger.debug(f"ENTER::Partition.get::{self._identity}") if len(self.call_queue): self.drain_call_queue() ...
1,883
def test_custom_function_action_no_perm_response(self): action_data = { ACTION_CHECKBOX_NAME: [self.s1.pk], "action": "no_perm", "index": 0, } response = self.client.post( reverse("admin:admin_views_externalsubscriber_changelist"), action_...
A custom action may returns an HttpResponse with a 403 code.
11
27
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_custom_function_action_no_perm_response(self): action_data = { ACTION_CHECKBOX_NAME: [self.s1.pk], "action": "no_perm", "index":...
1,884
def limit(self, *args): return self.applyfunc(lambda x: x.limit(*args)) # https://github.com/sympy/sympy/pull/12854
Calculate the limit of each element in the matrix. ``args`` will be passed to the ``limit`` function. Examples ======== >>> from sympy import Matrix >>> from sympy.abc import x, y >>> M = Matrix([[x, y], [1, 0]]) >>> M.limit(x, 2) Matrix([ [2, y]...
50
9
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def limit(self, *args): return self.applyfunc(lambda x: x.limit(*args)) # https://github.com/sympy/sympy/pull/12854 ``` ###Assistant : Calculate the limit of e...
1,885
def test_device_classes_aligned(): non_numeric_device_classes = { SensorDeviceClass.DATE, SensorDeviceClass.DURATION, SensorDeviceClass.TIMESTAMP, } for device_class in SensorDeviceClass: if device_class in non_numeric_device_classes: continue asse...
Make sure all sensor device classes are also available in NumberDeviceClass.
11
26
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_device_classes_aligned(): non_numeric_device_classes = { SensorDeviceClass.DATE, SensorDeviceClass.DURATION, SensorDeviceClass.TIMESTAMP, } ...
1,886
def valid_tess_config(outdir): cfg_file = outdir / 'test.cfg' with cfg_file.open('w') as f: f.write( ) yield cfg_file
\ load_system_dawg 0 language_model_penalty_non_dict_word 0 language_model_penalty_non_freq_dict_word 0
7
15
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def valid_tess_config(outdir): cfg_file = outdir / 'test.cfg' with cfg_file.open('w') as f: f.write( ) yield cfg_file ``` ###Assistant ...
1,887
def year_lookup_bounds_for_datetime_field(self, value, iso_year=False): if iso_year: first = datetime.datetime.fromisocalendar(value, 1, 1) second = datetime.datetime.fromisocalendar( value + 1, 1, 1 ) - datetime.timedelta(microseconds=1) else...
Return a two-elements list with the lower and upper bound to be used with a BETWEEN operator to query a DateTimeField value using a year lookup. `value` is an int, containing the looked-up year. If `iso_year` is True, return bounds for ISO-8601 week-numbering years.
44
59
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def year_lookup_bounds_for_datetime_field(self, value, iso_year=False): if iso_year: first = datetime.datetime.fromisocalendar(value, 1, 1) second = ...
1,888
def gegenbauer_poly(n, a, x=None, polys=False): r return named_poly(n, dup_gegenbauer, None, "Gegenbauer polynomial", (x, a), polys)
Generates the Gegenbauer polynomial `C_n^{(a)}(x)`. Parameters ========== n : int Degree of the polynomial. x : optional a Decides minimal domain for the list of coefficients. polys : bool, optional If True, return a Poly, otherwise (default) return an expression.
40
15
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def gegenbauer_poly(n, a, x=None, polys=False): r return named_poly(n, dup_gegenbauer, None, "Gegenbauer polynomial", (x, a), polys) ``` ###Assistant : Generates the Ge...
1,889
async def async_update(self, now=None): if not self.pollable_characteristics: self.async_update_available_state() _LOGGER.debug( "HomeKit connection not polling any characteristics: %s", self.unique_id ) return if self._polling_lo...
Poll state of all entities attached to this bridge/accessory.
9
68
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python async def async_update(self, now=None): if not self.pollable_characteristics: self.async_update_available_state() _LOGGER.debug( "Hom...
1,890
def _merge(self, start, end, left, right): # type: (int, int, int, int) -> Iterator[Tuple[int, int]] lslice, rslice = self._left[left:right], self._right[left:right] i = start = min([start]+lslice[:1]) end = max([end]+rslice[-1:]) for j, k in zip(lslice, rslice): ...
Return an iterator of intervals to be fetched. Args: start (int): Start of needed interval end (int): End of needed interval left (int): Index of first overlapping downloaded data right (int): Index after last overlapping downloaded data
37
58
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _merge(self, start, end, left, right): # type: (int, int, int, int) -> Iterator[Tuple[int, int]] lslice, rslice = self._left[left:right], self._right[left:right]...
1,891
def is_python_identifier(self): # type: (str) -> bool # Ref: https://stackoverflow.com/a/55802320/595220 return bool(re.match(_VALID_IDENTIFIER_STRING_REGEX, self)) PB_EXTENSIONS = ('.yml', '.yaml')
Determine whether the given string is a Python identifier.
9
17
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def is_python_identifier(self): # type: (str) -> bool # Ref: https://stackoverflow.com/a/55802320/595220 return bool(re.match(_VALID_IDENTIFIER_STRING_REGEX, self))...
1,892
def _stream_response(self, start, end, base_headers=HEADERS): # type: (int, int, Dict[str, str]) -> Response headers = base_headers.copy() headers['Range'] = f'bytes={start}-{end}' # TODO: Get range requests to be correctly cached headers['Cache-Control'] = 'no-cache' ...
Return HTTP response to a range request from start to end.
11
35
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _stream_response(self, start, end, base_headers=HEADERS): # type: (int, int, Dict[str, str]) -> Response headers = base_headers.copy() headers['Range'] =...
1,893
def _inject_greasemonkey_scripts(self, scripts): if sip.isdeleted(self._widget): return # Since we are inserting scripts into a per-tab collection, # rather than just injecting scripts on page load, we need to # make sure we replace existing scripts, not just add ne...
Register user JavaScript files with the current tab. Args: scripts: A list of GreasemonkeyScripts.
14
203
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _inject_greasemonkey_scripts(self, scripts): if sip.isdeleted(self._widget): return # Since we are inserting scripts into a per-tab collection, ...
1,894
def config(self) -> dict: global _CONFIG # pylint: disable=global-statement if not _CONFIG: model_name = self._config_section logger.debug("Loading config for: %s", model_name) _CONFIG = Config(model_name, configfile=self._configfile).config_dict ret...
dict: The configuration dictionary for current plugin, as set by the user's configuration settings.
14
26
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def config(self) -> dict: global _CONFIG # pylint: disable=global-statement if not _CONFIG: model_name = self._config_section logger.debug("...
1,895
def execute(): frappe.reload_doc("stock", "doctype", "stock_entry") if frappe.db.has_column("Stock Entry", "add_to_transit"): frappe.db.sql( ) frappe.db.sql( ) frappe.reload_doc("stock", "doctype", "warehouse_type") if not frappe.db.exists("Warehouse Type", "Transit"): doc = frappe.new_doc("W...
UPDATE `tabStock Entry` SET stock_entry_type = 'Material Transfer', purpose = 'Material Transfer', add_to_transit = 1 WHERE stock_entry_type = 'Send to Warehouse' UPDATE `tabStock Entry` SET stock_entry_type = 'Material Transfer', purp...
39
44
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def execute(): frappe.reload_doc("stock", "doctype", "stock_entry") if frappe.db.has_column("Stock Entry", "add_to_transit"): frappe.db.sql( ) frappe.db.sql( ) frappe.r...
1,896
def query_task(doctype, txt, searchfield, start, page_len, filters): from frappe.desk.reportview import build_match_conditions search_string = "%%%s%%" % txt order_by_string = "%s%%" % txt match_conditions = build_match_conditions("Task") match_conditions = ("and" + match_conditions) if match_conditions else "" ...
select name, subject from `tabTask` where (`%s` like %s or `subject` like %s) %s order by case when `subject` like %s then 0 else 1 end, case when `%s` like %s then 0 else 1 end, `%s`, subject limit %s, %s
41
53
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def query_task(doctype, txt, searchfield, start, page_len, filters): from frappe.desk.reportview import build_match_conditions search_string = "%%%s%%" % txt order_by_string = "%s%%" % t...
1,897
def _parse_name(self, name): if name.endswith("_float32_vars"): error_msg = ( "Policies ending in '_float32_vars' have been removed " "from TensorFlow." ) if name in ("infer_float32_vars", "infer_with_float32_vars"): er...
Parses a Policy name into a compute and variable dtype. Args: name: The name of the policy: Returns: The (compute_dtype, variable_dtype) pair.
22
242
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _parse_name(self, name): if name.endswith("_float32_vars"): error_msg = ( "Policies ending in '_float32_vars' have been removed " ...
1,898
def reraise_exceptions_as_crashes(): try: yield except BaseException as exc: state = exception_to_crashed_state(exc) raise Crash(message=state.message, cause=exc, state=state) from exc
Detect crashes during this context, wrapping unexpected exceptions into `Crash` signals.
11
17
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def reraise_exceptions_as_crashes(): try: yield except BaseException as exc: state = exception_to_crashed_state(exc) raise Crash(message=state.message, c...
1,899
def resoure_check(): MINIMUM_ALLOWED_MEMORY = 4 MINIMUM_ALLOWED_CPUS = 2 MINIMUM_ALLOWED_DISK = 20 print("\nChecking resources.\n") # Memory current available svmem = psutil.virtual_memory() mem_available = get_size(svmem.available) # Cpus current available cpus_available = ps...
Use gsutil to get resources in bytes for memory and disk
11
60
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def resoure_check(): MINIMUM_ALLOWED_MEMORY = 4 MINIMUM_ALLOWED_CPUS = 2 MINIMUM_ALLOWED_DISK = 20 print("\nChecking resources.\n") # Memory current available s...