ASHu2/docs-python-v1
Dataset Card for Dataset Name This dataset card aims to be a base template for creating python docs from methods. This is formatted from semeru/code-code-galeras-code-completion-from-docstring-3k-deduped Dataset Description Curated by: semeru/code-code-galeras-code-completion-from-docstring-3k-deduped Language(s) (NLP): Python License: [More Information Needed] Dataset Sources [optional] Repository:… See the full description on the dataset page: https://huggingface.co/datasets/ASHu2/docs-python-v1.
228
1,code,docs,doc_len,words,lang,prompt20,"def rolling(self, *args, **kwargs) -> RollingGroupby:3 4 from pandas.core.window import RollingGroupby5 6 return RollingGroupby(7 self._selected_obj,8 *args,9 _grouper=self.grouper,10 _as_index=self.as_index,11 **kwargs,12 )13","14 Return a rolling grouper, providing rolling functionality per group.15 ",9,18,Python,"16 ###User : Below is a Python method which does a task. Create a documentation for the below code : 17 ```Python18 def rolling(self, *args, **kwargs) -> RollingGroupby:19 20 from pandas.core.window import RollingGroupby21 22 return RollingGroupby(23 self._selected_obj,24 *args,25 _grouper=self.grouper,26 _as_index=self.as_index,27 **kwargs,28 )29 30 ```31 ###Assistant : 32 Return a rolling grouper, providing rolling functionality per group.33 34 "351,"def expected_degree_graph(w, seed=None, selfloops=True):36 r37 n = len(w)38 G = nx.empty_graph(n)39 40 # If there are no nodes are no edges in the graph, return the empty graph.41 if n == 0 or max(w) == 0:42 return G43 44 rho = 1 / sum(w)45 # Sort the weights in decreasing order. The original order of the46 # weights dictates the order of the (integer) node labels, so we47 # need to remember the permutation applied in the sorting.48 order = sorted(enumerate(w), key=itemgetter(1), reverse=True)49 mapping = {c: u for c, (u, v) in enumerate(order)}50 seq = [v for u, v in order]51 last = n52 if not selfloops:53 last -= 154 for u in range(last):55 v = u56 if not selfloops:57 v += 158 factor = seq[u] * rho59 p = min(seq[v] * factor, 1)60 while v < n and p > 0:61 if p != 1:62 r = seed.random()63 v += math.floor(math.log(r, 1 - p))64 if v < n:65 q = min(seq[v] * factor, 1)66 if seed.random() < q / p:67 G.add_edge(mapping[u], mapping[v])68 v += 169 p = q70 return G71 72","Returns a random graph with given expected degrees.73 74 Given a sequence of expected degrees $W=(w_0,w_1,\ldots,w_{n-1})$75 of length $n$ this algorithm assigns an edge between node $u$ and76 node $v$ with probability77 78 .. math::79 80 p_{uv} = \frac{w_u w_v}{\sum_k w_k} .81 82 Parameters83 ----------84 w : list85 The list of expected degrees.86 selfloops: bool (default=True)87 Set to False to remove the possibility of self-loop edges.88 seed : integer, random_state, or None (default)89 Indicator of random number generation state.90 See :ref:`Randomness<randomness>`.91 92 Returns93 -------94 Graph95 96 Examples97 --------98 >>> z = [10 for i in range(100)]99 >>> G = nx.expected_degree_graph(z)100 101 Notes102 -----103 The nodes have integer labels corresponding to index of expected degrees104 input sequence.105 106 The complexity of this algorithm is $\mathcal{O}(n+m)$ where $n$ is the107 number of nodes and $m$ is the expected number of edges.108 109 The model in [1]_ includes the possibility of self-loop edges.110 Set selfloops=False to produce a graph without self loops.111 112 For finite graphs this model doesn't produce exactly the given113 expected degree sequence. Instead the expected degrees are as114 follows.115 116 For the case without self loops (selfloops=False),117 118 .. math::119 120 E[deg(u)] = \sum_{v \ne u} p_{uv}121 = w_u \left( 1 - \frac{w_u}{\sum_k w_k} \right) .122 123 124 NetworkX uses the standard convention that a self-loop edge counts 2125 in the degree of a node, so with self loops (selfloops=True),126 127 .. math::128 129 E[deg(u)] = \sum_{v \ne u} p_{uv} + 2 p_{uu}130 = w_u \left( 1 + \frac{w_u}{\sum_k w_k} \right) .131 132 References133 ----------134 .. [1] Fan Chung and L. Lu, Connected components in random graphs with135 given expected degree sequences, Ann. Combinatorics, 6,136 pp. 125-145, 2002.137 .. [2] Joel Miller and Aric Hagberg,138 Efficient generation of networks with given expected degrees,139 in Algorithms and Models for the Web-Graph (WAW 2011),140 Alan Frieze, Paul Horn, and Paweł Prałat (Eds), LNCS 6732,141 pp. 115-126, 2011.142 ",298,179,Python,"143 ###User : Below is a Python method which does a task. Create a documentation for the below code : 144 ```Python145 def expected_degree_graph(w, seed=None, selfloops=True):146 r147 n = len(w)148 G = nx.empty_graph(n)149 150 # If there are no nodes are no edges in the graph, return the empty graph.151 if n == 0 or max(w) == 0:152 return G153 154 rho = 1 / sum(w)155 # Sort the weights in decreasing order. The original order of the156 # weights dictates the order of the (integer) node labels, so we157 # need to remember the permutation applied in the sorting.158 order = sorted(enumerate(w), key=itemgetter(1), reverse=True)159 mapping = {c: u for c, (u, v) in enumerate(order)}160 seq = [v for u, v in order]161 last = n162 if not selfloops:163 last -= 1164 for u in range(last):165 v = u166 if not selfloops:167 v += 1168 factor = seq[u] * rho169 p = min(seq[v] * factor, 1)170 while v < n and p > 0:171 if p != 1:172 r = seed.random()173 v += math.floor(math.log(r, 1 - p))174 if v < n:175 q = min(seq[v] * factor, 1)176 if seed.random() < q / p:177 G.add_edge(mapping[u], mapping[v])178 v += 1179 p = q180 return G181 182 183 ```184 ###Assistant : Returns a random graph with given expected degrees.185 186 Given a sequence of expected degrees $W=(w_0,w_1,\ldots,w_{n-1})$187 of length $n$ this algorithm assigns an edge between node $u$ and188 node $v$ with probability189 190 .. math::191 192 p_{uv} = \frac{w_u w_v}{\sum_k w_k} .193 194 Parameters195 ----------196 w : list197 The list of expected degrees.198 selfloops: bool (default=True)199 Set to False to remove the possibility of self-loop edges.200 seed : integer, random_state, or None (default)201 Indicator of random number generation state.202 See :ref:`Randomness<randomness>`.203 204 Returns205 -------206 Graph207 208 Examples209 --------210 >>> z = [10 for i in range(100)]211 >>> G = nx.expected_degree_graph(z)212 213 Notes214 -----215 The nodes have integer labels corresponding to index of expected degrees216 input sequence.217 218 The complexity of this algorithm is $\mathcal{O}(n+m)$ where $n$ is the219 number of nodes and $m$ is the expected number of edges.220 221 The model in [1]_ includes the possibility of self-loop edges.222 Set selfloops=False to produce a graph without self loops.223 224 For finite graphs this model doesn't produce exactly the given225 expected degree sequence. Instead the expected degrees are as226 follows.227 228 For the case without self loops (selfloops=False),229 230 .. math::231 232 E[deg(u)] = \sum_{v \ne u} p_{uv}233 = w_u \left( 1 - \frac{w_u}{\sum_k w_k} \right) .234 235 236 NetworkX uses the standard convention that a self-loop edge counts 2237 in the degree of a node, so with self loops (selfloops=True),238 239 .. math::240 241 E[deg(u)] = \sum_{v \ne u} p_{uv} + 2 p_{uu}242 = w_u \left( 1 + \frac{w_u}{\sum_k w_k} \right) .243 244 References245 ----------246 .. [1] Fan Chung and L. Lu, Connected components in random graphs with247 given expected degree sequences, Ann. Combinatorics, 6,248 pp. 125-145, 2002.249 .. [2] Joel Miller and Aric Hagberg,250 Efficient generation of networks with given expected degrees,251 in Algorithms and Models for the Web-Graph (WAW 2011),252 Alan Frieze, Paul Horn, and Paweł Prałat (Eds), LNCS 6732,253 pp. 115-126, 2011.254 255 "2562,"def save(self, path):257 258 os.makedirs(path, exist_ok=True)259 with open(os.path.join(path, ""metrics.json""), ""w"") as fp:260 json.dump(self.metrics, fp)261 262 artifacts_metadata = {263 artifact_name: {264 ""uri"": artifact.uri,265 ""class_name"": _get_fully_qualified_class_name(artifact),266 }267 for artifact_name, artifact in self.artifacts.items()268 }269 with open(os.path.join(path, ""artifacts_metadata.json""), ""w"") as fp:270 json.dump(artifacts_metadata, fp)271 272 artifacts_dir = os.path.join(path, ""artifacts"")273 os.mkdir(artifacts_dir)274 275 for artifact_name, artifact in self.artifacts.items():276 artifact._save(os.path.join(artifacts_dir, artifact_name))277",Write the evaluation results to the specified local filesystem path,10,49,Python,"278 ###User : Below is a Python method which does a task. Create a documentation for the below code : 279 ```Python280 def save(self, path):281 282 os.makedirs(path, exist_ok=True)283 with open(os.path.join(path, ""metrics.json""), ""w"") as fp:284 json.dump(self.metrics, fp)285 286 artifacts_metadata = {287 artifact_name: {288 ""uri"": artifact.uri,289 ""class_name"": _get_fully_qualified_class_name(artifact),290 }291 for artifact_name, artifact in self.artifacts.items()292 }293 with open(os.path.join(path, ""artifacts_metadata.json""), ""w"") as fp:294 json.dump(artifacts_metadata, fp)295 296 artifacts_dir = os.path.join(path, ""artifacts"")297 os.mkdir(artifacts_dir)298 299 for artifact_name, artifact in self.artifacts.items():300 artifact._save(os.path.join(artifacts_dir, artifact_name))301 302 ```303 ###Assistant : Write the evaluation results to the specified local filesystem path304 "3053,"def test_build_group_generic_issue_attachment(self):306 307 event = self.store_event(308 data={""message"": ""Hello world"", ""level"": ""error""}, project_id=self.project.id309 )310 event = event.for_group(event.groups[0])311 occurrence = self.build_occurrence(level=""info"")312 occurrence.save(project_id=self.project.id)313 event.occurrence = occurrence314 315 event.group.type = GroupType.PROFILE_BLOCKED_THREAD316 317 attachments = SlackIssuesMessageBuilder(group=event.group, event=event).build()318 319 assert attachments[""title""] == occurrence.issue_title320 assert attachments[""text""] == occurrence.evidence_display[0].value321 assert attachments[""fallback""] == f""[{self.project.slug}] {occurrence.issue_title}""322 assert attachments[""color""] == ""#2788CE"" # blue for info level323",Test that a generic issue type's Slack alert contains the expected values,12,51,Python,"324 ###User : Below is a Python method which does a task. Create a documentation for the below code : 325 ```Python326 def test_build_group_generic_issue_attachment(self):327 328 event = self.store_event(329 data={""message"": ""Hello world"", ""level"": ""error""}, project_id=self.project.id330 )331 event = event.for_group(event.groups[0])332 occurrence = self.build_occurrence(level=""info"")333 occurrence.save(project_id=self.project.id)334 event.occurrence = occurrence335 336 event.group.type = GroupType.PROFILE_BLOCKED_THREAD337 338 attachments = SlackIssuesMessageBuilder(group=event.group, event=event).build()339 340 assert attachments[""title""] == occurrence.issue_title341 assert attachments[""text""] == occurrence.evidence_display[0].value342 assert attachments[""fallback""] == f""[{self.project.slug}] {occurrence.issue_title}""343 assert attachments[""color""] == ""#2788CE"" # blue for info level344 345 ```346 ###Assistant : Test that a generic issue type's Slack alert contains the expected values347 "3484,"def apply(self, func, mask=None) -> 'ImageProcessor':349 350 img = orig_img = self._img351 img = func(img).astype(orig_img.dtype)352 if img.ndim != 4:353 raise Exception('func used in ImageProcessor.apply changed format of image')354 355 if mask is not None:356 mask = self._check_normalize_mask(mask)357 img = ne.evaluate('orig_img*(1-mask) + img*mask').astype(orig_img.dtype)358 359 self._img = img360 return self361","362 apply your own function on internal image363 364 image has NHWC format. Do not change format, but dims can be changed.365 366 func callable (img) -> img367 368 example:369 370 .apply( lambda img: img-[102,127,63] )371 ",31,45,Python,"372 ###User : Below is a Python method which does a task. Create a documentation for the below code : 373 ```Python374 def apply(self, func, mask=None) -> 'ImageProcessor':375 376 img = orig_img = self._img377 img = func(img).astype(orig_img.dtype)378 if img.ndim != 4:379 raise Exception('func used in ImageProcessor.apply changed format of image')380 381 if mask is not None:382 mask = self._check_normalize_mask(mask)383 img = ne.evaluate('orig_img*(1-mask) + img*mask').astype(orig_img.dtype)384 385 self._img = img386 return self387 388 ```389 ###Assistant : 390 apply your own function on internal image391 392 image has NHWC format. Do not change format, but dims can be changed.393 394 func callable (img) -> img395 396 example:397 398 .apply( lambda img: img-[102,127,63] )399 400 "4015,"def predict(self, x):402 403 404 # start the timer405 self.timer.start()406 407 v_, _ = self.eval_out() # evaluate the ratings and the associated probabilities408 vp = self.sess.run(v_, feed_dict={self.vu: x})409 410 # stop the timer411 self.timer.stop()412 413 log.info(""Done inference, time %f2"" % self.timer.interval)414 415 return vp416","Returns the inferred ratings. This method is similar to recommend_k_items() with the417 exceptions that it returns all the inferred ratings418 419 Basic mechanics:420 421 The method samples new ratings from the learned joint distribution, together with422 their probabilities. The input x must have the same number of columns as the one used423 for training the model, i.e. the same number of items, but it can have an arbitrary number424 of rows (users).425 426 Args:427 x (numpy.ndarray, int32): Input user/affinity matrix. Note that this can be a single vector, i.e.428 the ratings of a single user.429 430 Returns:431 numpy.ndarray, float:432 - A matrix with the inferred ratings.433 - The elapsed time for predediction.434 ",108,38,Python,"435 ###User : Below is a Python method which does a task. Create a documentation for the below code : 436 ```Python437 def predict(self, x):438 439 440 # start the timer441 self.timer.start()442 443 v_, _ = self.eval_out() # evaluate the ratings and the associated probabilities444 vp = self.sess.run(v_, feed_dict={self.vu: x})445 446 # stop the timer447 self.timer.stop()448 449 log.info(""Done inference, time %f2"" % self.timer.interval)450 451 return vp452 453 ```454 ###Assistant : Returns the inferred ratings. This method is similar to recommend_k_items() with the455 exceptions that it returns all the inferred ratings456 457 Basic mechanics:458 459 The method samples new ratings from the learned joint distribution, together with460 their probabilities. The input x must have the same number of columns as the one used461 for training the model, i.e. the same number of items, but it can have an arbitrary number462 of rows (users).463 464 Args:465 x (numpy.ndarray, int32): Input user/affinity matrix. Note that this can be a single vector, i.e.466 the ratings of a single user.467 468 Returns:469 numpy.ndarray, float:470 - A matrix with the inferred ratings.471 - The elapsed time for predediction.472 473 "4746,"def raw_decode(self, s, idx=0):475 476 try:477 obj, end = self.scan_once(s, idx)478 except StopIteration as err:479 raise JSONDecodeError(""Expecting value"", s, err.value) from None480 return obj, end481","Decode a JSON document from ``s`` (a ``str`` beginning with482 a JSON document) and return a 2-tuple of the Python483 representation and the index in ``s`` where the document ended.484 485 This can be used to decode a JSON document from a string that may486 have extraneous data at the end.487 488 ",50,24,Python,"489 ###User : Below is a Python method which does a task. Create a documentation for the below code : 490 ```Python491 def raw_decode(self, s, idx=0):492 493 try:494 obj, end = self.scan_once(s, idx)495 except StopIteration as err:496 raise JSONDecodeError(""Expecting value"", s, err.value) from None497 return obj, end498 499 ```500 ###Assistant : Decode a JSON document from ``s`` (a ``str`` beginning with501 a JSON document) and return a 2-tuple of the Python502 representation and the index in ``s`` where the document ended.503 504 This can be used to decode a JSON document from a string that may505 have extraneous data at the end.506 507 508 "5097,"def has_bridges(G, root=None):510 511 try:512 next(bridges(G))513 except StopIteration:514 return False515 else:516 return True517 518 519@not_implemented_for(""multigraph"")520@not_implemented_for(""directed"")","Decide whether a graph has any bridges.521 522 A *bridge* in a graph is an edge whose removal causes the number of523 connected components of the graph to increase.524 525 Parameters526 ----------527 G : undirected graph528 529 root : node (optional)530 A node in the graph `G`. If specified, only the bridges in the531 connected component containing this node will be considered.532 533 Returns534 -------535 bool536 Whether the graph (or the connected component containing `root`)537 has any bridges.538 539 Raises540 ------541 NodeNotFound542 If `root` is not in the graph `G`.543 544 NetworkXNotImplemented545 If `G` is a directed graph.546 547 Examples548 --------549 The barbell graph with parameter zero has a single bridge::550 551 >>> G = nx.barbell_graph(10, 0)552 >>> nx.has_bridges(G)553 True554 555 On the other hand, the cycle graph has no bridges::556 557 >>> G = nx.cycle_graph(5)558 >>> nx.has_bridges(G)559 False560 561 Notes562 -----563 This implementation uses the :func:`networkx.bridges` function, so564 it shares its worst-case time complexity, $O(m + n)$, ignoring565 polylogarithmic factors, where $n$ is the number of nodes in the566 graph and $m$ is the number of edges.567 568 ",167,14,Python,"569 ###User : Below is a Python method which does a task. Create a documentation for the below code : 570 ```Python571 def has_bridges(G, root=None):572 573 try:574 next(bridges(G))575 except StopIteration:576 return False577 else:578 return True579 580 581@not_implemented_for(""multigraph"")582@not_implemented_for(""directed"")583 ```584 ###Assistant : Decide whether a graph has any bridges.585 586 A *bridge* in a graph is an edge whose removal causes the number of587 connected components of the graph to increase.588 589 Parameters590 ----------591 G : undirected graph592 593 root : node (optional)594 A node in the graph `G`. If specified, only the bridges in the595 connected component containing this node will be considered.596 597 Returns598 -------599 bool600 Whether the graph (or the connected component containing `root`)601 has any bridges.602 603 Raises604 ------605 NodeNotFound606 If `root` is not in the graph `G`.607 608 NetworkXNotImplemented609 If `G` is a directed graph.610 611 Examples612 --------613 The barbell graph with parameter zero has a single bridge::614 615 >>> G = nx.barbell_graph(10, 0)616 >>> nx.has_bridges(G)617 True618 619 On the other hand, the cycle graph has no bridges::620 621 >>> G = nx.cycle_graph(5)622 >>> nx.has_bridges(G)623 False624 625 Notes626 -----627 This implementation uses the :func:`networkx.bridges` function, so628 it shares its worst-case time complexity, $O(m + n)$, ignoring629 polylogarithmic factors, where $n$ is the number of nodes in the630 graph and $m$ is the number of edges.631 632 633 "6348,"def wheel_metadata(source, dist_info_dir):635 # type: (ZipFile, str) -> Message636 637 path = f""{dist_info_dir}/WHEEL""638 # Zip file path separators must be /639 wheel_contents = read_wheel_metadata_file(source, path)640 641 try:642 wheel_text = wheel_contents.decode()643 except UnicodeDecodeError as e:644 raise UnsupportedWheel(f""error decoding {path!r}: {e!r}"")645 646 # FeedParser (used by Parser) does not raise any exceptions. The returned647 # message may have .defects populated, but for backwards-compatibility we648 # currently ignore them.649 return Parser().parsestr(wheel_text)650 651","Return the WHEEL metadata of an extracted wheel, if possible.652 Otherwise, raise UnsupportedWheel.653 ",13,65,Python,"654 ###User : Below is a Python method which does a task. Create a documentation for the below code : 655 ```Python656 def wheel_metadata(source, dist_info_dir):657 # type: (ZipFile, str) -> Message658 659 path = f""{dist_info_dir}/WHEEL""660 # Zip file path separators must be /661 wheel_contents = read_wheel_metadata_file(source, path)662 663 try:664 wheel_text = wheel_contents.decode()665 except UnicodeDecodeError as e:666 raise UnsupportedWheel(f""error decoding {path!r}: {e!r}"")667 668 # FeedParser (used by Parser) does not raise any exceptions. The returned669 # message may have .defects populated, but for backwards-compatibility we670 # currently ignore them.671 return Parser().parsestr(wheel_text)672 673 674 ```675 ###Assistant : Return the WHEEL metadata of an extracted wheel, if possible.676 Otherwise, raise UnsupportedWheel.677 678 "6799,"def remove_column(self, i, *args, **kwargs):680 681 table = self.table.remove_column(i, *args, **kwargs)682 name = self.table.column_names[i]683 blocks = []684 for tables in self.blocks:685 blocks.append(686 [687 t.remove_column(t.column_names.index(name), *args, **kwargs) if name in t.column_names else t688 for t in tables689 ]690 )691 return ConcatenationTable(table, blocks)692","693 Create new Table with the indicated column removed.694 695 Args:696 i (:obj:`int`):697 Index of column to remove.698 699 Returns:700 :class:`datasets.table.Table`:701 New table without the column.702 ",23,40,Python,"703 ###User : Below is a Python method which does a task. Create a documentation for the below code : 704 ```Python705 def remove_column(self, i, *args, **kwargs):706 707 table = self.table.remove_column(i, *args, **kwargs)708 name = self.table.column_names[i]709 blocks = []710 for tables in self.blocks:711 blocks.append(712 [713 t.remove_column(t.column_names.index(name), *args, **kwargs) if name in t.column_names else t714 for t in tables715 ]716 )717 return ConcatenationTable(table, blocks)718 719 ```720 ###Assistant : 721 Create new Table with the indicated column removed.722 723 Args:724 i (:obj:`int`):725 Index of column to remove.726 727 Returns:728 :class:`datasets.table.Table`:729 New table without the column.730 731 "73210,"def test_cable_cannot_terminate_to_a_wireless_interface(self):733 734 wireless_interface = Interface(device=self.device1, name=""W1"", type=InterfaceTypeChoices.TYPE_80211A)735 cable = Cable(a_terminations=[self.interface2], b_terminations=[wireless_interface])736 with self.assertRaises(ValidationError):737 cable.clean()738","739 A cable cannot terminate to a wireless interface740 ",8,14,Python,"741 ###User : Below is a Python method which does a task. Create a documentation for the below code : 742 ```Python743 def test_cable_cannot_terminate_to_a_wireless_interface(self):744 745 wireless_interface = Interface(device=self.device1, name=""W1"", type=InterfaceTypeChoices.TYPE_80211A)746 cable = Cable(a_terminations=[self.interface2], b_terminations=[wireless_interface])747 with self.assertRaises(ValidationError):748 cable.clean()749 750 ```751 ###Assistant : 752 A cable cannot terminate to a wireless interface753 754 "75511,"def get_test_db_clone_settings(self, suffix):756 757 # When this function is called, the test database has been created758 # already and its name has been copied to settings_dict['NAME'] so759 # we don't need to call _get_test_db_name.760 orig_settings_dict = self.connection.settings_dict761 return {762 **orig_settings_dict,763 ""NAME"": ""{}_{}"".format(orig_settings_dict[""NAME""], suffix),764 }765","766 Return a modified connection settings dict for the n-th clone of a DB.767 ",13,43,Python,"768 ###User : Below is a Python method which does a task. Create a documentation for the below code : 769 ```Python770 def get_test_db_clone_settings(self, suffix):771 772 # When this function is called, the test database has been created773 # already and its name has been copied to settings_dict['NAME'] so774 # we don't need to call _get_test_db_name.775 orig_settings_dict = self.connection.settings_dict776 return {777 **orig_settings_dict,778 ""NAME"": ""{}_{}"".format(orig_settings_dict[""NAME""], suffix),779 }780 781 ```782 ###Assistant : 783 Return a modified connection settings dict for the n-th clone of a DB.784 785 "78612,"def open(self, host='', port=IMAP4_PORT, timeout=None):787 788 self.host = host789 self.port = port790 self.sock = self._create_socket(timeout)791 self.file = self.sock.makefile('rb')792 793","Setup connection to remote server on ""host:port""794 (default: localhost:standard IMAP4 port).795 This connection will be used by the routines:796 read, readline, send, shutdown.797 ",23,17,Python,"798 ###User : Below is a Python method which does a task. Create a documentation for the below code : 799 ```Python800 def open(self, host='', port=IMAP4_PORT, timeout=None):801 802 self.host = host803 self.port = port804 self.sock = self._create_socket(timeout)805 self.file = self.sock.makefile('rb')806 807 808 ```809 ###Assistant : Setup connection to remote server on ""host:port""810 (default: localhost:standard IMAP4 port).811 This connection will be used by the routines:812 read, readline, send, shutdown.813 814 "81513,"def synchronized_output_end_sequence(self) -> str:816 817 if self.synchronised_output:818 return TERMINAL_MODES_ANSI_SEQUENCES[Mode.SynchronizedOutput][""end_sync""]819 return """"820","821 Returns the ANSI sequence that we should send to the terminal to tell it that822 it should stop buffering the content we're about to send.823 If the terminal doesn't seem to support synchronised updates the string will be empty.824 825 Returns:826 str: the ""synchronised output stop"" ANSI sequence. It will be ab empty string827 if the terminal emulator doesn't seem to support the ""synchronised updates"" mode.828 ",65,10,Python,"829 ###User : Below is a Python method which does a task. Create a documentation for the below code : 830 ```Python831 def synchronized_output_end_sequence(self) -> str:832 833 if self.synchronised_output:834 return TERMINAL_MODES_ANSI_SEQUENCES[Mode.SynchronizedOutput][""end_sync""]835 return """"836 837 ```838 ###Assistant : 839 Returns the ANSI sequence that we should send to the terminal to tell it that840 it should stop buffering the content we're about to send.841 If the terminal doesn't seem to support synchronised updates the string will be empty.842 843 Returns:844 str: the ""synchronised output stop"" ANSI sequence. It will be ab empty string845 if the terminal emulator doesn't seem to support the ""synchronised updates"" mode.846 847 "84814,"def _band_penalty_coefficients(self, fc, q, gain, filter_frs):849 850 ref_frs = biquad.digital_coeffs(self.frequency, 192e3, *biquad.peaking(fc, q, gain, fs=192e3))851 est_sums = np.sum(filter_frs, axis=1)852 ref_sums = np.sum(ref_frs, axis=1)853 penalties = np.zeros((len(fc),))854 mask = np.squeeze(ref_sums) != 0.0855 penalties[mask] = est_sums[mask] / ref_sums[mask]856 return 10 * (1 - np.expand_dims(penalties, 1))857","Calculates penalty coefficients for filters if their transition bands extend beyond Nyquist frequency858 859 The calculation is based on ratio of frequency response integrals between 44.1 kHz and 192 kHz860 861 Args:862 fc: Filter center frequencies, 1-D array863 q: Filter qualities, 1-D array864 gain: Filter gains, 1-D array865 filter_frs: Filter frequency responses, 2-D array, one fr per row866 867 Returns:868 Column array of penalty coefficients, one per filter869 ",65,42,Python,"870 ###User : Below is a Python method which does a task. Create a documentation for the below code : 871 ```Python872 def _band_penalty_coefficients(self, fc, q, gain, filter_frs):873 874 ref_frs = biquad.digital_coeffs(self.frequency, 192e3, *biquad.peaking(fc, q, gain, fs=192e3))875 est_sums = np.sum(filter_frs, axis=1)876 ref_sums = np.sum(ref_frs, axis=1)877 penalties = np.zeros((len(fc),))878 mask = np.squeeze(ref_sums) != 0.0879 penalties[mask] = est_sums[mask] / ref_sums[mask]880 return 10 * (1 - np.expand_dims(penalties, 1))881 882 ```883 ###Assistant : Calculates penalty coefficients for filters if their transition bands extend beyond Nyquist frequency884 885 The calculation is based on ratio of frequency response integrals between 44.1 kHz and 192 kHz886 887 Args:888 fc: Filter center frequencies, 1-D array889 q: Filter qualities, 1-D array890 gain: Filter gains, 1-D array891 filter_frs: Filter frequency responses, 2-D array, one fr per row892 893 Returns:894 Column array of penalty coefficients, one per filter895 896 "89715,"def test_predict_on_toy_problem(global_random_seed):898 899 clf1 = LogisticRegression(random_state=global_random_seed)900 clf2 = RandomForestClassifier(n_estimators=10, random_state=global_random_seed)901 clf3 = GaussianNB()902 903 X = np.array(904 [[-1.1, -1.5], [-1.2, -1.4], [-3.4, -2.2], [1.1, 1.2], [2.1, 1.4], [3.1, 2.3]]905 )906 907 y = np.array([1, 1, 1, 2, 2, 2])908 909 assert_array_equal(clf1.fit(X, y).predict(X), [1, 1, 1, 2, 2, 2])910 assert_array_equal(clf2.fit(X, y).predict(X), [1, 1, 1, 2, 2, 2])911 assert_array_equal(clf3.fit(X, y).predict(X), [1, 1, 1, 2, 2, 2])912 913 eclf = VotingClassifier(914 estimators=[(""lr"", clf1), (""rf"", clf2), (""gnb"", clf3)],915 voting=""hard"",916 weights=[1, 1, 1],917 )918 assert_array_equal(eclf.fit(X, y).predict(X), [1, 1, 1, 2, 2, 2])919 920 eclf = VotingClassifier(921 estimators=[(""lr"", clf1), (""rf"", clf2), (""gnb"", clf3)],922 voting=""soft"",923 weights=[1, 1, 1],924 )925 assert_array_equal(eclf.fit(X, y).predict(X), [1, 1, 1, 2, 2, 2])926 927",Manually check predicted class labels for toy dataset.,8,104,Python,"928 ###User : Below is a Python method which does a task. Create a documentation for the below code : 929 ```Python930 def test_predict_on_toy_problem(global_random_seed):931 932 clf1 = LogisticRegression(random_state=global_random_seed)933 clf2 = RandomForestClassifier(n_estimators=10, random_state=global_random_seed)934 clf3 = GaussianNB()935 936 X = np.array(937 [[-1.1, -1.5], [-1.2, -1.4], [-3.4, -2.2], [1.1, 1.2], [2.1, 1.4], [3.1, 2.3]]938 )939 940 y = np.array([1, 1, 1, 2, 2, 2])941 942 assert_array_equal(clf1.fit(X, y).predict(X), [1, 1, 1, 2, 2, 2])943 assert_array_equal(clf2.fit(X, y).predict(X), [1, 1, 1, 2, 2, 2])944 assert_array_equal(clf3.fit(X, y).predict(X), [1, 1, 1, 2, 2, 2])945 946 eclf = VotingClassifier(947 estimators=[(""lr"", clf1), (""rf"", clf2), (""gnb"", clf3)],948 voting=""hard"",949 weights=[1, 1, 1],950 )951 assert_array_equal(eclf.fit(X, y).predict(X), [1, 1, 1, 2, 2, 2])952 953 eclf = VotingClassifier(954 estimators=[(""lr"", clf1), (""rf"", clf2), (""gnb"", clf3)],955 voting=""soft"",956 weights=[1, 1, 1],957 )958 assert_array_equal(eclf.fit(X, y).predict(X), [1, 1, 1, 2, 2, 2])959 960 961 ```962 ###Assistant : Manually check predicted class labels for toy dataset.963 "96416,"def fit_transform(self, X, y=None):965 966 self._validate_params()967 return self._transform(X, fitting=True)968","Learn a list of feature name -> indices mappings and transform X.969 970 Like fit(X) followed by transform(X), but does not require971 materializing X in memory.972 973 Parameters974 ----------975 X : Mapping or iterable over Mappings976 Dict(s) or Mapping(s) from feature names (arbitrary Python977 objects) to feature values (strings or convertible to dtype).978 979 .. versionchanged:: 0.24980 Accepts multiple string values for one categorical feature.981 982 y : (ignored)983 Ignored parameter.984 985 Returns986 -------987 Xa : {array, sparse matrix}988 Feature vectors; always 2-d.989 ",78,8,Python,"990 ###User : Below is a Python method which does a task. Create a documentation for the below code : 991 ```Python992 def fit_transform(self, X, y=None):993 994 self._validate_params()995 return self._transform(X, fitting=True)996 997 ```998 ###Assistant : Learn a list of feature name -> indices mappings and transform X.999 1000 Like fit(X) followed by transform(X), but does not require1001 materializing X in memory.1002 1003 Parameters1004 ----------1005 X : Mapping or iterable over Mappings1006 Dict(s) or Mapping(s) from feature names (arbitrary Python1007 objects) to feature values (strings or convertible to dtype).1008 1009 .. versionchanged:: 0.241010 Accepts multiple string values for one categorical feature.1011 1012 y : (ignored)1013 Ignored parameter.1014 1015 Returns1016 -------1017 Xa : {array, sparse matrix}1018 Feature vectors; always 2-d.1019 1020 "102117,"def _on_feature_permission_requested(self, url, feature):1022 1023 page = self._widget.page()1024 grant_permission = functools.partial(1025 page.setFeaturePermission, url, feature,1026 QWebEnginePage.PermissionPolicy.PermissionGrantedByUser)1027 deny_permission = functools.partial(1028 page.setFeaturePermission, url, feature,1029 QWebEnginePage.PermissionPolicy.PermissionDeniedByUser)1030 1031 permission_str = debug.qenum_key(QWebEnginePage, feature)1032 1033 if not url.isValid():1034 # WORKAROUND for https://bugreports.qt.io/browse/QTBUG-851161035 is_qtbug = (qtutils.version_check('5.15.0',1036 compiled=False,1037 exact=True) and1038 self._tab.is_private and1039 feature == QWebEnginePage.Feature.Notifications)1040 logger = log.webview.debug if is_qtbug else log.webview.warning1041 logger(""Ignoring feature permission {} for invalid URL {}"".format(1042 permission_str, url))1043 deny_permission()1044 return1045 1046 if feature not in self._options:1047 log.webview.error(""Unhandled feature permission {}"".format(1048 permission_str))1049 deny_permission()1050 return1051 1052 if (1053 feature in [QWebEnginePage.Feature.DesktopVideoCapture,1054 QWebEnginePage.Feature.DesktopAudioVideoCapture] and1055 qtutils.version_check('5.13', compiled=False) and1056 not qtutils.version_check('5.13.2', compiled=False)1057 ):1058 # WORKAROUND for https://bugreports.qt.io/browse/QTBUG-780161059 log.webview.warning(""Ignoring desktop sharing request due to ""1060 ""crashes in Qt < 5.13.2"")1061 deny_permission()1062 return1063 1064 question = shared.feature_permission(1065 url=url.adjusted(QUrl.UrlFormattingOption.RemovePath),1066 option=self._options[feature], msg=self._messages[feature],1067 yes_action=grant_permission, no_action=deny_permission,1068 abort_on=[self._tab.abort_questions])1069 1070 if question is not None:1071 page.featurePermissionRequestCanceled.connect(1072 functools.partial(self._on_feature_permission_cancelled,1073 question, url, feature))1074",Ask the user for approval for geolocation/media/etc..,7,125,Python,"1075 ###User : Below is a Python method which does a task. Create a documentation for the below code : 1076 ```Python1077 def _on_feature_permission_requested(self, url, feature):1078 1079 page = self._widget.page()1080 grant_permission = functools.partial(1081 page.setFeaturePermission, url, feature,1082 QWebEnginePage.PermissionPolicy.PermissionGrantedByUser)1083 deny_permission = functools.partial(1084 page.setFeaturePermission, url, feature,1085 QWebEnginePage.PermissionPolicy.PermissionDeniedByUser)1086 1087 permission_str = debug.qenum_key(QWebEnginePage, feature)1088 1089 if not url.isValid():1090 # WORKAROUND for https://bugreports.qt.io/browse/QTBUG-851161091 is_qtbug = (qtutils.version_check('5.15.0',1092 compiled=False,1093 exact=True) and1094 self._tab.is_private and1095 feature == QWebEnginePage.Feature.Notifications)1096 logger = log.webview.debug if is_qtbug else log.webview.warning1097 logger(""Ignoring feature permission {} for invalid URL {}"".format(1098 permission_str, url))1099 deny_permission()1100 return1101 1102 if feature not in self._options:1103 log.webview.error(""Unhandled feature permission {}"".format(1104 permission_str))1105 deny_permission()1106 return1107 1108 if (1109 feature in [QWebEnginePage.Feature.DesktopVideoCapture,1110 QWebEnginePage.Feature.DesktopAudioVideoCapture] and1111 qtutils.version_check('5.13', compiled=False) and1112 not qtutils.version_check('5.13.2', compiled=False)1113 ):1114 # WORKAROUND for https://bugreports.qt.io/browse/QTBUG-780161115 log.webview.warning(""Ignoring desktop sharing request due to ""1116 ""crashes in Qt < 5.13.2"")1117 deny_permission()1118 return1119 1120 question = shared.feature_permission(1121 url=url.adjusted(QUrl.UrlFormattingOption.RemovePath),1122 option=self._options[feature], msg=self._messages[feature],1123 yes_action=grant_permission, no_action=deny_permission,1124 abort_on=[self._tab.abort_questions])1125 1126 if question is not None:1127 page.featurePermissionRequestCanceled.connect(1128 functools.partial(self._on_feature_permission_cancelled,1129 question, url, feature))1130 1131 ```1132 ###Assistant : Ask the user for approval for geolocation/media/etc..1133 "113418,"def add_find_python(self):1135 1136 1137 start = 4021138 for ver in self.versions:1139 install_path = r""SOFTWARE\Python\PythonCore\%s\InstallPath"" % ver1140 machine_reg = ""python.machine."" + ver1141 user_reg = ""python.user."" + ver1142 machine_prop = ""PYTHON.MACHINE."" + ver1143 user_prop = ""PYTHON.USER."" + ver1144 machine_action = ""PythonFromMachine"" + ver1145 user_action = ""PythonFromUser"" + ver1146 exe_action = ""PythonExe"" + ver1147 target_dir_prop = ""TARGETDIR"" + ver1148 exe_prop = ""PYTHON"" + ver1149 if msilib.Win64:1150 # type: msidbLocatorTypeRawValue + msidbLocatorType64bit1151 Type = 2+161152 else:1153 Type = 21154 add_data(self.db, ""RegLocator"",1155 [(machine_reg, 2, install_path, None, Type),1156 (user_reg, 1, install_path, None, Type)])1157 add_data(self.db, ""AppSearch"",1158 [(machine_prop, machine_reg),1159 (user_prop, user_reg)])1160 add_data(self.db, ""CustomAction"",1161 [(machine_action, 51+256, target_dir_prop, ""["" + machine_prop + ""]""),1162 (user_action, 51+256, target_dir_prop, ""["" + user_prop + ""]""),1163 (exe_action, 51+256, exe_prop, ""["" + target_dir_prop + ""]\\python.exe""),1164 ])1165 add_data(self.db, ""InstallExecuteSequence"",1166 [(machine_action, machine_prop, start),1167 (user_action, user_prop, start + 1),1168 (exe_action, None, start + 2),1169 ])1170 add_data(self.db, ""InstallUISequence"",1171 [(machine_action, machine_prop, start),1172 (user_action, user_prop, start + 1),1173 (exe_action, None, start + 2),1174 ])1175 add_data(self.db, ""Condition"",1176 [(""Python"" + ver, 0, ""NOT TARGETDIR"" + ver)])1177 start += 41178 assert start < 5001179","Adds code to the installer to compute the location of Python.1180 1181 Properties PYTHON.MACHINE.X.Y and PYTHON.USER.X.Y will be set from the1182 registry for each version of Python.1183 1184 Properties TARGETDIRX.Y will be set from PYTHON.USER.X.Y if defined,1185 else from PYTHON.MACHINE.X.Y.1186 1187 Properties PYTHONX.Y will be set to TARGETDIRX.Y\\python.exe",45,167,Python,"1188 ###User : Below is a Python method which does a task. Create a documentation for the below code : 1189 ```Python1190 def add_find_python(self):1191 1192 1193 start = 4021194 for ver in self.versions:1195 install_path = r""SOFTWARE\Python\PythonCore\%s\InstallPath"" % ver1196 machine_reg = ""python.machine."" + ver1197 user_reg = ""python.user."" + ver1198 machine_prop = ""PYTHON.MACHINE."" + ver1199 user_prop = ""PYTHON.USER."" + ver1200 machine_action = ""PythonFromMachine"" + ver