messages
listlengths
3
3
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*- #\nfrom __future__ import unicode_literals\n\nAUTHOR = 'Jake VanderPlas'\nSITENAME = 'Python Data Science Handbook'\nSITESUBTITLE = u'Essential Tools for Working with Data'\nSITEURL = ''\nSITESUBURL = 'PythonDataScienceHandbook/'\nPATH = 'content'\nTIMEZONE = 'America/Los_Angeles'\nDEFAULT_LANG = 'en'\n\n# Feed generation is usually not desired when developing\nFEED_ALL_ATOM = None\nCATEGORY_FEED_ATOM = None\nTRANSLATION_FEED_ATOM = None\nAUTHOR_FEED_ATOM = None\nAUTHOR_FEED_RSS = None\n\n# Set the article URL\nARTICLE_URL = 'blog/{date:%Y}/{date:%m}/{date:%d}/{slug}/'\nARTICLE_SAVE_AS = 'blog/{date:%Y}/{date:%m}/{date:%d}/{slug}/index.html'\n\nDEFAULT_PAGINATION = 10\n\n# Uncomment following line if you want document-relative URLs when developing\n#RELATIVE_URLS = True\n\n#MARKUP = ('md', 'ipynb')\n#PLUGINS = ['ipynb.markup']\n\nMARKUP = ['md']\nPLUGIN_PATHS = ['./plugins', './plugins/pelican-plugins']\nPLUGINS = [\n 'summary', # auto-summarizing articles\n 'feed_summary', # use summaries for RSS, not full articles\n 'ipynb.liquid', # for embedding notebooks\n 'liquid_tags.img', # embedding images\n 'liquid_tags.video', # embedding videos\n 'liquid_tags.include_code', # including code blocks\n 'liquid_tags.literal'\n]\nIGNORE_FILES = ['.ipynb_checkpoints']\n\n# for liquid tags\nCODE_DIR = 'downloads/code'\nNOTEBOOK_DIR = 'downloads/notebooks'\n\n# THEME SETTINGS\nTHEME = './theme/'\n\nABOUT_PAGE = " }, { "role": "assistant", "content": "'/pages/about.html'\nTWITTER_USERNAME = 'jakevdp'\nGITHUB_USERNAME = 'jakevdp'\nSTACKOVERFLOW_ADDRESS = 'http://stackoverflow.com/users/2937831/jakevdp'\nAUTHOR_WEBSITE = 'http://vanderplas.com'\nAUTHOR_BLOG = 'http://jakevdp.github.io'\nAUTHOR_CV = \"http://staff.washington.edu/jakevdp/media/pdfs/CV.pdf\"\nSHOW_ARCHIVES = True\nSHOW_FEED = False # Need to address large feeds\n\nENABLE_MATHJAX = True\n\nSTATIC_PATHS = ['images', 'figures', 'videos', 'downloads', 'favicon.ico']\n\n# Footer info\n\nLICENSE_URL = \"https://github.com/jakevdp/jakevdp.github.io-source/blob/master/LICENSE\"\nLICENSE = \"MIT\"\n" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "r index in outlier_ids])\n elif images is not None:\n outlier_images = [images[index] for index in outlier_ids]\n outlier_embeddings = self.embedding_model.embed_images(outlier_images, verbose=self.verbose)\n else:\n outlier_embeddings = self.embedding_model.embed_documents(outlier_docs)\n similarity = cosine_similarity(outlier_embeddings, self.topic_embeddings_[self._outliers:])\n\n # Update topics\n similarity[similarity threshold] = 0\n outlier_topics = iter([np.argmax(sim) if sum(sim) 0 else -1 for sim in similarity])\n new_topics = [topic if topic != -1 else next(outlier_topics) for topic in topics]\n\n return new_topics\n\n def visualize_topics(self,\n topics: List[int] = None,\n top_n_topics: int = None,\n custom_labels: bool = False,\n title: str = \"bIntertopic Distance Map/b\",\n width: int = 650,\n height: int = 650) - go.Figure:\n \"\"\" Visualize topics, their sizes, and their corresponding words\n\n This visualization is highly inspired by LDAvis, a great visualization\n technique typically reserved for LDA.\n\n Arguments:\n topics: A selection of topics to visualize\n top_n_topics: Only select the top n most frequent topics\n custom_labels: Whether to use custom topic labels that were defined using \n `topic_model.set_topic_labels`.\n title: Title of the plot.\n width: The width of the figure.\n height: The height of the figure.\n\n Examples:\n\n To visualize the topics simply run:\n\n ```python\n topic_model.visualize_topics()\n ```\n\n Or if you want to save the resulting figure:\n\n ```python\n fig = topic_model.visualize_topics()\n fig.write_html(\"path/to/file.html\")\n ```\n \"\"\"\n check_is_fitted(self)\n return plotting.visualize_topics(self,\n topics=topics,\n top_n_topics=top_n_topics,\n custom_labels=custom_labels,\n title=title,\n width=width,\n height=height)\n\n def visualize_documents(self,\n docs: List[str],\n topics: List[int] = None,\n embeddings: np.ndarray = None,\n reduced_embeddings: np.ndarray = None,\n sample: float = None,\n hide_annotations: bool = False,\n hide_document_hover: bool = False,\n custom_labels: bool = False,\n title: str = \"bDocuments and Topics/b\",\n width: int = 1200,\n height: int = 750) - go.Figure:\n \"\"\" Visualize documents and their topics in 2D\n\n Arguments:\n topic_model: A fitted BERTopic instance.\n docs: The documents you used when calling either `fit` or `fit_transform`\n topics: A selection of topics to visualize.\n Not to be confused with the topics that you get from `.fit_transform`.\n For example, if you want to visualize only to" }, { "role": "assistant", "content": "pics 1 through 5:\n `topics = [1, 2, 3, 4, 5]`.\n embeddings: The embeddings of all documents in `docs`.\n reduced_embeddings: The 2D reduced embeddings of all documents in `docs`.\n sample: The percentage of documents in each topic that you would like to keep.\n Value can be between 0 and 1. Setting this value to, for example,\n 0.1 (10% of documents in each topic) makes it easier to visualize\n millions of documents as a subset is chosen.\n hide_annotations: Hide the names of the traces on top of each cluster.\n hide_document_hover: Hide the content of the documents when hovering over\n specific points. Helps to speed up generation of visualization.\n custom_labels: Whether to use custom topic labels that were defined using\n `topic_model.set_topic_labels`.\n title: Title of the plot.\n width: The width of the figure.\n height: The height of the figure." } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": " assert len(words) == 10\n\n assert len(topic_model.get_topic_freq()) 2\n assert len(topic_model.get_topics()) == len(topic_model.get_topic_freq())\n\n # Test extraction of document info\n document_info = topic_model.get_document_info(documents)\n assert len(document_info) == len(documents)\n\n # Test transform\n doc = \"This is a new document to predict.\"\n topics_test, probs_test = topic_model.transform([doc, doc])\n\n assert len(topics_test) == 2\n\n # Test topics over time\n timestamps = [i % 10 for i in range(len(documents))]\n topics_over_time = topic_model.topics_over_time(documents, timestamps)\n\n assert topics_over_time.Frequency.sum() == len(documents)\n assert len(topics_over_time.Topic.unique()) == len(set(topics))\n\n # Test hierarchical topics\n hier_topics = topic_model.hierarchical_topics(documents)\n\n assert len(hier_topics) 0\n assert hier_topics.Parent_ID.astype(int).min() max(topics)\n\n # Test creation of topic tree\n tree = topic_model.get_topic_tree(hier_topics, tight_layout=False)\n assert isinstance(tree, str)\n assert len(tree) 10\n\n # Test find topic\n similar_topics, similarity = topic_model.find_topics(\"query\", top_n=2)\n assert len(similar_topics) == 2\n assert len(similarity) == 2\n assert max(similarity) = 1\n\n # Test topic reduction\n nr_topics = len(set(topics))\n nr_topics = 2 if nr_topics 2 else nr_topics - 1\n topic_model.reduce_topics(documents, nr_topics=nr_topics)\n\n assert len(topic_model.get_topic_freq()) == nr_topics\n assert len(topic_model.topics_) == len(topics)\n\n # Test update topics\n topic = topic_model.get_topic(1)[:10]\n vectorizer_model = topic_model.vectorizer_model\n topic_model.update_topics(documents, n_gram_range=(2, 2))\n\n updated_topic = topic_model.get_topic(1)[:10]\n\n topic_model.update_topics(documents, vectorizer_model=vectorizer_model)\n original_t" }, { "role": "assistant", "content": "opic = topic_model.get_topic(1)[:10]\n\n assert topic != updated_topic\n if topic_model.representation_model is not None:\n assert topic != original_topic" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "ent\"] = s\n self.app[\"COM\"] = s # compatibility\n self.applist.append((\"COM\", s))\n\n\ndef SOF(self, marker):\n #\n # Start of frame marker. Defines the size and mode of the\n # image. JPEG is colour blind, so we use some simple\n # heuristics to map the number of layers to an appropriate\n # mode. Note that this could be made a bit brighter, by\n # looking for JFIF and Adobe APP markers.\n\n n = i16(self.fp.read(2)) - 2\n s = ImageFile._safe_read(self.fp, n)\n self._size = i16(s, 3), i16(s, 1)\n\n self.bits = s[0]\n if self.bits != 8:\n msg = f\"cannot handle {self.bits}-bit layers\"\n raise SyntaxError(msg)\n\n self.layers = s[5]\n if self.layers == 1:\n self._mode = \"L\"\n elif self.layers == 3:\n self._mode = \"RGB\"\n elif self.layers == 4:\n self._mode = \"CMYK\"\n else:\n msg = f\"cannot handle {self.layers}-layer images\"\n raise SyntaxError(msg)\n\n if marker in [0xFFC2, 0xFFC6, 0xFFCA, 0xFFCE]:\n self.info[\"progressive\"] = self.info[\"progression\"] = 1\n\n if self.icclist:\n # fixup icc profile\n self.icclist.sort() # sort by sequence number\n if self.icclist[0][13] == len(self.icclist):\n profile = []\n for p in self.icclist:\n profile.append(p[14:])\n icc_profile = b\"\".join(profile)\n else:\n icc_profile = None # wrong number of fragments\n self.info[\"icc_profile\"] = icc_profile\n self.icclist = []\n\n for i in range(6, len(s), 3):\n t = s[i : i + 3]\n # 4-tuples: id, vsamp, hsamp, qtable\n self.layer.append((t[0], t[1] // 16, t[1] & 15, t[2]))\n\n\ndef DQT(self, marker):\n #\n # Define quantization table. Note that there might be more\n # than one table in each marker.\n\n # FIXME: The quantization tables can be used to estimate the\n # compression quality.\n\n n = i16(self.fp.read(2)) - 2\n s = ImageFile._safe_read(self.fp, n)\n while len(s):\n v = s[0]\n precision = 1 if (v // 16 == 0) else 2 # in bytes\n qt_length = 1 + precision * 64\n if len(s) qt_length:\n msg = \"bad quantization table marker\"\n raise SyntaxError(msg)\n data = array.array(\"B\" if precision == 1 else \"H\", s[1:qt_length])\n if sys.byteorder == \"little\" and precision 1:\n data.byteswap() # the values are always big-endian\n self.quantization[v & 15] = [data[i] for i in zigzag_index]\n s = s[qt_length:]\n\n\n#\n# JPEG marker table\n\nMARKER = {\n 0xFFC0: (\"SOF0\", \"Baseline DCT\", SOF),\n 0xFFC1: (\"SOF1\", \"Extended Sequential DCT\", SOF),\n 0xFFC2: (\"SOF2\", \"Progressive DCT\", SOF),\n 0xFFC3: (\"SOF3\", \"Spatial lossless\", SOF),\n 0xFFC4: (\"DHT\", \"Define Huffman table\", Skip),\n 0xFFC5: (\"SOF5\", \"Differential sequential DCT\", SOF),\n 0xFFC6: (\"SOF6\", \"Differential progressive DCT\", SOF),\n 0xFFC7: (\"SOF7\", \"Differential spatial\", SOF),\n 0xFFC8: (\"JPG\", \"Extension\", None),\n 0xFFC9: (\"SOF9\", \"Extended sequential DCT (AC)\", SOF),\n 0xFFCA: (\"SOF10\", \"Progressive DCT (AC)\", SOF),\n 0xFFCB: (\"SOF11\", \"Spatial lossless DCT (AC)\", SOF),\n 0xFFCC: (\"DAC\", \"Define arithmetic coding conditioning\", Skip),\n 0xFFCD: (\"SOF13\", \"Differential sequential DCT (AC)\", SOF),\n 0xFFCE: (\"SOF14\", \"Differential progressive DCT (AC)\", SOF),\n 0xFFCF: (\"SOF15\", \"Differential spatial (AC)\", SOF),\n 0xFFD0: (\"RST0\", \"Restart 0\", None),\n 0xFFD1: (\"RST1\", \"Restart 1\", None),\n 0xFFD2: (\"RST2\", \"Restart 2\", None),\n 0xFFD3: (\"RST3\", \"Restart 3\", None),\n 0xFFD4: (\"RST4\", \"Restart 4\", None),\n 0xFFD5: (\"RST5\", \"Restart 5\", None),\n 0xFFD6: (\"RST6\", \"Restart 6\", None),\n 0xFFD7: (\"RST7\", \"Restart 7\", None),\n 0xFFD8: (\"SOI\", \"Start of image\", None),\n 0xFFD9: (\"EOI\", \"End of image\", None),\n 0xFFDA: (\"SOS\", \"Start of scan\", Skip),\n 0xFFDB: (\"DQT\", \"Define quantization table\", DQT),\n 0xFFDC: (\"DNL\", \"Define number of lines\", Skip),\n 0xFFDD: (\"DRI\", \"Define restart interval\", Skip),\n 0xFFDE: (\"DHP\", \"Define hierarchical progression\", SOF),\n 0xFFDF: (\"EXP\", \"Expand reference component\", Skip),\n 0xFFE0: (\"APP0\", \"Application segment 0\", APP),\n 0xFFE1: (\"APP1\", \"Application segment 1\", APP),\n 0xFFE2: (\"APP2\", \"Application segment 2\", APP),\n 0xFFE3: (\"APP3\", \"Application segment 3\", APP),\n 0xFFE4: (\"APP4\", \"Application segment 4\", APP),\n 0xFFE5: (\"APP5\", \"Application segment 5\", APP),\n 0xFFE6: (\"APP6\", \"Application segment 6\", APP),\n 0xFFE7: (\"APP7\", \"Application segment 7\", APP),\n 0xFFE8: (\"APP8\", \"Application segment 8\", APP),\n 0xFFE9: (\"APP9\", \"Application segment 9\", APP),\n 0xFFEA: (\"APP10\", \"Application segment 10\", APP),\n 0xFFEB: (\"APP11\", \"Application segment 11\", APP),\n 0xFFEC: (\"APP12\", \"Application segment 12\", APP),\n 0xFFED: (\"APP13\", \"Application segment 13\", APP),\n 0xFFEE: (\"APP14\", \"Application segment 14\", APP),\n 0xFFEF: (\"APP15\", \"Application segment 15\", APP),\n 0xFFF0: (\"JPG0\", \"Extension 0\", None),\n 0xFFF1: (\"JPG1\", \"Extension 1\", None),\n 0xFFF2: (\"JPG2\", \"Extension 2\", None),\n 0xFFF3: (\"JPG3\", \"Extension 3\", None),\n 0xFFF4: (\"JPG4\", \"Extension 4\", None),\n 0xFFF5: (\"JPG5\", \"Extension 5\", None),\n 0xFFF6: (\"JPG6\", \"Extension 6\", None),\n 0xFFF7: (\"JPG7\", \"Extension 7\", None),\n 0xFFF8: (\"JPG8\", \"Extension 8\", None),\n 0xFFF9: (\"JPG9\", \"Extension 9\", None),\n 0xFFFA: (\"JPG10\", \"Extension 10\", None),\n 0xFFFB: (\"JPG11\", \"Extension 11\", None),\n 0xFFFC: (\"JPG12\", \"Extension 12\", None),\n 0xFFFD: (\"JPG13\", \"Extension 13\", None),\n 0xFFFE: (\"COM\", \"Comment\", COM),\n}\n\n\ndef _accept(prefix):\n # Magic number was taken from https://en.wikipedia.org/wiki/JPEG\n return prefix[:3] == b\"\\xFF\\xD8\\xFF\"\n\n\n##\n# Image plugin for JPEG and JFIF images.\n\n\nclass JpegImageFile(ImageFile.ImageFile):\n format = \"JPEG\"\n format_description = \"JPEG (ISO 10918)\"\n\n def _open(self):\n s = self.fp.read(3)\n\n if not _accept(s):\n msg = \"not a JPEG file\"\n raise SyntaxError(msg)\n s = b\"\\xFF\"\n\n # Create attributes\n self.bits = self.layers = 0\n\n # JPEG specifics (internal)\n self.layer = []\n self.huffman_dc = {}\n self.huffman_ac = {}\n self.quantization = {}\n self.app = {} # compatibility\n self.applist = []\n self.icclist = []\n\n while True:\n i = s[0]\n if i == 0xFF:\n s = s + self.fp.read(1)\n i = i16(s)\n else:\n # Skip non-0xFF junk\n s = self.fp.read(1)\n continue\n\n if i in MARKER:\n name, description, handler = MARKER[i]\n if handler is not None:\n handler(self, i)\n if i == 0xFFDA: # start of scan\n rawmode = self.mode\n if self.mode == \"CMYK\":\n rawmode = \"CMYK;I\" # assume adobe conventions\n self.tile = [(\"jpeg\", (0, 0) + self.size, 0, (rawmode, \"\"))]\n # self.__offset = self.fp.tell()\n break\n s = self.fp.read(1)\n elif i == 0 or i == 0xFFFF:\n # padded marker or junk; move on\n s = b\"\\xff\"\n elif i == 0xFF00: # Skip extraneous data (escaped 0xFF)\n s = self.fp.read(1)\n else:\n msg = \"no marker found\"\n raise SyntaxError(msg)\n\n def load_read(self, read_bytes):\n \"\"\"\n internal: read more image data\n For premature EOF and LOAD_TRUNCATED_IMAGES adds EOI marker\n so libjpeg can finish decoding\n \"\"\"\n s = self.fp.read(read_bytes)\n\n if not s and ImageFile.LOAD_TRUNCATED_IMAGES and not hasattr(self, \"_ended\"):\n # Premature EOF.\n # Pretend file is finished adding EOI marker\n self._ended = True\n return b\"\\xFF\\xD9\"\n\n return s\n\n def draft(self, mode, size):\n if len(self.tile) != 1:\n return\n\n # Protect from second call\n if self.decoderconfig:\n return\n\n d, e, o, a = self.tile[0]\n scale = 1\n original_size = self.size\n\n if a[0] == \"RGB\" and mode in [\"L\", \"YCbCr\"]:\n self._mode = mode\n a = mode, \"\"\n\n if size:\n scale = min(self.size[0] // size[0], self.size[1] // size[1])\n for s in [8, 4, 2, 1]:\n if scale = s:\n break\n e = (\n e[0],\n e[1],\n (e[2] - e[0] + s - 1) // s + e[0],\n (e[3] - e[1] + s - 1) // s + e[1],\n )\n self._size = ((self.size[0] + s - 1) // s, (self.size[1] + s - 1) // s)\n scale = s\n\n self.tile = [(d, e, o, a)]\n self.decoderconfig = (scale, 0)\n\n b" }, { "role": "assistant", "content": "ox = (0, 0, original_size[0] / scale, original_size[1] / scale)\n return self.mode, box" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "#!/usr/bin/python\n#\n# Licensed to Cloudera, Inc. under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. Cloudera, Inc. licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in co" }, { "role": "assistant", "content": "mpliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "import asyncio\n\nimport pytest\n\nfrom flask import Blueprint\nfrom flask import Flask\nfrom flask import request\nfrom flask.views import MethodView\nfrom flask.views import View\n\npytest.importorskip(\"asgiref\")\n\n\nclass AppError(Exception):\n pass\n\n\nclass BlueprintError(Exception):\n pass\n\n\nclass AsyncView(View):\n methods = [\"GET\", \"POST\"]\n\n async def dispatch_request(self):\n await asyncio.sleep(0)\n return request.method\n\n\nclass AsyncMethodView(MethodView):\n async def get(self):\n await asyncio.sleep(0)\n return \"GET\"\n\n async def post(self):\n await asyncio.sleep(0)\n return \"POST\"\n\n\n@pytest.fixture(name=\"async_app\")\ndef _async_app():\n app = Flask(__name__)\n\n @app.route(\"/\", methods=[\"GET\", \"POST\"])\n @app.route(\"/home\", methods=[\"GET\", \"POST\"])\n async def index():\n await asyncio.sleep(0)\n return request.method\n\n @app.errorhandler(AppError)\n async def handle(_):\n return \"\", 412\n\n @app.route(\"/e" }, { "role": "assistant", "content": "rror\")\n async def error():\n raise AppError()\n\n blueprint = Blueprint(\"bp\", __name__)\n\n @blueprint.route(\"/\", methods=[\"GET\", \"POST\"])\n async def bp_index():\n await asyncio.sleep(0)\n return request.method\n\n @blueprint.errorhandler(BlueprintError)\n async def bp_handle(_):\n return \"\", 412\n\n @blueprint.route(\"/error\")\n async def bp_error():\n raise BlueprintError()\n\n app.register_blueprint(blueprint, url_prefix=\"/bp\")\n\n app.add_url_rule(\"/view\", view_func=AsyncView.as_view(\"view\"))\n app.add_url_rule(\"/methodview\", view_func=AsyncMethodView.as_view(\"methodview\"))\n\n return app" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "import inspect\nimport json\nimport os\nfrom collections import defaultdict\nfrom logging import getLogger\n\nfrom fastapi import APIRouter\n\nfrom pmtrendviz.models.factory import ModelFactory\nfrom pmtrendviz.utils import get_models_dir\n\nlogger = getLogger('pmtrendviz.api.routers.models')\n\n\ndef fetch_available_models(): # type: ignore\n models_dir = get_models_dir()\n models = []\n for model in os.listdir(models_dir):\n model_path = os.path.join(models_dir, model)\n if os.path.isdir(model_path):\n with open(os.path.join(model_path, 'config.json')) as config_fp:\n models.append({\n 'name': model,\n 'path': model_path,\n 'config': json.load(config_fp)\n })\n\n logger.debug(f'Found {len(models)} models: {models}')\n return models\n\n\nrouter = APIRouter(\n prefix=\"/models\",\n tags=[\"models\"]\n)\n\n\n@router.get(\"/public\")\ndef get_public_models(): # type: ignore\n raise NotImplementedError\n\n\n@router.get(\"/saved\")\ndef get_saved_models(): # type: ignore\n models = fetch_available_model" }, { "role": "assistant", "content": "s()\n logger.debug(models)\n return models" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "#!/usr/bin/python\n#\n# Licensed to Cloudera, Inc. under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. Cloudera, Inc. licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n#\n# Template for python Hadoop streaming. Fill in the map() and reduce()\n# functions, which should call emit(), as appropriate.\n#\n# Test your script with\n# cat input | python wordcount.py map | sort | python wordcount.py reduce\n\nimport sys\nimport re\ntry:\n import simplejson as json\nexcept ImportError:\n import json\n\nimport __builtin__\n\ndef map(line):\n words = line.split()\n for word in words:\n emit(word, str(1))\n \ndef reduce(key, values):\n emit(key, str(sum(__builtin__.map(int,values))))\n\n# Common library code follows:\n\ndef emit(key, value):\n \"\"\"\n Emits a key-value pair. Key and value should be strings.\n \"\"\"\n try:\n print \"\\t\".join( (key, value) )\n except:\n pass\n\ndef run_map():\n \"\"\"Calls map() for each input value.\"\"\"\n for line in sys.stdin:\n line = line.rstrip()\n map(line)\n\ndef run_reduce():\n \"\"\"Gathers reduce() data in memory, and calls reduce().\"\"\"\n prev_key = None\n values = []\n for line in sys.stdin:\n line = line.rstrip()\n key, value = re.split(\"\\t\", line, 1)\n if prev_key == key:\n values.append(value)\n else:\n if prev_key is not None:\n reduce(prev_key, values)\n prev_key = key\n values = [ value ]\n\n if prev_key is not None:\n reduce(prev_key, values)\n\ndef main():\n \"\"\"Runs map or reduce code, per arguments.\"\"\"\n if len(sys.argv) != 2 or sys.argv[1] not in (\"map\", \"reduce\"):\n print \"Usage: %s map|reduce\" % sys.argv[" }, { "role": "assistant", "content": "0]\n sys.exit(1)\n if sys.argv[1] == \"map\":\n run_map()\n elif sys.argv[1] == \"reduce\":\n run_reduce()\n else:\n assert False" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "ave_okay'] = slave_okay\n client = pymongo.MongoClient(**options)\n\n if ensure_direct:\n # make sure we are connected to mongod/mongos that was specified; mongodb drivers\n # have the tendency of doing \"magical\" things in terms of connecting to other boxes\n test_collection = client['local']['test']\n test_cursor = test_collection.find(slave_okay=True, limit=1)\n connection = test_cursor.collection.database.connection\n if connection.host != host or connection.port != port:\n raise ValueError(\"connected to %s:%d (expected %s:%d)\" %\n (connection.host, connection.port, host, port))\n\n return client\n\n\ndef parse_mongo_url(url):\n \"\"\"\n Takes in pseudo-URL of form\n\n host[:port]/db/collection (e.g. localhost/prod_maestro/emails)\n\n and returns a dictionary containing elements 'host', 'port', 'db', 'collection'\n \"\"\"\n try:\n host, db, collection = url.split('/')\n except ValueError:\n raise ValueError(\"urls be of format: host[:port]/db/collection\")\n\n host_tokens = host.split(':')\n if len(host_tokens) == 2:\n host = host_tokens[0]\n port = int(host_tokens[1])\n elif len(host_tokens) == 1:\n port = 27017\n elif len(host_tokens) 2:\n raise ValueError(\"urls be of format: host[:port]/db/collection\")\n\n return dict(host=host, port=port, db=db, collection=collection)\n\n\ndef _source_file_syntax():\n print \"--source files must be of the following format:\"\n print \"database_name.collection_name\"\n print \"mongo-shard-1.foo.com\"\n print \"mongo-shard-2.foo.com:27019\"\n print \"...\"\n sys.exit(1)\n\n\ndef parse_source_file(filename):\n \"\"\"\n parses an input file passed to the --source parameter as a list of dicts that contain\n these fields:\n\n host\n port\n db: database name\n collection\n \"\"\"\n sources = []\n\n with open(filename, \"r\") as source_file:\n fullname = source_file.readline().strip()\n try:\n db, collection = fullname.split('.')\n except ValueError:\n _source_file_syntax()\n\n " }, { "role": "assistant", "content": " for source in [line.strip() for line in source_file]:\n tokens = source.split(':')\n if len(tokens) == 1:\n host = tokens[0]\n port = 27017\n elif len(tokens) == 2:\n host, port = tokens\n port = int(port)\n else:\n raise ValueError(\"%s is not a valid source\", source)\n\n sources.append(dict(host=host, port=port, db=db, collection=collection))\n\n return sources" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "rganization = config['openai']['organization_id'].strip('\"').strip(\"'\")\n ENGINE = config['openai']['engine'].strip('\"').strip(\"'\")\n\n prompt_config = {\n 'engine': ENGINE,\n 'temperature': TEMPERATURE,\n 'max_tokens': MAX_TOKENS,\n 'shell': SHELL,\n 'multi_turn': MULTI_TURN,\n 'token_count': 0\n }\n \n return PromptFile(PROMPT_CONTEXT.name, prompt_config)\n\ndef is_sensitive_content(content):\n \"\"\"\n Check if the content contains sensitive content\n Refer to https://beta.openai.com/docs/engines/content-filter for explanation\n \"\"\"\n\n if len(content) == 0:\n return False\n \n response = openai.Completion.create(\n engine=\"content-filter-alpha\",\n prompt = \"||\"+content+\"\\n--\\nLabel:\",\n temperature=0,\n max_tokens=1,\n top_p=0,\n logprobs=10\n )\n \n output_label = response[\"choices\"][0][\"text\"]\n\n # This is the probability at which we evaluate that a \"2\" is likely real\n # vs. should be discarded as a false positive\n toxic_threshold = -0.355\n\n if output_label == \"2\":\n # If the model returns \"2\", return its confidence in 2 or other output-labels\n logprobs = response[\"choices\"][0][\"logprobs\"][\"top_logprobs\"][0]\n\n # If the model is not sufficiently confident in \"2\",\n # choose the most probable of \"0\" or \"1\"\n # Guaranteed to have a confidence for 2 since this was the selected token.\n if logprobs[\"2\"] toxic_threshold:\n logprob_0 = logprobs.get(\"0\", None)\n logprob_1 = logprobs.get(\"1\", None)\n\n # If both \"0\" and \"1\" have probabilities, set the output label\n # to whichever is most probable\n if logprob_0 is not None and logprob_1 is not None:\n if logprob_0 = logprob_1:\n output_label = \"0\"\n else:\n output_label = \"1\"\n " }, { "role": "assistant", "content": " # If only one of them is found, set output label to that one\n elif logprob_0 is not None:\n output_label = \"0\"\n elif logprob_1 is not None:\n output_label = \"1\"" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "import contextlib\nimport os.path\n\nimport pytest\n\nfrom PIL import Image, ImageColor, ImageDraw, ImageFont, features\n\nfrom .helper import (\n assert_image_equal,\n assert_image_equal_tofile,\n assert_image_similar_tofile,\n hopper,\n skip_unless_feature,\n)\n\nBLACK = (0, 0, 0)\nWHITE = (255, 255, 255)\nGRAY = (190, 190, 190)\nDEFAULT_MODE = \"RGB\"\nIMAGES_PATH = os.path.join(\"Tests\", \"images\", \"imagedraw\")\n\n# Image size\nW, H = 100, 100\n\n# Bounding box points\nX0 = int(W / 4)\nX1 = int(X0 * 3)\nY0 = int(H / 4)\nY1 = int(X0 * 3)\n\n# Bounding boxes\nBBOX = (((X0, Y0), (X1, Y1)), [(X0, Y0), (X1, Y1)], (X0, Y0, X1, Y1), [X0, Y0, X1, Y1])\n\n# Coordinate sequences\nPOINTS = (\n ((10, 10), (20, 40), (30, 30)),\n [(10, 10), (20, 40), (30, 30)],\n (10, 10, 20, 40, 30, 30),\n [10, 10, 20, 40, 30, 30],\n)\n\nKITE_POINTS = (\n ((10, 50), (70, 10), (90, 50), (70, 90), (10, 50)),\n [(10, 50), (70, 10), (90, 50), (70, 90), (10, 50)],\n)\n\n\ndef test_sanity():\n im = hopper(\"RGB\").copy()\n\n draw = ImageDraw.ImageDraw(im)\n draw = ImageDraw.Draw(im)\n\n draw.ellipse(list(range(4)))\n draw.line(list(range(10)))\n draw.polygon(list(range(100)))\n draw.rectangle(list(range(4)))\n\n\ndef test_valueerror():\n with Image.open(\"Tests/images/chi.gif\") as im:\n draw" }, { "role": "assistant", "content": " = ImageDraw.Draw(im)\n draw.line((0, 0), fill=(0, 0, 0))" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "\"\"\"\nTests for the throttling implementations in the permissions module.\n\"\"\"\n\nimport pytest\nfrom django.contrib.auth.models import User\nfrom django.core.cache import cache\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.http import HttpRequest\nfrom django.test import TestCase\n\nfrom rest_framework.request import Request\nfrom rest_framework.response import Response\nfrom rest_framework.settings import api_settings\nfrom rest_framework.test import APIRequestFactory, force_authenticate\nfrom rest_framework.throttling import (\n AnonRateThrottle, BaseThrottle, ScopedRateThrottle, SimpleRateThrottle,\n UserRateThrottle\n)\nfrom rest_framework.views import APIView\n\n\nclass User3SecRateThrottle(UserRateThrottle):\n rate = '3/sec'\n scope = 'seconds'\n\n\nclass User3MinRateThrottle(UserRateThrottle):\n rate = '3/min'\n scope = 'minutes'\n\n\nclass User6MinRateThrottle(UserRateThrottle):\n rate = '6/min'\n scope = 'minutes'\n\n\nclass NonTimeThrottle(BaseThrottle):\n def allow_request(self, request, view):\n if not hasattr(self.__class__, 'called'):\n self.__class__.called = True\n return True\n return False\n\n\nclass MockView_DoubleThrottling(APIView):\n throttle_classes = (User3SecRateThrottle, User6MinRateThrottle,)\n\n def get(self, request):\n return Response('foo')\n\n\nclass MockView(APIView):\n throttle_classes = (User3SecRateThrottle,)\n\n def get(self, request):\n return Response('foo')\n\n\nclass MockView_MinuteThrottling(APIView):\n throttle_classes = (User3MinRateThrottle,)\n\n def get(self, request):\n return Response('foo')\n\n\nclass MockView_NonTimeThrottling(APIView):\n throttle_classes = (NonTimeThrottle,)\n\n def get(self, request):\n return Response('foo')\n\n\nclass ThrottlingTests(TestCase):\n def setUp(self):\n \"\"\"\n Reset the cache so that no throttles will be active\n \"\"\"\n cache.clear()\n self.factory = APIRequestFactory()\n\n def test_requests_are_throttled(self):\n \"\"\"\n Ensure request rate is limited\n \"\"\"\n request = self.factory.get('/')\n for dummy in range(4):\n response = MockView.as_view()(request)\n assert response.status_code == 429\n\n def set_throttle_timer(self, view, value):\n \"\"\"\n Explicitly set the timer, overriding time.time()\n \"\"\"\n for cls in view.throttle_classes:\n cls.timer = lambda self: value\n\n def test_request_throttling_expires(self):\n \"\"\"\n Ensure request rate is limited for a limited duration only\n \"\"\"\n self.set_throttle_timer(MockView, 0)\n\n request = self.factory.get('/')\n for dummy in range(4):\n response = MockView.as_view()(request)\n assert response.status_code == 429\n\n # Advance the timer by one second\n self.set_throttle_timer(MockView, 1)\n\n response = MockView.as_view()(request)\n assert response.status_code == 200\n\n def ensure_is_throttled(self, view, expect):\n request = self.factory.get('/')\n request.user = User.objects.create(username='a')\n for dummy in range(3):\n " }, { "role": "assistant", "content": " view.as_view()(request)\n request.user = User.objects.create(username='b')\n response = view.as_view()(request)\n assert response.status_code == expect" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": " locale_parts = match.groupdict()\n language = locale_parts[\"language\"].lower()\n territory = (\n locale_parts[\"territory\"][:2].upper()\n + locale_parts[\"territory\"][2:]\n )\n proposed_locale = f\"{language}_{territory}\"\n else:\n # It could be a language in uppercase\n proposed_locale = locale.lower()\n\n # Recheck if the proposed locale is valid\n if is_valid_locale(proposed_locale):\n self.stdout.write(\n \"invalid locale %s, did you mean %s?\"\n % (\n locale,\n proposed_locale,\n ),\n )\n else:\n self.stdout.write(\"invalid locale %s\" % locale)\n\n continue\n if self.verbosity 0:\n self.stdout.write(\"processing locale %s\" % locale)\n for potfile in potfiles:\n self.write_po_file(potfile, locale)\n finally:\n if not self.keep_pot:\n self.remove_potfiles()\n\n @cached_property\n def gettext_version(self):\n # Gettext tools will output system-encoded bytestrings instead of UTF-8,\n # when looking up the version. It's especially a problem on Windows.\n out, err, status = popen_wrapper(\n [\"xgettext\", \"--version\"],\n stdout_encoding=DEFAULT_LOCALE_ENCODING,\n )\n m = re.search(r\"(\\d+)\\.(\\d+)\\.?(\\d+)?\", out)\n if m:\n return tuple(int(d) for d in m.groups() if d is not None)\n else:\n raise CommandError(\"Unable to get gettext version. Is it installed?\")\n\n @cached_property\n def settings_available(self):\n try:\n settings.LOCALE_PATHS\n except ImproperlyConfigured:\n if self.verbosity 1:\n self.stderr.write(\"Running without configured settings.\")\n return False\n return True\n\n def build_potfiles(self):\n \"\"\"\n Build pot files and apply msguniq to them.\n \"\"" }, { "role": "assistant", "content": "\"" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": ") + exponent\n whole_digits = total_digits\n decimal_places = 0\n elif len(digittuple) abs(exponent):\n # 123.45\n total_digits = len(digittuple)\n whole_digits = total_digits - abs(exponent)\n decimal_places = abs(exponent)\n else:\n # 0.001234\n total_digits = abs(exponent)\n whole_digits = 0\n decimal_places = total_digits\n\n if self.max_digits is not None and total_digits self.max_digits:\n self.fail('max_digits', max_digits=self.max_digits)\n if self.decimal_places is not None and decimal_places self.decimal_places:\n self.fail('max_decimal_places', max_decimal_places=self.decimal_places)\n if self.max_whole_digits is not None and whole_digits self.max_whole_digits:\n self.fail('max_whole_digits', max_whole_digits=self.max_whole_digits)\n\n return value\n\n def to_representation(self, value):\n coerce_to_string = getattr(self, 'coerce_to_string', api_settings.COERCE_DECIMAL_TO_STRING)\n\n if value is None:\n if coerce_to_string:\n return ''\n else:\n return None\n\n if not isinstance(value, decimal.Decimal):\n value = decimal.Decimal(str(value).strip())\n\n quantized = self.quantize(value)\n\n if self.normalize_output:\n quantized = quantized.normalize()\n\n if not coerce_to_string:\n return quantized\n if self.localize:\n return localize_input(quantized)\n\n return '{:f}'.format(quantized)\n\n def quantize(self, value):\n \"\"\"\n Quantize the decimal value to the configured precision.\n \"\"\"\n if self.decimal_places is None:\n return value\n\n context = decimal.getcontext().copy()\n if self.max_digits is not None:\n context.prec = self.max_digits\n return value.quantize(\n decimal.Decimal('.1') ** self.decimal_places,\n rounding=self.rounding,\n context=context\n )\n\n\n# Date & time fields...\n\nclass DateTimeField(Field):\n default_error_messages = {\n 'invalid': _('Datetime has wrong format. Use one of these formats instead: {format}.'),\n 'date': _('Expected a datetime but got a date.'),\n 'make_aware': _('Invalid datetime for the timezone \"{timezone}\".'),\n 'overflow': _('Datetime value out of range.')\n }\n datetime_parser = datetime.datetime.strptime\n\n def __init__(self, format=empty, input_formats=None, default_timezone=None, **kwargs):\n if format is not empty:\n self.format = format\n if input_formats is not None:\n self.input_formats = input_formats\n if default_timezone is not None:\n self.timezone = default_timezone\n super().__init__(**kwargs)\n\n def enforce_timezone(self, value):\n \"\"\"\n When `self.default_timezone` is `None`, always return naive datetimes.\n When `self.default_timezone` is not `None`, always return aware datetimes.\n \"\"\"\n field_timezone = self.timezone if hasattr(self, 'timezone') else self.default_timezone()\n\n if field_timezone is not None:\n if timezone.is_aware(value):\n try:\n return value.astimezone(field_timezone)\n except OverflowError:\n self.fail('overflow')\n try:\n dt = timezone.make_aware(value, field_timezone)\n # When the resulting datetime is a ZoneInfo instance, it won't necessarily\n # throw given an invalid datetime, so we need to specifically check.\n if not valid_datetime(dt):\n self.fail('make_aware', timezone=field_timezone)\n return dt\n except Exception as e:\n if pytz and isinstance(e, pytz.exceptions.InvalidTimeError):\n self.fail('make_aware', timezone=field_timezone)\n raise e\n elif (field_timezone is None) and timezone.is_aware(value):\n return timezone.make_naive(value, datetime.timezone.utc)\n return value\n\n def default_timezone(self):\n return timezone.get_current_timezone() if settings.USE_TZ else None\n\n def to_internal_value(self, value):\n input_formats = getattr(self, 'input_formats', api_settings.DATETIME_INPUT_FORMATS)\n\n if isinstance(value, datetime.date) and not isinstance(value, datetime.datetime):\n self.fail('date')\n\n if isinstance(value, datetime.datetime):\n return self.enforce_timezone(value)\n\n for input_format in input_formats:\n with contextlib.suppress(ValueError, TypeError):\n if input_format.lower() == ISO_8601:\n parsed = parse_datetime(value)\n if parsed is not None:\n return self.enforce_timezone(parsed)\n\n parsed = self.datetime_parser(value, input_format)\n return self.enforce_timezone(parsed)\n\n humanized_format = humanize_datetime.datetime_formats(input_formats)\n self.fail('invalid', format=humanized_format)\n\n def to_representation(self, value):\n if not value:\n return None\n\n output_format = getattr(self, 'format', api_settings.DATETIME_FORMAT)\n\n if output_format is None or isinstance(value, str):\n return value\n\n value = self.enforce_timezone(value)\n\n if output_format.lower() == ISO_8601:\n value = value.isoformat()\n if value.endswith('+00:00'):\n value = value[:-6] + 'Z'\n return value\n return value.strftime(output_format)\n\n\nclass DateField(Field):\n default_error_messages = {\n 'invalid': _('Date has wrong format. Use one of these formats instead: {format}.'),\n 'datetime': _('Expected a date but got a datetime.'),\n }\n datetime_parser = datetime.datetime.strptime\n\n def __init__(self, format=empty, input_formats=None, **kwargs):\n if format is not empty:\n self.format = format\n if input_formats is not None:\n self.input_formats = input_formats\n super().__init__(**kwargs)\n\n def to_internal_value(self, value):\n input_formats = getattr(self, 'input_formats', api_settings.DATE_INPUT_FORMATS)\n\n if isinstance(value, datetime.datetime):\n self.fail('datetime')\n\n if isinstance(value, datetime.date):\n return value\n\n for input_format in input_formats:\n if input_format.lower() == ISO_8601:\n try:\n parsed = parse_date(value)\n except (ValueError, TypeError):\n pass\n else:\n if parsed is not None:\n return parsed\n else:\n try:\n parsed = self.datetime_parser(value, input_format)\n except (ValueError, TypeError):\n pass\n else:\n return parsed.date()\n\n humanized_format = humanize_datetime.date_formats(input_formats)\n self.fail('invalid', format=humanized_format)\n\n def to_representation(self, value):\n if not value:\n return None\n\n output_format = getattr(self, 'format', api_settings.DATE_FORMAT)\n\n if output_format is None or isinstance(value, str):\n return value\n\n # Applying a `DateField` to a datetime value is almost always\n # not a sensible thing to do, as it means naively dropping\n # any explicit or implicit timezone info.\n assert not isinstance(value, datetime.datetime), (\n 'Expected a `date`, but got a `datetime`. Refusing to coerce, '\n 'as this may mean losing timezone information. Use a custom '\n 'read-only field and deal with timezone issues explicitly.'\n )\n\n if output_format.lower() == ISO_8601:\n return value.isoformat()\n\n return value.strftime(output_format)\n\n\nclass TimeField(Field):\n defau" }, { "role": "assistant", "content": "lt_error_messages = {\n 'invalid': _('Time has wrong format. Use one of these formats instead: {format}.'),\n }" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for lite.py functionality related to select TF op usage.\"\"\"\n\nimport os\n\nfrom absl.testing import parameterized\nimport numpy as np\nimport tensorflow as tf\n\nfrom tensorflow.core.framework import graph_pb2\nfrom tensorflow.lite.python import lite\nfrom tensorflow.lite.python import test_util as tflite_test_util\nfrom tensorflow.lite.python.convert import register_custom_opdefs\nfrom tensorflow.lite.python.interpreter import Interpreter\nfrom tensorflow.lite.python.testdata import double_op\nfrom tensorflow.python.client import session\nfrom tensorflow.python.eager import def_function\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.framework.importer import import_graph_def\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import list_ops\nfrom tensorflow.python.ops import nn_ops\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.platform import test\nfrom tensorflow.python.saved_model import saved_model\nfrom tensorflow.python.trackable import autotrackable\n\n\nclass FromSessionTest(test_util.TensorFlowTestCase, parameterized.TestCase):\n\n @parameterized.named_parameters(\n ('EnableMlirConverter', True), # enable mlir\n ('DisableMlirConverter', False)) # disable mlir\n def testFlexMode(self, enable_mlir):\n with ops.Graph().as_default():\n in_tensor = array_ops.placeholder(shape=[1, 4], dtype=dtypes.float32)\n out_tensor = in_tensor + in_tensor\n sess = session.Session()\n\n # Convert model and ensure model is not None.\n converter = lite.TFLiteConverter.from_session(sess, [in_tensor],\n [out_tensor])\n converter.target_spec.supported_ops = set([lite.OpsSet.SELECT_TF_OPS])\n converter.experimental_new_converter = enable_mlir\n tflite_model = converter.convert()\n self.assertTrue(tflite_model)\n\n # Check the model works with TensorFlow ops.\n interpreter = Interpreter(model_content=tflite_model)\n interpreter.allocate_tensors()\n input_details = interpreter.get_input_details()\n test_input = np.array([[1.0, 2.0, 3.0, 4.0]], dtype=np.float32)\n interpreter.set_tensor(input_details[0]['index'], test_input)\n interpreter.invoke()\n\n output_details = interpreter.get_output_details()\n expected_output = np.array([[2.0, 4.0, 6.0, 8.0]], dtype=np.float32)\n output_data = interpreter.get_tensor(output_details[0]['index'])\n self.assertTrue((expected_output == output_data).all())\n\n def testFlexWithAutomaticPassThrough(self):\n # Create a graph that has one L2Loss op.\n with ops.Graph().as_default():\n with session.Session() as sess:\n in_tensor = array_ops.placeholder(\n shape=[4], dtype=dtypes.float32, name='input')\n out_tensor = nn_ops.l2_loss(in_tensor)\n converter = lite.TFLiteConverter.from_session(sess, [in_tensor],\n [out_tensor])\n converter.target_spec.supported_ops = set([lite.OpsSet.SELECT_TF_OPS])\n converter._experimental_allow_all_select_tf_ops = True\n tflite_model = converter.convert()\n self.assertTrue(tflite_model)\n self.assertIn('FlexL2Loss', tflite_test_util.get_ops_list(tflite_model))\n\n def testDeprecatedFlags(self):\n with ops.Graph().as_default():\n in_tensor = array_ops.placeholder(shape=[1, 4], dtype=dtypes.float32)\n out_tensor = in_tensor + in_tensor\n sess = session.Session()\n\n # Convert model and ensure model is not None.\n converter = lite.TFLiteConverter.from_session(sess, [in_tensor],\n [out_tensor])\n converter.target_ops = set([lite.OpsSet.SELECT_TF_OPS])\n\n # Ensure `target_ops` is set to the correct value after flag deprecation.\n self.assertEqual(converter.target_ops, set([lite.OpsSet.SELECT_TF_OPS]))\n self.assertEqual(converter.target_spec.supported_ops,\n set([lite.OpsSet.SELECT_TF_OPS]))\n\n tflite_model = converter.convert()\n self.assertTrue(tflite_model)\n\n # Check the model works with TensorFlow ops.\n interpreter = Interpreter(model_content=tflite_model)\n interpreter.allocate_tensors()\n input_details = interpreter.get_input_details()\n test_input = np.array([[1.0, 2.0, 3.0, 4.0]], dtype=np.float32)\n interpreter.set_tensor(input_details[0]['index'], test_input)\n interpreter.invoke()\n\n output_details = interpreter.get_output_details()\n expected_output = np.array([[2.0, 4.0, 6.0, 8.0]], dtype=np.float32)\n output_data = interpreter.get_tensor(output_details[0]['index'])\n self.assertTrue((expected_output == output_data).all())\n\n\nclass FromConcreteFunctionTest(test_util.TensorFlowTestCase,\n parameterized.TestCase):\n\n @parameterized.named_parameters(\n ('EnableMlirConverter', True), # enable mlir\n ('DisableMlirConverter', False)) # disable mlir\n @test_util.run_v2_only\n def testFloat(self, enable_mlir):\n input_data = constant_op.constant(1., shape=[1])\n root = autotrackable.AutoTrackable()\n root.v1 = variables.Variable(3.)\n root.v2 = variables.Variable(2.)\n root.f = def_function.function(lambda x: root.v1 * root.v2 * x)\n concrete_func = root.f.get_concrete_function(input_data)\n\n # Convert model.\n converter = lite.TFLiteConverterV2.from_concrete_functions([concrete_func],\n root)\n converter.target_spec.supported_ops = set([lite.OpsSet.SELECT_TF_OPS])\n converter.experimental_new_converter = enable_mlir\n tflite_model = converter.convert()\n\n # Check the model works with TensorFlow ops.\n interpreter = Interpreter(model_content=tflite_model)\n interpreter.allocate_tensors()\n input_details = interpreter.get_input_details()\n test_input = np.array([4.0], dtype=np.float32)\n interpreter.set_tensor(input_details[0]['index'], test_input)\n interpreter.invoke()\n\n output_details = interpreter.get_output_details()\n expected_output = np.array([24.0], dtype=np.float32)\n output_data = interpreter.get_tensor(output_details[0]['index'])\n self.assertTrue((expected_output == output_data).all())\n\n # Ensure that input TFLite buffer is not reused for ops such as\n # `TensorListSetItem`. The example model has a while loop, and the while body\n # has a `TensorListSetItem` op which takes the output from a `Where` op.\n @test_util.run_v2_only\n def testDisableFlexTensorMemoryReusing(self):\n\n @tf.function(input_signature=[\n tf.TensorSpec(shape=[2, 3], dtype=tf.float32, name='x')\n ])\n def model(x):\n l = list_ops.tensor_list_reserve(\n element_dtype=tf.int64," }, { "role": "assistant", "content": " element_shape=[None, 1], num_elements=2)" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "er == 'imagemagick' and html == 'html5'\n # ImageMagick delegates to ffmpeg for this format.\n and not animation.FFMpegWriter.isAvailable()):\n pytest.skip('Requires FFMpeg')\n # create here rather than in the fixture otherwise we get __del__ warnings\n # about producing no output\n anim = animation.FuncAnimation(**anim)\n with plt.rc_context({'animation.writer': writer,\n 'animation.html': html}):\n html = anim._repr_html_()\n if want is None:\n assert html is None\n with pytest.warns(UserWarning):\n del anim # Animation was never run, so will warn on cleanup.\n np.testing.break_cycles()\n else:\n assert want in html\n\n\n@pytest.mark.parametrize(\n 'anim',\n [{'save_count': 10, 'frames': iter(range(5))}],\n indirect=['anim']\n)\ndef test_no_length_frames(anim):\n anim.save('unused.null', writer=NullMovieWriter())\n\n\ndef test_movie_writer_registry():\n assert len(animation.writers._registered) 0\n mpl.rcParams['animation.ffmpeg_path'] = \"not_available_ever_xxxx\"\n assert not animation.writers.is_available(\"ffmpeg\")\n # something guaranteed to be available in path and exits immediately\n bin = \"true\" if sys.platform != 'win32' else \"where\"\n mpl.rcParams['animation.ffmpeg_path'] = bin\n assert animation.writers.is_available(\"ffmpeg\")\n\n\n@pytest.mark.parametrize(\n \"method_name\",\n [pytest.param(\"to_html5_video\", marks=pytest.mark.skipif(\n not animation.writers.is_available(mpl.rcParams[\"animation.writer\"]),\n reason=\"animation writer not installed\")),\n \"to_jshtml\"])\n@pytest.mark.parametrize('anim', [dict(frames=1)], indirect=['anim'])\ndef test_embed_limit(method_name, caplog, tmpdir, anim):\n caplog.set_level(\"WARNING\")\n with tmpdir.as_cwd():\n with mpl.rc_context({\"animation.embed_limit\": 1e-6}): # ~1 byte.\n getattr(anim, method_name)()\n assert len(caplog.rec" }, { "role": "assistant", "content": "ords) == 1\n record, = caplog.records\n assert (record.name == \"matplotlib.animation\"\n and record.levelname == \"WARNING\")" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "from collections import deque\n\nclass FasterOrderedDict(dict):\n \"\"\"\n Faster than using the standard library class collections.OrderedDict,\n because OrderedDict is pure Python. This class delegates every\n operation to dict/deque, which are both C-based.\n\n This handles only the operations that matter to the rest of Hydra and probably\n won't work for other use cases without modification.\n \"\"\"\n def __init__(self):\n dict.__init__(self)\n self._elems = deque()\n\n def __delitem__(self, key):\n \"\"\"\n slow but should be uncommon for our uses\n \"\"\"\n dict.__delitem__(self, key)\n self._elems.remove(key)\n\n def __setitem__(self, key, data):\n if key in self:\n dict.__setitem__(self, key, data)\n else:\n self._elems.append(key)\n dict.__setitem__(self, key, data)\n\n def __repr__(self):\n elems = ', '.join" }, { "role": "assistant", "content": "([\"'%s': %s\" % (elem, self[elem])\n for elem in self._elems])\n return '{%s}' % elems" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "#!/usr/bin/env python\n# encoding: utf-8\n\"\"\"\ndelicious_import.py\n\nCreated by Hilary Mason on 2010-11-28.\nCopyright (c) 2010 Hilary Mason. All rights reserved.\n\"\"\"\n\nimport sys\nimport urllib\nimport csv\nfrom xml.dom import minidom\n\n\nclass delicious_import(object):\n def __init__(self, username, password=''):\n\t\t# API URL: https://user:passwd@api.del.icio.us/v1/posts/all\n url = \"https://%s:%s@api.del.icio.us/v1/posts/all\" % (username, password)\n h = urllib.urlopen(url)\n c" }, { "role": "assistant", "content": "ontent = h.read()\n h.close()" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "on\n maps or list of prediction result filenames.\n gt_seg_maps (list[ndarray] | list[str]): list of ground truth\n segmentation maps or list of label filenames.\n num_classes (int): Number of categories.\n ignore_index (int): Index that will be ignored in evaluation.\n nan_to_num (int, optional): If specified, NaN values will be replaced\n by the numbers defined by the user. Default: None.\n label_map (dict): Mapping old labels to new labels. Default: dict().\n reduce_zero_label (bool): Wether ignore zero label. Default: False.\n beta (int): Determines the weight of recall in the combined score.\n Default: False.\n\n\n Returns:\n dict[str, float | ndarray]: Default metrics.\n aAcc float: Overall accuracy on all images.\n Fscore ndarray: Per category recall, shape (num_classes, ).\n Precision ndarray: Per category precision, shape (num_classes, ).\n Recall ndarray: Per category f-score, shape (num_classes, ).\n \"\"\"\n fscore_result = eval_metrics(\n results=results,\n gt_seg_maps=gt_seg_maps,\n num_classes=num_classes,\n ignore_index=ignore_index,\n metrics=['mFscore'],\n nan_to_num=nan_to_num,\n label_map=label_map,\n reduce_zero_label=reduce_zero_label,\n beta=beta)\n return fscore_result\n\n\ndef eval_metrics(results,\n gt_seg_maps,\n num_classes,\n ignore_index,\n metrics=['mIoU'],\n nan_to_num=None,\n label_map=dict(),\n reduce_zero_label=False,\n beta=1):\n \"\"\"Calculate evaluation metrics\n Args:\n results (list[ndarray] | list[str]): List of prediction segmentation\n maps or list of prediction result filenames.\n gt_seg_maps (list[ndarray] | list[str]): list of ground truth\n segmentation maps or list of label filenames.\n num_classes (int): Number of categories.\n ignore_index (int): Index that will be ignored in evaluation.\n metrics (list[str] | str): Metrics to be evaluated, 'mIoU' and 'mDice'.\n nan_to_num (int, optional): If specified, NaN values will be replaced\n by the numbers defined by the user. Default: None.\n label_map (dict): Mapping old labels to new labels. Default: dict().\n reduce_zero_label (bool): Wether ignore zero label. Default: False.\n Returns:\n float: Overall accuracy on all images.\n ndarray: Per category accuracy, shape (num_classes, ).\n ndarray: Per category evaluation metrics, shape (num_classes, ).\n \"\"\"\n if isinstance(metrics, str):\n metrics = [metrics]\n allowed_metrics = ['mIoU', 'mDice', 'mFscore']\n if not set(metrics).issubset(set(allowed_metrics)):\n raise KeyError('metrics {} is not supported'.format(metrics))\n\n total_area_intersect, total_area_union, total_area_pred_label, \\\n total_area_label = total_intersect_and_union(\n results, gt_seg_maps, num_classes, ignore_index, label_map,\n reduce_zero_label)\n all_acc = total_area_intersect.sum() / total_area_label.sum()\n ret_metrics = OrderedDict({'aAcc': all_acc})\n for metri" }, { "role": "assistant", "content": "c in metrics:\n if metric == 'mIoU':\n iou = total_area_intersect / total_area_union\n acc = total_area_intersect / total_area_label\n ret_metrics['IoU'] = iou\n ret_metrics['Acc'] = acc\n elif metric == 'mDice':\n dice = 2 * total_area_intersect / (\n total_area_pred_label + total_area_label)\n acc = total_area_intersect / total_area_label\n ret_metrics['Dice'] = dice\n ret_metrics['Acc'] = acc\n elif metric == 'mFscore':\n precision = total_area_intersect / total_area_pred_label\n recall = total_area_intersect / total_area_label\n f_value = torch.tensor(\n [f_score(x[0], x[1], beta) for x in zip(precision, recall)])\n ret_metrics['Fscore'] = f_value\n ret_metrics['Precision'] = precision\n ret_metrics['Recall'] = recall\n\n ret_metrics = {\n metric: value.numpy()\n for metric, value in ret_metrics.items()\n }\n if nan_to_num is not None:\n ret_metrics = OrderedDict({\n metric: np.nan_to_num(metric_value, nan=nan_to_num)\n for metric, metric_value in ret_metrics.items()\n })\n return ret_metrics" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "es to draw from X\n to train each base estimator.\n\n - If None (default), then draw `X.shape[0]` samples.\n - If int, then draw `max_samples` samples.\n - If float, then draw `max(round(n_samples * max_samples), 1)` samples. Thus,\n `max_samples` should be in the interval `(0.0, 1.0]`.\n\n .. versionadded:: 0.22\n\n monotonic_cst : array-like of int of shape (n_features), default=None\n Indicates the monotonicity constraint to enforce on each feature.\n - 1: monotonically increasing\n - 0: no constraint\n - -1: monotonically decreasing\n\n If monotonic_cst is None, no constraints are applied.\n\n Monotonicity constraints are not supported for:\n - multioutput regressions (i.e. when `n_outputs_ 1`),\n - regressions trained on data with missing values.\n\n Read more in the :ref:`User Guide monotonic_cst_gbdt`.\n\n .. versionadded:: 1.4\n\n Attributes\n ----------\n estimator_ : :class:`~sklearn.tree.DecisionTreeRegressor`\n The child estimator template used to create the collection of fitted\n sub-estimators.\n\n .. versionadded:: 1.2\n `base_estimator_` was renamed to `estimator_`.\n\n base_estimator_ : DecisionTreeRegressor\n The child estimator template used to create the collection of fitted\n sub-estimators.\n\n .. deprecated:: 1.2\n `base_estimator_` is deprecated and will be removed in 1.4.\n Use `estimator_` instead.\n\n estimators_ : list of DecisionTreeRegressor\n The collection of fitted sub-estimators.\n\n feature_importances_ : ndarray of shape (n_features,)\n The impurity-based feature importances.\n The higher, the more important the feature.\n The importance of a feature is computed as the (normalized)\n total reduction of the criterion brought by that feature. It is also\n known as the Gini importance.\n\n Warning: impurity-based feature importances can be misleading for\n high cardinality features (many unique values). See\n :func:`sklearn.inspection.permutation_importance` as an alternative.\n\n n_featur" }, { "role": "assistant", "content": "es_in_ : int\n Number of features seen during :term:`fit`." } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "import os\nimport time\nimport configparser\n\nfrom pathlib import Path\n\n\nAPI_KEYS_LOCATION = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'openaiapirc')\n\nclass PromptFile:\n context_source_filename = \"\"\n default_context_filename = \"current_context.txt\"\n default_file_path = os.path.join(os.path.dirname(__file__), \"..\", default_context_filename)\n default_config_path = os.path.join(os.path.dirname(__file__), \"..\", \"current_context.config\")\n\n def __init__(self, file_name, config):\n self.context_source_filename = \"{}-context.txt\".format(config['shell']) # feel free to set your own default context path here\n \n self.file_path = self.default_file_path\n self.config_path = self.default_config_path\n\n # loading in one of the saved contexts\n if file_name != self.default_context_filename:\n self.load_context(file_name, True)\n\n def has_config(self):\n \"\"\"\n Check if the prompt file has a corresponding config file\n \"\"\"\n return os.path.isfile(self.config_path)\n \n def read_config(self):\n \"\"\"\n Read the prompt config and return a dictionary\n \"\"\"\n\n if self.has_config() == False:\n self.set_config(self.config)\n return self.config\n \n with open(self.config_path, 'r') as f:\n lines = f.readlines()\n\n config = {\n 'engine': lines[0].split(':')[1].strip(),\n 'temperature': float(lines[1].split(':')[1].strip()),\n 'max_tokens': int(lines[2].split(':')[1].strip()),\n 'shell': lines[3].split(':')[1].strip(),\n 'multi_turn': lines[4].split(':')[1].strip(),\n 'token_count': int(lines[5].split(':')[1].strip())\n }\n\n self.config = config\n return self.config \n \n def set_config(self, config):\n \"\"\"\n Set the prompt headers with the new config\n \"\"\"\n self.config = config\n \n with open(self.config_path, 'w') as f:\n f.write('engine: {}\\n'.format(self.config['engine']))\n f.write('temperature: {}\\n'.format(self.config['temperature']))\n f.write('max_tokens: {}\\n'.format(self.config['max_tokens']))\n f.write('shell: {}\\n'.format(self.config['shell']))\n f.write('multi_turn: {}\\n'.format(self.config['multi_turn']))\n f.write('token_count: {}\\n'.format(self.config['token_count']))\n \n def show_config(self):\n print('\\n')\n # read the dictionary into a list of # lines\n lines = []\n for key, value in self.config.items():\n lines.append('# {}: {}\\n'.format(key, value))\n print(''.join(lines))\n \n def add_input_output_pair(self, user_query, prompt_response):\n \"\"\"\n Add lines to file_name and update the token_count\n \"\"\"\n\n with open(self.file_path, 'a') as f:\n f.write(user_query)\n f.write(prompt_response)\n \n if self.config['multi_turn'] == 'on':\n self.config['token_count'] += len(user_query.split()) + len(prompt_response.split())\n self.set_config(self.config)\n \n def read_prompt_file(self, input):\n \"\"\"\n Get the updated prompt file\n Checks for token overflow and appends the current input\n\n Returns: the prompt file after appending the input\n \"\"\"\n\n input_tokens_count = len(input.split())\n need_to_refresh = (self.config['token_count'] + input_tokens_count 2048)\n\n if need_to_refresh:\n # delete first 2 lines of prompt context file\n with open(self.file_path, 'r') as f:\n lines = f.readlines()\n prompt = lines[2:] # drop first 2 lines of prompt\n with open(self.file_path, 'w') as f:\n f.writelines(prompt)\n\n # get input from prompt file\n with open(self.file_path, 'r') as f:\n lines = f.readlines()\n\n return ''.join(lines)\n \n def get_token_count(self):\n \"\"\"\n Get the actual token count\n \"\"\"\n token_count = 0\n if self.has_config():\n with open(self.config_path, 'r') as f:\n lines = f.readlines()\n token_count = int(lines[5].split(':')[1].strip())\n \n true_token_count" }, { "role": "assistant", "content": " = 0" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "# Reproductions/tests for crashes/read errors in TiffDecode.c\n\n# When run in Python, all of these images should fail for\n# one reason or another, either as a buffer overrun,\n# unrecognized datastream, or truncated image file.\n# There shouldn't be any segfaults.\n#\n# if run like\n# `valgrind --tool=memcheck pytest test_tiff_crashes.py 2&1 | grep TiffDecode.c`\n# the output should be empty. There may be Python issues\n# in the valgrind especially if run in a debug Python\n# version.\n\nimport pytest\n\nfrom PIL import Image\n\nfrom .helper import on_ci\n\n\n@pytest.mark.parametrize(\n \"test_file\",\n [\n \"Tests/images/crash_1.tif\",\n \"Tests/images/crash_2.tif\",\n \"Tests/images/crash-2020-10-test.tif\",\n \"Tests/images/crash-0c7e0e8e11ce787078f00b5b0ca409a167f070e0.tif\",\n \"Tests/images/crash-0e16d3bfb83be87356d026d66919deaefca44dac.tif\",\n \"Tests/images/crash-1152ec2d1a1a71395b6f2ce6721c38924d025bf3.tif\",\n \"Tests/images/crash-1185209cf7655b5aed8ae5e77784dfdd18ab59e9.tif\",\n \"Tests/images/crash-338516dbd2f0e83caddb8ce256c22db3bd6dc40f.tif\",\n \"Tests/images/crash-4f085cc12ece8cde18758d42608bed6a2a2cfb1c.tif\",\n \"Tests/images/crash-86214e58da443d2b80820cff9677a38a33dcbbca.tif\",\n \"Tests/images/crash-f46f5b2f43c370fe65706c11449f567ecc345e74.tif\",\n \"T" }, { "role": "assistant", "content": "ests/images/crash-63b1dffefc8c075ddc606c0a2f5fdc15ece78863.tif\",\n \"Tests/images/crash-74d2a78403a5a59db1fb0a2b8735ac068a75f6e3.tif\",\n \"Tests/images/crash-81154a65438ba5aaeca73fd502fa4850fbde60f8.tif\",\n \"Tests/images/crash-0da013a13571cc8eb457a39fee8db18f8a3c7127.tif\",\n ],\n)\n@pytest.mark.filterwarnings(\"ignore:Possibly corrupt EXIF data\")\n@pytest.mark.filterwarnings(\"ignore:Metadata warning\")\n@pytest.mark.filterwarnings(\"ignore:Truncated File Read\")\ndef test_tiff_crashes(test_file):\n try:\n with Image.open(test_file) as im:\n im.load()\n except FileNotFoundError:\n if not on_ci():\n pytest.skip(\"test image not found\")\n return\n raise\n except OSError:\n pass\n" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "------\n self : object\n \"\"\"\n if _refit:\n self.classes_ = None\n\n first_call = _check_partial_fit_first_call(self, classes)\n X, y = self._validate_data(X, y, reset=first_call)\n if sample_weight is not None:\n sample_weight = _check_sample_weight(sample_weight, X)\n\n # If the ratio of data variance between dimensions is too small, it\n # will cause numerical errors. To address this, we artificially\n # boost the variance by epsilon, a small fraction of the standard\n # deviation of the largest dimension.\n self.epsilon_ = self.var_smoothing * np.var(X, axis=0).max()\n\n if first_call:\n # This is the first call to partial_fit:\n # initialize various cumulative counters\n n_features = X.shape[1]\n n_classes = len(self.classes_)\n self.theta_ = np.zeros((n_classes, n_features))\n self.var_ = np.zeros((n_classes, n_features))\n\n self.class_count_ = np.zeros(n_classes, dtype=np.float64)\n\n # Initialise the class prior\n # Take into account the priors\n " }, { "role": "assistant", "content": " if self.priors is not None:\n priors = np.asarray(self.priors)\n # Check that the provided prior matches the number of classes\n if len(priors) != n_classes:\n raise ValueError(\"Number of priors must match number of classes.\")\n # Check that the sum is 1\n if not np.isclose(priors.sum(), 1.0):\n raise ValueError(\"The sum of the priors should be 1.\")\n # Check that the priors are non-negative\n if (priors 0).any():\n raise ValueError(\"Priors must be non-negative.\")\n self.class_prior_ = priors\n else:\n # Initialize the priors to zeros for each class\n self.class_prior_ = np.zeros(len(self.classes_), dtype=np.float64)\n else:\n if X.shape[1] != self.theta_.shape[1]:\n msg = \"Number of features %d does not match previous data %d.\"\n raise ValueError(msg % (X.shape[1], self.theta_.shape[1]))\n # Put epsilon back in each time\n self.var_[:, :] -= self.epsilon_" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": " if \"wsgi.input_terminated\" in request.environ:\n app.logger.debug(\n \"environ wsgi.input_terminated already set, keeping: %s\"\n % request.environ[\"wsgi.input_terminated\"]\n )\n else:\n request.environ[\"wsgi.input_terminated\"] = 1\n else:\n abort(501, \"Chunked requests are not supported for server %s\" % server)\n\n\n@app.after_request\ndef set_cors_headers(response):\n response.headers[\"Access-Control-Allow-Origin\"] = request.headers.get(\"Origin\", \"*\")\n response.headers[\"Access-Control-Allow-Credentials\"] = \"true\"\n\n if request.method == \"OPTIONS\":\n # Both of these headers are only used for the \"preflight request\"\n # http://www.w3.org/TR/cors/#access-control-allow-methods-response-header\n response.headers[\n \"Access-Control-Allow-Methods\"\n ] = \"GET, POST, PUT, DELETE, PATCH, OPTIONS\"\n response.headers[\"Access-Control-Max-Age\"] = \"3600\" # 1 hour cache\n if request.headers.get(\"Access-Control-Request-Headers\") is not None:\n response.headers[\"Access-Control-Allow-Headers\"] = request.headers[\n \"Access-Control-Request-Headers\"\n ]\n return response\n\n\n# ------\n# Routes\n# ------\n\n\n@app.route(\"/legacy\")\ndef view_landing_page():\n \"\"\"Generates Landing Page in legacy layout.\"\"\"\n return render_template(\"index.html\")\n\n\n@app.route(\"/html\")\ndef view_html_page():\n \"\"\"Returns a simple HTML document.\n ---\n tags:\n - Response formats\n produces:\n - text/html\n responses:\n 200:\n description: An HTML page.\n \"\"\"\n\n return render_template(\"moby.html\")\n\n\n@app.route(\"/robots.txt\")\ndef view_robots_page():\n \"\"\"Returns some robots.txt rules.\n ---\n tags:\n - Response formats\n produces:\n - text/plain\n responses:\n 200:\n description: Robots file\n \"\"\"\n\n response = make_response()\n response.data = ROBOT_TXT\n response.content_type = \"text/plain\"\n return response\n\n\n@app.route(\"/deny\")\ndef view_deny_page():\n \"\"\"Returns page denied by robots.txt rules.\n ---\n tags:\n - Response formats\n produces:\n - text/plain\n responses:\n 200:\n description: Denied message\n \"\"\"\n response = make_response()\n response.data = ANGRY_ASCII\n response.content_type = \"text/plain\"\n return response\n # return \"YOU SHOULDN'T BE HERE\"\n\n\n@app.route(\"/ip\")\ndef view_origin():\n \"\"\"Returns the requester's IP Address.\n ---\n tags:\n - Request inspection\n produces:\n - application/json\n responses:\n 200:\n description: The Requester's IP Address.\n \"\"\"\n\n return jsonify(origin=request.headers.get(\"X-Forwarded-For\", request.remote_addr))\n\n\n@app.route(\"/uuid\")\ndef view_uuid():\n \"\"\"Return a UUID4.\n ---\n tags:\n - Dynamic data\n produces:\n - application/json\n responses:\n 200:\n description: A UUID4.\n \"\"\"\n\n return jsonify(uuid=str(uuid.uuid4()))\n\n\n@app.route(\"/headers\")\ndef view_headers():\n \"\"\"Return the incoming request's HTTP headers.\n ---\n tags:\n - Request inspection\n produces:\n - application/json\n responses:\n 200:\n description: The request's headers.\n \"\"\"\n\n return jsonify(get_dict('headers'))\n\n\n@app.route(\"/user-agent\")\ndef view_user_agent():\n \"\"\"Return the incoming requests's User-Agent header.\n ---\n tags:\n - Request inspection\n produces:\n - application/json\n responses:\n 200:\n description: The request's User-Agent header.\n \"\"\"\n\n headers = get_headers()\n\n return jsonify({\"user-agent\": headers[\"user-agent\"]})\n\n\n@app.route(\"/get\", methods=(\"GET\",))\ndef view_get():\n \"\"\"The request's query parameters.\n ---\n tags:\n - HTTP Methods\n produces:\n - application/json\n responses:\n 200:\n description: The request's query parameters.\n \"\"\"\n\n return jsonify(get_dict(\"url\", \"args\", \"headers\", \"origin\"))\n\n\n@app.route(\"/anything\", methods=[\"GET\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\", \"TRAC" }, { "role": "assistant", "content": "E\"])" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "f.set_ticks_position('none')\n self._wrap_locator_formatter()\n\n def _set_scale(self, value, **kwargs):\n if value != 'linear':\n raise NotImplementedError(\n \"The xscale cannot be set on a polar plot\")\n super()._set_scale(value, **kwargs)\n # LinearScale.set_default_locators_and_formatters just set the major\n # locator to be an AutoLocator, so we customize it here to have ticks\n # at sensible degree multiples.\n self.get_major_locator().set_params(steps=[1, 1.5, 3, 4.5, 9, 10])\n self._wrap_locator_formatter()\n\n def _copy_tick_props(self, src, dest):\n \"\"\"Copy the props from src tick to dest tick.\"\"\"\n if src is None or dest is None:\n return\n super()._copy_tick_props(src, dest)\n\n # Ensure that tick transforms are independent so that padding works.\n trans = dest._get_text1_transform()[0]\n dest.label1.set_transform(trans + dest._text1_translate)\n trans = dest._get_text2_transform()[0]\n dest.label2.set_transform(trans + dest._text2_translate)\n\n\nclass RadialLocator(mticker.Locator):\n \"\"\"\n Used to locate radius ticks.\n\n Ensures that all ticks are strictly positive. For all other tasks, it\n delegates to the base `.Locator` (which may be different depending on the\n scale of the *r*-axis).\n \"\"\"\n\n def __init__(self, base, axes=None):\n self.base = base\n self._axes = axes\n\n def set_axis(self, axis):\n self.base.set_axis(axis)\n\n def __call__(self):\n # Ensure previous behaviour with full circle non-annular views.\n if self._axes:\n if _is_full_circle_rad(*self._axes.viewLim.intervalx):\n rorigin = self._axes.get_rorigin() * self._axes.get_rsign()\n if self._axes.get_rmin() = rorigin:\n return [tick for tick in self.base() if tick rorigin]\n return self.base()\n\n def _zero_in_bounds(self):\n \"\"\"\n Return True if zero is within the valid values for the\n scale of the radial axis.\n \"\"\"\n vmin, vmax = self._axes.yaxis._scale.limit_range_for_scale(0, 1, 1e-5)\n return vmin == 0\n\n def nonsingular(self, vmin, vmax):\n # docstring inherited\n if self._zero_in_bounds() and (vmin, vmax) == (-np.inf, np.inf):\n # Initial view limits\n return (0, 1)\n else:\n return self.base.nonsingular(vmin, vmax)\n\n def view_limits(self, vmin, vmax):\n vmin, vmax = self.base.view_limits(vmin, vmax)\n if self._zero_in_bounds() and vmax vmin:\n # this allows inverted r/y-lims\n vmin = min(0, vmin)\n return mtransforms.nonsingular(vmin, vmax)\n\n\nclass _ThetaShift(mtransforms.ScaledTranslation):\n \"\"\"\n Apply a padding shift based on axes theta limits.\n\n This is used to create padding for radial ticks.\n\n Parameters\n ----------\n axes : `~matplotlib.axes.Axes`\n The owning axes; used to determine limits.\n pad : float\n The padding to apply, in points.\n mode : {'min', 'max', 'rlabel'}\n Whether to shift away from the start (``'min'``) or the end (``'max'``)\n of the axes, or using the rlabel position (``'rlabel'``).\n \"\"\"\n def __init__(self, axes, pad, mode):\n super().__init__(pad, pad, axes.figure.dpi_scale_trans)\n self.set_children(axes._realViewLim)\n self.axes = axes\n self.mode = mode\n self.pad = pad\n\n __str__ = mtransforms._make_str_method(\"axes\", \"pad\", \"mode\")\n\n def get_matrix(self):\n if self._invalid:\n if self.mode == 'rlabel':\n angle = (\n np.deg2rad(self.axes.get_rlabel_position()\n * self.axes.get_theta_direction())\n + self.axes.get_theta_offset()\n - np.pi / 2\n )\n elif self.mode == 'min':\n angle = self.axes._realViewLim.xmin - np.pi / 2\n elif self.mode == 'max':\n angle = self.axes._realViewLim.xmax + np.pi / 2\n self._t = (self.pad * np.cos(angle) / 72, self.pad * np.sin(angle) / 72)\n return super().get_matrix()\n\n\nclass RadialTick(maxis.YTick):\n \"\"\"\n A radial-axis tick.\n\n This subclass of `.YTick` provides radial ticks with some small\n modification to their re-positioning such that ticks are rotated based on\n axes limits. This results in ticks that are correctly perpendicular to\n the spine. Labels are also rotated to be perpendicular to the spine, when\n 'auto' rotation is enabled.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.label1.set_rotation_mode('anchor')\n self.label2.set_rotation_mode('anchor')\n\n def _determine_anchor(self, mode, angle, start):\n # Note: angle is the (spine angle - 90) because it's used for the tick\n # & text setup, so all numbers below are -90 from (normed) spine angle.\n if mode == 'auto':\n if start:\n if -90 = angle = 90:\n return 'left', 'center'\n else:\n return 'right', 'center'\n else:\n if -90 = angle = 90:\n return 'right', 'center'\n else:\n return 'left', 'center'\n else:\n if start:\n if angle -68.5:\n return 'center', 'top'\n elif angle -23.5:\n return 'left', 'top'\n elif angle 22.5:\n return 'left', 'center'\n elif angle 67.5:\n return 'left', 'bottom'\n elif angle 112.5:\n return 'center', 'bottom'\n elif angle 157.5:\n return 'right', 'bottom'\n elif angle 202.5:\n return 'right', 'center'\n elif angle 247.5:\n return 'right', 'top'\n else:\n return 'center', 'top'\n else:\n if angle -68.5:\n return 'center', 'bottom'\n elif angle -23.5:\n return 'right', 'bottom'\n elif angle 22.5:\n return 'right', 'center'\n elif angle 67.5:\n return 'right', 'top'\n elif angle 112.5:\n return 'center', 'top'\n elif angle 157.5:\n return 'left', 'top'\n elif angle 202.5:\n return 'left', 'center'\n elif angle 247.5:\n return 'left', 'bottom'\n else:\n return 'center', 'bottom'\n\n def update_position(self, loc):\n super().update_position(loc)\n axes = self.axes\n thetamin = axes.get_thetamin()\n thetamax = axes.get_thetamax()\n direction = axes.get_theta_direction()\n offset_rad = axes.get_theta_offset()\n offset = np.rad2deg(offset_rad)\n full = _is_full_circle_deg(thetamin, thetamax)\n\n if full:\n angle = (axes.get_rlabel_position() * direction +\n offset) % 360 - 90\n tick_angle = 0\n else:\n angle = (thetamin * direction + offset) % 360 - 90\n if direction 0:\n tick_angle = np.deg2rad(angle)\n else:\n tick_angle " }, { "role": "assistant", "content": "= np.deg2rad(angle + 180)\n text_angle = (angle + 90) % 180 - 90 # between -90 and +90.\n mode, user_angle = self._labelrotation" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "r_symbol\nfrom tensorflow.python.util.tf_export import tf_export\n\n\ndef _convert_to_sparse_tensor(sp_input):\n \"\"\"Convert `sp_input` to `SparseTensor` and return it.\n\n Args:\n sp_input: `SparseTensor` or `SparseTensorValue`.\n\n Returns:\n `sp_input` converted to `SparseTensor`.\n\n Raises:\n ValueError: if `sp_input` is neither `SparseTensor` nor `SparseTensorValue`.\n \"\"\"\n if isinstance(sp_input, sparse_tensor.SparseTensorValue):\n return sparse_tensor.SparseTensor.from_value(sp_input)\n if not isinstance(sp_input, sparse_tensor.SparseTensor):\n raise TypeError(\"Input must be a SparseTensor.\")\n return sp_input\n\n\ndef _convert_to_sparse_tensors(sp_inputs):\n \"\"\"Convert `sp_inputs` to `SparseTensor` objects and return them.\n\n Args:\n sp_inputs: `list` or `tuple` of `SparseTensor` or `SparseTensorValue`\n objects.\n\n Returns:\n `sp_inputs` converted to `SparseTensor` objects.\n\n Raises:\n ValueError: if any item in `sp_inputs` is neither `SparseTensor` nor\n `SparseTensorValue`.\n \"\"\"\n if isinstance(sp_inputs, list):\n return [_convert_to_sparse_tensor(sp_input) for sp_input in sp_inputs]\n if isinstance(sp_inputs, tuple):\n return (_convert_to_sparse_tensor(sp_input) for sp_input in sp_inputs)\n raise TypeError(\"Inputs must be a list or tuple.\")\n\n\ndef _make_int64_tensor(value, name):\n if isinstance(value, compat.integral_types):\n return ops.convert_to_tensor(value, name=name, dtype=dtypes.int64)\n if not isinstance(value, tensor_lib.Tensor):\n raise TypeError(\"{} must be an integer value\".format(name))\n if value.dtype == dtypes.int64:\n return value\n return math_ops.cast(value, dtypes.int64)\n\n\n@tf_export(\"sparse.from_dense\")\ndef from_dense(tensor, name=None):\n \"\"\"Converts a dense tensor into a sparse tensor.\n\n Only elements not equal to zero will be present in the result. The resulting\n `SparseTensor` has the same dtype and shape as the input.\n\n sp = tf.sparse.from_dense([0, 0, 3, 0, 1])\n sp.shape.as_list()\n [5]\n sp.values.numpy()\n array([3, 1], dtype=int32)\n sp.indices.numpy()\n array([[2],\n [4]])\n\n Args:\n tensor: A dense `Tensor` to be converted to a `SparseTensor`.\n name: Optional name for the op.\n\n Returns:\n The `SparseTensor`.\n \"\"\"\n with ops.name_scope(name, \"dense_to_sparse\"):\n tensor = ops.convert_to_tensor(tensor)\n indices = array_ops.where_v2(\n math_ops.not_equal(tensor, array_ops.zeros_like(tensor)))\n values = array_ops.gather_nd(tensor, indices)\n shape = array_ops.shape(tensor, out_type=dtypes.int64)\n return sparse_tensor.SparseTensor(indices, values, shape)\n\n\n@tf_export(\"sparse.expand_dims\")\ndef sparse_expand_dims(sp_input, axis=None, name=None):\n \"\"\"Returns a tensor with an length 1 axis inserted at index `axis`.\n\n Given a tensor `input`, this operation inserts a dimension of length 1 at the\n dimension index `axis` of `input`'s shape. The dimension index follows python\n indexing rules: It's zero-based, a negative index it is counted backward\n from the end.\n\n This operation is useful to:\n\n * Add an outer \"batch\" dimension to a single element.\n * Align axes for broadcasting.\n * To add an inner vector length axis to a tensor of scalars.\n\n For example:\n\n If you have a sparse tensor with shape `[height, width, depth]`:\n\n sp = tf.sparse.SparseTensor(indices=[[3,4,1]], values=[7,],\n ... dense_shape=[10,10,3])\n\n You can add an outer `batch` axis by passing `axis=0`:\n\n tf.sparse.expand_dims(sp, axis=0).shape.as_list()\n [1, 10, 10, 3]\n\n The new axis location matches Python `list.insert(axis, 1)`:\n\n tf.sparse.expand_dims(sp, axis=1).shape.as_list()\n [10, 1, 10, 3]\n\n Following standard python indexing rules, a negative `axis` counts from the\n end so `axis=-1` adds an inner most dimension:\n\n tf.sparse.expand_dims(sp, axis=-1).shape.as_list()\n [10, 10, 3, 1]\n\n Note: Unlike `tf.expand_dims` this function includes a default value for the\n `axis`: `-1`. So if `axis is not specified, an inner dimension is added.\n\n sp.shape.as_list()\n [10, 10, 3]\n tf.sparse.expand_dims(sp).shape.as_list()\n [10, 10, 3, 1]\n\n This operation requires that `axis` is a valid index for `input.shape`,\n following python indexing rules:\n\n ```\n -1-tf.rank(input) = axis = tf.rank(input)\n ```\n\n This operation is related to:\n\n * `tf.expand_dims`, which provides this functionality for dense tensors.\n * `tf.squeeze`, which removes dimensions of size 1, from dense tensors.\n * `tf.sparse.reshape`, which provides more flexible reshaping capability.\n\n Args:\n sp_input: A `SparseTensor`.\n axis: 0-D (scalar). Specifies the dimension index at which to expand the\n shape of `input`. Must be in the range `[-rank(sp_input) - 1,\n rank(sp_input)]`. Defaults to `-1`.\n name: The name of the output `SparseTensor`.\n\n Returns:\n A `SparseTensor` with the same data as `sp_input`, but its shape has an\n additional dimension of size 1 added.\n \"\"\"\n rank = sp_input.dense_shape.get_shape()[0]\n if rank is None:\n rank = array_ops.shape(sp_input.dense_shape)[0]\n axis = -1 if axis is None else axis\n\n with ops.name_scope(name, default_name=\"expand_dims\", values=[sp_input]):\n if isinstance(axis, compat.integral_types):\n axis = ops.convert_to_tensor(axis, name=\"axis\", dtype=dtypes.int32)\n elif not isinstance(axis, tensor_lib.Tensor):\n raise TypeError(\"axis must be an integer value in range [-rank(sp_input)\"\n \" - 1, rank(sp_input)]\")\n\n # Convert axis to a positive value if it is negative.\n axis = array_ops.where_v2(axis = 0, axis, axis + rank + 1)\n\n # Create the new column of indices for the sparse tensor by slicing\n # the indices and inserting a new column of indices for the new dimension.\n column_size = array_ops.shape(sp_input.indices)[0]\n new_index = array_ops.zeros([column_size, 1], dtype" }, { "role": "assistant", "content": "=dtypes.int64)" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "\"\"\"\nHelper functions for creating user-friendly representations\nof serializer classes and serializer fields.\n\"\"\"\nimport re\n\nfrom django.db import models\nfrom django.utils.encoding import force_str\nfrom django.utils.functional import Promise\n\n\ndef manager_repr(value):\n model = value.model\n opts = model._meta\n names_and_managers = [\n (manager.name, manager)\n for manager\n in opts.managers\n ]\n for manager_name, manager_instance in names_and_managers:\n if manager_instance == value:\n return '%s.%s.all()' % (model._meta.object_name, manager_name)\n return repr(value)\n\n\ndef smart_repr(value):\n if isinstance(value, models.Manager):\n return manager_repr(value)\n\n if isinstance(value, Promise) and value._delegate_text:\n value = force_str(value)\n\n value = repr(value)\n\n # Representations like u'help text'\n # should simply be presented as 'help text'\n if value.startswith(\"u'\") and value.endswith(\"'\"):\n return value[1:]\n\n # Representations like\n # django.core.validators.RegexValidator object at 0x1047af050\n # Should be presented as\n # django.core.validators.RegexValidator object\n return re.sub(' at 0x[0-9A-Fa-f]{4,32}', '', value)\n\n\ndef field_repr(field, force_many=False):\n kwargs = field._kwargs\n if force_many:\n kwargs = kwargs.copy()\n kwargs['many'] = True\n kwargs.pop('child', None)\n\n arg_string = ', '.join([smart_repr(val) for val in field._args])\n kwarg_string = ', '.join([\n '%s=%s' % (key, smart_repr(val))\n for key, val in sorted(kwargs.items())\n ])\n if arg_string and kwarg_string:\n arg_string += ', '\n\n if force_many:\n class_name = f" }, { "role": "assistant", "content": "orce_many.__class__.__name__\n else:\n class_name = field.__class__.__name__\n\n return \"%s(%s%s)\" % (class_name, arg_string, kwarg_string)" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "m most common place\nif len(train_df.Embarked[ train_df.Embarked.isnull() ]) 0:\n train_df.Embarked[ train_df.Embarked.isnull() ] = train_df.Embarked.dropna().mode().values\n\nPorts = list(enumerate(np.unique(train_df['Embarked']))) # determine all values of Embarked,\nPorts_dict = { name : i for i, name in Ports } # set up a dictionary in the form Ports : index\ntrain_df.Embarked = train_df.Embarked.map( lambda x: Ports_dict[x]).astype(int) # Convert all Embark strings to int\n\n# All the ages with no data - make the median of all Ages\nmedian_age = train_df['Age'].dropna().median()\nif len(train_df.Age[ train_df.Age.isnull() ]) 0:\n train_df.loc[ (train_df.Age.isnull()), 'Age'] = median_age\n\n# Remove the Name column, Cabin, Ticket, and Sex (since I copied and filled it to Gender)\ntrain_df = train_df.drop(['Name', 'Sex', 'Ticket', 'Cabin', 'PassengerId'], axis=1) \n\n\n# TEST DATA\ntest_df = pd.read_csv('test.csv', header=0) # Load the test file into a dataframe\n\n# I need to do the same with the test data now, so that the columns are the same as the training data\n# I need to convert all strings to integer classifiers:\n# female = 0, Male = 1\ntest_df['Gender'] = test_df['Sex'].map( {'female': 0, 'male': 1} ).astype(int)\n\n# Embarked from 'C', 'Q', 'S'\n# All missing Embarked - just make them embark from most common place\nif len(test_df.Embarked[ test_df.Embarked.isnull() ]) 0:\n test_df.Embarked[ test_df.Embarked.isnull() ] = test_df.Embarked.dropna().mode().values\n# Again convert all Embarked strings to int\ntest_df.Embarked = test_df.Embarked.map( lambda x: Ports_dict[x]).astype(int)\n\n\n# All the ages with no data - make the median of all Ages\nmedian_age = test_df['Age'].dropna().median()\nif len(test_df.Age[ test_df.Age.isnull() ]) 0:\n test_df.loc[ (test_df.Age.isnull()), 'Age'] = median_age\n\n# All the missing Fares - assume median of their respective class\nif len(test_df.Fare[ test_df.Fare.isnull() ]) 0:\n median_fare = np.zeros(3)\n for f in range(0,3): # loop 0 to 2\n median_fare[f] = test_df[ test_df.Pclass == f+1 ]['Fare'].dropna().median()\n for f in range(0,3): # loop 0 to 2\n test_df.loc[ (test_df.Fare.isnull()) & (test_df.Pclass == f+1 ), 'Fare'] = median_fare[f]\n\n# Collect the test data's PassengerIds before dropping it\nids = test_df['PassengerId'].values\n# Remove the Name column, Cabin, Ticket, and Sex (since I copied and filled it to Gender)\ntest_df = test_df.drop(['Name', 'Sex', 'Ticket', 'Cabin', 'Passen" }, { "role": "assistant", "content": "gerId'], axis=1)" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "import os\nimport shutil\nimport pytest\nfrom tempfile import mkstemp, mkdtemp\nfrom subprocess import Popen, PIPE\nimport importlib.metadata\nfrom distutils.errors import DistutilsError\n\nfrom numpy.testing import assert_, assert_equal, assert_raises\nfrom numpy.distutils import ccompiler, customized_ccompiler\nfrom numpy.distutils.system_info import system_info, ConfigParser, mkl_info\nfrom numpy.distutils.system_info import AliasedOptionError\nfrom numpy.distutils.system_info import default_lib_dirs, default_include_dirs\nfrom numpy.distutils import _shell_utils\n\n\ntry:\n if importlib.metadata.version('setuptools') = '60':\n # pkg-resources gives deprecation warnings, and there may be more\n # issues. We only support setuptools 60\n pytest.skip(\"setuptools is too new\", allow_module_level=True)\nexcept importlib.metadata.PackageNotFoundError:\n # we don't require `setuptools`; if it is not found, continue\n pass\n\n\ndef get_class(name, notfound_action=1):\n \"\"\"\n notfound_action:\n 0 - do nothing\n 1 - display warning message\n 2 - raise error\n \"\"\"\n cl = {'temp1': Temp1Info,\n 'temp2': Temp2Info,\n 'duplicate_options': DuplicateOptionInfo,\n }.get(name.lower(), _system_info)\n return cl()\n\nsimple_site = \"\"\"\n[ALL]\nlibrary_dirs = {dir1:s}{pathsep:s}{dir2:s}\nlibraries = {lib1:s},{lib2:s}\nextra_compile_args = -I/fake/directory -I\"/path with/spaces\" -Os\nruntime_library_dirs = {dir1:s}\n\n[temp1]\nlibrary_dirs = {dir1:s}\nlibraries = {lib1:s}\nruntime_library_dirs = {dir1:s}\n\n[temp2]\nlibrary_dirs = {dir2:s}\nlibraries = {lib2:s}\nextra_link_args = -Wl,-rpath={lib2_escaped:s}\nrpath = {dir2:s}\n\n[duplicate_options]\nmylib_libs = {lib1:s}\nlibraries = {lib2:s}\n\"\"\"\nsite_cfg = simple_site\n\nfakelib_c_text = \"\"\"\n/* This file is generated from numpy/distutils/testing/test_system_info.py */\n#includestdio.h\nvoid foo(void) {\n printf(\"Hello foo\");\n}\nvoid bar(void) {\n printf(\"Hello bar\");\n}\n\"\"\"\n\ndef have_compiler():\n \"\"\" Return True if there appears to be an executable compiler\n \"\"\"\n compiler = customized_ccompiler()\n try:\n cmd = compiler.compiler # Unix compilers\n except AttributeError:\n try:\n if not compiler.initialized:\n compiler.initialize() # MSVC is different\n except (DistutilsError, ValueError):\n return False\n cmd = [compiler.cc]\n try:\n p = Popen(cmd, stdout=PIPE, stderr=PIPE)\n p.stdout.close()\n p.stderr.close()\n p.wait()\n except OSError:\n return False\n return True\n\n\nHAVE_COMPILER = have_compiler()\n\n\nclass _system_info(system_info):\n\n def __init__(self,\n default_lib_dirs=default_lib_dirs,\n default_include_dirs=default_include_dirs,\n verbosity=1,\n ):\n self.__class__.info = {}\n self.local_prefixes = []\n defaults = {'library_dirs': '',\n 'include_dirs': '',\n 'runtime_library_dirs': '',\n 'rpath': '',\n 'src_dirs': '',\n 'se" }, { "role": "assistant", "content": "arch_static_first': \"0\",\n 'extra_compile_args': '',\n 'extra_link_args': ''}\n self.cp = ConfigParser(defaults)" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "import os\nimport time\n\nfrom pathlib import Path\nfrom prompt_file import *\n\ndef get_command_result(input, prompt_file):\n \"\"\"\n Checks if the input is a command and if so, executes it\n Currently supported commands:\n - start multi-turn\n - stop multi-turn\n - default context\n - show context n\n - view context\n - save context\n - clear context\n - load context filename\n - set engine engine\n - set temperature temperature\n - set max_tokens max_tokens\n - set shell shell\n\n Returns: command result or \"\" if no command matched\n \"\"\"\n if prompt_file == None:\n return \"\", None\n \n config = prompt_file.config\n # configuration setting commands\n if input.__contains__(\"set\"):\n # set temperature temperature\n if input.__contains__(\"temperature\"):\n input = input.split()\n if len(input) == 4:\n config['temperature'] = float(input[3])\n prompt_file.set_config(config)\n print(\"# Temperature set to \" + str(config['temperature']))\n return \"config set\", prompt_file\n else:\n return \"\", prompt_file\n # set max_tokens max_tokens\n elif input.__contains__(\"max_tokens\"):\n input = input.split()\n if len(input) == 4:\n config['max_tokens'] = int(input[3])\n prompt_file.set_config(config)\n print(\"# Max tokens set to \" + str(config['max_tokens']))\n return \"config set\", prompt_file\n else:\n return \"\", prompt_file\n elif input.__contains__(\"shell\"):\n input = input.split()\n if len(input) == 4:\n config['shell'] = input[3]\n prompt_file.set_config(config)\n print(\"# Shell set to \" + str(config['shell']))\n return \"config set\", prompt_file\n else:\n return \"\", prompt_file\n elif input.__contains__(\"engine\"):\n input = input.split()\n if len(input) == 4:\n config['engine'] = input[3]\n prompt_file.set_config(config)\n print(\"# Engine set to \" + str(config['engine']))\n return \"config set\", prompt_file\n else:\n return \"\", prompt_file\n\n if input.__contains__(\"show config\"):\n prompt_file.show_config()\n return \"config shown\", prompt_file\n\n # multi turn/single turn commands\n if input.__contains__(\"multi-turn\"):\n # start context\n if input.__contains__(\"start\"):\n if config['multi_turn'] == 'off':\n prompt_file.start_multi_turn()\n return \"multi turn mode on\", prompt_file\n \n return \"multi turn mode on\", prompt_file\n \n # stop context\n if input.__contains__(\"stop\"):\n prompt_file.stop_multi_turn()\n return \"multi turn mode off\", prompt_file\n \n # context file commands\n if input.__contains__(\"context\"):\n if input.__contains__(\"default\"):\n prompt_file.default_context()\n return \"stopped context\", prompt_file\n \n # show context n\n if input.__contains__(\"show\"):\n print('\\n')\n with open(prompt_file.file_name, 'r') as f:\n lines = f.readlines()\n lines = lines[6:] # skip headers\n \n line_numbers = 0\n if len(input.split()) 3:\n line_numbers = int(input.split()[3])\n \n if line_numbers != 0:\n for line in lines[-line_numbers:]:\n print('\\n# '+line, end='')\n else:\n print('\\n# '.join(lines))\n return \"context shown\", prompt_file\n \n # edit context\n if input.__contains__(\"view\"):\n # open the prompt file in text editor\n if config['shell'] != 'powershell':\n os.system('open {}'.format(prompt_file.file_path))\n else:\n os.system('start {}'.format(prompt_file.file_path))\n return \"context shown\", prompt_file\n\n # save context filename\n if input.__contains__(\"save\"):\n # save the current prompt file to a new file\n # if filename not specified use the current time (to avoid name conflicts)\n\n filename = time.strftime(\"%Y-%m-%d_%H-%M-%S\") + \".txt\"\n if len(input.split()) == 4:\n filename = input.split()[3]\n \n prompt_file.save_to(filename)\n return \"context saved\", prompt_file\n \n # clear context\n if input.__contains__(\"clear\"):\n # temporary saving deleted prompt file\n prompt_file.default_context()\n return \"unlearned interaction\", prompt_file\n \n # load context filename\n if input.__contains_" }, { "role": "assistant", "content": "_(\"load\"):\n" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "es: Elasticsearch\n The Elasticsearch client\n \"\"\"\n # Convert the new_predictions DataFrame to a list of dictionaries\n # The columns of the new_predicitons DataFrame are 'PMID', 'date', 'date_completed', 'label', 'text'\n # Only the 'PMID', 'date', 'date_completed', and 'label' columns are needed\n new_predictions = new_predictions[['PMID', 'date', 'date_completed', 'label']].to_dict(orient='records')\n\n logger.debug(f'Adding {len(new_predictions)} new predictions to the predictions index {index}: First 5: {new_predictions[:5]}')\n\n # Add the new predictions to the predictions index\n helpers.bulk(es, [{'_index': index, '_id': int(doc['PMID']), '_source': doc} for doc in new_predictions])\n\n def _compute_cluster_names(self, X: Union[List[str], pd.Series]) - None:\n \"\"\"\n Compute the cluster names\n\n Parameters\n ----------\n X : Union[List[str], Series]\n The documents\n y : np.ndarray\n The labels\n\n Returns\n -------\n Dict[int, str]\n The cluster names\n \"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def _preprocess(self, X: Union[List[str], pd.Series]) - Union[List[str], pd.Series]:\n \"\"\"\n Preprocess a batch of documents\n\n Parameters\n ----------\n X : Union[List[str], Series]\n The documents\n\n Returns\n -------\n Union[List[str], Series]\n The preprocessed documents\n \"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def _preprocess_single(self, x: str) - str:\n \"\"\"\n Preprocess a single document\n\n Parameters\n ----------\n x : str\n The document\n\n Returns\n -------\n st" }, { "role": "assistant", "content": "r\n The preprocessed document\n \"\"\"\n raise NotImplementedError" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "import numpy as np\nfrom keras.models import *\nfrom keras.layers import *\nfrom keras.applications.vgg16 import VGG16\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.optimizers import *\nfrom keras.callbacks import ModelCheckpoint\nimport cv2\n\ndef train_generator(batch_size=32):\n data_gen_args = dict(featurewise_center=True,\n rotation_range=90.,\n width_shift_range=0.1,\n height_shift_range=0.1,\n fill_mode=\"constant\",\n cval=255,\n horizontal_flip=True,\n vertical_flip=True,\n zoom_range=0.2)\n image_datagen = ImageDataGenerator(**data_gen_args)\n mask_datagen = ImageDataGenerator(**data_gen_args)\n\n seed = 1\n image_generator = image_datagen.flow_from_directory(\n 'data/train/images',\n class_mode=None,\n batch_size=batch_size,\n color_mode='rgb',\n target_size=(512,512),\n #save_to_dir='./data/gen/images',\n seed=seed)\n\n mask_generator = mask_datagen.flow_from_directory(\n 'data/train/masks',\n class_mode=None,\n color_mode='grayscale',\n target_size=(512,512),\n batch_size=batch_size,\n #save_to_dir='./data/gen/masks',\n seed=seed)\n\n # combine generators into one which yields image and masks\n train_generator = zip(image_generator, mask_generator)\n for (imgs, masks) in train_generator:\n imgs = imgs / 255.0\n masks = masks / 255.0\n yield (imgs,masks)\n\n\ndef vgg10_unet(input_shape=(256,256,3), weights='imagenet'):\n vgg16_model = VGG16(input_shape=input_shape, weights=weights, include_top=False)\n\n block4_pool = vgg16_model.get_layer('block4_pool').output\n block5_conv1 = Conv2D(1024, 3, activation='relu', padding='same', kernel_initializer='he_normal')(block4_pool)\n block5_conv2 = Conv2D(1024, 3, activation='relu', padding='same', kernel_initializer='he_normal')(block5_conv1)\n block5_drop = Dropout(0.5)(block5_conv2)\n\n block6_up = Conv2D(512, 2, activation='relu', padding='same', kernel_initializer='he_normal')(\n UpSampling2D(size=(2, 2))(block5_drop))\n block6_merge = Concatenate(axis=3)([vgg16_model.get_layer('block4_conv3').output, block6_up])\n block6_conv1 = Conv2D(512, 3, activation='relu', padding='same', kernel_initializer='he_normal')(block6_merge)\n block6_conv2 = Conv2D(512, 3, activation='relu', padding='same', kernel_initializer='he_normal')(block6_conv1)\n block6_conv3 = Conv2D(512, 3, activation='relu', padding='same', kernel_initializer='he_normal')(block6_conv2)\n\n block7_up = Conv2D(256, 2, activation='relu', padding='same', kernel_initializer='he_normal')(\n UpSampling2D(size=(2, 2))(block6_conv3))\n block7_merge = Concatenate(axis=3)([vgg16_model.get_layer('block3_conv3').output, block7_up])\n block7_conv1 = Conv2D(256, 3, activation='relu', padding='same', kernel_initializer='he_normal')(block7_merge)\n block7_conv2 = Conv2D(256, 3, activation='relu', padding='same', kernel_initializer='he_normal')(block7_conv1)\n block7_conv3 = Conv2D(256, 3, activation='relu', padding='same', kernel_initializer='he_normal')(block7_conv2)\n\n block8_up = Conv2D(128, 2, activation='relu', padding='same', kernel_initializer='he_normal')(\n UpSampling2D(size=(2, 2))(block7_conv3))\n block8_merge = Concatenate(axis=3)([vgg16_model.get_layer('block2_conv2').output, block8_up])\n block8_conv1 = Conv2D(128, 3, activation='relu', padding='same', kernel_initializer='he_normal')(block8_merge)\n block8_conv2 = Conv2D(128, 3, activation='relu', padding='same', kernel_initializer='he_normal')(block8_conv1)\n\n block9_up = Conv2D(64, 2, activation='relu', padding='same', kernel_initializer='he_normal')(\n UpSampling2D(size=(2, 2))(block8_conv2))\n block9_merge = Concatenate(axis=3)([vgg16_model.get_layer('block1_conv2').output, block9_up])\n block9_conv1 = Conv2D(64, 3, activation='relu', padding='same', kernel_initializer='he_normal')(block9_merge)\n block9_conv2 = Conv2D(64, 3, activation='relu'" }, { "role": "assistant", "content": ", padding='same', kernel_initializer='he_normal')(block9_conv1)\n\n block10_conv1 = Conv2D(64, 3, activation='relu', padding='same', kernel_initializer='he_normal')(block9_conv2)\n block10_conv2 = Conv2D(1, 1, activation='sigmoid')(block10_conv1)\n\n model = Model(inputs=vgg16_model.input, outputs=block10_conv2)\n return model" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": " r.set_bounds(\n tt.get_window_extent(renderer)\n .transformed(ax.transAxes.inverted())\n .bounds)\n ax.add_patch(r)\n\n horal = 'left'\n for nn, st in enumerate(sts):\n tt = ax.text(0.2 * nn + 0.1, 0.5, st, horizontalalignment=horal,\n verticalalignment='bottom')\n draw_box(ax, tt)\n ax.text(1.2, 0.5, 'Bottom align', color='C2')\n\n ax.axhline(1.3, color='C2', linewidth=0.3)\n for nn, st in enumerate(sts):\n tt = ax.text(0.2 * nn + 0.1, 1.3, st, horizontalalignment=horal,\n verticalalignment='top')\n draw_box(ax, tt)\n ax.text(1.2, 1.3, 'Top align', color='C2')\n\n ax.axhline(1.8, color='C2', linewidth=0.3)\n for nn, st in enumerate(sts):\n tt = ax.text(0.2 * nn + 0.1, 1.8, st, horizontalalignment=horal,\n verticalalignment='baseline')\n draw_box(ax, tt)\n ax.text(1.2, 1.8, 'Baseline align', color='C2')\n\n ax.axhline(0.1, color='C2', linewidth=0.3)\n for nn, st in enumerate(sts):\n tt = ax.text(0.2 * nn + 0.1, 0.1, st, horizontalalignment=horal,\n verticalalignment='bottom', rotation=20)\n draw_box(ax, tt)\n ax.text(1.2, 0.1, 'Bot align, rot20', color='C2')\n\n\n@image_comparison(['antialiased.png'], style='mpl20')\ndef test_antialiasing():\n mpl.rcParams['text.antialiased'] = False # Passed arguments should override.\n\n fig = plt.figure(figsize=(5.25, 0.75))\n fig.text(0.3, 0.75, \"antialiased\", horizontalalignment='center',\n verticalalignment='center', antialiased=True)\n fig.text(0.3, 0.25, r\"$\\sqrt{x}$\", horizontalalignment='center',\n verticalalignment='center', antialiased=True)\n\n mpl.rcParams['text.antialiased'] = True # Passed arguments should override.\n fig.text(0.7, 0.75, \"not antialiased\", horizontalalignment='center',\n verticalalignment='center', antialiased=False)\n fig.text(0.7, 0.25, r\"$\\sqrt{x}$\", horizontalalignment='center',\n verticalalignment='center', antialiased=False)\n\n mpl.rcParams['text.antialiased'] = False # Should not affect existing text.\n\n\ndef test_afm_kerning():\n fn = mpl.font_manager.findfont(\"Helvetica\", fontext=\"afm\")\n with open(fn, 'rb') as fh:\n afm = mpl._afm.AFM(fh)\n assert afm.string_width_height('VAVAVAVAVAVA') == (7174.0, 718)\n\n\n@image_comparison(['text_contains.png'])\ndef test_contains():\n fig = plt.figure()\n ax = plt.axes()\n\n mevent = MouseEvent('button_press_event', fig.canvas, 0.5, 0.5, 1, None)\n\n xs = np.linspace(0.25, 0.75, 30)\n ys = np.linspace(0.25, 0.75, 30)\n xs, ys = np.meshgrid(xs, ys)\n\n txt = plt.text(\n 0.5, 0.4, 'hello world', ha='center', fontsize=30, rotation=30)\n # uncomment to draw the text's bounding box\n # txt.set_bbox(dict(edgecolor='black', facecolor='none'))\n\n # draw the text. This is important, as the contains method can only work\n # when a renderer exists.\n fig.canvas.draw()\n\n for x, y in zip(xs.flat, ys.flat):\n mevent.x, mevent.y = plt.gca().transAxes.transform([x, y])\n contains, _ = txt.contains(mevent)\n color = 'yellow' if contains else 'red'\n\n # capture the viewLim, plot a point, and reset the viewLim\n vl = ax.viewLim.frozen()\n ax.plot(x, y, 'o', color=color)\n ax.viewLim.set(vl)\n\n\ndef test_annotation_contains():\n # Check that Annotation.contains looks at the bboxes of the text and the\n # arrow separately, not at the joint bbox.\n fig, ax = plt.subplots()\n ann = ax.annotate(\n \"hello\", xy=(.4, .4), xytext=(.6, .6), arrowprops={\"arrowstyle\": \"-\"})\n fig.canvas.draw() # Needed for the same " }, { "role": "assistant", "content": "reason as in test_contains.\n event = MouseEvent(\n \"button_press_event\", fig.canvas, *ax.transData.transform((.5, .6)))\n assert ann.contains(event) == (False, {})" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "st_context(f: t.Callable) - t.Callable:\n \"\"\"A helper function that decorates a function to retain the current\n request context. This is useful when working with greenlets. The moment\n the function is decorated a copy of the request context is created and\n then pushed when the function is called. The current session is also\n included in the copied request context.\n\n Example::\n\n import gevent\n from flask import copy_current_request_context\n\n @app.route('/')\n def index():\n @copy_current_request_context\n def do_some_work():\n # do some work here, it can access flask.request or\n # flask.session like you would otherwise in the view function.\n ...\n gevent.spawn(do_some_work)\n return 'Regular response'\n\n .. versionadded:: 0.10\n \"\"\"\n ctx = _cv_request.get(None)\n\n if ctx is None:\n raise RuntimeError(\n \"'copy_current_request_context' can only be used when a\"\n \" request context is active, such as in a view function.\"\n )\n\n ctx = ctx.copy()\n\n def wrapper(*args, **kwargs):\n with ctx:\n return ctx.app.ensure_sync(f)(*args, **kwargs)\n\n return update_wrapper(wrapper, f)\n\n\ndef has_request_context() - bool:\n \"\"\"If you have code that wants to test if a request context is there or\n not this function can be used. For instance, you may want to take advantage\n of request information if the request object is available, but fail\n silently if it is unavailable.\n\n ::\n\n class User(db.Model):\n\n def __init__(self, username, remote_addr=None):\n self.username = username\n if remote_addr is None and has_request_context():\n remote_addr = request.remote_addr\n self.remote_addr = remote_addr\n\n Alternatively you can also just test any of the context bound objects\n (such as :class:`request` or :class:`g`) for truthness::\n\n class User(db.Model):\n\n def __init__(self, username, remote_addr=None):\n self.username = username\n if remote_addr is None and request:\n remote_addr = request.remote_addr\n self.remote_addr = remote_addr\n\n .. versionadded:: 0.7\n \"\"\"\n return _cv_request.get(None) is not None\n\n\ndef has_app_context() - bool:\n \"\"\"Works like :func:`has_request_context` but for the application\n context. You can also just do a boolean check on the\n :data:`current_app` object instead.\n\n .. versionadded:: 0.9\n \"\"\"\n return _cv_app.get(None) is not None\n\n\nclass AppContext:\n \"\"\"The app context contains application-specific information. An app\n context is created and pushed at the beginning of each request if\n one is not already active. An app context is also pushed when\n running CLI commands.\n \"\"\"\n\n def __init__(self, app: Flask) - None:\n self.app = app\n self.url_adapter = app.create_url_adapter(None)\n self.g: _AppCtxGlobals = app.app_ctx_globals_class()\n self._cv_tokens: list[contextvars.Token] = []\n\n def push(self) - None:\n \"\"\"Binds the app context to the current context.\"\"\"\n self._cv_tokens.append(_cv_app.set(self))\n appcontext_pushed.send(self.app, _async_wrapper=self.app.ensure_sync)\n\n def pop(self, exc: BaseException | None = _sentinel) - None: # type: ignore\n \"\"\"Pops the app context.\"\"\"\n try:\n if len(self._cv_tokens) == 1:\n if exc is _sentinel:\n exc = sys.exc_info()[1]\n self.app.do_teardown_appcontext(exc)\n finally:\n ctx = _cv_app.get()\n _cv_app.reset(self._cv_tokens.pop())\n\n if ctx is not self:\n raise AssertionError(\n f\"Popped wrong app context. ({ctx!r} instead of {self!r})\"\n )\n\n appcontext_popped.send(self.app, _async_wrapper=self.app.ensure_sync)\n\n def __enter__(self) - AppContext:\n self.push()\n return self\n\n def __exit__(\n self,\n exc_type: type | None,\n exc_value: BaseException | None,\n tb: TracebackType | None,\n ) - None:\n self.pop(exc_value)\n\n\nclass RequestContext:\n \"\"\"The request context contains per-request information. The Flask\n app creates and pushes it at the beginning of the request, then pops\n it at the end of the request. It " }, { "role": "assistant", "content": "will create the URL adapter and\n request object for the WSGI environment provided.\n\n Do not attempt to use this class directly, instead use\n :meth:`~flask.Flask.test_request_context` and\n :meth:`~flask.Flask.request_context` to create this object.\n\n When the request context is popped, it will evaluate all the\n functions registered on the application for teardown execution\n (:meth:`~flask.Flask.teardown_request`).\n\n The request context is automatically popped at the end of the\n request. When using the interactive debugger, the context will be\n restored so ``request`` is still accessible. Similarly, the test\n client can preserve the context after the request ends. However,\n teardown functions may already have closed some resources such as\n database connections.\n \"\"\"" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "\"\"\"\n.. redirect-from:: /users/customizing\n.. redirect-from:: /tutorials/introductory/customizing\n\n.. _customizing:\n\n=====================================================\nCustomizing Matplotlib with style sheets and rcParams\n=====================================================\n\nTips for customizing the properties and default styles of Matplotlib.\n\nThere are three ways to customize Matplotlib:\n\n1. :ref:`Setting rcParams at runtimecustomizing-with-dynamic-rc-settings`.\n2. :ref:`Using style sheetscustomizing-with-style-sheets`.\n3. :ref:`Changing your matplotlibrc filecustomizing-with-matplotlibrc-files`.\n\nSetting rcParams at runtime takes precedence over style sheets, style\nsheets take precedence over :file:`matplotlibrc` files.\n\n.. _customizing-with-dynamic-rc-settings:\n\nRuntime rc settings\n===================\n\nYou can dynamically change the default rc (runtime configuration)\nsettings in a python script or interactively from the py" }, { "role": "assistant", "content": "thon shell. All\nrc settings are stored in a dictionary-like variable called\n:data:`matplotlib.rcParams`, which is global to the matplotlib package.\nSee `matplotlib.rcParams` for a full list of configurable rcParams.\nrcParams can be modified directly, for example:\n\"\"\"" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "'Yes'\n\n\tif community_creation_admin_only == True:\n\t\tnew_comm = \"No\"\n\telse:\n\t\tnew_comm = \"Yes\"\n\n\tif federation_enabled == False or federated_allowed != []:\n\t\tfed = 'No'\n\telse:\n\t\tfed = \"Yes\"\n\tprint( \"\\tfederation_enabled:|\" +str(federation_enabled)+ \"|\" )\n\tprint( \"\\tfederated_allowed:|\" +str(federated_allowed)+ \"|\" )\n\tprint( \"\\tfed:|\" +str(fed)+ \"|\" )\n\n\tif enable_downvotes == True:\n\t\tdownvotes = \"Yes\"\n\telse:\n\t\tdownvotes = \"No\"\n\n\tif registration_mode == \"closed\":\n\t\tnew_users = \"No\"\n\telse:\n\t\tnew_users = \"Yes\"\n\n\t# stupid way to say gimmie the 'uptime_alltime' data from the json where\n\t# the 'domain' matches this iteration lemmy instance's domain\n\tuptime = [x['uptime_alltime'] for x in uptime_data['data']['nodes'] if x['domain'] == domain]\n\n\t# stupid way to say gimmie the 'monthsmonitored' data from the json where\n\t# the 'domain' matches this iteration lemmy instance's domain\n\tage = [x['monthsmonitored'] for x in age_data['data']['nodes'] if x['domain'] == domain]\n\n\t# did we figure out an uptime for this domain?\n\tif uptime == []:\n\t\t# we couldn't find an uptime; set it to '??'\n\t\tuptime = '??'\n\telse:\n\t\t# we got an uptime! Format it for the table\n\n\t\tuptime = uptime[0]\n\t\t# let's keep the data simple\n\t\tuptime = round(float(uptime))\n\t\tuptime = str(uptime)+ \"%\"\n\n\t# did we figure out an age for this domain?\n\tif age == []:\n\t\t# we couldn't find an uptime; set it to '??'\n\t\tage = '??'\n\telse:\n\t\t# we got an uptime! Format it for the table\n\n\t\tage = age[0]\n\t\t# let's keep the data simple\n\t\tage = round(float(age))\n\n\tcsv_contents += \"[\" +name+ \"](https://\" +domain+ \"),\"\n\tcsv_contents += new_users+ \",\"\n\tcsv_contents += new_comm+ \",\"\n\tcsv_contents += fed+ \",\"\n\tcsv_contents += adult+ \",\"\n\tcsv_contents += downvotes+ \",\"\n\tcsv_contents += str(users_month)+ ','\n\tcsv_contents += str(blocking)+ ','\n\tcsv_contents += str(blocked_by)+ ','\n\tcsv_contents += str(uptime)+ ','\n\tcsv_contents += str(age)+ ','\n\tcsv_contents += version\n\tcsv_contents += \"\\n\"\n\n# write the instance data table to the csv file\nwith open( OUT_CSV, \"w\" ) as csv_file:\n\tcsv_file.write( csv_contents )\n\n#########################\n# RECOMMENDED INSTANCES #\n#########################\n\n# shrink the list to just a few recommended instances\nall_instances = list()\nrecommended_instances = list()\nwith open(OUT_CSV) as csv_file:\n\n\tfor instance in csv.DictReader( csv_file ):\n\t\tall_instances.append( instance )\n\n\t\t# only include instances that are \"yes\" across-the-board\n\t\tif instance['NU'] == \"Yes\" \\\n\t\t and instance['NC'] == \"Yes\" \\\n\t\t and instance['Fed'] == \"Yes\" \\\n\t\t and instance['Adult'] == \"Yes\" \\\n\t\t and instance['↓V'] == \"Yes\":\n\n\t\t\trecommended_instances.append( instance )\n\n# remove instances with too few or too may users\nrecommended_instances = [x for x in recommended_instances if int(x['Users']) 60 and int(x['Users']) 1000]\n\n# get a lits of all the instances that have more than 1 blocked instance and\n# then get the average number of instances that are blocked\ntry:\n\tbi_list = [ int(x['BI']) for x in all_instances if int(x['BI']) 1 ]\n\tbi_avg = numpy.average( bi_list )\nexcept (Exception, RuntimeWarning) as e:\n\tprint( \"WARNING: Caught numpy exception when calculating bi_avg: \" +str(e) )\n\tbi_avg = 2\n\n# get a lits of all the instances that are blocked by more than 1 instance and\n# then get the average number of that instances are are blocked\ntry:\n\tbb_list = [ int(x['BB']) for x in all_instances if int(x['BB']) 1 ]\n\tbb_avg = numpy.average( bb_list )\nexcept (Exception, RuntimeWarning) as e:\n\tprint( \"WARNING: Caught numpy exception when calculating bb_avg: \" +str(e) )\n\tbb_avg = 2\n\nprint( \"bi_avg:|\" +str(bi_avg)+ \"|\" )\nprint( \"bb_avg:|\" +str(bb_avg)+ \"|\" )\n\n# remove instances that are blocking or blocked-by too many other instancesk\nrecommended_instances = [ x for x in recommended_instances if int(x['BI']) = bi_avg and int(x['BB']) = bb_avg ]\n\n# remove instances that haven't been online for 2 months\nrecommended_instances = [ x for x in recommended_instances if int(x['MO']) = 2 ]\n\n# limit to those with the best uptime; first we make sure that we actually\n# have the uptime data\nuptime_available = [x for x in recommended_instances if x['UT'] != '??']\n\n# do we have uptime data?\nif uptime_available != list():\n\t# we have uptime data; proceed with reducing the set of recommended_instances\n\t# based on uptime\n\n\t# loop down from 100% to 0%\n\tfor percent_uptime in reversed(range(100)):\n\n\t\thigh_uptime_instances = [x for x in recommended_instances if x['UT'] != '??' and int(x['UT'][:-1]) percent_uptime]\n\n\t\t# do we have more than one instance above this uptime?\n\t\tif len(high_uptime_instances) 1:\n\t\t\t# we already have enough instances; ignore the rest with lower uptime\n\t\t\trecommended_instances = high_uptime_instances\n\t\t\tbreak\n\n# prepare data for csv file\ncsv_contents = \"Instance,NU,NC,Fed,Adult,↓V,Users,BI,BB,UT,MO,Version\\n\"\nfor instance in recommended_instances:\n\tcsv_contents += instance['Instance']+ ','\n\tcsv_contents += instance['NU']+ ','\n\tcsv_contents += instance['NC']+ ','\n\tcsv_contents += instance['Fed']+ ','\n\tcsv_contents += instance['Adult']+ ','\n\tcsv_contents += instance['↓V']+ ','\n\tcsv_contents += instance['Users']+ ','\n\tcsv_contents += instance['BI']+ ','\n\tcsv_contents += instance['BB']+ ','\n\tcsv_contents += instance['UT']+ ','\n\tcsv_contents += instance['MO']+ ','\n\tcsv_contents += instance['Version']\n\tcsv_contents += \"\\n\"\n\n# write the recommended instance data table to a csv file\nwith open( 'recommended-instances.csv', \"w\" ) as csv_file:\n\tcsv_file.write( csv_contents )\n\n# convert csv file data to markdown table\ndf = pd.read_csv( 'recommended-instances.csv' )\nrecommended_markdown_table = df.to_markdown( tablefmt='pipe', index = False )\n\n# add newline to protect the table from getting klobbered by the text around it\nrecommended_markdown_table = \"\\n\" + recommended_markdown_table + \"\\n\"\n\nreadme_contents += \"\"\"\n# Recommended Instances\n\nJust **click on a random instance** from the below \"recommended\" instances.\n\nDon't overthink this. **It doesn't matter which instance you use.** You'll still be able to interact with communities (subreddits) on all other instances, regardless of which instance your account lives 🙂\n\"\"\"\n\n# add the markdown table to the readme's contents\nreadme_contents += recommended_markdown_table\n\nreadme_contents += \"\"\"\n# What's next?\n\n## Subscribe to ~~Subreddits~~ Communities\n\nAfter you pick an instance and register an account, you'll want to subscribe to communities. You can subscribe to \"local\" communities on your instance, and (if you chose an instance that isn't siloed) you can also subscribe to \"remote\" communities on other instances.\n\nTo **find popular communities** across all lemmy instances in the fediverse, you can use the [Lemmy Community Browser](https://browse.feddit.de/) run by feddit.de.\n\n * https://browse.feddit.de/\n\nIf you want a more direct mapping of your favorite /r/subreddits to lemmy, checkout these sites:\n\n1. [redditmigration.com](https://redditmigration.com/)\n1. [sub.rehab](https://sub.rehab/?searchTerm=&visibleServices=lemmy&officialOnly=false&newOnly=false&favoriteOnly=false&sortBy=users_active_week)\n1. yoasif's [Unofficial Subreddit Migration List](https://www.quippd.com/writing/2023/06/15/unofficial-subreddit-migration-list-lemmy-kbin-etc.html)\n\n\na href=\"https://tech.michaelaltfield.net/2023/06/11/lemmy-migration-find-subreddits-communities/\"img src=\"lemmy-migration-find-subreddits-communities.jpg\" alt=\"How To Find Lemmy Communities\" //a\n\nFor more information, see my guide on [How to Find Popular Lemmy Communities](https://tech.michaelaltfield.net/2023/06/11/lemmy-migration-find-subreddits-communities/)\n\n## Other links\n\nYou may want to also checkout the following websites for more information about Lemmy\n\n * [Official Lemmy Documentation](https://join-lemmy.org/docs/en/index.html)\n * [Intro to Lemmy Guide](https://tech.michaelaltfield.net/2023/06/11/lemmy-migration-find-subreddits-communities/) - How to create a lemmy account, find, and subscribe-to popular communities\n * [Lemmy Community Browser](https://browse.feddit.de/) - List of all communities across all lemmy instances, sorted by popularity\n * [Lemmy Map](https://lemmymap.feddit.de) - Data visualization of lemmy instances\n * [The Federation Info](https://the-federation.info/platform/73) - Another table comparing lemmy instances (with pretty charts)\n * [Federation Observer](https://lemmy.fediverse.observer/list) - Yet another table comparing lemmy instances\n * [FediDB](https://fedidb.org/software/lemmy) - Yet another site comparing lemmy instances (with pretty charts)\n * [Lemmy Sourcecode](https://github.com/LemmyNet/lemmy)\n * [Jerboa (Official Android Client)](https://f-droid.org/packages/com.jerboa/)\n * [Mlem (iOS Client)](https://apps.apple.com/gb/app/mlem-for-lemmy/id6450543782)\n\n\"\"\"\n\n#################\n# ALL INSTANCES #\n#################\n\n# convert csv file data to markdown table\ndf = pd.read_csv( OUT_CSV )\nmarkdown_table = df.to_markdown( tablefmt='pipe', index = False )\n\n# a" }, { "role": "assistant", "content": "dd newline to protect the table from getting klobbered by the text around it" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "import json\nimport os\n\nimport numpy as np\nimport pandas as pd\nimport torch\nfrom datasets import Dataset\nfrom transformers import AutoModelForSequenceClassification, AutoTokenizer, PreTrainedModel, PreTrainedTokenizer, Trainer, TrainerCallback, TrainerControl, TrainerState, TrainingArguments\n\nfrom .data.load import combine_positive_negative_da" }, { "role": "assistant", "content": "ta, get_all_types, get_granularity, get_negative_data, get_positive_data, get_type\nfrom .data.preprocessing import combine_premise_hypothesis, construct_hypothesis\nfrom .predict import predict_type\nfrom .utils import get_models_dir" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": " for idx, frame in enumerate(frames):\n cam_name = os.path.join(path, frame[\"file_path\"] + extension)\n\n # NeRF 'transform_matrix' is a camera-to-world transform\n c2w = np.array(frame[\"transform_matrix\"])\n # change from OpenGL/Blender camera axes (Y up, Z back) to COLMAP (Y down, Z forward)\n c2w[:3, 1:3] *= -1\n\n # get the world-to-camera transform and set R, T\n w2c = np.linalg.inv(c2w)\n R = np.transpose(w2c[:3,:3]) # R is stored transposed due to 'glm' in CUDA code\n T = w2c[:3, 3]\n\n image_path = os.path.join(path, cam_name)\n image_name = Path(cam_name).stem\n image = Image.open(image_path)\n\n im_data = np.array(image.convert(\"RGBA\"))\n\n bg = np.array([1,1,1]) if white_background else np.array([0, 0, 0])\n\n norm_data = im_data / 255.0\n arr = norm_data[:,:,:3] * norm_data[:, :, 3:4] + bg * (1 - norm_data[:, :, 3:4])\n image = Image.fromarray(np.array(arr*255.0, dtype=np.byte), \"RGB\")\n\n fovy = focal2fov(fov2focal(fovx, image.size[0]), image.size[1])\n FovY = fovy \n FovX = fovx\n\n cam_infos.append(CameraInfo(uid=idx, R=R, T=T, FovY=FovY, FovX=FovX, image=image,\n image_path=image_path, image_name=image_name, width=image.size[0], height=image.size[1]))\n \n return cam_infos\n\ndef readNerfSyntheticInfo(path, white_background, eval, extension=\".png\"):\n print(\"Reading Training Transforms\")\n train_cam_infos = readCamerasFromTransforms(path, \"transforms_train.json\", white_background, extension)\n print(\"Reading Test Transforms\")\n test_cam_infos = readCamerasFromTransforms(path, \"transforms_test.json\", white_background, extension)\n \n if not eval:\n train_cam_infos.extend(test_cam_info" }, { "role": "assistant", "content": "s)\n test_cam_infos = []\n\n nerf_normalization = getNerfppNorm(train_cam_infos)\n\n ply_path = os.path.join(path, \"points3d.ply\")\n if not os.path.exists(ply_path):\n # Since this data set has no colmap data, we start with random points\n num_pts = 100_000\n print(f\"Generating random point cloud ({num_pts})...\")\n \n # We create random points inside the bounds of the synthetic Blender scenes\n xyz = np.random.random((num_pts, 3)) * 2.6 - 1.3\n shs = np.random.random((num_pts, 3)) / 255.0\n pcd = BasicPointCloud(points=xyz, colors=SH2RGB(shs), normals=np.zeros((num_pts, 3)))\n\n storePly(ply_path, xyz, SH2RGB(shs) * 255)\n try:\n pcd = fetchPly(ply_path)\n except:\n pcd = None\n\n scene_info = SceneInfo(point_cloud=pcd,\n train_cameras=train_cam_infos,\n test_cameras=test_cam_infos,\n nerf_normalization=nerf_normalization,\n ply_path=ply_path)\n return scene_info\n\nsceneLoadTypeCallbacks = {\n \"Colmap\": readColmapSceneInfo,\n \"Blender\" : readNerfSyntheticInfo\n}" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "xs, n=None):\n \"\"\"Draw a sample from xs with the same length as xs.\n\n xs: sequence\n n: sample size (default: len(xs))\n\n returns: NumPy array\n \"\"\"\n if n is None:\n n = len(xs)\n return np.random.choice(xs, n, replace=True)\n\n\ndef SampleRows(df, nrows, replace=False):\n \"\"\"Choose a sample of rows from a DataFrame.\n\n df: DataFrame\n nrows: number of rows\n replace: whether to sample with replacement\n\n returns: DataDf\n \"\"\"\n indices = np.random.choice(df.index, nrows, replace=replace)\n sample = df.loc[indices]\n return sample\n\n\ndef ResampleRows(df):\n \"\"\"Resamples rows from a DataFrame.\n\n df: DataFrame\n\n returns: DataFrame\n \"\"\"\n return SampleRows(df, len(df), replace=True)\n\n\ndef ResampleRowsWeighted(df, column='finalwgt'):\n \"\"\"Resamples a DataFrame using probabilities proportional to given column.\n\n df: DataFrame\n column: string column name to use as weights\n\n returns: DataFrame\n \"\"\"\n weights = df[column]\n cdf = Cdf(dict(weights))\n indices = cdf.Sample(len(weights))\n sample = df.loc[indices]\n return sample\n\n\ndef PercentileRow(array, p):\n \"\"\"Selects the row from a sorted array that maps to percentile p.\n\n p: float 0--100\n\n returns: NumPy array (one row)\n \"\"\"\n rows, cols = array.shape\n index = int(rows * p / 100)\n return array[index,]\n\n\ndef PercentileRows(ys_seq, percents):\n \"\"\"Given a collection of lines, selects percentiles along vertical axis.\n\n For example, if ys_seq contains simulation results like ys as a\n function of time, and percents contains (5, 95), the result would\n be a 90% CI for each vertical slice of the simulation results.\n\n ys_seq: sequence of lines (y values)\n percents: list of percentiles (0-100) to select\n\n returns: list of NumPy arrays, one for each pe" }, { "role": "assistant", "content": "rcentile\n \"\"\"\n nrows = len(ys_seq)\n ncols = len(ys_seq[0])\n array = np.zeros((nrows, ncols))\n\n for i, ys in enumerate(ys_seq):\n array[i,] = ys\n\n array = np.sort(array, axis=0)\n\n rows = [PercentileRow(array, p) for p in percents]\n return rows" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": " for camera_model in CAMERA_MODELS])\n\n\ndef qvec2rotmat(qvec):\n return np.array([\n [1 - 2 * qvec[2]**2 - 2 * qvec[3]**2,\n 2 * qvec[1] * qvec[2] - 2 * qvec[0] * qvec[3],\n 2 * qvec[3] * qvec[1] + 2 * qvec[0] * qvec[2]],\n [2 * qvec[1] * qvec[2] + 2 * qvec[0] * qvec[3],\n 1 - 2 * qvec[1]**2 - 2 * qvec[3]**2,\n 2 * qvec[2] * qvec[3] - 2 * qvec[0] * qvec[1]],\n [2 * qvec[3] * qvec[1] - 2 * qvec[0] * qvec[2],\n 2 * qvec[2] * qvec[3] + 2 * qvec[0] * qvec[1],\n 1 - 2 * qvec[1]**2 - 2 * qvec[2]**2]])\n\ndef rotmat2qvec(R):\n Rxx, Ryx, Rzx, Rxy, Ryy, Rzy, Rxz, Ryz, Rzz = R.flat\n K = np.array([\n [Rxx - Ryy - Rzz, 0, 0, 0],\n [Ryx + Rxy, Ryy - Rxx - Rzz, 0, 0],\n [Rzx + Rxz, Rzy + Ryz, Rzz - Rxx - Ryy, 0],\n [Ryz - Rzy, Rzx - Rxz, Rxy - Ryx, Rxx + Ryy + Rzz]]) / 3.0\n eigvals, eigvecs = np.linalg.eigh(K)\n qvec = eigvecs[[3, 0, 1, 2], np.argmax(eigvals)]\n if qvec[0] 0:\n qvec *= -1\n return qvec\n\nclass Image(BaseImage):\n def qvec2rotmat(self):\n return qvec2rotmat(self.qvec)\n\ndef read_next_bytes(fid, num_bytes, format_char_sequence, endian_character=\"\"):\n \"\"\"Read and unpack the next bytes from a binary file.\n :param fid:\n :param num_bytes: Sum of combination of {2, 4, 8}, e.g. 2, 6, 16, 30, etc.\n :param format_char_sequence: List of {c, e, f, d, h, H, i, I, l, L, q, Q}.\n :param endian_character: Any of {@, =, , , !}\n :return: Tuple of read and unpacked values.\n \"\"\"\n data = fid.read(num_bytes)\n return struct.unpack(endian_character + format_char_sequence, data)\n\ndef read_points3D_text(path):\n \"\"\"\n see: src/base/reconstruction.cc\n void Reconstruction::ReadPoints3DText(const std::string& path)\n void Reconstruction::WritePoints3DText(const std::string& path)\n \"\"\"\n xyzs = None\n rgbs = None\n errors = None\n num_points = 0\n with open(path, \"r\") as fid:\n while True:\n line = fid.readline()\n if not line:\n break\n line = line.strip()\n if len(line) 0 and line[0] != \"#\":\n num_points += 1\n\n\n xyzs = np.empty((num_points, 3))\n rgbs = np.empty((num_points, 3))\n errors = np.empty((num_points, 1))\n count = 0\n with open(path, \"r\") as fid:\n while True:\n line = fid.readline()\n if not line:\n break\n line = line.strip()\n if len(line) 0 and line[0] != \"#\":\n elems = line.split()\n xyz = np.array(tuple(map(float, elems[1:4])))\n " }, { "role": "assistant", "content": " rgb = np.array(tuple(map(int, elems[4:7])))\n error = np.array(float(elems[7]))\n xyzs[count] = xyz\n rgbs[count] = rgb\n errors[count] = error\n count += 1\n\n return xyzs, rgbs, errors" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "alize_heatmap(self,\n topics=topics,\n top_n_topics=top_n_topics,\n n_clusters=n_clusters,\n custom_labels=custom_labels,\n title=title,\n width=width,\n height=height)\n\n def visualize_barchart(self,\n topics: List[int] = None,\n top_n_topics: int = 8,\n n_words: int = 5,\n custom_labels: bool = False,\n title: str = \"Topic Word Scores\",\n width: int = 250,\n height: int = 250) - go.Figure:\n \"\"\" Visualize a barchart of selected topics\n\n Arguments:\n topics: A selection of topics to visualize.\n top_n_topics: Only select the top n most frequent topics.\n n_words: Number of words to show in a topic\n custom_labels: Whether to use custom topic labels that were defined using\n `topic_model.set_topic_labels`.\n title: Title of the plot.\n width: The width of each figure.\n height: The height of each figure.\n\n Returns:\n fig: A plotly figure\n\n Examples:\n\n To visualize the barchart of selected topics\n simply run:\n\n ```python\n topic_model.visualize_barchart()\n ```\n\n Or if you want to save the resulting figure:\n\n ```python\n fig = topic_model.visualize_barchart()\n fig.write_html(\"path/to/file.html\")\n ```\n \"\"\"\n check_is_fitted(self)\n return plotting.visualize_barchart(self,\n topics=topics,\n top_n_topics=top_n_topics,\n n_words=n_words,\n custom_labels=custom_labels,\n title=title,\n width=width,\n height=height)\n\n def save(self,\n " }, { "role": "assistant", "content": " path,\n serialization: Literal[\"safetensors\", \"pickle\", \"pytorch\"] = \"pickle\",\n save_embedding_model: Union[bool, str] = True,\n save_ctfidf: bool = False):" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "from __future__ import annotations\nimport json\nimport logging\nimport math\n" }, { "role": "assistant", "content": "import os\nimport sys\nimport hashlib\nfrom dataclasses import dataclass, field" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "import numpy as np\nfrom keras.models import *\nfrom keras.layers import *\nfrom keras.applications.vgg16 import VGG16\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.optimizers import *\nfrom keras.callbacks import ModelCheckpoint\nimport cv2\n\ndef train_generator(batch_size=32):\n data_gen_args = dict(featurewise_center=True,\n rotation_range=90.,\n width_shift_range=0.1,\n height_shift_range=0.1,\n fill_mode=\"constant\",\n cval=255,\n horizontal_flip=True,\n vertical_flip=True,\n zoom_range=0.2)\n image_datagen = ImageDataGenerator(**data_gen_args)\n mask_datagen = ImageDataGenerator(**data_gen_args)\n\n seed = 1\n image_generator = image_datagen.flow_fr" }, { "role": "assistant", "content": "om_directory(\n 'data/train/images',\n class_mode=None,\n batch_size=batch_size,\n color_mode='rgb',\n target_size=(512,512),\n #save_to_dir='./data/gen/images',\n seed=seed)" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "import csv\nimport pylab as pl\n\nfrom sklearn import datasets\nfrom sklearn.decompo" }, { "role": "assistant", "content": "sition import PCA" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "from dataclasses import asdict, dataclass\nfrom enum import Enum\nfrom typing import (\n Any,\n Dict,\n List,\n Mapping,\n Optional,\n Sequence,\n Tuple,\n)\nfrom aleph_alpha_client.prompt import Prompt\n\n\n@dataclass(frozen=True)\nclass EmbeddingRequest:\n \"\"\"\n Embeds a text and returns vectors that can be used for downstream tasks (e.g. semantic similarity) and models (e.g. classifiers).\n\n Parameters:\n prompt\n The text and/or image(s) to be embedded.\n\n layers\n A list of layer indices from which to return embeddings.\n\n * Index 0 corresponds to the word embeddings used as input to the first transformer layer\n * Index 1 corresponds to the hidden state as output by the first transformer layer, index 2 to the output of the second layer etc.\n * Index -1 corresponds to the last transformer layer (not the language modelling head), index -2 to the second last layer etc.\n\n pooling\n Pooling operation to use.\n Pooling operations include:\n\n * mean: aggregate token embeddings across the sequence dimension using an average\n * max: aggregate token embeddings across the sequence dimension using a maximum\n * last_token: just use the last token\n * abs_max: aggregate token embeddings across the sequence dimension using a maximum of absolute values\n\n type\n Type of the embedding (e.g. symmetric or asymmetric)\n\n tokens\n Flag indicating whether the tokenized prompt is to be returned (True) or not (False)\n\n normalize\n Return normalized embeddings. This can be used to save on additional compute when applying a cosine similarity metric.\n\n Note that at the moment this parameter does not yet have any effect. This will change as soon as the\n corresponding feature is available in the backend\n\n contextual_control_threshold (float, default None)\n If set to None, attention control parameters only apply to those tokens that have\n explicitly b" }, { "role": "assistant", "content": "een set in the request.\n If set to a non-None value, we apply the control parameters to similar tokens as well.\n Controls that have been applied to one token will then be applied to all other tokens\n that have at least the similarity score defined by this parameter.\n The similarity score is the cosine similarity of token embeddings." } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "import json\nimport os\nimport shutil\n\nimport numpy as np\nimport pandas as pd\nimport urllib3\nfrom tqdm import tqdm\n\nfrom ..utils import get_data_dir, get_labels\nfrom .preprocessing import get_granularity, get_type, stringify_context\n\n\ndef download_data(target_dir: str = None) - None:\n \"\"\"\n Download the Ultra-Fine Entity Typing (ACL 2018) data from the web.\n For more information, see https://www.cs.utexas.edu/~eunsol/html_pages/open_entity.html\n\n Parameters\n ----------\n target_dir : str, optional\n The directory to download the data to. The default is 'data'.\n \"\"\"\n DATA_URL = 'http://nlp.cs.washington.edu/entity_type/data/ultrafine_acl18.tar.gz'\n\n if target_dir is None:\n target_dir = get_data_dir()\n\n print(f'Downloading the data from {DATA_URL} to {target_dir}...')\n\n # Create the data directory if it does not exist\n os.makedirs(target_dir, exist_ok=True)\n\n # Download the data\n http = urllib3.PoolManager()\n with http.request('GET', DATA_URL, preload_content=False) as r, open('dat" }, { "role": "assistant", "content": "a/ultrafine_acl18.tar.gz', 'wb') as out_file:\n shutil.copyfileobj(r, out_file)\n\n # Extract the data\n print('Extracting the data...')\n shutil.unpack_archive('data/ultrafine_acl18.tar.gz', 'data')\n\n # Remove the tar.gz file\n os.remove('data/ultrafine_acl18.tar.gz')\n\n # Move the files form the 'data/release/ontonotes/' directory to the 'data' directory\n for filename in os.listdir('data/release/ontonotes/'):\n shutil.move(f'data/release/ontonotes/{filename}', f'data/{filename}')\n\n # Remove the 'data/release/' directory\n shutil.rmtree('data/release')" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "l.set_topic_labels`.\n title: Title of the plot.\n width: The width of the figure.\n height: The height of the figure.\n\n Examples:\n\n To visualize the topics simply run:\n\n ```python\n topic_model.visualize_documents(docs)\n ```\n\n Do note that this re-calculates the embeddings and reduces them to 2D.\n The advised and prefered pipeline for using this function is as follows:\n\n ```python\n from sklearn.datasets import fetch_20newsgroups\n from sentence_transformers import SentenceTransformer\n from bertopic import BERTopic\n from umap import UMAP\n\n # Prepare embeddings\n docs = fetch_20newsgroups(subset='all', remove=('headers', 'footers', 'quotes'))['data']\n sentence_model = SentenceTransformer(\"all-MiniLM-L6-v2\")\n embeddings = sentence_model.encode(docs, show_progress_bar=False)\n\n # Train BERTopic\n topic_model = BERTopic().fit(docs, embeddings)\n\n # Reduce dimensionality of embeddings, this step is optional\n # reduced_embeddings = UMAP(n_neighbors=10, n_components=2, min_dist=0.0, metric='cosine').fit_transform(embeddings)\n\n # Run the visualization with the original embeddings\n topic_model.visualize_documents(docs, embeddings=embeddings)\n\n # Or, if you have reduced the original embeddings already:\n topic_model.visualize_documents(docs, reduced_embeddings=reduced_embeddings)\n ```\n\n Or if you want to save the resulting figure:\n\n ```python\n fig = topic_model.visualize_documents(docs, reduced_embeddings=reduced_embeddings)\n fig.write_html(\"path/to/file.html\")\n ```\n\n iframe src=\"../getting_started/visualization/documents.html\"\n style=\"width:1000px; height: 800px; border: 0px;\"\"/iframe\n \"\"\"\n check_is_fitted(self)\n return plotting.visualize_documents(self,\n docs=docs,\n topics=topics,\n embeddings=embeddings,\n reduced_embeddings=reduced_embeddings,\n sample=sample,\n hide_annotations=hide_annotations,\n hide_document_hover=hide_document_hover,\n custom_labels=custom_labels,\n title=title,\n width=width,\n height=height)\n\n def visualize_hierarchical_documents(self,\n docs: List[str],\n hierarchical_topics: pd.DataFrame,\n topics: List[int] = None,\n embeddings: np.ndarray = None,\n reduced_embeddings: np.ndarray = None,\n sample: Union[float, int] = None,\n hide_annotations: bool = False,\n hide_document_hover: bool = True,\n nr_levels: int = 10,\n level_scale: str = 'linear',\n custom_labels: bool = False,\n title: str = \"bHierarchical Documents and Topics/b\",\n width: int = 1200,\n height: int = 750) - go.Figure:\n \"\"\" Visualize documents and their topics in 2D at different levels of hierarchy\n\n Arguments:\n docs: The documents you used when calling either `fit` or `fit_transform`\n hierarchical_topics: A dataframe that contains a hierarchy of topics\n represented by their parents and their children\n topics: A selection of topics to visualize.\n Not to be confused with the topics that you get from `.fit_transform`.\n For example, if you want to visualize only topics 1 through 5:\n `topics = [1, 2, 3, 4, 5]`.\n embeddings: The embeddings of all documents in `docs`.\n reduced_embeddings: The 2D reduced embeddings of all documents in `docs`.\n sample: The percentage of documents in each topic that you would like to keep.\n Value can be between 0 and 1. Setting this value to, for example,\n 0.1 (10% of documents in each topic) makes it easier to visualize\n millions of documents as a subset is chosen.\n hide_annotations: Hide the names of the traces on top of each cluster.\n hide_document_hover: Hide the content of the documents when hovering over\n specific points. Helps to speed up generation of visualizations.\n nr_levels: The number of levels to be visualized in the hierarchy. First, the distances\n in `hierarchical_topics.Distance` are split in `nr_levels` lists of distances with\n equal length. Then, for each list of distances, the merged topics are selected that\n have a distance less or equal to the maximum distance of the selected list of distances.\n NOTE: To get all possible merged steps, make sure that `nr_levels` is equal to\n the length of `hierarchical_topics`.\n level_scale: Whether to apply a linear or logarithmic ('log') scale levels of the distance\n vector. Linear scaling will perform an equal number of merges at each level\n while logarithmic scaling will perform more mergers in earlier levels to\n provide more resolution at higher levels (this can be used for when the number\n of topics is large).\n custom_labels: Whether to use custom topic labels that were defined using\n `topic_model.set_topic_labels`.\n NOTE: Custom labels are only generated for the original\n un-merged topics.\n title: Title of the plot.\n width: The width of the figure.\n height: The height of the figure.\n\n Examples:\n\n To visualize the topics simply run:\n\n ```python\n topic_model.visualize_hierarchical_documents(docs, hierarchical_topics)\n ```\n\n Do note that this re-calculates the embeddings and reduces them to 2D.\n The advised and prefered pipeline for using this function is as follows:\n\n ```python\n from sklearn.datasets import fetch_20newsgroups\n from sentence_transformers import SentenceTransformer\n from bertopic import BERTopic\n from umap import UMAP\n\n # Prepare embeddings\n docs = fetch_20newsgroups(subset='all', remove=('headers', 'footers', 'quotes'))['data']\n sentence_model = SentenceTransformer(\"all-MiniLM-L6-v2\")\n embeddings = sentence_model.encode(docs, show_progress_bar=False)\n\n # Train BERTopic and extract hierarchical topics\n topic_model = BERTopic().fit(docs, embeddings)\n hierarchical_topics = topic_model.hierarchical_topics(docs)\n\n # Reduce dimensionality of embeddings, this step is optional\n # reduced_embeddings = UMAP(n_neighbors=10, n_components=2, min_dist=0.0, metric='cosine').fit_transform(embeddings)\n\n # Run the visualization with the original embeddings\n topic_model.visualize_hierarchical_documents(docs, hierarchical_topics, embeddings=embeddings)\n\n # Or, if you have reduced the original embeddings already:\n topic_model.visualize_hierarchical_documents(docs, hierarchical_topics, reduced_embeddings=reduced_embeddings)\n ```\n\n Or if you want to save the resulting figure:\n\n ```python\n fig = topic_model.visualize_hierarchical_documents(docs, hierarchical_topics, reduced_embeddings=reduced_embeddings)\n fig.write_html(\"path/to/file.html\")\n ```\n\n iframe src=\"../getting_started/visualization/hierarchical_documents.html\"\n style=\"width:1000px; height: 770px; border: 0px;\"\"/iframe\n \"\"\"\n check_is_fitted(self)\n return plotting.visualize_hierarchical_documents(self,\n docs=docs,\n hierarchical_topics=hierarchical_topics,\n topics=topics,\n embeddings=embeddings,\n reduced_embeddings=reduced_embeddings,\n sample=sample,\n hide_annotations=hide_annotations,\n hide_document_hover=hide_document_hover,\n " }, { "role": "assistant", "content": " nr_levels=nr_levels,\n level_scale=level_scale,\n custom_labels=custom_labels,\n title=title,\n width=width,\n height=height)" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "t_init(self):\n # Smoke test for bug where warm_start=True is set at init\n y = self.X[:, 0]\n regressor = PySRRegressor(warm_start=True, max_evals=10)\n regressor.fit(self.X, y)\n\n def test_noisy(self):\n y = self.X[:, [0, 1]] ** 2 + self.rstate.randn(self.X.shape[0], 1) * 0.05\n model = PySRRegressor(\n # Test that passing a single operator works:\n unary_operators=\"sq(x) = x^2\",\n binary_operators=\"plus\",\n extra_sympy_mappings={\"sq\": lambda x: x**2},\n **self.default_test_kwargs,\n procs=0,\n denoise=True,\n early_stop_condition=\"stop_if(loss, complexity) = loss 0.05 && complexity == 2\",\n )\n # We expect in this case that the \"best\"\n # equation should be the right one:\n model.set_params(model_selection=\"best\")\n # Also try without a temp equation file:\n model.set_params(temp_equation_file=False)\n model.fit(self.X, y)\n self.assertLessEqual(model.get_best()[1][\"loss\"], 1e-2)\n self.assertLessEqual(model.get_best()[1][\"loss\"], 1e-2)\n\n def test_pandas_resample_with_nested_constraints(self):\n X = pd.DataFrame(\n {\n \"T\": self.rstate.randn(500),\n \"x\": self.rstate.randn(500),\n \"unused_feature\": self.rstate.randn(500),\n }\n )\n true_fn = lambda x: np.array(x[\"T\"] + x[\"x\"] ** 2 + 1.323837)\n y = true_fn(X)\n noise = self.rstate.randn(500) * 0.01\n y = y + noise\n # We also test y as a pandas array:\n y = pd.Series(y)\n # Resampled array is a different order of features:\n Xresampled = pd.DataFrame(\n {\n \"unused_feature\": self.rstate.randn(100),\n \"x\": self.rstate.randn(100),\n \"T\": self.rstate.randn(100),\n }\n )\n model = PySRRegressor(\n unary_operators=[],\n binary_operators=[\"+\", \"*\", \"/\", \"-\"],\n **self.default_test_kwargs,\n denoise=True,\n nested_constraints={\"/\": {\"+\": 1, \"-\": 1}, \"+\": {\"*\": 4}},\n early_stop_condition=\"stop_if(loss, complexity) = loss 1e-3 && complexity == 7\",\n )\n model.fit(X, y, Xresampled=Xresampled)\n self.assertNotIn(\"unused_feature\", model.latex())\n self.assertIn(\"T\", model.latex())\n self.assertIn(\"x\", model.latex())\n self.assertLessEqual(model.get_best()[\"loss\"], 1e-1)\n fn = model.get_best()[\"lambda_format\"]\n X2 = pd.DataFrame(\n {\n \"T\": self.rstate.randn(100),\n \"unused_feature\": self.rstate.randn(100),\n \"x\": self.rstate.randn(100),\n }\n )\n self.assertLess(np.average((fn(X2) - true_fn(X2)) ** 2), 1e-1)\n self.assertLess(np.average((model.predict(X2) - true_fn(X2)) ** 2), 1e-1)\n\n def test_high_dim_selection_early_stop(self):\n X = pd.DataFrame({f\"k{i}\": self.rstate.randn(10000) for i in range(10)})\n Xresampled = pd.DataFrame({f\"k{i}\": self.rstate.randn(100) for i in range(10)})\n y = X[\"k7\"] ** 2 + np.cos(X[\"k9\"]) * 3\n\n model = PySRRegressor(\n unary_operators=[\"cos\"],\n select_k_features=3,\n early_stop_condition=1e-4, # Stop once most accurate equation is 1e-4 MSE\n maxsize=12,\n **self.default_test_kwargs,\n )\n model.set_params(model_selection=\"accuracy\")\n model.fit(X, y, Xresampled=Xresampled)\n self.assertLess(np.average((model.predict(X) - y) ** 2), 1e-4)\n # Again, but with numpy arrays:\n model.fit(X.values, y.values, Xresampled=Xresampled.values)\n self.assertLess(np.average((model.predict(X.values) - y.values) ** 2), 1e-4)\n\n def test_load_model(self):\n \"\"\"See if we can load a ran model from the equation file.\"\"\"\n csv_file_data = \"\"\"\n Complexity,Loss,Equation\n 1,0.19951081,\"1.9762075\"\n 3,0.12717344,\"(f0 + 1.4724599)\"\n 4,0.104823045,\"pow_abs(2.2683423, cos(f3))\\\"\"\"\"\n # Strip the indents:\n csv_file_data = \"\\n\".join([l.strip() for l in csv_file_data.split(\"\\n\")])\n\n for from_backup in [False, True]:\n rand_dir = Path(tempfile.mkdtemp())\n equation_filename = str(rand_dir / \"equation.csv\")\n with open(equation_filename + (\".bkup\" if from_backup else \"\"), \"w\") as f:\n f.write(csv_file_data)\n model = PySRRegressor.from_file(\n equation_filename,\n n_features_in=5,\n feature_names_in=[\"f0\", \"f1\", \"f2\", \"f3\", \"f4\"],\n binary_operators=[\"+\", \"*\", \"/\", \"-\", \"^\"],\n unary_operators=[\"cos\"],\n )\n X = self.rstate.rand(100, 5)\n y_truth = 2.2683423 ** np.cos(X[:, 3])\n y_test = model.predict(X, 2)\n\n np.testing.assert_allclose(y_truth, y_test)\n\n def test_load_model_simple(self):\n # Test that we can simply load a model from its equation file.\n y = self.X[:, [0, 1]] ** 2\n model = PySRRegressor(\n # Test that passing a single operator works:\n unary_operators=\"sq(x) = x^2\",\n binary_operators=\"plus\",\n extra_sympy_mappings={\"sq\": lambda x: x**2},\n **self.default_test_kwargs,\n procs=0,\n denoise=True,\n early_stop_condition=\"stop_if(loss, complexity) = loss 0.05 && complexity == 2\",\n )\n rand_dir = Path(tempfile.mkdtemp())\n equation_file = rand_dir / \"equations.csv\"\n model.set_params(temp_equation_file=False)\n model.set_params(equation_file=equation_file)\n model.fit(self.X, y)\n\n # lambda functions are removed from the pickling, so we need\n # to pass it during the loading:\n model2 = PySRRegressor.from_file(\n model.equation_file_, extra_sympy_mappings={\"sq\": lambda x: x**2}\n )\n\n np.testing.assert_allclose(model.predict(self.X), model2.predict(self.X))\n\n # Try again, but using only the pickle file:\n for file_to_delete in [str(equation_file), str(equation_file) + \".bkup\"]:\n if os.path.exists(file_to_delete):\n os.remove(file_to_delete)\n\n pickle_file = rand_dir / \"equations.pkl\"\n model3 = PySRRegressor.from_file(\n model.equation_file_, extra_sympy_mappings={\"sq\": lambda x: x**2}\n )\n np.testing.assert_allclose(model.predict(self.X), model3.predict(self.X))\n\n\ndef manually_create_model(equations, feature_names=None):\n if feature_names is None:\n feature_names = [\"x0\", \"x1\"]\n\n model = PySRRegressor(\n progress=False,\n niterations=1,\n extra_sympy_mappings={},\n output_jax_format=False,\n model_selection=\"accuracy\",\n equation_file=\"equation_file.csv\",\n )\n\n # Set up internal parameters as if it had been fitted:\n if isinstance(equations, list):\n # Multi-output.\n model.equation_file_ = \"equation_file.csv\"\n model.nout_ = len(equations)\n model.selection_mask_ = None\n model.feature_names_in_ = np.array(feature_names, dtype=object)\n for i in range(model.nout_):\n equations[i][\"complexity loss equation\".split(\" \")].to_csv(\n f\"equation_file.csv.out{i+1}.bkup\"\n )\n else:\n model.equation_file_ = \"equation_file.csv\"\n model.nout_ = 1\n model.selection_mask_ = None\n model.feature_names_in_ = np.array(feature_names, dtype=object)\n equations[\"complexity loss equation\".split(\" \")].to_csv(\n \"equation_file.csv.bkup\"\n )\n\n model.refresh()\n\n return model\n\n\nclass TestBest(unittest.TestCase):\n def setUp(self):\n self.rstate = np.random.RandomState(0)\n self.X = self.rstate.randn(10, 2)\n self.y = np.cos(self.X[:, 0]) ** 2\n equations = pd.DataFrame(\n {\n \"equation\": [\"1.0\", \"cos(x0)\", \"square(cos(x0))\"],\n \"loss\": [1.0, 0.1, 1e-5],\n \"complexity\": [1, 2, 3],\n }\n )\n self.model = manually_create_model(equations)\n self.equations_ = self.model.equations_\n\n def test_best(self):\n self.assertEqual(self.model.sympy(), sympy.cos(sympy.Symbol(\"x0\")) ** 2)\n\n def test_index_selection(self):\n self.assertEqual(self.model.sympy(-1), sympy.cos(sympy.Symbo" }, { "role": "assistant", "content": "l(\"x0\")) ** 2)\n self.assertEqual(self.model.sympy(2), sympy.cos(sympy.Symbol(\"x0\")) ** 2)\n self.assertEqual(self.model.sympy(1), sympy.cos(sympy.Symbol(\"x0\")))\n self.assertEqual(self.model.sympy(0), 1.0)" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "\n arr = np.repeat([0.0, 1.0], n_points) # binary\n assert_almost_equal(matthews_corrcoef(arr, arr), 1.0)\n arr = np.repeat([0.0, 1.0, 2.0], n_points) # multiclass\n assert_almost_equal(matthews_corrcoef(arr, arr), 1.0)\n\n y_true, y_pred = random_ys(n_points)\n assert_almost_equal(matthews_corrcoef(y_true, y_true), 1.0)\n assert_almost_equal(matthews_corrcoef(y_true, y_pred), mcc_safe(y_true, y_pred))\n\n\ndef test_precision_recall_f1_score_multiclass():\n # Test Precision Recall and F1 Score for multiclass classification task\n y_true, y_pred, _ = make_prediction(binary=False)\n\n # compute scores with default labels introspection\n p, r, f, s = precision_recall_fscore_support(y_true, y_pred, average=None)\n assert_array_almost_equal(p, [0.83, 0.33, 0.42], 2)\n assert_array_almost_equal(r, [0.79, 0.09, 0.90], 2)\n assert_array_almost_equal(f, [0.81, 0.15, 0.57], 2)\n assert_array_equal(s, [24, 31, 20])\n\n # averaging tests\n ps = precision_score(y_true, y_pred, pos_label=1, average=\"micro\")\n assert_array_almost_equal(ps, 0.53, 2)\n\n rs = recall_score(y_true, y_pred, average=\"micro\")\n assert_array_almost_equal(rs, 0.53, 2)\n\n fs = f1_score(y_true, y_pred, average=\"micro\")\n assert_array_almost_equal(fs, 0.53, 2)\n\n ps = precision_score(y_true, y_pred, average=\"macro\")\n assert_array_almost_equal(ps, 0.53, 2)\n\n rs = recall_score(y_true, y_pred, average=\"macro\")\n assert_array_almost_equal(rs, 0.60, 2)\n\n fs = f1_score(y_true, y_pred, average=\"macro\")\n assert_array_almost_equal(fs, 0.51, 2)\n\n ps = precision_score(y_true, y_pred, average=\"weighted\")\n assert_array_almost_equal(ps, 0.51, 2)\n\n rs = recall_score(y_true, y_pred, average=\"weighted\")\n assert_array_almost_equal(rs, 0.53, 2)\n\n fs = f1_score(y_true, y_pred, average=\"weighted\")\n assert_array_almost_equal(fs, 0.47, 2)\n\n with pytest.raises(ValueError):\n precision_score(y_true, y_pred, average=\"samples\")\n with pytest.raises(ValueError):\n recall_score(y_true, y_pred, average=\"samples\")\n with pytest.raises(ValueError):\n f1_score(y_true, y_pred, average=\"samples\")\n with pytest.raises(ValueError):\n fbeta_score(y_true, y_pred, average=\"samples\", beta=0.5)\n\n # same prediction but with and explicit label ordering\n p, r, f, s = precision_recall_fscore_support(\n y_true, y_pred, labels=[0, 2, 1], average=None\n )\n assert_array_almost_equal(p, [0.83, 0.41, 0.33], 2)\n assert_array_almost_equal(r, [0.79, 0.90, 0.10], 2)\n assert_array_almost_equal(f, [0.81, 0.57, 0.15], 2)\n assert_array_equal(s, [24, 20, 31])\n\n\n@pytest.mark.parametrize(\"average\", [\"samples\", \"micro\", \"macro\", \"weighted\", None])\ndef test_precision_refcall_f1_score_multilabel_unordered_labels(average):\n # test that labels need not be sorted in the multilabel case\n y_true = np.array([[1, 1, 0, 0]])\n y_pred = np.array([[0, 0, 1, 1]])\n p, r, f, s = precision_recall_fscore_support(\n y_true, y_pred, labels=[3, 0, 1, 2], warn_for=[], average=average\n )\n assert_array_equal(p, 0)\n assert_array_equal(r, 0)\n assert_array_equal(f, 0)\n if average is None:\n assert_array_equal(s, [0, 1, 1, 0])\n\n\ndef test_precision_recall_f1_score_binary_averaged():\n y_true = np.array([0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1])\n y_pred = np.array([1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1])\n\n # compute scores with default labels introspection\n ps, rs, fs, _ = precision_recall_fscore_support(y_true, y_pred, average=None)\n p, r, f, _ = precision_recall_fscore_support(y_true, y_pred, average=\"macro\")\n assert p == np.mean(ps)\n assert r == np.mean(rs)\n assert f == np.mean(fs)\n p, r, f, _ = precision_recall_fscore_support(y_true, y_pred, average=\"weighted\")\n support = np.bincount(y_true)\n assert p == np.average(ps, weights=support)\n assert r == np.average(rs, weights=support)\n assert f == np.average(fs, weights=support)\n\n\ndef test_zero_precision_recall():\n # Check that pathological cases do not bring NaNs\n\n old_error_settings = np.seterr(all=\"raise\")\n\n try:\n y_true = np.array([0, 1, 2, 0, 1, 2])\n y_pred = np.array([2, 0, 1, 1, 2, 0])\n\n assert_almost_equal(precision_score(y_true, y_pred, average=\"macro\"), 0.0, 2)\n assert_almost_equal(recall_score(y_true, y_pred, average=\"macro\"), 0.0, 2)\n assert_almost_equal(f1_score(y_true, y_pred, average=\"macro\"), 0.0, 2)\n\n finally:\n np.seterr(**old_error_settings)\n\n\ndef test_confusion_matrix_multiclass_subset_labels():\n # Test confusion matrix - multi-class case with subset of labels\n y_true, y_pred, _ = make_prediction(binary=False)\n\n # compute confusion matrix with only first two labels considered\n cm = confusion_matrix(y_true, y_pred, labels=[0, 1])\n assert_array_equal(cm, [[19, 4], [4, 3]])\n\n # compute confusion matrix with explicit label ordering for only subset\n # of labels\n cm = confusion_matrix(y_true, y_pred, labels=[2, 1])\n assert_array_equal(cm, [[18, 2], [24, 3]])\n\n # a label not in y_true should result in zeros for that row/column\n extra_label = np.max(y_true) + 1\n cm = confusion_matrix(y_true, y_pred, labels=[2, extra_label])\n assert_array_equal(cm, [[18, 0], [0, 0]])\n\n\n@pytest.mark.parametrize(\n \"labels, err_msg\",\n [\n ([], \"'labels' should contains at least one label.\"),\n ([3, 4], \"At least one label specified must be in y_true\"),\n ],\n ids=[\"empty list\", \"unknown labels\"],\n)\ndef test_confusion_matrix_error(labels, err_msg):\n y_true, y_pred, _ = make_prediction(binary=False)\n with pytest.raises(ValueError, match=err_msg):\n confusion_matrix(y_true, y_pred, labels=labels)\n\n\n@pytest.mark.parametrize(\n \"labels\", (None, [0, 1], [0, 1, 2]), ids=[\"None\", \"binary\", \"multiclass\"]\n)\ndef test_confusion_matrix_on_zero_length_input(labels):\n expected_n_classes = len(labels) if labels else 0\n expected = np.zeros((expected_n_classes, expected_n_classes), dtype=int)\n cm = confusion_matrix([], [], labels=labels)\n assert_array_equal(cm, expected)\n\n\ndef test_confusion_matrix_dtype():\n y = [0, 1, 1]\n weight = np.ones(len(y))\n # confusion_matrix returns int64 by default\n cm = confusion_matrix(y, y)\n assert cm.dtype == np.int64\n # The dtype of confusion_matrix is always 64 bit\n for dtype in [np.bool_, np.int32, np.uint64]:\n cm = confusion_matrix(y, y, sample_weight=weight.astype(dtype, copy=False))\n assert cm.dtype == np.int64\n for dtype in [np.float32, np.float64, None, object]:\n cm = confusion_matrix(y, y, sample_weight=weight.astype(dtype, copy=False))\n assert cm.dtype == np.float64\n\n # np.iinfo(np.uint32).max should be accumulated correctly\n weight = np.full(len(y), 4294967295, dtype=np.uint32)\n cm = confusion_matrix(y, y, sample_weight=weight)\n assert cm[0, 0] == 4294967295\n assert cm[1, 1] == 8589934590\n\n # np.iinfo(np.int64).max should cause an overflow\n weight = np.full(len(y), 9223372036854775807, dtype=np.int64)\n cm = confusion_matrix(y, y, sample_weight=weight)\n assert cm[0, 0] == 9223372036854775807\n assert cm[1, 1] == -2\n\n\n@pytest.mark.parametrize(\"dtype\", [\"Int64\", \"Float64\", \"boolean\"])\ndef test_confusion_matrix_pandas_nullable(dtype):\n \"\"\"Checks that confusion_matrix works with pandas nullable dtypes.\n\n Non-regression test for gh-25635.\n \"\"\"\n pd = pytest.importorskip(\"pandas\")\n\n y_ndarray = np.array([1, 0, 0, 1, 0, 1, 1, 0, 1])\n y_true = pd.Series(y_ndarray, dtype=dtype)\n y_predicted = pd.Series([0, 0, 1, 1, 0, 1, 1, 1, 1], dtype=\"int64\")\n\n output = confusion_matrix(y_true, y_predicted)\n expected_output = confusion_matrix(y_ndarray, y_predicted)\n\n assert_array_equal(output, expected_output)\n\n\ndef test_classification_report_multiclass():\n # Test performance report\n iris = datasets.load_iris()\n y_true, y_pred, _ = make_prediction(dataset=iris, binary=False)\n\n # print classification report with class names\n expected_report = \"\"\"\\\n precision recall f1-score support\n\n setosa 0.83 0.79 0.81 24\n versicolor 0.33 0.10 0.15 31\n virginica 0.42 0.90 0.57 20\n\n accuracy 0.53 75\n macro avg 0.53 0.60 0.51 75\nweighted avg 0.51 0.53 0.47 75\n\"\"\"\n report = classificatio" }, { "role": "assistant", "content": "n_report(\n y_true,\n y_pred,\n labels=np.arange(len(iris.target_names)),\n target_names=iris.target_names,\n )\n assert report == expected_report" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "t inside a strategy scope and within a\n `tf.distribute.Strategy.run` function. The `ReplicaContext` object has an\n `all_reduce` method for aggregating across all replicas.\n\n\nNote that we provide a default version of `tf.distribute.Strategy` that is\nused when no other strategy is in scope, that provides the same API with\nreasonable default behavior.\n\"\"\"\n# pylint: enable=line-too-long\n\nimport collections\nimport contextlib\nimport copy\nimport enum # pylint: disable=g-bad-import-order\nimport functools\nimport threading\nimport weakref\n\nimport six\n\nfrom tensorflow.python import tf2\nfrom tensorflow.python.autograph.core import ag_ctx as autograph_ctx\nfrom tensorflow.python.autograph.impl import api as autograph\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.distribute import collective_util\nfrom tensorflow.python.distribute import device_util\nfrom tensorflow.python.distribute import numpy_dataset\nfrom tensorflow.python.distribute import reduce_util\nfrom tensorflow.python.eager import context as eager_context\nfrom tensorflow.python.eager import def_function\nfrom tensorflow.python.eager import monitoring\nfrom tensorflow.python.eager import tape\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import indexed_slices\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import tensor as tensor_lib\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.framework import tensor_util\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import custom_gradient\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import ref_variable\nfrom tensorflow.python.ops import summary_ops_v2\nfrom tensorflow.python.ops import variable_scope\nfrom tensorflow.python.ops import variable_v1\nfrom tensorflow.python.platform import tf_logging\nfrom tensorflow.python.trackable import base as trackable\nfrom tensorflow.python.types import distribute as ds_types\nfrom tensorflow.python.util import deprecation\nfrom tensorflow.python.util import nest\nfrom tensorflow.python.util import tf_contextlib\nfrom tensorflow.python.util.deprecation import deprecated\nfrom tensorflow.python.util.tf_export import tf_export\nfrom tensorflow.tools.docs import doc_controls\n\n# ------------------------------------------------------------------------------\n# Context tracking whether in a strategy.update() or .update_non_slot() call.\n\n\n_update_replica_id = threading.local()\n\n\ndef get_update_replica_id():\n \"\"\"Get the current device if in a `tf.distribute.Strategy.update()` call.\"\"\"\n try:\n return _update_replica_id.current\n except AttributeError:\n return None\n\n\nclass UpdateContext(object):\n \"\"\"Context manager when you are in `update()` or `update_non_slot()`.\"\"\"\n\n __slots__ = [\"_replica_id\", \"_old_replica_id\"]\n\n def __init__(self, replica_id):\n self._replica_id = replica_id\n self._old_replica_id = None\n\n def __enter__(self):\n self._old_replica_id = get_update_replica_id()\n _update_replica_id.current = self._replica_id\n\n def __exit__(self, exception_type, exception_value, traceback):\n del exception_type, exception_value, traceback\n _update_replica_id.current = self._old_replica_id\n\n\n# ------------------------------------------------------------------------------\n# Internal API for validating the current thread mode\n\n\ndef _require_cross_replica_or_default_context_extended(extended,\n error_message=None):\n \"\"\"Verify in cross-replica context.\"\"\"\n context = _get_per_thread_mode()\n cross_replica = context.cross_replica_context\n if cross_replica is not None and cross_replica.extended is extended:\n return\n if context is _get_default_replica_mode():\n return\n strategy = extended._container_strategy() # pylint: disable=protected-access\n # We have an error to report, figure out the right message.\n if context.strategy is not strategy:\n _wrong_strategy_scope(strategy, context)\n assert cross_replica is None\n if not error_message:\n error_message = (\"Method requires being in cross-replica context, use \"\n \"get_replica_context().merge_call()\")\n raise RuntimeError(error_message)\n\n\ndef _wrong_strategy_scope(strategy, context):\n # Figure out the right error message.\n if not has_strategy():\n raise RuntimeError(\n 'Need to be inside \"with strategy.scope()\" for %s' %\n (strategy,))\n else:\n raise RuntimeError(\n \"Mixing different tf.distribute.Strategy objects: %s is not %s\" %\n (context.strategy, strategy))\n\n\ndef require_replica_context(replica_ctx):\n \"\"\"Verify in `replica_ctx` replica context.\"\"\"\n context = _get_per_thread_mode()\n if context.replica_context is replica_ctx: return\n # We have an error to report, figure out the right message.\n if context.replica_context is None:\n raise RuntimeError(\"Need to be inside `call_for_each_replica()`\")\n if context.strategy is replica_ctx.strategy:\n # Two different ReplicaContexts with the same tf.distribute.Strategy.\n raise RuntimeError(\"Mismatching ReplicaContext.\")\n raise RuntimeError(\n \"Mismatching tf.distribute.Strategy objects: %s is not %s.\" %\n (context.strategy, replica_ctx.str" }, { "role": "assistant", "content": "ategy))" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "\"\"\"\nThis script copies all notebooks from the book into the website directory, and\ncreates pages which wrap them and link together.\n\"\"\"\nimport os\nimport nbformat\nimport shutil\n\nPAGEFILE = \"\"\"title: {title}\nurl:\nsave_as: {htmlfile}\nTemplate: {template}\n\n{{% notebook notebooks/{notebook_file} cells[{cells}] %}}\n\"\"\"\n\nINTRO_TEXT = \"\"\"This website contains the full text of the [Python Data Science Handbook](http://shop.oreilly.com/product/0636920034919.do) by Jake VanderPlas; the content is available [on GitHub](https://github.com/jakevdp/PythonDataScienceHandbook) in the form of" }, { "role": "assistant", "content": " Jupyter notebooks.\n\nThe text is released under the [CC-BY-NC-ND license](https://creativecommons.org/licenses/by-nc-nd/3.0/us/legalcode), and code is released under the [MIT license](https://opensource.org/licenses/MIT).\n\nIf you find this content useful, please consider supporting the work by [buying the book](http://shop.oreilly.com/product/0636920034919.do)!\n\"\"\"" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "from __future__ import annotations\n\nimport os\nimport typing as t\nfrom collections import defaultdict\nfrom functools import update_wrapper\n\nfrom .. import typing as ft\nfrom .scaffold import _endpoint_from_view_func\nfrom .scaffold import _sentinel\nfrom .scaffold import Scaffold\nfrom .scaffold import setupmethod\n\nif t.TYPE_CHECKING: # pragma: no cover\n from .app import App\n\nDeferredSetupFunction = t.Callable[[\"BlueprintSetupState\"], t.Callable]\nT_after_request = t.TypeVar(\"T_after_request\", bound=ft.AfterRequestCallable)\nT_before_request = t.TypeVar(\"T_before_request\", bound=ft.BeforeRequestCallable)\nT_error_handler = t.TypeVar(\"T_error_handler\", bound=ft.ErrorHandlerCallable)\nT_teardown = t.TypeVar(\"T_teardown\", bound=ft.TeardownCallable)\nT_template_context_processor = t.TypeVar(\n \"T_template_context_processor\", bound=ft.TemplateContextProcessorCallable\n)\nT_template_filter = t.TypeVar(\"T_template_filter\", bound=ft.TemplateFilterCallable)\nT_template_global = t.TypeVar(\"T_template_global\", bound=ft.TemplateGlobalCallable)\nT_template_test = t.TypeVar(\"T_template_test\", bound=ft.TemplateTestCallable)\nT_url_defaults = t.TypeVar(\"T_url_defaults\", bound=ft.URLDefaultCallable)\nT_url_value_preprocessor = t.TypeVar(\n \"T_url_value_preprocessor\", bound=ft.URLValuePreprocessorCallable\n)\n\n\nclass BlueprintSetupState:\n \"\"\"Temporary holder object for registering a blueprint with the\n application. An instance of this class is created by the\n :meth:`~flask.Blueprint.make_setup_state` method and later passed\n to all register callback functions.\n \"\"\"\n\n def __init__(\n self,\n blueprint: Blueprint,\n app: App,\n options: t.Any,\n first_registration: bool,\n ) - None:\n #: a reference to the current application\n self.app = app\n\n #: a reference to the blueprint that created this setup state.\n self.blueprint = blueprint\n\n #: a dictionary with all options that were passed to the\n #: :meth:`~flask.Flask.register_blueprint` method.\n self.options = options\n\n #: as blueprints can be registered multiple times with the\n #: application and not everything wants to be registered\n #: multiple times on it, this attribute can be used to figure\n #: out if the blueprint was registered in the past already.\n self.first_registration = first_registration\n\n subdomain = self.options.get(\"subdomain\")\n if subdomain is None:\n subdomain = self.blueprint.subdomain\n\n #: The subdomain that the blueprint should be active for, ``None``\n #: otherwise.\n self.subdomain = subdomain\n\n url_prefix = self.options.get(\"url_prefix\")\n if url_prefix is None:\n url_prefix = self.blueprint.url_prefix\n #: The prefix that should be used for all URLs defined on the\n #: blueprint.\n self.url_prefix = url_prefix\n\n self.name = self.options.get(\"name\", blueprint.name)\n self.name_prefix = self.options.get(\"name_prefix\", \"\")\n\n #: A dictionary with URL defaults that is added to each and every\n #: URL that was defined with the blueprint.\n self.url_defaults = dict(self.blueprint.url_values_defaults)\n self.url_defaults.update(self.options.get(\"url_defaults\", ()))\n\n def add_url_rule(\n self,\n rule: str,\n endpoint: str | None = None,\n view_func: t.Callable | None = None,\n **options: t.Any,\n ) - None:\n \"\"\"A helper method to register a rule (and optionally a view function)\n to the application. The endpoint is automatically prefixed with the\n blueprint's name.\n \"\"\"\n if self.url_prefix is not None:\n if rule:\n rule = \"/\".join((self.url_prefix.rstrip(\"/\"), rule.lstrip(\"/\")))\n else:\n rule = self.url_prefix\n options.setdefault(\"subdomain\", self.subdomain)\n if endpoint is None:\n endpoint = _endpoint_from_view_func(view_func) # type: ignore\n defaults = self.url_defaults\n if \"defaults\" in options:\n defaults = dict(defaults, **options.pop(\"defaults\"))\n\n self.app.add_url_rule(\n rule,\n f\"{self.name_prefix}.{self.name}.{endpoint}\".lstrip(\".\"),\n view_func,\n " }, { "role": "assistant", "content": " defaults=defaults,\n **options,\n )" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "import os\nimport shutil\nimport time\nfrom typing import Tuple\n\nimport numpy as np\nimport pandas as pd\nimport pytest\nfrom sklearn.pipeline import Pipeline\n\nfrom pmtrendviz.models.factory import ModelFactory\nfrom pmtrendviz.models.manager import SimpleSklearnPipelineManager\nfrom pmtrendviz.train.data import sample_training_data\nfrom pmtrendviz.utils import get_es_client, get_models_dir\n\n\n@pytest.mark.usefixtures('manage_pytest_index', 'manage_prediction_indices')\nclass TestSimpleSklearnPipelineManager:\n sample_data: pd.DataFrame = pd.DataFrame()\n n_samples: int = 1000\n index: str = 'pytest'\n model_name: str = 'pytest-model'\n model = 'tfidf_truncatedsvd_kmeans'\n stop_words = 'english'\n max_df: float = 0.999\n min_df: float = 0.001\n n_components: int = 100\n n_clusters: int = 69\n ngram_range: Tuple[int, int] = (1, 1)\n random_state: int = 42\n include_title: bool = True\n include_abstract: bool = True\n include_keywords_major: bool = False\n include_keywords_minor: bool = False\n\n @classmethod\n def setup_class(cls) - None:\n # Clear the test model directory\n shutil.rmtree(os.path.join(get_models_dir(), cls.model_name), ignore_errors=True)\n\n # Sample some data\n cls.sample_data = sample_training_data(cls.index, random_state=42, n_samples=cls.n_samples, method='forward')['text']\n\n @classmethod\n def teardown_class(cls) - None:\n # Clear the test model directory\n shutil.rmtree(os.path.join(get_models_dir(), cls.model_name), ignore_errors=True)\n\n def teardown_method(self) - None:\n # Clear the test model directory\n shutil.rmtree(os.path.join(get_models_dir(), self.model_name), ignore_errors=True)\n\n def test_sample_data(self) - None:\n assert len(self.sample_data) == self.n_samples\n\n def test_create_default_simple_sklearn_pipeline_manager(self) - None:\n manager = ModelFactory.create(\n self.model,\n self.include_title,\n self.include_abstract,\n self.include_keywords_major,\n self.include_keywords_minor,\n stop_words=self.stop_words,\n max_df=self.max_df,\n min_df=self.min_df,\n n_components=self.n_components,\n n_clusters=self.n_clusters,\n ngram_range=self.ngram_range,\n random_state=None)\n\n assert manager is not None\n assert isinstance(manager.model, Pipeline)\n assert manager.random_state is None\n assert manager.preprocessing_args == {\n 'include_title': True,\n 'include_abstract': True,\n 'include_keywords_major': False,\n 'include_keywords_minor': False,\n }\n\n assert (manager.cluster_names.columns == ['name']).all()\n assert len(manager.cluster_names) == 0\n\n def test_create_custom_simple_sklearn_pipeline_manager(self) - None:\n manager = ModelFactory.create(\n self.model,\n self.include_title,\n self.include_abstract,\n True,\n self.include_keywords_minor,\n stop_words=self.stop_words,\n max_df=self.max_df,\n min_df=self.min_df,\n n_components=self.n_components,\n n_clusters=self.n_clusters,\n ngram_range=self.ngram_range,\n random_state=42)\n\n assert manager.random_state == 42\n assert manager.preprocessing_args == {\n 'include_title': True,\n 'include_abstract': True,\n 'include_keywords_major': True,\n 'include_keywords_minor': False,\n }\n\n def test_set_name(self) - None:\n manager = ModelFactory.create(\n self.model,\n self.include_title,\n self.include_abstract,\n self.include_keywords_major,\n self.include_keywords_minor,\n stop_words=self.stop_words,\n max_df=self.max_df,\n min_df=self.min_df,\n n_components=self.n_components,\n n_clusters=self.n_clusters,\n ngram_range=self.ngram_range,\n random_state=self.random_state)\n manager.set_name(self.model_name)\n\n assert manager._name == self.model_name\n\n def test_construct_predictions_index_name(self) - None:\n manager = ModelFactory.create(\n self.model,\n self.include_title,\n self.include_abstract,\n self.include_keywords_major,\n self.include_keywords_minor,\n stop_words=self.stop_words,\n max_df=self.max_df,\n min_df=self.min_df,\n n_components=self.n_components,\n n_clusters=self.n_clusters,\n ngram_range=self.ngram_range,\n random_state=self.random_state)\n manager.set_name(self.model_name)\n predictions_index_name = manager._construct_predictions_index_name(self.index)\n predictions_file_name = manager._construct_predictions_file_name(self.index)\n\n assert manager._name == self.model_name\n assert predictions_index_name == f'{self.index}_{manager._name}_predictions'\n assert predictions_file_name == f'{self.index}_predictions.json'\n\n def test_fit(self) - None:\n manager = ModelFactory.create(\n self.model,\n self.include_title,\n self.include_abstract,\n self.include_keywords_major,\n self.include_keywords_minor,\n stop_words=self.stop_words,\n max_df=self.max_df,\n min_df=self.min_df,\n n_components=self.n_components,\n n_clusters=self.n_clusters,\n ngram_range=self.ngram_range,\n random_state=self.random_state)\n\n manager.fit(self.sample_data)\n\n assert manager.model['clustering_kmeans'].labels_.shape == (self.n_samples,)\n assert len(manager.cluster_names) == self.n_clusters\n\n def test_predict(self) - None:\n manager = ModelFactory.create(\n self.model,\n self.include_title,\n self.include_abstract,\n self.include_keywords_major,\n self.include_keywords_minor,\n stop_words=self.stop_words,\n max_df=self.max_df,\n min_df=self.min_df,\n n_components=self.n_components,\n n_clusters=self.n_clusters,\n ngram_range=self.ngram_range,\n random_state=self.random_state)\n\n manager.fit(self.sample_data)\n predictions = manager.predict(self.sample_data)\n\n assert isinstance(predictions, np.ndarray)\n assert" }, { "role": "assistant", "content": " predictions.shape == (self.n_samples,)" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "type_str', 'y', 'y_type', and 'original_y_str' columns\n df.drop(['annot_id', 'y_type_str', 'y', 'y_type', 'original_y_str'], axis=1, inplace=True, errors='ignore')\n\n # Convert the 'left_context_token' and 'right_context_token' columns into a string\n df['left_context_token'] = df['left_context_token'].apply(stringify_context)\n df['right_context_token'] = df['right_context_token'].apply(stringify_context)\n\n # Reconstruct the sentence from the 'left_context_token', 'mention_span', and 'right_context_token' columns\n df['sentence'] = df['left_context_token'] + ' ' + df['mention_span'] + ' ' + df['right_context_token']\n\n # Drop the 'left_context_token' and 'right_context_token' columns\n df.drop(['left_context_token', 'right_context_token'], axis=1, inplace=True, errors='ignore')\n\n # For each instance and for each type in the 'y_str' column, create a new row\n if explode:\n df = df.explode('y_str')\n\n # Rename the 'y_str' column to 'full_type'\n df.rename(columns={'y_str': 'full_type'}, inplace=True)\n\n # Reset the index\n df.reset_index(drop=True, inplace=True)\n\n # Calculate the granularity of the type\n if explode:\n df['granularity'] = df['full_type'].apply(get_granularity)\n\n # Add the 'label' column\n labels = get_labels()\n df['label'] = labels['ENTAILMENT']\n df['label'] = df['label'].astype(int)\n\n return df\n\n\ndef get_all_types(granularity: int = -1) - pd.DataFrame:\n \"\"\"\n Get all the types in the training data.\n\n Parameters\n ----------\n granularity : int, optional\n The granularity of the type, measured from the root of the ontology, by default -1 (finest granularity)\n\n Returns\n -------\n all_types : pd.DataFrame\n A DataFrame containing all the full types and the types at the specified granularity.\n \"\"\"\n all_types_path = os.path.join(get_data_dir(), 'derived', 'all_types.csv')\n os.makedirs(os.path.dirname(all_types_path), exist_ok=True)\n\n if os.path.exists(all_types_path):\n # If the file exists, load the types from the file\n all_types = pd.read_csv(all_types_path)\n else:\n # If the file doesn't exist, take the types from the training data and save them\n train_data = get_positive_data('augmented_train.json', explode=True)\n all_types = pd.DataFrame(train_data['full_type'].unique(), columns=['full_type'])\n\n # Save the types to a file\n all_types.to_csv(all_types_path, index=False)\n\n # Get the types at the specified granularity\n all_types['type'] = all_types['full_type'].apply(lambda x: get_type(x, granularity=granularity))\n\n return all_types\n\n\ndef get_ambiguity_index(filename: str = 'augmented_train.json') - dict:\n \"\"\"\n Get the ambiguity index (a dictionary that maps each entity to a dictionary of types and their counts).\n\n Parameters\n ----------\n filename : str, optional\n The name of the json file, by default 'augmented_" }, { "role": "assistant", "content": "train.json'\n\n Returns\n -------\n ambiguity_index : dict\n The ambiguity index.\n \"\"\"" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "f infer_params(state_dict):\n # this code is copied from https://github.com/victorca25/iNNfer\n scale2x = 0\n scalemin = 6\n n_uplayer = 0\n plus = False\n\n for block in list(state_dict):\n parts = block.split(\".\")\n n_parts = len(parts)\n if n_parts == 5 and parts[2] == \"sub\":\n nb = int(parts[3])\n elif n_parts == 3:\n part_num = int(parts[1])\n if (part_num scalemin\n and parts[0] == \"model\"\n and parts[2] == \"weight\"):\n scale2x += 1\n if part_num n_uplayer:\n n_uplayer = part_num\n out_nc = state_dict[block].shape[0]\n if not plus and \"conv1x1\" in block:\n plus = True\n\n nf = state_dict[\"model.0.weight\"].shape[0]\n in_nc = state_dict[\"model.0.weight\"].shape[1]\n out_nc = out_nc\n scale = 2 ** scale2x\n\n return in_nc, out_nc, nf, nb, plus, scale\n\n\nclass UpscalerESRGAN(Upscaler):\n def __init__(self, dirname):\n self.name = \"ESRGAN\"\n self.model_url = \"https://github.com/cszn/KAIR/releases/download/v1.0/ESRGAN.pth\"\n self.model_name = \"ESRGAN_4x\"\n self.scalers = []\n self.user_path = dirname\n super().__init__()\n model_paths = self.find_models(ext_filter=[\".pt\", \".pth\"])\n scalers = []\n if len(model_paths) == 0:\n scaler_data = UpscalerData(self.model_name, self.model_url, self, 4)\n scalers.append(scaler_data)\n for file in model_paths:\n if file.startswith(\"http\"):\n name = self.model_name\n else:\n name = modelloader.friendly_name(file)\n\n scaler_data = UpscalerData(name, file, self, 4)\n self.scalers.append(scaler_data)\n\n def do_upscale(self, img, selected_model):\n try:\n model = self.load_model(selected_model)\n except Exception as e:\n print(f\"Unable to load ESRGAN model {selected_model}: {e}\", file=sys.stderr)\n return img\n model.to(devices.device_esrgan)\n img = esrgan_upscale(model, img)\n return img\n\n def load_model(self, path: str):\n if path.startswith(\"http\"):\n # TODO: this doesn't use `path` at all?\n filename = modelloader.load_file_from_url(\n url=self.model_url,\n model_dir=self.model_download_path,\n file_name=f\"{self.model_name}.pth\",\n )\n else:\n filename = path\n\n state_" }, { "role": "assistant", "content": "dict = torch.load(filename, map_location='cpu' if devices.device_esrgan.type == 'mps' else None)" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": " cc = torch.cat(c_crossattn, 1)\n out = self.diffusion_model(xc, t, context=cc)\n elif self.conditioning_key == 'hybrid-adm':\n assert c_adm is not None\n xc = torch.cat([x] + c_concat, dim=1)\n cc = torch.cat(c_crossattn, 1)\n out = self.diffusion_model(xc, t, context=cc, y=c_adm)\n elif self.conditioning_key == 'crossattn-adm':\n assert c_adm is not None\n cc = torch.cat(c_crossattn, 1)\n out = self.diffusion_model(x, t, context=cc, y=c_adm)\n elif self.conditioning_key == 'adm':\n cc = c_crossattn[0]\n out = self.diffusion_model(x, t, y=cc)\n else:\n raise NotImplementedError()\n\n return out\n\n\nclass LatentUpscaleDiffusion(LatentDiffusion):\n def __init__(self, *args, low_scale_config, low_scale_key=\"LR\", noise_level_key=None, **kwargs):\n super().__init__(*args, **kwargs)\n # assumes that neither the cond_stage nor the low_scale_model contain trainable params\n assert not self.cond_stage_trainable\n self.instantiate_low_stage(low_scale_config)\n self.low_scale_key = low_scale_key\n self.noise_level_key = noise_level_key\n\n def instantiate_low_stage(self, config):\n model = instantiate_from_config(config)\n self.low_scale_model = model.eval()\n self.low_scale_model.train = disabled_train\n for param in self.low_scale_model.parameters():\n param.requires_grad = False\n\n @torch.no_grad()\n def get_input(self, batch, k, cond_key=None, bs=None, log_mode=False):\n if not log_mode:\n z, c = super().get_input(batch, k, force_c_encode=True, bs=bs)\n else:\n z, c, x, xrec, xc = super().get_input(batch, self.first_stage_key, return_first_stage_outputs=True,\n force_c_encode=True, return_original_cond=True, bs=bs)\n x_low = batch[self.low_scale_key][:bs]\n x_low = rearrange(x_low, 'b h w c - b c h w')\n x_low = x_low.to(memory_format=torch.contiguous_format).float()\n zx, noise_level = self.low_scale_model(x_low)\n if self.noise_level_key is not None:\n # get noise level from batch instead, e.g. when extracting a custom noise level for bsr\n raise NotImplementedError('TODO')\n\n all_conds = {\"c_concat\": [zx], \"c_crossattn\": [c], \"c_adm\": noise_level}\n if log_mode:\n # TODO: maybe disable if too expensive\n x_low_rec = self.low_scale_model.decode(zx)\n return z, all_conds, x, xrec, xc, x_low, x_low_rec, noise_level\n return z, all_conds\n\n @torch.no_grad()\n def log_images(self, batch, N=8, n_row=4, sample=True, ddim_steps=200, ddim_eta=1., return_keys=None,\n plot_denoise_rows=False, plot_progressive_rows=True, plot_diffusion_rows=True,\n unconditional_guidance_scale=1., unconditional_guidance_label=None, use_ema_scope=True,\n **kwargs):\n ema_scope = self.ema_scope if use_ema_scope else nullcontext\n use_ddim = ddim_steps is not None\n\n log = dict()\n z, c, x, xrec, xc, x_low, x_low_rec, noise_level = self.get_input(batch, self.first_stage_key, bs=N,\n log_mode=True)\n N = min(x.shape[0], N)\n n_row = min(x.shape[0], n_row)\n log[\"inputs\"] = x\n log[\"reconstruction\"] = xrec\n log[\"x_lr\"] = x_low\n log[f\"x_lr_rec_@noise_levels{'-'.join(map(lambda x: str(x), list(noise_level.cpu().numpy())))}\"] = x_low_rec\n if self.model.conditioning_key is not None:\n if hasattr(self.cond_stage_model, \"decode\"):\n xc = self.cond_stage_model.decode(c)\n log[\"conditioning\"] = xc\n elif self.cond_stage_key in [\"caption\", \"txt\"]:\n xc = log_txt_as_img((x.shape[2], x.shape[3]), batch[self.cond_stage_key], size=x.shape[" }, { "role": "assistant", "content": "2] // 25)\n log[\"conditioning\"] = xc\n elif self.cond_stage_key in ['class_label', 'cls']:\n xc = log_txt_as_img((x.shape[2], x.shape[3]), batch[\"human_label\"], size=x.shape[2] // 25)\n log['conditioning'] = xc\n elif isimage(xc):\n log[\"conditioning\"] = xc\n if ismap(xc):\n log[\"original_conditioning\"] = self.to_rgb(xc)" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "#!/usr/bin/env python3\n################################################################################\n# File: generate_readme.py\n# Version: 0.4\n# Purpose: Creates the README.md file for this repo\n# Authors: Michael Altfield michael@michaelaltfield.net\n# Created: 2023-06-06\n# Updated: 2023-08-04\n################################################################################\n\n################################################################################\n# IMPORTS #\n################################################################################\n\nimport json, csv, numpy, datetime, warnings\nimport pandas as pd\n\n################################################################################\n# SETTINGS #\n################################################################################\n\nLEMMY_STATS_CRAWLER_FILENAME = 'lemmy-stats-crawler.json'\nLEMMY_STATS_CRAWLER_FILEPATH = 'lemmy-stats-crawler/' + LEMMY_STATS_CRAWLER_FILENAME\n\nUPTIME_FILENAME = 'uptime.json'\nAGE_FILENAME = 'age.json'\n\nOUT_CSV = 'awesome-lemmy-instances.csv'\n\n################################################################################\n# FUNCTIONS #\n################################################################################\n\n# do some checks on text that we get back from the instance's API because it\n# might break markdown or do something nasty\ndef sanitize_text( text ):\n\n\t# markdown table columns are delimited by pipes\n\ttext = text.replace( '|', '' )\n\n\t# newlines\n\ttext = text.replace( \"\\r\", '' )\n\ttext = text.replace( \"\\n\", '' )\n\n\t# commas fuck with our CSV file; replace it with this homoglyph (0x201A)\n\ttext = text.replace( \",\", '‚' )\n\n\treturn text\n\n################################################################################\n# MAIN BODY #\n################################################################################\n\n# catch runtime warnings from numpy on 'nan' errors when calculating averages\nwarnings.filterwarnings(\"error\")\n\n##################\n# CHECK SETTINGS #\n##############" }, { "role": "assistant", "content": "####" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "import functools\nimport gc\nimport gevent\nimport logging\nimport pymongo\nfrom pymongo.errors import AutoReconnect, ConnectionFailure, OperationFailure, TimeoutError\nimport signal\nimport sys\n\nloggers = {}\ndef get_logger(name):\n \"\"\"\n get a logger object with reasonable defaults for formatting\n\n @param name used to identify the logger (though not currently useful for anything)\n \"\"\"\n global loggers\n if name in loggers:\n return loggers[name]\n\n logger = logging.getLogger(name)\n logger.setLevel(logging.DEBUG)\n sh = logging.StreamHandler()\n sh.setFormatter(logging.Formatter(\"%(asctime)s [%(levelname)s:%(processName)s] %(message)s\",\n \"%m-%d %H:%M:%S\"))\n logger.addHandler(sh)\n\n loggers[name] = logger\n return logger\n\nlog = get_logger(\"utils\")\n\n\ndef mongo_connect(host, port, ensure_direct=False, secondary_only=False, max_pool_size=1,\n socketTimeoutMS=None, w=0, read_preference=None, document_class=dict,\n replicaSet=None, slave_okay=None):\n \"\"\"\n Same as MongoClient.connect, except that we are paranoid and ensure that cursors\n # point to what we intended to point them to. Also sets reasonable defaults for our\n needs.\n\n @param host host to connect to\n @param port port to connect to\n @param ensure_direct do safety checks to ensure we are connected to specified mongo instance\n\n most other keyword arguments mirror those for pymongo.MongoClient\n \"\"\"\n options = dict(\n host=host,\n port=port,\n socketTimeoutMS=socketTimeoutMS,\n use_greenlets=True,\n max_pool_size=max_pool_size,\n w=1,\n document_class=document_class)\n if replicaSet is not None:\n options['replicaSet'] = replicaSet\n if read_preference is not None:\n options['read_preference'] = read_preference\n if slave_okay is not None:\n options['slave_okay'] = slave_okay\n client" }, { "role": "assistant", "content": " = pymongo.MongoClient(**options)" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "import numpy as np\nimport pytest\n\nimport pandas as pd\nimport pandas._testing as tm\nfrom pandas.api.extensions import ExtensionArray\nfrom pandas.core.internals.blocks import EABackedBlock\n\n\nclass BaseConstructorsTests:\n def test_from_sequence_from_cls(self, data):\n result = type(data)._from_sequence(data, dtype=data.dtype)\n tm.assert_extension_array_equal(result, data)\n\n data = data[:0]\n result = type(data)._from_sequence(data, dtype=data.dtype)\n tm.assert_extension_array_equal(result, data)\n\n def test_array_from_scalars(self, data):\n scalars = [data[0], data[1], data[2]]\n result = data._from_sequence(scalars)\n assert isinstance(result, type(data))\n\n def test_series_constructor(self, data):\n result = pd.Series(data, copy=False)\n assert result.dtype == data.dtype\n assert len(result) == len(data)\n if hasattr(res" }, { "role": "assistant", "content": "ult._mgr, \"blocks\"):\n assert isinstance(result._mgr.blocks[0], EABackedBlock)\n assert result._mgr.array is data\n\n # Series[EA] is unboxed / boxed correctly\n result2 = pd.Series(result)\n assert result2.dtype == data.dtype\n if hasattr(result._mgr, \"blocks\"):\n assert isinstance(result2._mgr.blocks[0], EABackedBlock)" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "# -*- coding: utf-8 -*-\n\n\"\"\"\nhttpbin.filters\n~~~~~~~~~~~~~~~\n\nThis module provides response filter decorators.\n\"\"\"\n\nimport gzip as gzip2\nimport zlib\n\nimport brotli as _brotli\n\nfrom six import BytesIO\nfrom decimal import Decimal\nfrom time import time as now\n\nfrom decorator import decorator\nfrom flask import Flask, Response\n\n\napp = Flask(__name__)\n\n\n@decorator\ndef x_runtime(f, *args, **kwargs):\n \"\"\"X-Runtime Flask Response Decorator.\"\"\"\n\n _t0 = now()\n r = f(*args, **kwargs)\n _t1 = now()\n r.headers['X-Runtime'] = '{0}s'.format(Decimal(str(_t1 - _t0)))\n\n return r\n\n\n@decorator\ndef gzip(f, *args, **kwargs):\n \"\"\"GZip Flask Response Decorator.\"\"\"\n\n data = f(*args, **kwargs)\n\n if isinstance(data, Response):\n content = data.data\n else:\n content = data\n\n gzip_buffer = BytesIO()\n gzip_file = gzip2.GzipFile(\n mode='wb',\n compresslevel=4,\n fileobj=gzip_buffer\n )\n gzip_file.write(content)\n gzip_file.close()\n\n gzip_data = gzip_buffer.getvalue()\n\n if isinstance(data, Response):\n data.data = gzip_data\n data.headers['Content-Encoding'] = 'gzip'\n data.headers['Content-Length'] = str(len(data.data))\n\n return data\n\n return gzip_data\n\n\n@decorator\ndef deflate(f, *args, **kwargs):\n \"\"\"Deflate Flask Response Decorator.\"\"\"\n\n data = f(*args, **kwargs)\n\n if isinstance(data, Response):\n content = data.data\n else:\n content = data\n\n deflater = zlib.compressobj()\n deflated_data = deflater.compress(content)\n deflated_data += deflater.flush()\n\n if isinstance(data, Response):\n data.data = deflated_data\n data.headers['Content-Encoding'] = 'deflate'\n data.headers['Content-Length'] = str(len(data.data))\n\n ret" }, { "role": "assistant", "content": "urn data\n\n return deflated_data" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "cache__\")\n\n # clean the generated pxi files\n for pxifile in _pxifiles:\n pxifile_replaced = pxifile.replace(\".pxi.in\", \".pxi\")\n self._clean_me.append(pxifile_replaced)\n\n self._clean_trees.append(d for d in (\"build\", \"dist\") if os.path.exists(d))\n\n def finalize_options(self):\n pass\n\n def run(self):\n for clean_me in self._clean_me:\n try:\n os.unlink(clean_me)\n except OSError:\n pass\n for clean_tree in self._clean_trees:\n try:\n shutil.rmtree(clean_tree)\n except OSError:\n pass\n\n\n# we need to inherit from the versioneer\n# class as it encodes the version info\nsdist_class = cmdclass[\"sdist\"]\n\n\nclass CheckSDist(sdist_class):\n \"\"\"Custom sdist that ensures Cython has compiled all pyx files to c.\"\"\"\n\n _pyxfiles = [\n \"pandas/_libs/arrays.pyx\",\n \"pandas/_libs/lib.pyx\",\n \"pandas/_libs/hashtable.pyx\",\n \"pandas/_libs/tslib.pyx\",\n \"pandas/_libs/index.pyx\",\n \"pandas/_libs/internals.pyx\",\n \"pandas/_libs/algos.pyx\",\n \"pandas/_libs/join.pyx\",\n \"pandas/_libs/indexing.pyx\",\n \"pandas/_libs/interval.pyx\",\n \"pandas/_libs/hashing.pyx\",\n \"pandas/_libs/missing.pyx\",\n \"pandas/_libs/testing.pyx\",\n \"pandas/_libs/sparse.pyx\",\n \"pandas/_libs/ops.pyx\",\n \"pandas/_libs/parsers.pyx\",\n \"pandas/_libs/tslibs/base.pyx\",\n \"pandas/_libs/tslibs/ccalendar.pyx\",\n \"pandas/_libs/tslibs/dtypes.pyx\",\n \"pandas/_libs/tslibs/period.pyx\",\n \"pandas/_libs/tslibs/strptime.pyx\",\n \"pandas/_libs/tslibs/np_datetime.pyx\",\n \"pandas/_libs/tslibs/timedeltas.pyx\",\n \"pandas/_libs/tslibs/timestamps.pyx\",\n \"pandas/_libs/tslibs/timezones.pyx\",\n \"pandas/_libs/tslibs/conversion.pyx\",\n \"pandas/_libs/tslibs/fields.pyx\",\n \"pandas/_libs/tslibs/offsets.pyx\",\n \"pandas/_libs/tslibs/parsing.pyx\",\n \"pandas/_libs/tslibs/tzconversion.pyx\",\n \"pandas/_libs/tslibs/vectorized.pyx\",\n \"pandas/_libs/window/indexers.pyx\",\n \"pandas/_libs/writers.pyx\",\n \"pandas/_libs/sas.pyx\",\n \"pandas/_libs/byteswap.pyx\",\n ]\n\n _cpp_pyxfiles = [\n \"pandas/_libs/window/aggregations.pyx\",\n ]\n\n def initialize_options(self):\n sdist_class.initialize_options(self)\n\n def run(self):\n if \"cython\" in cmdclass:\n self.run_command(\"cython\")\n else:\n # If we are not running cython then\n # compile the extensions correctly\n pyx_files = [(self._pyxfiles, \"c\"), (self._cpp_pyxfiles, \"cpp\")]\n\n for pyxfiles, extension in pyx_files:\n for pyxfile in pyxfiles:\n sourcefile = pyxfile[:-3] + extension\n msg = (\n f\"{extension}-source file '{sourcefile}' not found.\\n\"\n \"Run 'setup.py cython' before sdist.\"\n )\n assert os.path.isfile(sourcefile), msg\n sdist_class.run(self)\n\n\nclass CheckingBuildExt(build_ext):\n \"\"\"\n Subclass build_ext to get clearer report if Cython is necessary.\n \"\"\"\n\n def check_cython_extensions(self, extensions):\n for ext in extensions:\n for src in ext.sources:\n if not os.path.exists(src):\n print(f\"{ext.name}: - [{ext.sources}]\")\n raise Exception(\n f\"\"\"Cython-generated file '{src}' not found.\n Cython is required to compile pandas from a development branch.\n Please install Cython or download a release package of pandas.\n \"\"\"\n )\n\n def build_extensions(self):\n self.check_cython_extensions(self.extensions)\n build_ext.build_extensions(self)\n\n\nclass CythonCommand(build_ext):\n \"\"\"\n Custom command subclassed from Cython.Distutils.build_ext\n to compile pyx-c, and stop there. All this does is override the\n C-compile method build_extension() with a no-op.\n \"\"\"\n\n def build_extension(self, ext):\n pass\n\n\nclass DummyBuildSrc(Command):\n \"\"\"numpy's build_src command interferes with Cython's build_ext.\"\"\"\n\n user_options = []\n\n def initialize_options(self):\n self.py_modules_dict = {}\n\n def finalize_options(self):\n pass\n\n def run(self):\n pass\n\n\ncmdclass[\"clean\"] = CleanCommand\ncmdclass[\"build_ext\"] = CheckingBuildExt\n\nif _CYTHON_INSTALLED:\n suffix = \".pyx\"\n cmdclass[\"cython\"] = CythonCommand\nelse:\n suffix = \".c\"\n cmdclass[\"build_src\"] = DummyBuildSrc\n\n# ----------------------------------------------------------------------\n# Preparation of compiler arguments\n\ndebugging_symbols_requested = \"--with-debugging-symbols\" in sys.argv\nif debugging_symbols_requested:\n sys.argv.remove(\"--with-debugging-symbols\")\n\n\nif sys.byteorder == \"big\":\n endian_macro = [(\"__BIG_ENDIAN__\", \"1\")]\nelse:\n endian_macro = [(\"__LITTLE_ENDIAN__\", \"1\")]\n\n\nextra_compile_args = []\nextra_link_args = []\nif is_platform_windows():\n if debugging_symbols_requested:\n extra_compile_args.append(\"/Z7\")\n extra_link_args.append(\"/DEBUG\")\nelse:\n # PANDAS_CI=1 is set in CI\n if os.environ.get(\"PANDAS_CI\", \"0\") == \"1\":\n extra_compile_args.append(\"-Werror\")\n if debugging_symbols_requested:\n extra_compile_args.append(\"-g3\")\n extra_compile_args.append(\"-UNDEBUG\")\n extra_compile_args.append(\"-O0\")\n\n# Build for at least macOS 10.9 when compiling on a 10.9 system or above,\n# overriding CPython distuitls behaviour which is to target the version that\n# python was built for. This may be overridden by setting\n# MACOSX_DEPLOYMENT_TARGET before calling setup.py\nif is_platform_mac():\n if \"MACOSX_DEPLOYMENT_TARGET\" not in os.environ:\n current_system = platform.mac_ver()[0]\n python_target = get_config_vars().get(\n \"MACOSX_DEPLOYMENT_TARGET\", current_system\n )\n target_macos_version = \"10.9\"\n parsed_macos_version = parse_version(target_macos_version)\n if (\n parse_version(str(python_target))\n parsed_macos_version\n = parse_version(current_system)\n ):\n os.environ[\"MACOSX_DEPLOYMENT_TARGET\"] = target_macos_version\n\n if sys.version_info[:2] == (3, 8): # GH 33239\n extra_compile_args.append(\"-Wno-error=deprecated-declarations\")\n\n # https://github.com/pandas-de" }, { "role": "assistant", "content": "v/pandas/issues/35559\n extra_compile_args.append(\"-Wno-error=unreachable-code\")" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "\"\"\"This script generates the papers.md file from the papers.yml file.\"\"\"\nfrom pathlib import Path\n\nimport yaml\n\ndata_file = \"papers.yml\"\npapers_header = Path(\"stylesheets\") / \"papers_header.txt\"\noutput_file = \"papers.md\"\n\n# Load YAML file:\nwith open(data_file, \"r\") as stream:\n papers = yaml.load(stream, Loader=yaml.SafeLoader)[\"papers\"]\n\n# Load header:\nwith open(papers_header, \"r\") as stream:\n header = stream.read()\n\nwith open(output_file, \"w\") as f:\n f.write(header)\n\n # First, we sort the papers by date.\n # This is in the format of \"2022-03-15\"\n papers = sorted(papers, key=lambda paper: paper[\"date\"], reverse=True)\n\n snippets = []\n for paper in papers:\n title = paper[\"title\"]\n authors = (\n \", \".join(paper[\"authors\"]).replace(\"(\", \"sup\").replace(\")\", \"/sup\")\n )\n affiliations = \", \".join(\n f\"sup{num}/sup{affil}\" for num, affil in paper[\"affiliations\"].items()\n )\n link = paper[\"link\"]\n " }, { "role": "assistant", "content": " abstract = paper[\"abstract\"]\n image_file = paper[\"image\"]\n\n # Begin:\n paper_snippet = f\"\"\"\n\nfigure markdown\n![](images/{image_file}){{ width=\"500\"}}\nfigcaption\n!-- Large font: --\nh2\na href=\"{link}\"{title}/a\n/h2\n/figcaption\n/figure\n\ncenter\n{authors}\n\nsmall{affiliations}/small\n/center\n\n**Abstract:** {abstract}\\n\\n\n\"\"\"\n snippets.append(paper_snippet)\n\n f.write(\"\\n\\n---\\n\\n\".join(snippets))\n" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "s.\n \"\"\"\n changes = self.get_changes([self.author_name_null], [self.author_name_default])\n # Right number/type of migrations?\n self.assertNumberMigrations(changes, \"testapp\", 1)\n self.assertOperationTypes(changes, \"testapp\", 0, [\"AlterField\"])\n self.assertOperationAttributes(\n changes, \"testapp\", 0, 0, name=\"name\", preserve_default=True\n )\n self.assertOperationFieldAttributes(\n changes, \"testapp\", 0, 0, default=\"Ada Lovelace\"\n )\n\n @mock.patch(\n \"django.db.migrations.questioner.MigrationQuestioner.ask_not_null_alteration\",\n side_effect=AssertionError(\"Should not have prompted for not null alteration\"),\n )\n def test_alter_field_to_not_null_with_db_default(self, mocked_ask_method):\n changes = self.get_changes(\n [self.author_name_null], [self.author_name_db_default]\n )\n self.assertNumberMigrations(changes, \"testapp\", 1)\n self.assertOperationTypes(changes, \"testapp\", 0, [\"AlterField\"])\n self.assertOperationAttributes(\n changes, \"testapp\", 0, 0, name=\"name\", preserve_default=True\n )\n self.assertOperationFieldAttributes(\n changes, \"testapp\", 0, 0, db_default=models.Value(\"Ada Lovelace\")\n )\n\n @mock.patch(\n \"django.db.migrations.questioner.MigrationQuestioner.ask_not_null_alteration\",\n return_value=models.NOT_PROVIDED,\n )\n def test_alter_field_to_not_null_without_default(self, mocked_ask_method):\n \"\"\"\n #23609 - Tests autodetection of nullable to non-nullable alterations.\n \"\"\"\n changes = self.get_changes([self.author_name_null], [self.author_name])\n self.assertEqual(mocked_ask_method.call_count, 1)\n # Right number/type of migrations?\n self.assertNumberMigrations(changes, \"testapp\", 1)\n self.assertOperationTypes(changes, \"testapp\", 0, [\"AlterField\"])\n self.assertOperationAttributes(\n changes, \"testapp\", 0, 0, name=\"name\", preserve_default=True\n )\n self.assertOperationFieldAttributes(\n changes, \"testapp\", 0, 0, default=models.NOT_PROVIDED\n )\n\n @mock.patch(\n \"django.db.migrations.questioner.MigrationQuestioner.ask_not_null_alteration\",\n return_value=\"Some Name\",\n )\n def test_alter_field_to_not_null_oneoff_default(self, mocked_ask_method):\n \"\"\"\n #23609 - Tests autodetection of nullable to non-nullable alterations.\n \"\"\"\n changes = self.get_changes([self.author_name_null], [self.author_name])\n self.assertEqual(mocked_ask_method.call_count, 1)\n # Right number/type of migrations?\n self.assertNumberMigrations(changes, \"testapp\", 1)\n self.assertOperationTypes(changes, \"testapp\", 0, [\"AlterField\"])\n self.assertOperationAttributes(\n changes, \"testapp\", 0, 0, name=\"name\", preserve_default=False\n )\n self.assertOperationFieldAttributes(\n changes, \"testapp\", 0, 0, default=\"Some Name\"\n )\n\n def test_rename_field(self):\n \"\"\"Tests autodetection of renamed fields.\"\"\"\n changes = self.get_changes(\n [self.author_name],\n [self.author_name_renamed],\n MigrationQuestioner({\"ask_rename\": True}),\n )\n # Right number/type of migrations?\n self.assertNumberMigrations(changes, \"testapp\", 1)\n self.assertOperationTypes(changes, \"testapp\", 0, [\"RenameField\"])\n self.assertOperationAttributes(\n changes, \"testapp\", 0, 0, old_name=\"name\", new_name=\"names\"\n )\n\n def test_rename_field_foreign_key_to_field(self):\n before = [\n ModelState(\n \"app\",\n \"Foo\",\n [\n (\"id\", models.AutoField(primary_key=True)),\n (\"field\", models.IntegerField(unique=True)),\n ],\n ),\n ModelState(\n \"app\",\n \"Bar\",\n [\n (\"id\", models.AutoField(primary_key=True)),\n (\n \"foo\",\n models.ForeignKey(\"app.Foo\", models.CASCADE, to_field=\"field\"),\n ),\n ],\n ),\n ]\n after = [\n ModelState(\n \"app\",\n \"Foo\",\n [\n (\"id\", models.AutoField(primary_key=True)),\n (\"renamed_field\", models.IntegerField(unique=True)),\n ],\n ),\n ModelState(\n \"app\",\n \"Bar\",\n [\n (\"id\", models.AutoField(primary_key=True)),\n (\n \"foo\",\n models.ForeignKey(\n \"app.Foo\", models.CASCADE, to_field=\"renamed_field\"\n ),\n ),\n ],\n ),\n ]\n changes = self.get_changes(\n before, after, MigrationQuestioner({\"ask_rename\": True})\n )\n # Right number/type of migrations?\n self.assertNumberMigrations(changes, \"app\", 1)\n self.assertOperationTypes(changes, \"app\", 0, [\"RenameField\"])\n self.assertOperationAttributes(\n changes, \"app\", 0, 0, old_name=\"field\", new_name=\"renamed_field\"\n )\n\n def test_foreign_object_from_to_fields_list(self):\n author_state = ModelState(\n \"app\",\n \"Author\",\n [(\"id\", models.AutoField(primary_key=True))],\n )\n book_state = ModelState(\n \"app\",\n \"Book\",\n [\n (\"id\", models.AutoField(primary_key=True)),\n (\"name\", models.CharField()),\n (\"author_id\", models.IntegerField()),\n (\n \"author\",\n models.ForeignObject(\n \"app.Author\",\n models.CASCADE,\n from_fields=[\"author_id\"],\n to_fields=[\"id\"],\n ),\n ),\n ],\n " }, { "role": "assistant", "content": " )\n book_state_copy = copy.deepcopy(book_state)\n changes = self.get_changes(\n [author_state, book_state],\n [author_state, book_state_copy],\n )\n self.assertEqual(changes, {})" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "#! /usr/bin/env python\n\n\n# dependencies to handle:\n# - gevent\n# - pymongo\n# - apt: python-dev\n# - apt: libevent-dev\n\nimport copier\nfrom copy_state_db import CopyStateDB\nimport multiprocessing\nimport oplog_applier\nimport os\nimport os.path\nfrom pymongo.read_preferences import ReadPreference\nimport string\nimport sys\nimport utils\n\nlog = utils.get_logger(__name__)\n\nPARENT_PROCESS_NAME = 'parent process'\n\n#\n# child processes\n#\n\ndef die(msg):\n log.error(msg)\n sys.exit(1)\n\n\ndef ensure_empty_dest(dest):\n client = utils.mongo_connect(dest['host'], dest['port'],\n ensure_direct=True,\n max_pool_size=1,\n read_preference=ReadPreference.PRIMARY)\n collection = client[dest['db']][dest['collection']]\n if collection.count() 0:\n die(\"destination must be empty!\")\n\n\ndef copy_collection_parent(sources, dest, state_db, args):\n \"\"\"\n drive the collection copying process by delegating work to a pool of worker processes\n \"\"\"\n\n # ensure state db has rows for each source/dest pair\n for source in sources:\n state_db.add_source_and_dest(source, dest)\n\n # space-pad all process names so that tabular output formats line up\n process_names = {repr(source): \"%s:%d\" % (source['host'], source['port'])\n for source in sources}\n process_names['parent'] = PARENT_PROCESS_NAME\n max_process_name_len = max(len(name) for name in process_names.itervalues())\n for key in process_names:\n process_names[key] = string.ljust(process_names[key], max_process_name_len)\n\n multiprocessing.current_process().name = process_names['parent']\n\n # -----------------------------------------------------------------------\n # perform initial copy, if it hasn't been done yet\n # --------------" }, { "role": "assistant", "content": "---------------------------------------------------------\n in_initial_copy = len(state_db.select_by_state(CopyStateDB.STATE_INITIAL_COPY))\n if in_initial_copy and in_initial_copy len(sources):\n die(\"prior attempt at initial copy failed; rerun with --restart\")\n if in_initial_copy 0:\n ensure_empty_dest(dest)\n\n # each worker process copies one shard\n processes = []\n for source in sources:\n name = process_names[repr(source)]\n process = multiprocessing.Process(target=copier.copy_collection,\n name=name,\n kwargs=dict(source=source,\n dest=dest,\n state_path=state_db._path,\n percent=args.percent))\n process.start()\n processes.append(process)\n\n\n # wait for all workers to finish\n utils.wait_for_processes(processes)" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": " except ModuleNotFoundError:\n return False\n\n return spec is not None\n\n\ndef repo_dir(name):\n return os.path.join(script_path, dir_repos, name)\n\n\ndef run_pip(command, desc=None, live=default_command_live):\n if args.skip_install:\n return\n\n index_url_line = f' --index-url {index_url}' if index_url != '' else ''\n return run(f'\"{python}\" -m pip {command} --prefer-binary{index_url_line}', desc=f\"Installing {desc}\", errdesc=f\"Couldn't install {desc}\", live=live)\n\n\ndef check_run_python(code: str) - bool:\n result = subprocess.run([python, \"-c\", code], capture_output=True, shell=False)\n return result.returncode == 0\n\n\ndef git_fix_workspace(dir, name):\n run(f'\"{git}\" -C \"{dir}\" fetch --refetch --no-auto-gc', f\"Fetching all contents for {name}\", f\"Couldn't fetch {name}\", live=True)\n run(f'\"{git}\" -C \"{dir}\" gc --aggressive --prune=now', f\"Pruning {name}\", f\"Couldn't prune {name}\", live=True)\n return\n\n\ndef run_git(dir, name, command, desc=None, errdesc=None, custom_env=None, live: bool = default_command_live, autofix=True):\n try:\n return run(f'\"{git}\" -C \"{dir}\" {command}', desc=desc, errdesc=errdesc, custom_env=custom_env, live=live)\n except RuntimeError:\n if not auto" }, { "role": "assistant", "content": "fix:\n raise\n\n print(f\"{errdesc}, attempting autofix...\")\n git_fix_workspace(dir, name)\n\n return run(f'\"{git}\" -C \"{dir}\" {command}', desc=desc, errdesc=errdesc, custom_env=custom_env, live=live)" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "#\n# The Python Imaging Library.\n# $Id$\n#\n# standard image operations\n#\n# History:\n# 2001-10-20 fl Created\n# 2001-10-23 fl Added autocontrast operator\n# 2001-12-18 fl Added Kevin's fit operator\n# 2004-03-14 fl Fixed potential division by zero in equalize\n# 2005-05-05 fl Fixed equalize for low number of values\n#\n# Copyright (c) 2001-2004 by Secret Labs AB\n# Copyright (c) 2001-2004 by Fredrik Lundh\n#\n# See the README file for information on usage and redistribution.\n#\n\nimport functools\nimport operator\nimport re\n\nfrom . import ExifTags, Image, ImagePalette\n\n#\n# helpers\n\n\ndef _border(border):\n if isinstance(border, tuple):\n if len(border) == 2:\n left, top = right, bottom = border\n elif len(border) == 4:\n left, top, right, bottom = border\n else:\n left = top = right = bottom = border\n return left, top, right, bottom\n\n\ndef _color(color, mode):\n if isinstance(color, str):\n from . import ImageColor\n\n color = ImageColor.getcolor(color, mode)\n return color\n\n\ndef _lut(image, lut):\n if image.mode == \"P\":\n # FIXME: apply to lookup table, not image data\n msg = \"mode P support coming soon\"\n raise NotImplementedError(msg)\n elif image.mode in (\"L\", \"RGB\"):\n if image.mode == \"RGB\" and len(lut) == 256:\n lut = lut + lut + lut\n return image.point(lut)\n else:\n msg = f\"not supported for mode {image.mode}\"\n raise OSError(msg)\n\n\n#\n# actions\n\n\ndef autocontrast(image, cutoff=0, ignore=None, mask=None, preserve_tone=False):\n \"\"\"\n Maximize (normalize) image contrast. This function calculates a\n histogram of the input image (or mask region), removes ``cutoff`` percent of the\n lightest and darkest pixels from the histogram, and remaps the image\n so that the darkest pixel becomes black (0), and the lightest\n becomes white (255).\n\n :param image: The image to process.\n :param cutoff: The percent to cut off from the histogram on the low and\n high ends. Either a tuple of (low, high), or a single\n number for both.\n :param ignore: The background pixel value (use None for no background).\n :param mask: Histogram used in contrast operation is computed using pixels\n within the mask. If no mask is given the entire image is used\n for histogram computation.\n :param preserve_tone: Preserve image tone in Photoshop-like style autocontrast.\n\n .. versionadded:: 8.2.0\n\n :return: An image.\n \"\"\"\n if preserve_tone:\n histogram = image.convert(\"L\").histogram(mask)\n else:\n histogram = image.histogram(mask)\n\n lut = []\n for layer in range(0, len(histogram), 256):\n h = histogram[layer : layer + 256]\n if ignore is not None:\n # get rid of outliers\n try:\n h[ignore] = 0\n except TypeError:\n # assume sequence\n for ix in ignore:\n h[ix] = 0\n if cutoff:\n # cut off pixels from both ends of the histogram\n if not isinstance(cutoff, tuple):\n cutoff = (cutoff, cutoff)\n # get number of pixels\n n = 0\n for ix in range(256):\n n = n + h[ix]\n # remove cutoff% pixels from the low end\n cut = n * cutoff[0] // 100\n for lo in range(256):\n if cut h[lo]:\n cut = cut - h[lo]\n h[lo] = 0\n else:\n h[lo] -= cut\n cut = 0\n if cut = 0:\n " }, { "role": "assistant", "content": " break\n # remove cutoff% samples from the high end\n cut = n * cutoff[1] // 100\n for hi in range(255, -1, -1):\n if cut h[hi]:\n cut = cut - h[hi]\n h[hi] = 0\n else:\n h[hi] -= cut\n cut = 0\n if cut = 0:\n break\n # find lowest/highest samples after preprocessing\n for lo in range(256):\n if h[lo]:\n break\n for hi in range(255, -1, -1):\n if h[hi]:\n break\n if hi = lo:\n # don't bother\n lut.extend(list(range(256)))\n else:\n scale = 255.0 / (hi - lo)\n offset = -lo * scale\n for ix in range(256):\n ix = int(ix * scale + offset)\n if ix 0:\n ix = 0\n elif ix 255:\n ix = 255\n lut.append(ix)\n return _lut(image, lut)" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "_increasing:\n if isna(values).any():\n raise ValueError(f\"Merge keys contain null values on {side} side\")\n raise ValueError(f\"{side} keys must be sorted\")\n\n if isinstance(values, ArrowExtensionArray):\n values = values._maybe_convert_datelike_array()\n\n if needs_i8_conversion(values.dtype):\n values = values.view(\"i8\")\n\n elif isinstance(values, BaseMaskedArray):\n # we've verified above that no nulls exist\n values = values._data\n elif isinstance(values, ExtensionArray):\n values = values.to_numpy()\n\n # error: Incompatible return value type (got \"Union[ExtensionArray,\n # Any, ndarray[Any, Any], ndarray[Any, dtype[Any]], Index, Series]\",\n # expected \"ndarray[Any, Any]\")\n return values # type: ignore[return-value]\n\n def _get_join_indexers(self) - tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]]:\n \"\"\"return the join indexers\"\"\"\n\n # values to compare\n left_values = (\n self.left.index._values if self.left_index else self.left_join_keys[-1]\n )\n right_values = (\n self.right.index._values if self.right_index else self.right_join_keys[-1]\n )\n\n # _maybe_require_matching_dtypes already checked for dtype matching\n assert left_values.dtype == right_values.dtype\n\n tolerance = self.tolerance\n if tolerance is not None:\n # TODO: can we reuse a tolerance-conversion function from\n # e.g. TimedeltaIndex?\n if needs_i8_conversion(left_values.dtype):\n tolerance = Timedelta(tolerance)\n # TODO: we have no test cases with PeriodDtype here; probably\n # need to adjust tolerance for that case.\n if left_values.dtype.kind in \"mM\":\n # Make sure the i8 representation for tolerance\n # matches that for left_values/right_values.\n lvs = ensure_wrapped_if_datetimelike(left_values)\n tolerance = tolerance.as_unit(lvs.unit)\n\n tolerance = tolerance._value\n\n # initial type conversion as needed\n left_values = self._convert_values_for_libjoin(left_values, \"left\")\n right_values = self._convert_values_for_libjoin(right_values, \"right\")\n\n # a \"by\" parameter requires special handling\n if self.left_by is not None:\n # remove 'on' parameter from values if one existed\n if self.left_index and self.right_index:\n left_join_keys = self.left_join_keys\n right_join_keys = self.right_join_keys\n else:\n left_join_keys = self.left_join_keys[0:-1]\n right_join_keys = self.right_join_keys[0:-1]\n\n mapped = [\n _factorize_keys(\n left_join_keys[n],\n right_join_keys[n],\n sort=False,\n how=\"left\",\n )\n for n in range(len(left_join_keys))\n ]\n\n if len(left_join_keys) == 1:\n left_by_values = mapped[0][0]\n right_by_values = mapped[0][1]\n else:\n arrs = [np.concatenate(m[:2]) for m in mapped]\n shape = tuple(m[2] for m in mapped)\n group_index = get_group_index(\n arrs, shape=shape, sort=False, xnull=False\n )\n left_len = len(left_join_keys[0])\n left_by_values = group_index[:left_len]\n right_by_values = group_index[left_len:]\n\n left_by_values = ensure_int64(left_by_values)\n right_by_values = ensure_int64(right_by_values)\n\n # choose appropriate function by type\n func = _asof_by_function(self.direction)\n return func(\n left_values,\n right_values,\n left_by_values,\n right_by_values,\n self.allow_exact_matches,\n tolerance,\n )\n else:\n # choose appropriate function by type\n func = _asof_by_function(self.direction)\n return func(\n left_values,\n right_values,\n None,\n None,\n self.allow_exact_matches,\n tolerance,\n False,\n )\n\n\ndef _get_multiindex_indexer(\n join_keys: list[ArrayLike], index: MultiIndex, sort: bool\n) - tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]]:\n # left & right join labels and num. of levels at each location\n mapped = (\n _factorize_keys(index.levels[n]._values, join_keys[n], sort=sort)\n for n in range(index.nlevels)\n )\n zipped = zip(*mapped)\n rcodes, lcodes, shape = (list(x) for x in zipped)\n if sort:\n rcodes = list(map(np.take, rcodes, index.codes))\n else:\n i8copy = lambda a: a.astype(\"i8\", subok=False, copy=True)\n rcodes = list(map(i8copy, index.codes))\n\n # fix right labels if there were any nulls\n for i, join_key in enumerate(join_keys):\n mask = index.codes[i] == -1\n if mask.any():\n # check if there already was any nulls at this location\n # if there was, it is factorized to `shape[i] - 1`\n a = join_key[lcodes[i] == shape[i] - 1]\n if a.size == 0 or not a[0] != a[0]:\n shape[i] += 1\n\n rcodes[i][mask] = shape[i] - 1\n\n # get flat i8 join keys\n lkey, rkey = _get_join_keys(lcodes, rcodes, tuple(shape), sort)\n return lkey, rkey\n\n\ndef _get_empty_indexer() - tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]]:\n \"\"\"Return empty join indexers.\"\"\"\n return (\n np.array([], dtype=np.intp),\n np.array([], dtype=np.intp),\n )\n\n\ndef _get_no_sort_one_missing_indexer(\n n: int, left_missing: bool\n) - tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]]:\n \"\"\"\n Return join indexers where all of one side is selected without sorting\n and none of the other side is selected.\n\n Parameters\n ----------\n n : int\n Length of indexers to create.\n left_missing : bool\n If True, the left indexer will contain only -1's.\n If False, the right indexer will contain only -1's.\n\n Returns\n -------\n np.ndarray[np.intp]\n Left indexer\n np.ndarray[np.intp]\n Right indexer\n \"\"\"\n idx = np.arange(n, dtype=np.intp)\n idx_missing = np.full(shape=n, fill_value=-1, dtype=np.intp)\n if left_missing:\n return idx_missing, idx\n return idx, idx_missing\n\n\ndef _left_join_on_index(\n left_ax: Index, right_ax: Index, join_keys: list[ArrayLike], sort: bool = False\n) - tuple[Index, npt.NDArray[np.intp] | None, npt.NDArray[np.intp]]:\n if isinstance(right_ax, MultiIndex):\n lkey, rkey = _get_multiindex_indexer(join_keys, right_ax, sort=sort)\n else:\n # error: Incompatible types in assignment (expression has type\n # \"Union[Union[ExtensionArray, ndarray[Any, Any]], Index, Series]\",\n # variable has type \"ndarray[Any, dtype[signedinteger[Any]]]\")\n lkey = join_keys[0] # type: ignore[assignment]\n # error: Incompatible types in assignment (expression has type \"Index\",\n # variable has type \"ndarray[Any, dtype[signedinteger[Any]]]\")\n rkey = right_ax._values # type: ignore[assignment]\n\n left_key, right_key, count = _factorize_keys(lkey, rkey, sort=sort)\n left_indexer, right_indexer = libjoin.left_outer_join(\n " }, { "role": "assistant", "content": " left_key, right_key, count, sort=sort\n )\n\n if sort or len(left_ax) != len(left_indexer):\n # if asked to sort or there are 1-to-many matches\n join_index = left_ax.take(left_indexer)\n return join_index, left_indexer, right_indexer\n\n # left frame preserves order & length of its index\n return left_ax, None, right_indexer" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "#!/usr/bin/env python3\n\"\"\"\nA script to create C code-coverage reports based on the output of\nvalgrind's callgrind tool.\n\n\"\"\"\nimport os\nimport re\nimport sys\nfrom xml.sax.saxutils import quoteattr, escape\n\ntry:\n import pygments\n if tuple([int(x) for x in pygments.__version__.split('.')]) (0, 11):\n raise ImportError()\n from pygments import highlight\n from pygments.lexers import CLexer\n from pygments.formatters import HtmlFormatter\n has_pygments = True\nexcept ImportError:\n print(\"This script requires pygments 0.11 or greater to generate HTML\")\n has_pygments = False\n\n\nclass FunctionHtmlFormatter(HtmlFormatter):\n \"\"\"Custom HTML formatter to insert extra information with the lines.\"\"\"\n def __init__(self, lines, **kwargs):\n HtmlFormatter.__init__(self, **kwargs)\n self.lines = lines\n\n def wrap(self, source, outfile):\n for i, (c, t) in enumerate(HtmlFormatter.wrap(self, source, outfile)):\n as_functions = self.lines.get(i-1, None)\n if as_functions is not None:\n yield 0, ('div title=%s style=\"background: #ccffcc\"[%2d]' %\n (quoteattr('as ' + ', '.join(as_functions)),\n len(as_functions)))\n else:\n yield 0, ' '\n yield c, t\n if as_functions is not None:\n yield 0, '/div'\n\n\nclass SourceFile:\n def __init__(self, path):\n self.path = path\n self.lines = {}\n\n def mark_line(self, lineno, as_func=None):\n line = self.lines.setdefault(lineno, set())\n if as_func is not None:\n as_func = as_func.split(\"'\", 1)[0]\n line.add(as_func)\n\n def write_text(self, fd):\n source = open(self.path, \"r\")\n for i, line in enumerate(source):\n if i + 1 in self.lines:\n fd.write(\" \")\n else:\n fd.write(\"! \")\n fd.write(line)\n source.close()\n\n def write_html(self, fd):\n source = open(self.path, 'r')\n code = source.read()\n lexer = CLexer()\n formatter = FunctionHtmlFormatter(\n self.lines,\n full=True,\n linenos='inline')\n fd.write(highlight(code, lexer, formatter))\n source.close()\n\n\nclass SourceFiles:\n def __init__(self):\n self.files = {}\n self.prefix = None\n\n def get_file(self, path):\n if path not in self.files:\n self.files[path] = SourceFile(path)\n if self.prefix is None:\n self.prefix = path\n else:\n self.prefix = os.path.commonprefix([self.prefix, path])\n return self.files[path]\n\n def clean_path(self, path):\n path = path[len(self.prefix):]\n return re.sub(r\"[^A-Za-z0-9\\.]\", '_', path)\n\n def write_text(self, root):\n for path, source in self.files.items():\n fd = open(os.path.join(root, self.clean_path(path)), \"w\")\n source.write_text(fd)\n fd.close()\n\n def write_html(self, root):\n for path, source in self.files.items():\n fd = open(os.path.join(root, self.clean_path(path) + \".html\"), \"w\")\n source.write_html(fd)\n fd.close()\n\n fd = open(os.path.join(root, 'index.html'), 'w')\n fd.write(\"html\")\n paths = sorted(self.files.keys())\n for path in paths:\n fd.write('pa href=\"%s.html\"%s/a/p' %\n (self.clean_path(path), escape(path[len(self.prefix):])))\n fd.write(\"/html\")\n fd.close()\n\n\ndef collect_stats(files, fd, pattern):\n # TODO: Handle compressed callgrind files\n line_regexs = [\n re.compile(r\"(?Plineno[0-9]+)(\\s[0-9]+)+\"),\n re.compile(r\"((jump)|(jcnd))=([0-9]+)\\s(?Plineno[0-9]+)\")\n ]\n\n current_file = None\n current_function = N" }, { "role": "assistant", "content": "one" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "x_t = (\n expand_dims(sigma_t / sigma_s, dims) * x\n - expand_dims(alpha_t * phi_1, dims) * model_s\n )\n if return_intermediate:\n return x_t, {'model_s': model_s}\n else:\n return x_t\n else:\n phi_1 = torch.expm1(h)\n if model_s is None:\n model_s = self.model_fn(x, s)\n x_t = (\n expand_dims(torch.exp(log_alpha_t - log_alpha_s), dims) * x\n - expand_dims(sigma_t * phi_1, dims) * model_s\n )\n if return_intermediate:\n return x_t, {'model_s': model_s}\n else:\n return x_t\n\n def singlestep_dpm_solver_second_update(self, x, s, t, r1=0.5, model_s=None, return_intermediate=False,\n solver_type='dpm_solver'):\n \"\"\"\n Singlestep solver DPM-Solver-2 from time `s` to time `t`.\n Args:\n x: A pytorch tensor. The initial value at time `s`.\n s: A pytorch tensor. The starting time, with the shape (x.shape[0],).\n t: A pytorch tensor. The ending time, with the shape (x.shape[0],).\n r1: A `float`. The hyperparameter of the second-order solver.\n model_s: A pytorch tensor. The model function evaluated at time `s`.\n If `model_s` is None, we evaluate the model by `x` and `s`; otherwise we directly use it.\n return_intermediate: A `bool`. If true, also return the model value at time `s` and `s1` (the intermediate time).\n solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers.\n The type slightly impacts the performance. We recommend to use 'dpm_solver' type.\n Returns:\n x_t: A pytorch tensor. The approximated solution at time `t`.\n \"\"\"\n if solver_type not in ['dpm_solver', 'taylor']:\n raise ValueError(\"'solver_type' must be either 'dpm_solver' or 'taylor', got {}\".format(solver_type))\n if r1 is None:\n r1 = 0.5\n ns = self.noise_schedule\n dims = x.dim()\n lambda_s, lambda_t = ns.marginal_lambda(s), ns.marginal_lambda(t)\n h = lambda_t - lambda_s\n lambda_s1 = lambda_s + r1 * h\n s1 = ns.inverse_lambda(lambda_s1)\n log_alpha_s, log_alpha_s1, log_alpha_t = ns.marginal_log_mean_coeff(s), ns.marginal_log_mean_coeff(\n s1), ns.marginal_log_mean_coeff(t)\n sigma_s, sigma_s1, sigma_t = ns.marginal_std(s), ns.marginal_std(s1), ns.marginal_std(t)\n alpha_s1, alpha_t = torch.exp(log_alpha_s1), torch.exp(log_alpha_t)\n\n if self.predict_x0:\n phi_11 = torch.expm1(-r1 * h)\n phi_1 = torch.expm1(-h)\n\n if model_s is None:\n model_s = self.model_fn(x, s)\n x_s1 = (\n expand_dims(sigma_s1 / sigma_s, dims) * x\n - expand_dims(alpha_s1 * phi_11, dims) * model_s\n )\n model_s1 = self.model_fn(x_s1, s1)\n if solver_type == 'dpm_solver':\n x_t = (\n expand_dims(sigma_t / sigma_s, dims) * x\n - expand_dims(alpha_t * phi_1, dims) * model_s\n - (0.5 / r1) * expand_dims(alpha_t * phi_1, dims) * (model_s1 - model_s)\n )\n elif solver_type == 'taylor':\n x_t = (\n expand_dims(sigma_t / sigma_s, dims) * x\n - expand_dims(alpha_t * phi_1, dims) * model_s\n + (1. / r1) * expand_dims(alpha_t * ((torch.exp(-h) - 1.) / h + 1.), dims) * (\n model_s1 - model_s)\n )\n else:\n phi_11 = torch.expm1(r1 * h)\n phi_1 = torch.expm1(h)\n\n if model_s is None:\n model_s = self.model_fn(x, s)\n x_s1 = (\n expand_dims(torch.exp(log_alpha_s1 - log_alpha_s), dims) * x\n - expand_dims(sigma_s1 * phi_11, dims) * model_s\n )\n model_s1 = self.model_fn(x_s1, s1)\n if solver_type == 'dpm_solver':\n x_t = (\n expand_dims(torch.exp(log_alpha_t - log_alpha_s), dims) * x\n - expand_dims(sigma_t * phi_1, dims) * model_s\n - (0.5 / r1) * expand_dims(sigma_t * phi_1, dims) * (model_s1 - model_s)\n )\n elif solver_type == 'taylor':\n x_t = (\n expand_dims(torch.exp(log_alpha_t - log_alpha_s), dims) * x\n - expand_dims(sigma_t * phi_1, dims) * model_s\n - (1. / r1) * expand_dims(sigma_t * ((torch.exp(h) - 1.) / h - 1.), dims) * (model_s1 - model_s)\n )\n if return_intermediate:\n return x_t, {'model_s': model_s, 'model_s1': model_s1}\n else:\n return x_t\n\n def singlestep_dpm_solver_third_update(self, x, s, t, r1=1. / 3., r2=2. / 3., model_s=None, model_s1=None,\n return_intermediate=False, solver_type='dpm_solver'):\n \"\"\"\n Singlestep solver DPM-Solver-3 from time `s` to time `t`.\n Args:\n x: A pytorch tensor. The initial value at time `s`.\n s: A pytorch tensor. The starting time, with the shape (x.shape[0],).\n t: A pytorch tensor. The ending time, with the shape (x.shape[0],).\n r1: A `float`. The hyperparameter of the third-order solver.\n r2: A `float`. The hyperparameter of the third-order solver.\n model_s: A pytorch tensor. The model function evaluated at time `s`.\n If `model_s` is None, we evaluate the model by `x` and `s`; otherwise we directly use it.\n model_s1: A pytorch tensor. The model function evaluated at time `s1` (the intermediate time given by `r1`).\n If `model_s1` is None, we evaluate the model at `s1`; otherwise we directly use it.\n return_intermediate: A `bool`. If true, also return the model value at time `s`, `s1` and `s2` (the intermediate times).\n solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers.\n The type slightly impacts the performance. We recommend to use 'dpm_solver' type.\n Returns:\n x_t: A pytorch tensor. The approximated solution at time `t`.\n \"\"\"\n if solver_type not in ['dpm_solver', 'taylor']:\n raise ValueError(\"'solver_type' must be either 'dpm_solver' or 'taylor', got {}\".format(solver_type))\n if r1 is None:\n r1 = 1. / 3.\n if r2 is None:\n r2 = 2. / 3.\n ns = self.noise_schedule\n dims = x.dim()\n lambda_s, lambda_t = ns.marginal_lambda(s), ns.marginal_lambda(t)\n h = lambda_t - lambda_s\n lambda_s1 = lambda_s + r1 * h\n lambda_s2 = lambda_s + r2 * h\n s1 = ns.inverse_lambda(lambda_s1)\n s2 = ns.inverse_lambda(lambda_s2)\n log_alpha_s, log_alpha_s1, log_alpha_s2, log_alpha_t = ns.marginal_log_mean_coeff(\n s), ns.marginal_log_mean_coeff(s1), ns.marginal_log_mean_coeff(s2), ns.marginal_log_mean_coeff(t)\n sigma_s, sigma_s1, sigma_s2, sigma_t = ns.marginal_std(s), ns.marginal_std(s1), ns.marginal_std(\n s2), ns.marginal_std(t)\n alpha_s1, alpha_s2, alpha_t = torch.exp(log_alpha_s1), torch.exp(log_alpha_s2), torch.exp(log_alpha_t)\n\n if self.predict_x0:\n phi_11 = torch.expm1(-r1 * h)\n phi_12 = torch.expm1(-r2 * h)\n phi_1 = torch.expm1(-h)\n phi_22 = torch.expm1(-r2 * h) / (r2 * h) + 1.\n phi_2 = phi_1 / h + 1.\n phi_3 = phi_2 / h - 0.5\n\n if model_s is None:\n model_s = self.mode" }, { "role": "assistant", "content": "l_fn(x, s)\n if model_s1 is None:\n x_s1 = (\n expand_dims(sigma_s1 / sigma_s, dims) * x\n - expand_dims(alpha_s1 * phi_11, dims) * model_s\n )\n model_s1 = self.model_fn(x_s1, s1)\n x_s2 = (\n expand_dims(sigma_s2 / sigma_s, dims) * x\n - expand_dims(alpha_s2 * phi_12, dims) * model_s\n + r2 / r1 * expand_dims(alpha_s2 * phi_22, dims) * (model_s1 - model_s)\n )\n model_s2 = self.model_fn(x_s2, s2)\n if solver_type == 'dpm_solver':\n x_t = (\n expand_dims(sigma_t / sigma_s, dims) * x\n - expand_dims(alpha_t * phi_1, dims) * model_s\n + (1. / r2) * expand_dims(alpha_t * phi_2, dims) * (model_s2 - model_s)\n )\n elif solver_type == 'taylor':\n D1_0 = (1. / r1) * (model_s1 - model_s)\n D1_1 = (1. / r2) * (model_s2 - model_s)\n D1 = (r2 * D1_0 - r1 * D1_1) / (r2 - r1)\n D2 = 2. * (D1_1 - D1_0) / (r2 - r1)\n x_t = (\n expand_dims(sigma_t / sigma_s, dims) * x\n - expand_dims(alpha_t * phi_1, dims) * model_s\n + expand_dims(alpha_t * phi_2, dims) * D1\n - expand_dims(alpha_t * phi_3, dims) * D2\n )" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "temperature=0.12\n )\n \n # complete the prompt\n result = client.complete(request, model=model_name)\n \"\"\"\n response = self._post_request(\"complete\", request, model)\n return CompletionResponse.from_json(response)\n\n def tokenize(\n self,\n request: TokenizationRequest,\n model: str,\n ) - TokenizationResponse:\n \"\"\"Tokenizes the given prompt for the given model.\n\n Parameters:\n request (TokenizationRequest, required):\n Parameters for the requested tokenization.\n\n model (string, required):\n Name of model to use. A model name refers to a model architecture (number of parameters among others).\n Always the latest version of model is used.\n\n Examples:\n request = TokenizationRequest(\n prompt=\"hello\", token_ids=True, tokens=True\n )\n response = client.tokenize(request, model=model_name)\n \"\"\"\n response = self._post_request(\n \"tokenize\",\n request,\n model,\n )\n return TokenizationResponse.from_json(response)\n\n def detokenize(\n self,\n request: DetokenizationRequest,\n model: str,\n ) - DetokenizationResponse:\n \"\"\"Detokenizes the given prompt for the given model.\n\n Parameters:\n request (DetokenizationRequest, required):\n Parameters for the requested detokenization.\n\n model (string, required):\n Name of model to use. A model name refers to a model architecture (number of parameters among others).\n Always the latest version of model is used.\n\n Examples:\n request = DetokenizationRequest(token_ids=[2, 3, 4])\n response = client.detokenize(request, model=model_name)\n \"\"\"\n response = sel" }, { "role": "assistant", "content": "f._post_request(\n \"detokenize\",\n request,\n model,\n )\n return DetokenizationResponse.from_json(response)" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "elf.all_negative_prompts]\n\n self.main_prompt = self.all_prompts[0]\n self.main_negative_prompt = self.all_negative_prompts[0]\n\n def cached_params(self, required_prompts, steps, extra_network_data, hires_steps=None, use_old_scheduling=False):\n \"\"\"Returns parameters that invalidate the cond cache if changed\"\"\"\n\n return (\n required_prompts,\n steps,\n hires_steps,\n use_old_scheduling,\n opts.CLIP_stop_at_last_layers,\n shared.sd_model.sd_checkpoint_info,\n extra_network_data,\n opts.sdxl_crop_left,\n opts.sdxl_crop_top,\n self.width,\n self.height,\n )\n\n def get_conds_with_caching(self, function, required_prompts, steps, caches, extra_network_data, hires_steps=None):\n \"\"\"\n Returns the result of calling function(shared.sd_model, required_prompts, steps)\n using a cache to store the result if the same arguments have been used before.\n\n cache is an array containing two elements. The first element is a tuple\n representing the previously used arguments, or None if no arguments\n have been used before. The second element is where the previously\n computed result is stored.\n\n caches is a list with items described above.\n \"\"\"\n\n if shared.opts.use_old_scheduling:\n old_schedules = prompt_parser.get_learned_conditioning_prompt_schedules(required_prompts, steps, hires_steps, False)\n new_schedules = prompt_parser.get_learned_conditioning_prompt_schedules(required_prompts, steps, hires_steps, True)\n if old_schedules != new_schedules:\n self.extra_generation_params[\"Old prompt editing timelines\"] = True\n\n cached_params = self.cached_params(required_prompts, steps, extra_network_data, hires_steps, shared.opts.use_old_scheduling)\n\n for cache in caches:\n if cache[0] is not None and cached_params == cache[0]:\n return cache[1]\n\n cache = caches[0]\n\n with devices.autocast():\n cache[1] = function(shared.sd_model, required_prompts, steps, hires_steps, shared.opts.use_old_scheduling)\n\n cache[0] = cached_params\n return cache[1]\n\n def setup_conds(self):\n prompts = prompt_parser.SdConditioning(self.prompts, width=self.width, height=self.height)\n negative_prompts = prompt_parser.SdConditioning(self.negative_prompts, width=self.width, height=self.height, is_negative_prompt=True)\n\n sampler_config = sd_samplers.find_sampler_config(self.sampler_name)\n total_steps = sampler_config.total_steps(self.steps) if sampler_config else self.steps\n self.step_multiplier = total_steps // self.steps\n self.firstpass_steps = total_steps\n\n self.uc = self.get_conds_with_caching(prompt_parser.get_learned_conditioning, negative_prompts, total_steps, [self.cached_uc], self.extra_network_data)\n self.c = self.get_conds_with_caching(prompt_parser.get_multicond_learned_conditioning, prompts, total_steps, [self.cached_c], self.extra_network_data)\n\n def get_conds(self):\n return self.c, self.uc\n\n def parse_extra_network_prompts(self):\n self.prompts, self.extra_network_data = extra_networks.parse_prompts(self.prompts)\n\n def save_samples(self) - bool:\n \"\"\"Returns whether generated images need to be written to disk\"\"\"\n return opts.samples_save and not self.do_not_save_samples and (opts.save_incomplete_images or not state.interrupted and not state.skipped)\n\n\nclass Processed:\n def __init__(self, p: StableDiffusionProcessing, images_list, seed=-1, info=\"\", subseed=None, all_prompts=None, all_negative_prompts=None, all_seeds=None, all_subseeds=None, index_of_first_image=0, infotexts=None, comments=\"\"):\n self.images = images_list\n self.prompt = p.prompt\n self.negative_prompt = p.negative_prompt\n self.seed = seed\n self.subseed = subseed\n self.subseed_strength = p.subseed_strength\n self.info = info\n self.comments = \"\".join(f\"{comment}\\n\" for comment in p.comments)\n self.width = p.width\n self.height = p.height\n self.sampler_name = p.sampler_name\n self.cfg_scale = p.cfg_scale\n self.image_cfg_scale = getattr(p, 'image_cfg_scale', None)\n self.steps = p.steps\n self.batch_size = p.batch_size\n self.restore_faces = p.restore_faces\n self.face_restoration_model = opts.face_restoration_model if p.restore_faces else None\n self.sd_model_name = p.sd_model_name\n self.sd_model_hash = p.sd_model_hash\n self.sd_vae_name = p.sd_vae_name\n self.sd_vae_hash = p.sd_vae_hash\n self.seed_resize_from_w = p.seed_resize_from_w\n self.seed_resize_from_h = p.seed_resize_from_h\n self.den" }, { "role": "assistant", "content": "oising_strength = getattr(p, 'denoising_strength', None)\n self.extra_generation_params = p.extra_generation_params\n self.index_of_first_image = index_of_first_image\n self.styles = p.styles\n self.job_timestamp = state.job_timestamp\n self.clip_skip = opts.CLIP_stop_at_last_layers\n self.token_merging_ratio = p.token_merging_ratio\n self.token_merging_ratio_hr = p.token_merging_ratio_hr\n\n self.eta = p.eta\n self.ddim_discretize = p.ddim_discretize\n self.s_churn = p.s_churn\n self.s_tmin = p.s_tmin\n self.s_tmax = p.s_tmax\n self.s_noise = p.s_noise\n self.s_min_uncond = p.s_min_uncond\n self.sampler_noise_scheduler_override = p.sampler_noise_scheduler_override\n self.prompt = self.prompt if not isinstance(self.prompt, list) else self.prompt[0]\n self.negative_prompt = self.negative_prompt if not isinstance(self.negative_prompt, list) else self.negative_prompt[0]\n self.seed = int(self.seed if not isinstance(self.seed, list) else self.seed[0]) if self.seed is not None else -1\n self.subseed = int(self.subseed if not isinstance(self.subseed, list) else self.subseed[0]) if self.subseed is not None else -1\n self.is_using_inpainting_conditioning = p.is_using_inpainting_conditioning\n\n self.all_prompts = all_prompts or p.all_prompts or [self.prompt]\n self.all_negative_prompts = all_negative_prompts or p.all_negative_prompts or [self.negative_prompt]\n self.all_seeds = all_seeds or p.all_seeds or [self.seed]\n self.all_subseeds = all_subseeds or p.all_subseeds or [self.subseed]\n self.infotexts = infotexts or [info]" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "# Authors: Lars Buitinck\n# Dan Blanchard dblanchard@ets.org\n# License: BSD 3 clause\n\nfrom array import array\nfrom collections.abc import Iterable, Mapping\nfrom numbers import Number\nfrom operator import itemgetter\n\nimport numpy as np\nimport scipy.sparse as sp\n\nfrom ..base import BaseEstimator, TransformerMixin, _fit_context\nfrom ..utils import check_array\nfrom ..utils.validation import check_is_fitted\n\n\nclass DictVectorizer(TransformerMixin, BaseEstimator):\n \"\"\"Transforms lists of feature-value mappings to vectors.\n\n This transformer turns lists of mappings (dict-like objects) of feature\n names to feature values into Numpy arrays or scipy.sparse matrices for use\n with scikit-learn estimators.\n\n When feature values are strings, this transformer will do a binary one-hot\n (aka one-of-K) coding: one boolean-valued feature is constructed for each\n of the possible string values that the feature can take on. For instance,\n a feature \"f\" that can take on the values \"ham\" and \"spam\" will become two\n features in the output, one signifying \"f=ham\", the other \"f=spam\".\n\n If a feature value is a sequence or set of " }, { "role": "assistant", "content": "strings, this transformer\n will iterate over the values and will count the occurrences of each string\n value." } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "ta_put_form or raw_data_patch_form\n\n response_headers = dict(sorted(response.items()))\n renderer_content_type = ''\n if renderer:\n renderer_content_type = '%s' % renderer.media_type\n if renderer.charset:\n renderer_content_type += ' ;%s' % renderer.charset\n response_headers['Content-Type'] = renderer_content_type\n\n if getattr(view, 'paginator', None) and view.paginator.display_page_controls:\n paginator = view.paginator\n else:\n paginator = None\n\n csrf_cookie_name = settings.CSRF_COOKIE_NAME\n csrf_header_name = settings.CSRF_HEADER_NAME\n if csrf_header_name.startswith('HTTP_'):\n csrf_header_name = csrf_header_name[5:]\n csrf_header_name = csrf_header_name.replace('_', '-')\n\n return {\n 'content': self.get_content(renderer, data, accepted_media_type, renderer_context),\n 'code_style': pygments_css(self.code_style),\n 'view': view,\n 'request': request,\n 'response': response,\n 'user': request.user,\n 'description': self.get_description(view, response.status_code),\n 'name': self.get_name(view),\n 'version': VERSION,\n 'paginator': paginator,\n 'breadcrumblist': self.get_breadcrumbs(request),\n 'allowed_methods': view.allowed_methods,\n 'available_formats': [renderer_cls.format for renderer_cls in view.renderer_classes],\n 'response_headers': response_headers,\n\n 'put_form': self.get_rendered_html_form(data, view, 'PUT', request),\n 'post_form': self.get_rendered_html_form(data, view, 'POST', request),\n 'delete_form': self.get_rendered_html_form(data, view, 'DELETE', request),\n 'options_form': self.get_rendered_html_form(data, view, 'OPTIONS', request),\n\n 'extra_actions': self.get_extra_actions(view, response.status_code),\n\n 'filter_form': self.get_filter_form(data, view, request),\n\n 'raw_data_put_form': raw_data_put_form,\n 'raw_data_post_form': raw_data_post_form,\n 'raw_data_patch_form': raw_data_patch_form,\n 'raw_data_put_or_patch_form': raw_data_put_or_patch_form,\n\n 'display_edit_forms': bool(response.status_code != 403),\n\n 'api_settings': api_settings,\n 'csrf_cookie_name': csrf_cookie_name,\n 'csrf_header_name': csrf_header_name\n }\n\n def render(self, data, accepted_media_type=None, renderer_context=None):\n \"\"\"\n Render the HTML for the browsable API representation.\n \"\"\"\n self.accepted_media_type = accepted_media_type or ''\n self.renderer_context = renderer_context or {}\n\n template = loader.get_template(self.template)\n context = self.get_context(data, accepted_media_type, renderer_context)\n ret = template.render(context, request=renderer_context['request'])\n\n # Munge DELETE Response code to allow us to return content\n # (Do this *after* we've rendered the template so that we include\n # the normal deletion response code in the output)\n response = renderer_context['response']\n if response.status_code == status.HTTP_204_NO_CONTENT:\n response.status_code = status.HTTP_200_OK\n\n return ret\n\n\nclass AdminRenderer(BrowsableAPIRenderer):\n template = 'rest_framework/admin.html'\n format = 'admin'\n\n def render(self, data, accepted_media_type=None, renderer_context=None):\n s" }, { "role": "assistant", "content": "elf.accepted_media_type = accepted_media_type or ''\n self.renderer_context = renderer_context or {}" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "import platform\nimport unittest\n\nimport numpy as np\nimport pandas as pd\nimport sympy\n\nfrom .. import PySRRegressor, sympy2torch\n\n# Need to initialize Julia before importing torch...\n\n\ndef _import_torch():\n if platform.system() == \"Darwin\":\n # Import PyJulia, then Torch\n from ..julia_helpers import init_julia\n\n init_julia()\n\n import torch\n else:\n # Import Torch, then PyJulia\n # https://github.com/pytorch/pytorch/issues/78829\n import torch\n return torch\n\n\nclass TestTorch(unittest.TestCase):\n def setUp(self):\n np.random.seed(0)\n\n def test_sympy2torch(self):\n torch = _import_torch()\n x, y, z = sympy.symbols(\"x y z\")\n cosx = 1.0 * sympy.cos(x) + y\n\n X = torch.tensor(np.random.randn(1000, 3))\n true = 1.0 * torch.cos(X[:, 0]) + X[:, 1]\n torch_module = sympy2torch(cosx, [x, y, z])\n self.assertTrue(\n np.all(np.isclose(torch_module(X).detach().numpy(), true.detach().numpy()))\n )\n\n def test_pipeline_pandas(self):\n torch = _import_torch()\n X = pd.DataFrame(np.random.randn(100, 10))\n y = np.ones(X.shape[0])\n model = PySRRegressor(\n progress=False,\n max_evals=10000,\n model_selection=\"accuracy\",\n extra_sympy_mappings={},\n output_torch_format=True,\n )\n model.fit(X, y)\n\n equations = pd.DataFrame(\n {\n \"Equation\": [\"1.0\", \"cos(x1)\", \"square(cos(x1))\"],\n \"Loss\": [1.0, 0.1, 1e-5],\n \"Complexity\": [1, 2, 3],\n }\n )\n\n equations[\"Complexity Loss Equation\".split(\" \")].to_csv(\n \"equation_file.csv.bkup\"\n )\n\n m" }, { "role": "assistant", "content": "odel.refresh(checkpoint_file=\"equation_file.csv\")\n tformat = model.pytorch()\n self.assertEqual(str(tformat), \"_SingleSymPyModule(expression=cos(x1)**2)\")\n\n np.testing.assert_almost_equal(\n tformat(torch.tensor(X.values)).detach().numpy(),\n np.square(np.cos(X.values[:, 1])), # Selection 1st feature\n decimal=3,\n )" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "# Copyright (c) OpenMMLab. All rights reserved.\nimport numbers\nfrom math import cos, pi\n\nimport annotator." }, { "role": "assistant", "content": "uniformer.mmcv as mmcv" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.tree import DecisionTreeClassifier\nfrom ipywidgets import interact\n\n\ndef visualize_tree(estimator, X, y, boundaries=True,\n xlim=None, ylim=None, ax=None):\n ax = ax or plt.gca()\n \n # Plot the training points\n ax.scatter(X[:, 0], X[:, 1], c=y, s=30, cmap='viridis',\n clim=(y.min(), y.max()), zorder=3)\n ax.axis('tight')\n ax.axis('off')\n if xlim is None:\n xlim = ax.get_xlim()\n if ylim is None:\n ylim = ax.get_ylim()\n \n # fit the estimator\n estimator.fit(X, y)\n xx, yy = np.meshgrid(np.linspace(*xlim, num=200),\n np.linspace(*ylim, num=200))\n Z = estimator.predict(np.c_[xx.ravel(), yy.ravel()])\n\n # Put the result into a color plot\n n_classes = len(np.unique(y))\n Z = Z.reshape(xx.shape)\n contours = ax.contourf(xx, yy, Z, alpha=0.3,\n levels=np.arange(n_classes + 1) - 0.5,\n cmap='viridis', clim=(y.min(), y.max()),\n zorder=1)\n\n ax.set(xlim=xlim, ylim=ylim)\n \n # Plot the decision boundaries\n def plot_boundaries(i, xlim, ylim):\n if i = 0:\n tree = estimator.tree_\n \n if tree.feature[i] == 0:\n ax.plot([tree.threshold[i], tree.threshold[i]], ylim, '-k', zorder=2)\n plot_boundaries(tree.children_left[i],\n [xlim[0], tree.threshold[i]], ylim)\n plot_boundaries(tree.children_right[i],\n [tree.threshold[i], xlim[1]], ylim)\n \n elif tree.feature[i] == 1:\n ax.plot(xlim, [tree.threshold[i], tree.threshold[i]], '-k', zorder=2)\n plot_boundaries(tree.children_left[i], xlim,\n [ylim[0], tree.threshold[i]])\n plot_boundaries(tree.children_right[i], xlim,\n [tree.threshold[i], ylim[1]])\n \n if boundaries:\n plot_boundaries(0, xlim, ylim)\n\n\ndef plot_tree_interactive(X, y):\n def interactive_tree(depth=5):\n clf = DecisionTreeClassifier(max_depth=depth, random_state=0)\n visualize_tree(clf, X, y)\n\n return interact(interactive_tree, depth=[1, 5])\n\n\ndef randomized_tree_interactive(X, y):\n N = int(0.75 * X.shape[0])\n \n xlim = (X[:, 0].min(), X[:, 0].max())\n ylim = (X[:, 1].min(), X[:, 1].max())\n \n def fit_randomized_tree(random_state=0):\n clf = DecisionTreeClassifier(max_depth=15)\n " }, { "role": "assistant", "content": " i = np.arange(len(y))\n rng = np.random.RandomState(random_state)\n rng.shuffle(i)\n visualize_tree(clf, X[i[:N]], y[i[:N]], boundaries=False,\n xlim=xlim, ylim=ylim)\n \n interact(fit_randomized_tree, random_state=[0, 100]);" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": " [0, 1, 2, 3, 4, 5, 6],\n ]\n\n @classmethod\n def Colors(cls):\n \"\"\"Returns the list of colors.\n \"\"\"\n return cls.colors\n\n @classmethod\n def ColorGenerator(cls, n):\n \"\"\"Returns an iterator of color strings.\n\n n: how many colors will be used\n \"\"\"\n for i in cls.which_colors[n]:\n yield cls.colors[i]\n raise StopIteration('Ran out of colors in _Brewer.ColorGenerator')\n\n @classmethod\n def InitializeIter(cls, num):\n \"\"\"Initializes the color iterator with the given number of colors.\"\"\"\n cls.color_iter = cls.ColorGenerator(num)\n\n @classmethod\n def ClearIter(cls):\n \"\"\"Sets the color iterator to None.\"\"\"\n cls.color_iter = None\n\n @classmethod\n def GetIter(cls):\n \"\"\"Gets the color iterator.\"\"\"\n if cls.color_iter is None:\n cls.InitializeIter(7)\n\n return cls.color_iter\n\n\ndef PrePlot(num=None, rows=None, cols=None):\n \"\"\"Takes hints about what's coming.\n\n num: number of lines that will be plotted\n rows: number of rows of subplots\n cols: number of columns of subplots\n \"\"\"\n if num:\n _Brewer.InitializeIter(num)\n\n if rows is None and cols is None:\n return\n\n if rows is not None and cols is None:\n cols = 1\n\n if cols is not None and rows is None:\n rows = 1\n\n # resize the image, depending on the number of rows and cols\n size_map = {(1, 1): (8, 6),\n (1, 2): (14, 6),\n (1, 3): (14, 6),\n (2, 2): (10, 10),\n (2, 3): (16, 10),\n (3, 1): (8, 10),\n }\n\n if (rows, cols) in size_map:\n fig = pyplot.gcf()\n fig.set_size_inches(*size_map[rows, cols])\n\n # create the first subplot\n if rows 1 or cols 1:\n pyplot.subplot(rows, cols, 1)\n global SUBPLOT_ROWS, SUBPLOT_COLS\n SUBPLOT_ROWS = rows\n SUBPLOT_COLS = cols\n\n\ndef SubPlot(plot_number, rows=None, cols=None):\n \"\"\"Configures the number of subplots and changes the current plot.\n\n rows: int\n cols: int\n plot_number: int\n \"\"\"\n rows = rows or SUBPLOT_ROWS\n cols = cols or SUBPLOT_COLS\n pyplot.subplot(rows, cols, plot_number)\n\n\ndef _Underride(d, **options):\n \"\"\"Add key-value pairs to d only if key is not in d.\n\n If d is None, create a new dictionary.\n\n d: dictionary\n options: keyword args to add to d\n \"\"\"\n if d is None:\n d = {}\n\n for key, val in options.items():\n d.setdefault(key, val)\n\n return d\n\n\ndef Clf():\n \"\"\"Clears the figure and any hints that have been set.\"\"\"\n global LOC\n LOC = None\n _Brewer.ClearIter()\n pyplot.clf()\n fig = pyplot.gcf()\n fig.set_size_inches(8, 6)\n\n\ndef Figure(**options):\n \"\"\"Sets options for the current figure.\"\"\"\n _Underride(options, figsize=(6, 8))\n pyplot.figure(**options)\n\n\ndef _UnderrideColor(options):\n if 'color' in options:\n return options\n\n color_iter = _Brewer.GetIter()\n\n if color_iter:\n try:\n options['color'] = next(color_iter)\n except StopIteration:\n # TODO: reconsider whether this should warn\n # warnings.warn('Warning: Brewer ran out of colors.')\n _Brewer.ClearIter()\n return options\n\n\ndef Plot(obj, ys=None, style='', **options):\n \"\"\"Plots a line.\n\n Args:\n obj: sequence of x values, or Series, or anything with Render()\n ys: sequence of y values\n style: style string passed along to pyplot.plot\n options: keyword args passed to pyplot.plot\n \"\"\"\n options = _UnderrideColor(options)\n label = getattr(obj, 'label', '_nolegend_')\n options = _Underride(options, linewidth=3, alpha=0.8, label=label)\n\n xs = obj\n if ys is None:\n if hasattr(obj, 'Render'):\n xs, ys = obj.Render()\n if isinstance(obj, pandas.Series):\n ys = obj.values\n xs = obj.index\n\n if ys is None:\n pyplot.plot(xs, style, **options)\n else:\n pyplot.plot(xs, ys, style, **options)\n\n\ndef FillBetween(xs, y1, y2=None, where=None, **options):\n \"\"\"Plots a line.\n\n Args:\n xs: sequence of x values\n y1: sequence of y values\n y2: sequence of y values\n where: sequence of boolean\n options: keyword args passed to pyplot.fill_between\n \"\"\"\n options = _UnderrideColor(options)\n options = _Underride(options, linewidth=0, alpha=0.5)\n pyplot.fill_between(xs, y1, y2, where, **options)\n\n\ndef Bar(xs, ys, **options):\n \"\"\"Plots a line.\n\n Args:\n xs: sequence of x values\n ys: sequence of y values\n options: keyword args passed to pyplot.bar\n \"\"\"\n options = _UnderrideColor(options)\n options = _Underride(options, linewidth=0, alpha=0.6)\n pyplot.bar(xs, ys, **options)\n\n\ndef Scatter(xs, ys=None, **options):\n \"\"\"Makes a scatter plot.\n\n xs: x values\n ys: y values\n options: options passed to pyplot.scatter\n \"\"\"\n options = _Underride(options, color='blue', alpha=0.2, \n s=30, edgecolors='none')\n\n if ys is None and isinstance(xs, pandas.Series):\n ys = xs.values\n xs = xs.index\n\n pyplot.scatter(xs, ys, **options)\n\n\ndef HexBin(xs, ys, **options):\n \"\"\"Makes a scatter plot.\n\n xs: x values\n ys: y values\n options: options passed to pyplot.scatter\n \"\"\"\n options = _Underride(options, cmap=matplotlib.cm.Blues)\n pyplot.hexbin(xs, ys, **options)\n\n\ndef Pdf(pdf, **options):\n \"\"\"Plots a Pdf, Pmf, or Hist as a line.\n\n Args:\n pdf: Pdf, Pmf, or Hist object\n options: keyword args passed to pyplot.plot\n \"\"\"\n low, high = options.pop('low', None), options.pop('high', None)\n n = options.pop('n', 101)\n xs, ps = pdf.Render(low=low, high=high, n=n)\n options = _Underride(options, label=pdf.label)\n Plot(xs, ps, **options)\n\n\ndef Pdfs(pdfs, **options):\n \"\"\"Plots a sequence of PDFs.\n\n Options are passed along for all PDFs. If you want different\n options for each pdf, make multiple calls to Pdf.\n \n Args:\n pdfs: sequence of PDF objects\n options: keyword args passed to pyplot.plot\n \"\"\"\n for pdf in pdfs:\n Pdf(pdf, **options)\n\n\ndef Hist(hist, **options):\n \"\"\"Plots a Pmf or Hist with a bar plot.\n\n The default width of the bars is based on the minimum difference\n between values in the Hist. If that's too small, you can override\n it by providing a width keyword argument, in the same units\n as the values.\n\n Args:\n hist: Hist or Pmf object\n options: keyword args passed to pyplot.bar\n \"\"\"\n # find the minimum distance between adjacent values\n xs, ys = hist.Render()\n\n if 'width' not in options:\n try:\n options['width'] = 0.9 * np.diff(xs).min()\n except TypeError:\n warnings.warn(\"Hist: Can't compute bar width automatically.\"\n \"Check for non-numeric types in Hist.\"\n \"Or try providing width option.\"\n )\n\n options = _Underride(options, label=hist.label)\n options = _Underride(options, align='center')\n if options['align'] == 'left':\n options['align'] = 'edge'\n elif options['align'] == 'right':\n options['align'] = 'edge'\n options['width'] *= -1\n\n Bar(xs, ys, **options)\n\n\ndef Hists(hists, **options):\n \"\"\"Plots two histograms as interleaved bar plots.\n\n Options are passed along for all PMFs. If you want different\n options for each pmf, make multiple calls to Pmf.\n\n Args:\n hists: list of two Hist or Pmf objects\n options: keyword args passed to pyplot.plot\n \"\"\"\n for hist in hists:\n Hist(hist, **options)\n\n\ndef Pmf(pmf, **options):\n \"\"\"Plots a Pmf or Hist as a line.\n\n Args:\n pmf: Hist or Pmf object\n options: keyword args passed to pyplot.plot\n \"\"\"\n xs, ys = pmf.Render()\n low, high = min(xs), max(xs)\n\n width = options.pop('width', None)\n if width is None:\n try:\n width = np.diff(xs).min()\n except TypeError:\n warnings.warn(\"Pmf: Can't compute bar width automatically.\"\n \"Check for non-numeric types in Pmf.\"\n " }, { "role": "assistant", "content": " \"Or try providing width option.\")" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "import datetime\n\nfrom django.contrib.sites.models import Site\nfrom django.http import Http404\nfrom django.template import TemplateDoesNotExist\nfrom django.test import RequestFactory, TestCase\nfrom django.test.utils import override_settings\nfrom django.views.defaults import (\n bad_request,\n page_not_found,\n permission_denied,\n server_error,\n)\n\nfrom ..models import Article, Author, UrlArticle\n\n\n@override_settings(ROOT_URLCONF=\"view_tests.urls\")\nclass DefaultsTests(TestCase):\n \"\"\"Test django views in django/views/defaults.py\"\"\"\n\n nonexistent_urls = [\n \"/nonexistent_url/\", # this is in urls.py\n \"/other_nonexistent_url/\", # this NOT in urls.py\n ]\n request_factory = RequestFactory()\n\n @classmethod\n def setUpTestData(cls):\n author = Author.objects.create(name=\"Boris\")\n Article.objects.create(\n title=\"Old Article\",\n slug=\"old_article\",\n author=author,\n date_created=datetime.datetime(2001, 1, 1, 21, 22, 23),\n )\n Article.objects.create(\n title=\"Current Article\",\n slug=\"current_article\",\n author=author,\n date_created=datetime.datetime(2007, 9, 17, 21, 22, 23),\n )\n Article.objects.create(\n title=\"Future Article\",\n slug=\"future_article\",\n author=author,\n date_created=datetime.datetime(3000, 1, 1, 21, 22, 23),\n )\n cls.urlarticle = UrlArticle.objects.create(\n title=\"Old Article\",\n slug=\"old_article\",\n author=author,\n date_created=datetime.datetime(2001, 1, 1, 21, 22, 23),\n )\n Site(id=1, domain=\"testserver\", name=\"testserver\").save()\n\n def test_page_not_found(self):\n \"A 404 status is returned by the page_not_found view\"\n for url in self.nonexistent_urls:\n response = self.client.get(url)\n self.assertEqual(response.status_code, 404)\n self.assertIn(b\"h1Not Found/h1\", response.content)\n self.assertIn(\n b\"pThe requested resource was not found on this server./p\",\n response.content,\n )\n\n @override_settings(\n TEMPLATES=[\n {\n \"BACKEND\": \"django.template.backends.django.DjangoTemplates\",\n \"OPTIONS\": {\n \"loaders\": [\n (\n \"django.template.loaders.locmem.Loader\",\n {\n \"404.html\": \"{{ csrf_token }}\",\n },\n ),\n ],\n },\n }\n ]\n )\n def test_csrf_token_in_404(self):\n \"\"\"\n The 404 page should have the csrf_token available in the context\n \"\"\"\n # See ticket #14565\n for url in self.nonexistent_urls:\n response = self.client.get(url)\n self.assertNotEqual(response.content, b\"NOTPROVIDED\")\n self.assertNotEqual(response.content, b\"\")\n\n def test_server_error(self):\n \"The server_error view raises a 500 status\"\n response = self.client.get(\"/server_error/\")\n self.assertContains(response, b\"h1Server Error (500)/h1\", status_code=500)\n\n def test_bad_request(self):\n request = self.request_factory.get(\"/\")\n response = bad_request(request, Exception())\n self.assertContains(response, b\"h1Bad Request (400)/h1\", status_code=400)\n\n @override_settings(\n TEMPLATES=[\n {\n \"BACKEND\": \"django.template.backends.django.DjangoTemplates\",\n \"OPTIONS\": {\n \"loaders\": [\n (\n \"django.template.loaders.locmem.Loader\",\n {\n \"404.html\": (\n \"This is a test template for a 404 error \"\n \"(path: {{ request_path }}, \"\n \"exception: {{ exception }}).\"\n ),\n \"500.html\": \"This is a test template for a 500 error.\",\n },\n ),\n ],\n },\n }\n ]\n )\n def test_custom_templates(self):\n \"\"\"\n 404.html and 500.html templates are picked by their respective handler.\n \"\"\"\n response = self.client.get(\"/server_error/\")\n self.assertContains(response, \"test template for a 500 error\", status_code=500)\n response = self.client.get(\"/no_such_url/\")\n self.assertContains(response, \"path: /no_such_url/\", status_code=404)\n self.assertContains(response, \"exception: Resolver404\"," }, { "role": "assistant", "content": " status_code=404)\n response = self.client.get(\"/technical404/\")\n self.assertContains(\n response, \"exception: Testing technical 404.\", status_code=404\n )" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "import numpy as np\nfrom keras.models import *\nfrom keras.layers import *\nfrom keras.applications.vgg16 import VGG16\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.optimizers import *\nfrom keras.callbacks import ModelCheckpoint\nimport cv2\n\ndef train_generator(batch_size=32):\n data_gen_args = dict(featurewise_center=True,\n rotation_range=90.,\n width_shift_range=0.1,\n height_shift_range=0.1,\n fill_mode=\"constant\",\n cval=255,\n horizontal_flip=True,\n vertical_flip=True,\n zoom_range=0.2)\n image_datagen = ImageDataGenerator(**data_gen_args)\n mask_datagen = ImageDataGenerator(**data_gen_args)\n\n seed = 1\n image_generator = image_datagen.flow_from_directory(\n 'data/train/images',\n class_mode=None,\n batch_size=batch_size,\n color_mode='rgb',\n target_size=(512,512),\n #save_to_dir='./data/gen/images',\n seed=seed)\n\n mask_generator = mask_datagen.flow_from_directory(\n 'data/train/masks',\n class_mode=None,\n color_mode='grayscale',\n target_size=(512,512),\n batch_size=batch_size,\n #save_to_dir='./data/gen/masks',\n seed=seed)\n\n # combine generators into one which yields image and masks\n train_generator = zip(image_generator, mask_" }, { "role": "assistant", "content": "generator)\n for (imgs, masks) in train_generator:\n imgs = imgs / 255.0\n masks = masks / 255.0\n yield (imgs,masks)" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": " dimensional case the coefficients may be thought of as stored in\n the columns of `c`.\n tensor : boolean, optional\n If True, the shape of the coefficient array is extended with ones\n on the right, one for each dimension of `x`. Scalars have dimension 0\n for this action. The result is that every column of coefficients in\n `c` is evaluated for every element of `x`. If False, `x` is broadcast\n over the columns of `c` for the evaluation. This keyword is useful\n when `c` is multidimensional. The default value is True.\n\n .. versionadded:: 1.7.0\n\n Returns\n -------\n values : ndarray, algebra_like\n The shape of the return value is described above.\n\n See Also\n --------\n legval2d, leggrid2d, legval3d, leggrid3d\n\n Notes\n -----\n The evaluation uses Clenshaw recursion, aka synthetic division.\n\n \"\"\"\n c = np.array(c, ndmin=1, copy=False)\n if c.dtype.char in '?bBhHiIlLqQpP':\n c = c.astype(np.double)\n if isinstance(x, (tuple, list)):\n x = np.asarray(x)\n if isinstance(x, np.ndarray) and tensor:\n c = c.reshape(c.shape + (1,)*x.ndim)\n\n if len(c) == 1:\n c0 = c[0]\n c1 = 0\n elif len(c) == 2:\n c0 = c[0]\n c1 = c[1]\n else:\n nd = len(c)\n c0 = c[-2]\n c1 = c[-1]\n for i in range(3, len(c) + 1):\n tmp = c0\n nd = nd - 1\n c0 = c[-i] - (c1*(nd - 1))/nd\n c1 = tmp + (c1*x*(2*nd - 1))/nd\n return c0 + c1*x\n\n\ndef legval2d(x, y, c):\n \"\"\"\n Evaluate a 2-D Legendre series at points (x, y).\n\n This function returns the values:\n\n .. math:: p(x,y) = \\\\sum_{i,j} c_{i,j} * L_i(x) * L_j(y)\n\n The parameters `x` and `y` are converted to arrays only if they are\n tuples or a lists, otherwise they are treated as a scalars and they\n must have the same shape after conversion. In either case, either `x`\n and `y` or their elements must support multiplication and addition both\n with themselves and with the elements of `c`.\n\n If `c` is a 1-D array a one is implicitly appended to its s" }, { "role": "assistant", "content": "hape to make\n it 2-D. The shape of the result will be c.shape[2:] + x.shape.\n\n Parameters\n ----------\n x, y : array_like, compatible objects\n The two dimensional series is evaluated at the points `(x, y)`,\n where `x` and `y` must have the same shape. If `x` or `y` is a list\n or tuple, it is first converted to an ndarray, otherwise it is left\n unchanged and if it isn't an ndarray it is treated as a scalar.\n c : array_like\n Array of coefficients ordered so that the coefficient of the term\n of multi-degree i,j is contained in ``c[i,j]``. If `c` has\n dimension greater than two the remaining indices enumerate multiple\n sets of coefficients.\n\n Returns\n -------\n values : ndarray, compatible object\n The values of the two dimensional Legendre series at points formed\n from pairs of corresponding values from `x` and `y`.\n\n See Also\n --------\n legval, leggrid2d, legval3d, leggrid3d\n\n Notes\n -----\n\n .. versionadded:: 1.7.0\n\n \"\"\"\n return pu._valnd(legval, c, x, y)" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "ents += str(blocking)+ ','\n\tcsv_contents += str(blocked_by)+ ','\n\tcsv_contents += str(uptime)+ ','\n\tcsv_contents += str(age)+ ','\n\tcsv_contents += version\n\tcsv_contents += \"\\n\"\n\n# write the instance data table to the csv file\nwith open( OUT_CSV, \"w\" ) as csv_file:\n\tcsv_file.write( csv_contents )\n\n#########################\n# RECOMMENDED INSTANCES #\n#########################\n\n# shrink the list to just a few recommended instances\nall_instances = list()\nrecommended_instances = list()\nwith open(OUT_CSV) as csv_file:\n\n\tfor instance in csv.DictReader( csv_file ):\n\t\tall_instances.append( instance )\n\n\t\t# only include instances that are \"yes\" across-the-board\n\t\tif instance['NU'] == \"Yes\" \\\n\t\t and instance['NC'] == \"Yes\" \\\n\t\t and instance['Fed'] == \"Yes\" \\\n\t\t and instance['Adult'] == \"Yes\" \\\n\t\t and instance['↓V'] == \"Yes\":\n\n\t\t\trecommended_instances.append( instance )\n\n# remove instances with too few or too may users\nrecommended_instances = [x for x in recommended_instances if int(x['Users']) 60 and int(x['Users']) 1000]\n\n# get a lits of all the instances that have more than 1 blocked instance and\n# then get the average number of instances that are blocked\ntry:\n\tbi_list = [ int(x['BI']) for x in all_instances if int(x['BI']) 1 ]\n\tbi_avg = numpy.average( bi_list )\nexcept (Exception, RuntimeWarning) as e:\n\tprint( \"WARNING: Caught numpy exception when calculating bi_avg: \" +str(e) )\n\tbi_avg = 2\n\n# get a lits of all the instances that are blocked by more than 1 instance and\n# then get the average number of that instances are are blocked\ntry:\n\tbb_list = [ int(x['BB']) for x in all_instances if int(x['BB']) 1 ]\n\tbb_avg = numpy.average( bb_list )\nexcept (Exception, RuntimeWarning) as e:\n\tprint( \"WARNING: Caught numpy exception when calculating bb_avg: \" +str(e) )\n\tbb_avg = 2\n\nprint( \"bi_avg:|\" +str(bi_avg)+ \"|\" )\nprint( \"bb_avg:|\" +str(bb_avg)+ \"|\" )\n\n# remove instances that are blocking or blocked-by too many other instancesk\nrecommended_instances = [ x for x in recommended_instances if int(x['BI']) = bi_avg and int(x['BB']) = bb_avg ]\n\n# remove instances that haven't been online for 2 months\nrecommended_instances = [ x for x in recommended_instances if int(x['MO']) = 2 ]\n\n# limit to those with the best uptime; first we make sure that we actually\n# have the uptime data\nuptime_available = [x for x in recommended_instances if x['UT'] != '??']\n\n# do we have uptime data?\nif uptime_available != list():\n\t# we have uptime data; proceed with reducing the set of recommended_instances\n\t# based on uptime\n\n\t# loop down from 100% to 0%\n\tfor percent_uptime in reversed(range(100)):\n\n\t\thigh_uptime_instances = [x for x in recommended_instances if x['UT'] != '??' and int(x['UT'][:-1]) percent_uptime]\n\n\t\t# do we have more than one instance above this uptime?\n\t\tif len(high_uptime_instances) 1:\n\t\t\t# we already have enough instances; ignore the rest with lower uptime\n\t\t\trecommended_instances = high_uptime_instances\n\t\t\tbreak\n\n# prepare data for csv file\ncsv_contents = \"Instance,NU,NC,Fed,Adult,↓V,Users,BI,BB,UT,MO,Version\\n\"\nfor instance in recommended_instances:\n\tcsv_contents += instance['Instance']+ ','\n\tcsv_contents += instance['NU']+ ','\n\tcsv_contents += instance['NC']+ ','\n\tcsv_contents += instance['Fed']+ ','\n\tcsv_contents += instance['Adult']+ ','\n\tcsv_contents += instance['↓V']+ ','\n\tcsv_contents += instance['Users']+ ','\n\tcsv_contents += instance['BI']+ ','\n\tcsv_contents += instance['BB']+ ','\n\tcsv_contents += instance['UT']+ ','\n\tcsv_contents += instance['MO']+ ','\n\tcsv_contents += instance['Version']\n\tcsv_contents += \"\\n\"\n\n# write the recommended instance data table to a csv file\nwith open( 'recommended-instances.csv', \"w\" ) as csv_file:\n\tcsv_file.write( csv_contents )\n\n# convert csv file data to markdown table\ndf = pd.read_csv( 'recommended-instances.csv' )\nrecommended_markdown_table = df.to_markdown( tablefmt='pipe', index = False )\n\n# add newline to protect the table from getting klobbered by the text around it\nrecommended_markdown_table = \"\\n\" + recommended_markdown_table + \"\\n\"\n\nreadme_contents += \"\"\"\n# Recommended Instances\n\nJust **click on a random instance** from the below \"recommended\" instances.\n\nDon't overthink this. **It doesn't matter which instance you use.** You'll still be able to interact with communities (subreddits) on all other instances, regardless of which instance your account lives 🙂\n\"\"\"\n\n# add the markdown table to the readme's contents\nreadme_contents += recommended_markdown_table\n\nreadme_contents += \"\"\"\n# What's next?\n\n## Subscribe to ~~Subreddits~~ Communities\n\nAfter you pick an instance and register an account, you'll want to subscribe to communities. You can subscribe to \"local\" communities on your instance, and (if you chose an instance that isn't siloed) you can also subscribe to \"remote\" communities on other instances.\n\nTo **find popular communities** across all lemmy instances in the fediverse, you can use the [Lemmy Community Browser](https://browse.feddit.de/) run by feddit.de.\n\n * https://browse.feddit.de/\n\nIf you want a more direct mapping of your favorite /r/subreddits to lemmy, checkout these sites:\n\n1. [redditmigration.com](https://redditmigration.com/)\n1. [sub.rehab](https://sub.rehab/?searchTerm=&visibleServices=lemmy&officialOnly=false&newOnly=false&favoriteOnly=false&sortBy=users_active_week)\n1. yoasif's [Unofficial Subreddit Migration List](https://www.quippd.com/writing/2023/06/15/unofficial-subreddit-migration-list-lemmy-kbin-etc.html)\n\n\na href=\"https://tech.michaelaltfield.net/2023/06/11/lemmy-migration-find-subreddits-communities/\"img src=\"lemmy-migration-find-subreddits-communities.jpg\" alt=\"How To Find Lemmy Communities\" //" }, { "role": "assistant", "content": "a" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "er('block3_conv3').output, block7_up])\n block7_conv1 = Conv2D(256, 3, activation='relu', padding='same', kernel_initializer='he_normal')(block7_merge)\n block7_conv2 = Conv2D(256, 3, activation='relu', padding='same', kernel_initializer='he_normal')(block7_conv1)\n block7_conv3 = Conv2D(256, 3, activation='relu', padding='same', kernel_initializer='he_normal')(block7_conv2)\n\n block8_up = Conv2D(128, 2, activation='relu', padding='same', kernel_initializer='he_normal')(\n UpSampling2D(size=(2, 2))(block7_conv3))\n block8_merge = Concatenate(axis=3)([vgg16_model.get_layer('block2_conv2').output, block8_up])\n block8_conv1 = Conv2D(128, 3, activation='relu', padding='same', kernel_initializer='he_normal')(block8_merge)\n block8_conv2 = Conv2D(128, 3, activation='relu', padding='same', kernel_initializer='he_normal')(block8_conv1)\n\n block9_up = Conv2D(64, 2, activation='relu', padding='same', kernel_initializer='he_normal')(\n UpSampling2D(size=(2, 2))(block8_conv2))\n block9_merge = Concatenate(axis=3)([vgg16_model.get_layer('block1_conv2').output, block9_up])\n block9_conv1 = Conv2D(64, 3, activation='relu', padding='same', kernel_initializer='he_normal')(block9_merge)\n block9_conv2 = Conv2D(64, 3, activation='relu', padding='same', kernel_initializer='he_normal')(block9_conv1)\n\n block10_conv1 = Conv2D(64, 3, activation='relu', padding='same', kernel_initializer='he_normal')(block9_conv2)\n block10_conv2 = Conv2D(1, 1, activation='sigmoid')(block10_conv1)\n\n model = Model(inputs=vgg16_model.input, outputs=block10_conv2)\n return model\n\n\nif __name__ == '__main__':\n is_train = False\n if is_train:\n model = vgg10_unet(input_shape=(512,512,3), weights='imagenet')\n\n for index in range(15):\n model.layers[index].trainable = True\n model.compile(optimizer=Adam(lr=1e-4), loss='binary_crossentropy', metrics=['accuracy'])\n model_checkpoint = ModelCheckpoint('unet.h5', monitor='loss', verbose=1, save_best_only=True)\n model.fit_generator(train_generator(batch_size=4),\n steps_per_epoch=200,\n epochs=50,\n validation_data=train_generator(ba" }, { "role": "assistant", "content": "tch_size=4),\n validation_steps=50,\n callbacks=[model_checkpoint])" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "t importer\nfrom tensorflow.python.framework import meta_graph\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.framework import tensor_spec\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.grappler import tf_optimizer\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import control_flow_util\nfrom tensorflow.python.ops import control_flow_util_v2\nfrom tensorflow.python.ops import control_flow_v2_toggles\nfrom tensorflow.python.ops import custom_gradient\nfrom tensorflow.python.ops import gen_array_ops\nfrom tensorflow.python.ops import gen_list_ops\nfrom tensorflow.python.ops import gradient_checker_v2\nfrom tensorflow.python.ops import gradients_impl\nfrom tensorflow.python.ops import list_ops\nfrom tensorflow.python.ops import map_fn\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import random_ops\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.ops import while_loop\nfrom tensorflow.python.ops import while_v2\nfrom tensorflow.python.ops.ragged import ragged_factory_ops\nfrom tensorflow.python.ops.ragged import ragged_tensor\nfrom tensorflow.python.ops.while_v2 import while_loop as while_loop_v2\nfrom tensorflow.python.platform import test\n\n\ndef random_gamma(shape): # pylint: disable=invalid-name\n return random_ops.random_gamma(shape, 1.0)\n\n\ndef random_gamma_with_alpha_beta(shape): # pylint: disable=invalid-name\n return random_ops.random_gamma(\n shape, alpha=[[1.], [3.], [5.], [6.]], beta=[[3., 4.]])\n\n\ndef random_poisson_v2(shape): # pylint: disable=invalid-name\n return random_ops.random_poisson_v2(shape, 1.0)\n\n\ndef random_poisson_v2_with_lam(shape): # pylint: disable=invalid-name\n return random_ops.random_poisson_v2(shape, [12.2, 3.3])\n\n\ndef fill(shape): # pylint: disable=invalid-name\n return array_ops.fill(shape, 1.0)\n\n\nclass WhileV2Test(test.TestCase, parameterized.TestCase):\n\n @test_util.run_deprecated_v1\n def testSingleLoopVar(self):\n x = constant_op.constant(2.)\n ret = while_loop_v2(\n lambda v: v 8., lambda v: v * v, [x], return_same_structure=False)\n grad = gradients_impl.gradients(ret, [x])\n with self.cached_session():\n self.assertEqual(self.evaluate(ret), 16.)\n self.assertSequenceEqual(self.evaluate(grad), [32.])\n\n @test_util.run_deprecated_v1\n def testSingleLoopVarBackPropFalse(self):\n x = constant_op.constant(2.)\n ret = while_loop_v2(\n lambda v: v 8.,\n lambda v: v * v, [x],\n return_same_structure=False,\n back_prop=False)\n grad = gradients_impl.gradients(ret, [x])\n self.assertEqual(grad, [None])\n with self.cached_session():\n self.assertEqual(self.evaluate(ret), 16.)\n\n @test_util.run_deprecated_v1\n def testCustomGradient(self):\n x = constant_op.constant(2.)\n n = constant_op.constant(1., name=\"const-n\")\n m = variables.Variable(1.0)\n self.evaluate(variables.global_variables_initializer())\n\n def body_fn(v): # pylint: disable=invalid-name\n\n @custom_gradient.custom_gradient\n def inner_fn(v): # pylint: disable=inva" }, { "role": "assistant", "content": "lid-name\n\n def grad_fn(dy, variables=None): # pylint: disable=invalid-name, unused-argument, redefined-outer-name\n return dy * 2 * v * n * m, [v * v]\n\n return v * v * m, grad_fn\n\n return inner_fn(v)" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "redirect(\n url_for(\"{0}_redirect_n_times\".format(kind), n=n - 1, _external=external)\n )\n\n\n@app.route(\"/redirect-to\", methods=[\"GET\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\", \"TRACE\"])\ndef redirect_to():\n \"\"\"302/3XX Redirects to the given URL.\n ---\n tags:\n - Redirects\n produces:\n - text/html\n get:\n parameters:\n - in: query\n name: url\n type: string\n required: true\n - in: query\n name: status_code\n type: int\n post:\n consumes:\n - application/x-www-form-urlencoded\n parameters:\n - in: formData\n name: url\n type: string\n required: true\n - in: formData\n name: status_code\n type: int\n required: false\n patch:\n consumes:\n - application/x-www-form-urlencoded\n parameters:\n - in: formData\n name: url\n type: string\n required: true\n - in: formData\n name: status_code\n type: int\n required: false\n put:\n consumes:\n - application/x-www-form-urlencoded\n parameters:\n - in: formData\n name: url\n type: string\n required: true\n - in: formData\n name: status_code\n type: int\n required: false\n responses:\n 302:\n description: A redirection.\n \"\"\"\n\n args_dict = request.args.items()\n args = CaseInsensitiveDict(args_dict)\n\n # We need to build the response manually and convert to UTF-8 to prevent\n # werkzeug from \"fixing\" the URL. This endpoint should set the Location\n # header to the exact string supplied.\n response = app.make_response(\"\")\n response.status_code = 302\n if \"status_code\" in args:\n status_code = int(args[\"status_code\"])\n if status_code = 300 and status_code 400:\n response.status_code = status_code\n response.headers[\"Location\"] = args[\"url\"].encode(\"utf-8\")\n\n return response\n\n\n@app.route(\"/relative-redirect/int:n\")\ndef relative_redirect_n_times(n):\n \"\"\"Relatively 302 Redirects n times.\n ---\n tags:\n - Redirects\n parameters:\n - in: path\n name: n\n type: int\n produces:\n - text/html\n responses:\n 302:\n description: A redirection.\n \"\"\"\n\n assert n 0\n\n response = app.make_response(\"\")\n response.status_code = 302\n\n if n == 1:\n response.headers[\"Location\"] = url_for(\"view_get\")\n return response\n\n response.headers[\"Location\"] = url_for(\"relative_redirect_n_times\", n=n - 1)\n return response\n\n\n@app.route(\"/absolute-redirect/int:n\")\ndef absolute_redirect_n_times(n):\n \"\"\"Absolutely 302 Redirects n times.\n ---\n tags:\n - Redirects\n parameters:\n - in: path\n name: n\n type: int\n produces:\n - text/html\n responses:\n 302:\n description: A redirection.\n \"\"\"\n\n assert n 0\n\n if n == 1:\n return redirect(url_for(\"view_get\", _external=True))\n\n return _redirect(\"absolute\", n, True)\n\n\n@app.route(\"/stream/int:n\")\ndef stream_n_messages(n):\n \"\"\"Stream n JSON responses\n ---\n tags:\n - Dynamic data\n parameters:\n - in: path\n name: n\n type: int\n produces:\n - application/json\n responses:\n 200:\n description: Streamed JSON responses.\n \"\"\"\n response = get_dict(\"url\", \"args\", \"headers\", \"origin\")\n n = min(n, 100)\n\n def generate_stream():\n for i in range(n):\n response[\"id\"] = i\n yield json.dumps(response) + \"\\n\"\n\n return Response(generate_stream(), headers={\"Content-Type\": \"application/json\"})\n\n\n@app.route(\n \"/status/codes\", methods=[\"GET\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\", \"TRACE\"]\n)\ndef view_status_code(codes):\n \"\"\"Return status code or random status code if more than one are given\n ---\n tags:\n - Status codes\n parameters:\n - in: path\n name: codes\n produces:\n - text/plain\n responses:\n 100:\n description: Informational responses\n 200:\n description: Success\n 300:\n description: Redirection\n 400:\n description: Client Errors\n 500:\n description: Server Errors\n \"\"\"\n\n if \",\" not in codes:\n try:\n code = int(codes)\n except ValueError:\n return Response(\"Invalid status code\", status=400)\n return status_code(code)\n\n choices = []\n for choice in codes.split(\",\"):\n if \":\" not in choice:\n code = choice\n weight = 1\n else:\n code, weight = choice.split(\":\")\n\n try:\n choices.append((int(code), float(weight)))\n except ValueError:\n return Response(\"Invalid status code\", status=400)\n\n code = weighted_choice(choices)\n\n return status_code(code)\n\n\n@app.route(\"/response-headers\", methods=[\"GET\", \"POST\"])\ndef response_headers():\n \"\"\"Returns a set of response headers from the query string.\n ---\n tags:\n - Response inspection\n" }, { "role": "assistant", "content": " parameters:\n - in: query\n name: freeform\n explode: true\n allowEmptyValue: true\n schema:\n type: object\n additionalProperties:\n type: string\n style: form\n produces:\n - application/json\n responses:\n 200:\n description: Response headers\n \"\"\"" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "ue) == 1:\n value = value[0]\n d[key] = value\n response = jsonify(d)\n for key, value in headers.items(multi=True):\n response.headers.add(key, value)\n response_has_changed = response.data != original_data\n if not response_has_changed:\n break\n return response\n\n\n@app.route(\"/cookies\")\ndef view_cookies(hide_env=True):\n \"\"\"Returns cookie data.\n ---\n tags:\n - Cookies\n produces:\n - application/json\n responses:\n 200:\n description: Set cookies.\n \"\"\"\n\n cookies = dict(request.cookies.items())\n\n if hide_env and (\"show_env\" not in request.args):\n for key in ENV_COOKIES:\n try:\n del cookies[key]\n except KeyError:\n pass\n\n return jsonify(cookies=cookies)\n\n\n@app.route(\"/forms/post\")\ndef view_forms_post():\n \"\"\"Simple HTML form.\"\"\"\n\n return render_template(\"forms-post.html\")\n\n\n@app.route(\"/cookies/set/name/value\")\ndef set_cookie(name, value):\n \"\"\"Sets a cookie and redirects to cookie list.\n ---\n tags:\n - Cookies\n parameters:\n - in: path\n name: name\n type: string\n - in: path\n name: value\n type: string\n produces:\n - text/plain\n responses:\n 200:\n description: Set cookies and redirects to cookie list.\n \"\"\"\n\n r = app.make_response(redirect(url_for(\"view_cookies\")))\n r.set_cookie(key=name, value=value, secure=secure_cookie())\n\n return r\n\n\n@app.route(\"/cookies/set\")\ndef set_cookies():\n \"\"\"Sets cookie(s) as provided by the query string and redirects to cookie list.\n ---\n tags:\n - Cookies\n parameters:\n - in: query\n name: freeform\n explode: true\n allowEmptyValue: true\n schema:\n type: object\n additionalProperties:\n type: string\n style: form\n produces:\n - text/plain\n responses:\n 200:\n description: Redirect to cookie list\n \"\"\"\n\n cookies = dict(request.args.items())\n r = app.make_response(redirect(url_for(\"view_cookies\")))\n for key, value in cookies.items():\n r.set_cookie(key=key, value=value, secure=secure_cookie())\n\n return r\n\n\n@app.route(\"/cookies/delete\")\ndef delete_cookies():\n \"\"\"Deletes cookie(s) as provided by the query string and redirects to cookie list.\n ---\n tags:\n - Cookies\n parameters:\n - in: query\n name: freeform\n explode: true\n allowEmptyValue: true\n schema:\n type: object\n additionalProperties:\n type: string\n style: form\n produces:\n - text/plain\n responses:\n 200:\n description: Redirect to cookie list\n \"\"\"\n\n cookies = dict(request.args.items())\n r = app.make_response(redirect(url_for(\"view_cookies\")))\n for key, value in cookies.items():\n r.delete_cookie(key=key)\n\n return r\n\n\n@app.route(\"/basic-auth/user/passwd\")\ndef basic_auth(user=\"user\", passwd=\"passwd\"):\n \"\"\"Prompts the user for authorization using HTTP Basic Auth.\n ---\n tags:\n - Auth\n parameters:\n - in: path\n name: user\n type: string\n - in: path\n name: passwd\n type: string\n produces:\n - application/json\n responses:\n 200:\n description: Sucessful authentication.\n 401:\n description: Unsuccessful authentication.\n \"\"\"\n\n if not check_basic_auth(user, passwd):\n return status_code(401)\n\n return jsonify(authenticated=True, user=user)\n\n\n@app.route(\"/hidden-basic-auth/user/passwd\")\ndef hidden_basic_auth(user=\"user\", passwd=\"passwd\"):\n \"\"\"Prompts the user for authorization using HTTP Basic Auth.\n ---\n tags:\n - Auth\n parameters:\n - in: path\n name: user\n type: string\n - in: path\n name: passwd\n type: string\n produces:\n - application/json\n responses:\n 200:\n description: Sucessful authentication.\n 404:\n description: Unsuccessful authentication.\n \"\"\"\n\n if not check_basic_auth(user, passwd):\n return status_code(404)\n return jsonify(authenticated=True, user=user)\n\n\n@app.route(\"/bearer\")\ndef bearer_auth():\n \"\"\"Prompts the user for authorization using bearer authentication.\n ---\n tags:\n - Auth\n parameters:\n - in: header\n name: Authorization\n schema:\n type: string\n produces:\n - application/json\n responses:\n 200:\n description: Sucessful authentication.\n 401:\n description: Unsuccessful authentication.\n \"\"\"\n authorization = request.headers.get(\"Authorization\")\n if not (authorization and authorization.startswith(\"Bearer \")):\n response = app.make_response(\"\")\n response.headers[\"WWW-Authenticate\"] = \"Bearer\"\n response.status_code = 401\n return response\n slice_start = len(\"Bearer \")\n token = authorization[slice_start:]\n\n return jsonify(authenticated=True, token=token)\n\n\n@app.route(\"/digest-auth/qop/user/passwd\")\ndef digest_auth_md5(qop=None, user=\"user\", passwd=\"passwd\"):\n \"\"\"Prompts the user for authorization using Digest Auth.\n ---\n tags:\n - Auth\n parameters:\n - in: path\n name: qop\n type: string\n description: auth or auth-int\n - in: path\n name: user\n type: string\n - in: path\n name: passwd\n type: string\n produces:\n - application/json\n responses:\n 200:\n description: Sucessful authentication.\n 401:\n description: Unsuccessful authentication.\n \"\"\"\n return digest_auth(qop, user, passwd, \"MD5\", \"never\")\n\n\n@app.route(\"/digest-auth/qop/user/passwd/algorithm\")\ndef digest_auth_nostale(qop=None, user=\"user\", passwd=\"passwd\", algorithm=\"MD5\"):\n \"\"\"Prompts the user for authorization using Digest Auth + Algorithm.\n ---\n tags:\n - Auth\n parameters:\n - in: path\n name: qop\n type: string\n description: auth or auth-int\n - in: path\n name: user\n type: string\n - in: path\n name: passwd\n type: string\n - in: path\n name: algorithm\n type: string\n description: MD5, SHA-256, SHA-512\n default: MD5\n produces:\n - application/json\n responses:\n 200:\n description: Sucessful authentication.\n 401:\n description: Unsuccessful authentication.\n \"\"\"\n return digest_auth(qop, user, passwd, algorithm, \"never\")\n\n\n@app.route(\"/digest-auth/qop/user/passwd/algorithm/stale_after\")\ndef digest_auth(\n qop=None, user=\"user\", passwd=\"passwd\", algorithm=\"MD5\", stale_after=\"never\"\n):\n \"\"\"Prompts the user for authorization using Digest Auth + Algorithm.\n allow settings the stale_after argument.\n ---\n tags:\n - Auth\n parameters:\n - in: path\n name: qop\n type: string\n description: auth or auth-int\n - in: path\n name: user\n type: string\n - in: path\n name: passwd\n type: string\n - in: path\n name: algorithm\n type: string\n description: MD5, SHA-256, SHA-512\n default: MD5\n - in: path\n name: stale_after\n type: string\n default: never\n produces:\n - application/json\n responses:\n 200:\n description: Sucessful authentication.\n 401:\n description: Unsuccessful authentication.\n \"\"\"\n require_cookie_handling = request.args.get(\"require-cookie\", \"\").lower() in (\n \"1\",\n \"t\",\n \"true\",\n )\n if algorithm not in (\"MD5\", \"SHA-256\", \"SHA-512\"):\n algorithm = \"MD5\"\n\n if qop not in (\"auth\", \"auth-int\"):\n qop = None\n\n authorization = request.headers.get(\"Authorization\")\n credentials = None\n if authorization:\n credentials = parse_authorization_header(authorization)\n\n if (\n not authorization\n or not credentials\n or credentials.type.lower() != \"digest\"\n or (require_cookie_handling and \"Cookie\" not in request.headers)\n ):\n response = digest_challenge_response(app, qop, algorithm)\n response.set_cookie(\"stale_after\", value=stale_after)\n response.set_cookie(\"fake\", value=\"fake_value\")\n return response\n\n if require_cookie_handling and request.cookies.get(\"fake\") != \"fake_value\":\n response = jsonify({\"errors\": [\"missing cookie set on challenge\"]})\n response.set_cookie(\"fake\", value=\"fake_value\")\n response.status_code = 403\n return response\n\n current_nonce = credentials.get(\"nonce\")\n\n stale_after_value = None\n if \"stale_after\" in request.cookies:\n stale_after_value = request.cookies.get(\"stale_after\")\n\n if (\n \"last_nonce\" in request.cookies\n and current_nonce == request.cookies.get(\"last_nonce\")\n or stale_after_value == \"0\"\n ):\n response = digest_challenge_response(app, qop, algorithm, True)\n response.set_cookie(\"stale_after\", value=stale_after)\n response.set_cookie(\"last_nonce\", value=current_nonce)\n response.set_cookie(\"fake\", value=\"fake_value\")\n return response\n\n if not check_digest_auth(user, passwd):\n response = digest_challenge_response(app, qop, algorithm, False)\n response.set_cookie(\"stale_after\", value=stale_after)\n response.set_cookie(\"last_nonce\", value=current_nonce)\n response.set_cookie(\"fake\", value=\"fake_value\")\n return response\n\n response = jsonify(authenticated=True, user=user)\n response.set_cookie(\"fake\", value=\"fake_value\")\n if stale_after_value:\n response.set_cookie(\n \"stale_after\", value=next_stale_after_value(stale_after_value)\n " }, { "role": "assistant", "content": " )\n\n return response" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "there are infinitely\n many numbers `z` such that ``cos(z) = x``. The convention is to return\n the angle `z` whose real part lies in `[0, pi]`.\n\n For real-valued input data types, `arccos` always returns real output.\n For each value that cannot be expressed as a real number or infinity,\n it yields ``nan`` and sets the `invalid` floating point error flag.\n\n For complex-valued input, `arccos` is a complex analytic function that\n has branch cuts ``[-inf, -1]`` and `[1, inf]` and is continuous from\n above on the former and from below on the latter.\n\n The inverse `cos` is also known as `acos` or cos^-1.\n\n References\n ----------\n M. Abramowitz and I.A. Stegun, \"Handbook of Mathematical Functions\",\n 10th printing, 1964, pp. 79.\n https://personal.math.ubc.ca/~cbm/aands/page_79.htm\n\n Examples\n --------\n We expect the arccos of 1 to be 0, and of -1 to be pi:\n\n np.arccos([1, -1])\n array([ 0. , 3.14159265])\n\n Plot arccos:\n\n import matplotlib.pyplot as plt\n x = np.linspace(-1, 1, num=100)\n plt.plot(x, np.arccos(x))\n plt.axis('tight')\n plt.show()\n\n \"\"\")\n\nadd_newdoc('numpy._core.umath', 'arccosh',\n \"\"\"\n Inverse hyperbolic cosine, element-wise.\n\n Parameters\n ----------\n x : array_like\n Input array.\n $PARAMS\n\n Returns\n -------\n arccosh : ndarray\n Array of the same shape as `x`.\n $OUT_SCALAR_1\n\n See Also\n --------\n\n cosh, arcsinh, sinh, arctanh, tanh\n\n Notes\n -----\n `arccosh` is a multivalued function: for each `x` there are infinitely\n many numbers `z` such that `cosh(z) = x`. The convention is to return the\n `z` whose imaginary part lies in ``[-pi, pi]`` and the real part in\n ``[0, inf]``.\n\n For real-valued input data types, `arccosh` always returns real output.\n For each value that cannot be expressed as a real number or infinity, it\n yields ``nan`` and sets the `invalid` floating point error flag.\n\n For complex-valued input, `arccosh` is a complex analytical function that\n has a branch cut `[-inf, 1]` and is continuous from above on it.\n\n References\n ----------\n .. [1] M. Abramowitz and I.A. Stegun, \"Handbook of Mathematical Functions\",\n 10th printing, 1964, pp. 86.\n https://personal.math.ubc.ca/~cbm/aands/page_86.htm\n .. [2] Wikipedia, \"Inverse hyperbolic function\",\n https://en.wikipedia.org/wiki/Arccosh\n\n Examples\n --------\n np.arccosh([np.e, 10.0])\n array([ 1.65745445, 2.99322285])\n np.arccosh(1)\n 0.0\n\n \"\"\")\n\nadd_newdoc('numpy._core.umath', 'arcsin',\n \"\"\"\n Inverse sine, element-wise.\n\n Parameters\n ----------\n x : array_like\n `y`-coordinate on the unit circle.\n $PARAMS\n\n Returns\n -------\n angle : ndarray\n The inverse sine of each element in `x`, in radians and in the\n closed interval ``[-pi/2, pi/2]``.\n $OUT_SCALAR_1\n\n See Also\n --------\n sin, cos, arccos, tan, arctan, arctan2, emath.arcsin\n\n Notes\n -----\n `arcsin` is a multivalued function: for each `x` there are infinitely\n many numbers `z` such that :math:`sin(z) = x`. The convention is to\n return the angle `z` whose real part lies in [-pi/2, pi/2].\n\n For real-valued input data types, *arcsin* always returns real output.\n For each value that cannot be expressed as a real number or infinity,\n it yields ``nan`` and sets the `invalid` floating point error flag.\n\n For complex-valued input, `arcsin` is a complex analytic function that\n has, by convention, the branch cuts [-inf, -1] and [1, inf] and is\n continuous from above on the former and from below on the latter.\n\n The inverse sine is also known as `asin` or sin^{-1}.\n\n References\n ----------\n Abramowitz, M. and Stegun, I. A., *Handbook of Mathematical Functions*,\n 10th printing, New York: Dover, 1964, pp. 79ff.\n https://personal.math.ubc.ca/~cbm/aands/page_79.htm\n\n Examples\n --------\n np.arcsin(1) # pi/2\n 1.5707963267948966\n np.arcsin(-1) # -pi/2\n -1.5707963267948966\n np.arcsin(0)\n 0.0\n\n \"\"\")\n\nadd_newdoc('numpy._core.umath', 'arcsinh',\n \"\"\"\n Inverse hyperbolic sine element-wise.\n\n Parameters\n ----------\n x : array_like\n Input array.\n $PARAMS\n\n Returns\n -------\n out : ndarray or scalar\n Array of the same shape as `x`.\n $OUT_SCALAR_1\n\n Notes\n -----\n `arcsinh` is a multivalued function: for each `x` there are infinitely\n many numbers `z` such that `sinh(z) = x`. The convention is to return the\n `z` whose imaginary part lies in `[-pi/2, pi/2]`.\n\n For real-valued input data types, `arcsinh` always returns real output.\n For each value that cannot be expressed as a real number or infinity, it\n returns ``nan`` and sets the `invalid` floating point error flag.\n\n For complex-valued input, `arcsinh` is a complex analytical function that\n has branch cuts `[1j, infj]` and `[-1j, -infj]` and is continuous from\n the right on the former and from the left on the latter.\n\n The inverse hyperbolic sine is also known as `asinh` or ``sinh^-1``.\n\n References\n ----------\n .. [1] M. Abramowitz and I.A. Stegun, \"Handbook of Mathematical Functions\",\n 10th printing, 1964, pp. 86.\n https://personal.math.ubc.ca/~cbm/aands/page_86.htm\n .. [2] Wikipedia, \"Inverse hyperbolic function\",\n https://en.wikipedia.org/wiki/Arcsinh\n\n Examples\n --------\n np.arcsinh(np.array([np.e, 10.0]))\n array([ 1.72538256, 2.99822295])\n\n \"\"\")\n\nadd_newdoc('numpy._core.umath', 'arctan',\n \"\"\"\n Trigonometric inverse tangent, element-wise.\n\n The inverse of tan, so that if ``y = tan(x)`` then ``x = arctan(y)``.\n\n Parameters\n ----------\n x : array_like\n $PARAMS\n\n Returns\n -------\n out : ndarray or scalar\n Out has the same shape as `x`. Its real part is in\n ``[-pi/2, pi/2]`` (``arctan(+/-inf)`` returns ``+/-pi/2``).\n $OUT_SCALAR_1\n\n See Also\n --------\n arctan2 : The \"four quadrant\" arctan of the angle formed by (`x`, `y`)\n and the positive `x`-axis.\n angle : Argument of complex values.\n\n Notes\n -----\n `arctan` is a multi-valued function: for each `x` there are infinitely\n many numbers `z` such that tan(`z`) = `x`. The convention is to return\n the angle `z` whose real part lies in [-pi/2, pi/2].\n\n For real-valued input data types, `arctan` always returns real output.\n For each value that cannot be expressed as a real number or infinity,\n it yields ``nan`` and sets the `invalid` floating point error flag.\n\n For complex-valued input, `arctan` is a complex analytic function that\n has [``1j, infj``] and [``-1j, -infj``] as branch cuts, and is continuous\n from the left on the former and from the right on the latter.\n\n The inverse tangent is also known as `atan` or tan^{-1}.\n\n References\n ----------\n Abramowitz, M. " }, { "role": "assistant", "content": "and Stegun, I. A., *Handbook of Mathematical Functions*,\n 10th printing, New York: Dover, 1964, pp. 79.\n https://personal.math.ubc.ca/~cbm/aands/page_79.htm\n\n Examples\n --------\n We expect the arctan of 0 to be 0, and of 1 to be pi/4:\n\n np.arctan([0, 1])\n array([ 0. , 0.78539816])\n\n np.pi/4\n 0.78539816339744828\n\n Plot arctan:\n\n import matplotlib.pyplot as plt\n x = np.linspace(-10, 10)\n plt.plot(x, np.arctan(x))\n plt.axis('tight')\n plt.show()\n\n \"\"\")" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "ther in use cases such as search where you want to compare shorter queries against larger documents.\n\n `Document` embeddings are optimized for larger pieces of text to compare queries against.\n Query:\n `Document` and `Query` are used together in use cases such as search where you want to compare shorter queries against larger documents.\n\n `Query` embeddings are optimized for shorter texts, such as questions or keywords.\n \"\"\"\n\n Symmetric = \"symmetric\"\n Document = \"document\"\n Query = \"query\"\n\n\n@dataclass(frozen=True)\nclass SemanticEmbeddingRequest:\n \"\"\"\n Embeds a text and returns vectors that can be used for downstream tasks (e.g. semantic similarity) and models (e.g. classifiers).\n\n Parameters:\n prompt\n The text and/or image(s) to be embedded.\n representation\n Semantic representation to embed the prompt with.\n compress_to_size\n Options available: 128\n\n The default behavior is to return the full embedding, but you can optionally request an embedding compressed to a smaller set of dimensions.\n\n Full embedding sizes for supported models:\n - luminous-base: 5120\n\n The 128 size is expected to have a small drop in accuracy performance (4-6%), with the benefit of being much smaller, which makes comparing these embeddings much faster for use cases where speed is critical.\n\n The 128 size can also perform better if you are embedding really short texts or documents.\n\n normalize\n Return normalized embeddings. This can be used to save on additional compute when applying a cosine similarity metric.\n\n Note that at the moment this parameter does not yet have any effect. This will change as soon as the\n corresponding feature is available in the backend\n\n contextual_control_threshold (float, default None)\n If set to None, attention control parameters only apply to those tokens that have\n explicitly been set in the request.\n If set to a non-None value, we apply the control parameters to similar tokens as well.\n Controls that have been applied to one token will then be applied to all other tokens\n that have at least the similarity score defined by this parameter.\n The similarity score is the cosine similarity of token embeddings.\n\n control_log_additive (bool, default True)\n True: apply control by adding the log(control_factor) to attention scores.\n False: apply control by (attention_scores - - attention_scores.min(-1)) * control_factor\n\n Examples\n texts = [\n \"deep learning\",\n \"artificial intelligence\",\n \"deep diving\",\n \"artificial snow\",\n ]\n # Texts to compare\n embeddings = []\n for text in texts:\n request = SemanticEmbeddingRequest(prompt=Prompt.from_text(text), representation=SemanticRepresentation.Symmetric)\n result = model.semantic_embed(request)\n embeddings.append(result.embedding)\n \"\"\"\n\n prompt: Prompt\n representation: SemanticRepresentation\n compress_to_size: Optional[int] = None\n normalize: bool = False\n contextual_control_threshold: Optional[float] = None\n control_log_additive: Optional[bool] = True\n\n def to_json(self) - Mapping[str, Any]:\n return {\n **self._asdict(),\n \"representation\": self.representation.value,\n \"prompt\": self.prompt.to_json(),\n }\n\n def _asdict(self) - Mapping[str, Any]:\n return asdict(self)\n\n\n@dataclass(frozen=True)\nclass BatchSemanticEmbeddingRequest:\n \"\"\"\n Embeds multiple multi-modal prompts and returns their embeddings in the same order as they were supplied.\n\n Parameters:\n prompts\n A list of texts and/or images to be embedded.\n representation\n Semantic representation to embed the prompt with.\n compress_to_size\n Options available: 128\n\n The default behavior is to return the full embedding, but you can optionally request an embedding compressed to a smaller set of dimensions.\n\n Full embedding sizes for supported models:\n - luminous-base: 5120\n\n The 128 size is expected to have a small drop in accuracy performance (4-6%), with the benefit of being much smaller, which makes comparing these embeddings much faster for use cases where spe" }, { "role": "assistant", "content": "ed is critical." } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "_val, exc_tb=exc_tb)\n\n async def get_version(self) - str:\n \"\"\"Gets version of the AlephAlpha HTTP API.\"\"\"\n return await self._get_request_text(\"version\")\n\n async def _get_request_text(self, endpoint: str) - str:\n async with self.session.get(\n self.host + endpoint,\n ) as response:\n if not response.ok:\n _raise_for_status(response.status, await response.text())\n return await response.text()\n\n async def _get_request_json(\n self, endpoint: str\n ) - Union[List[Mapping[str, Any]], Mapping[str, Any]]:\n async with self.session.get(\n self.host + endpoint,\n ) as response:\n if not response.ok:\n _raise_for_status(response.status, await response.text())\n return await response.json()\n\n async def _post_request(\n self,\n endpoint: str,\n request: AnyRequest,\n model: Optional[str] = None,\n ) - Dict[str, Any]:\n json_body = self._build_json_body(request, model)\n\n query_params = self._build_query_parameters()\n\n async with self.session.post(\n self.host + endpoint, json=json_body, params=query_params\n ) as response:\n if not response.ok:\n _raise_for_status(response.status, await response.text())\n return await response.json()\n\n def _build_query_parameters(self) - Mapping[str, str]:\n return {\n # cannot use str() here because we want lowercase true/false in query string\n # Also do not want to send the nice flag with every request if it is false\n **({\"nice\": \"true\"} if self.nice else {}),\n }\n\n def _build_json_body(\n self, request: AnyRequest, model: Optional[str]\n ) - Mapping[str, Any]:\n json_body = dict(request.to_json())\n\n if model is not None:\n json_body[\"model\"] = model\n if self.hosting is not None:\n json_body[\"hosting\"] = self.hosting\n return json_body\n\n async def models(self) - List[Mapping[str, Any]]:\n \"\"\"\n Queries all models which are currently available.\n\n For documentation of the response, see https://docs.aleph-alpha.com/api/available-models/\n \"\"\"\n return await self._get_request_json(\"models_available\") # type: ignore\n\n async def complete(\n self,\n request: CompletionRequest,\n model: str,\n ) - CompletionResponse:\n \"\"\"Generates completions given a prompt.\n\n Parameters:\n request (CompletionRequest, required):\n Parameters for the requested completion.\n\n model (string, required):\n Name of model to use. A model name refers to a model architecture (number of parameters among others).\n Always the latest version of model is used.\n\n Examples:\n # create a prompt\n prompt = Prompt.from_text(\"An apple a day, \")\n \n # create a completion request\n request = CompletionRequest(\n prompt=prompt,\n maximum_tokens=32,\n stop_sequences=[\"###\",\"\\\\n\"],\n temperature=0.12\n )\n \n # complete the prompt\n result = await client.complete(request, model=model_name)\n \"\"\"\n response = await self._post_request(\n \"complete\",\n request,\n model,\n )\n return CompletionResponse.from_json(response)\n\n async def tokenize(\n self,\n request: TokenizationRequest,\n model: str,\n ) - TokenizationResponse:\n \"\"\"Tokenizes the given prompt for the given model.\n\n Parameters:\n request (TokenizationRequest, required):\n Parameters for the requested tokenization.\n\n model (string, required):\n Name of model to use. A model name refers to a model architecture (number of parameters among others).\n Always the latest version of model is used.\n\n Examples:\n request = TokenizationRequest(prompt=\"hello\", token_ids=True, tokens=True)\n response = await client.tokenize(request, model=model_name)\n \"\"\"\n response = await self._post_request(\n \"tokenize\",\n request,\n model,\n )\n return TokenizationResponse.from_json(response)\n\n async def detokenize(\n self,\n request: DetokenizationRequest,\n model: str,\n ) - DetokenizationResponse:\n \"\"\"Detokenizes the given prompt for the given model.\n\n Parameters:\n request (DetokenizationRequest, required):\n Parameters for the requested detokenization.\n\n model (string, required):\n Name of model to use. A model name refers to a model architecture (number of parameters among others).\n Always the latest version of model is used.\n\n Examples:\n request = DetokenizationRequest(token_ids=[2, 3, 4])\n response = await client.detokenize(request, model=model_name)\n \"\"\"\n response = await self._post_request(\n \"detokenize\",\n request,\n model,\n )\n return DetokenizationResponse.from_json(response)\n\n async def embed(\n self,\n request: EmbeddingRequest,\n model: str,\n ) - EmbeddingResponse:\n \"\"\"Embeds a text and returns vectors that can be used for downstream tasks (e.g. semantic similarity) and models (e.g. classifiers).\n\n Parameters:\n request (EmbeddingRequest, required):\n Parameters for the requested embedding.\n\n model (string, required):\n Name of " }, { "role": "assistant", "content": "model to use." } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "###########################################\n\nimport json, csv, numpy, datetime, warnings\nimport pandas as pd\n\n################################################################################\n# SETTINGS #\n################################################################################\n\nLEMMY_STATS_CRAWLER_FILENAME = 'lemmy-stats-crawler.json'\nLEMMY_STATS_CRAWLER_FILEPATH = 'lemmy-stats-crawler/' + LEMMY_STATS_CRAWLER_FILENAME\n\nUPTIME_FILENAME = 'uptime.json'\nAGE_FILENAME = 'age.json'\n\nOUT_CSV = 'awesome-lemmy-instances.csv'\n\n################################################################################\n# FUNCTIONS #\n################################################################################\n\n# do some checks on text that we get back from the instance's API because it\n# might break markdown or do something nasty\ndef sanitize_text( text ):\n\n\t# markdown table columns are delimited by pipes\n\ttext = text.replace( '|', '' )\n\n\t# newlines\n\ttext = text.replace( \"\\r\", '' )\n\ttext = text.replace( \"\\n\", '' )\n\n\t# commas fuck with our CSV file; replace it with this homoglyph (0x201A)\n\ttext = text.replace( \",\", '‚' )\n\n\treturn text\n\n################################################################################\n# MAIN BODY #\n################################################################################\n\n# catch runtime warnings from numpy on 'nan' errors when calculating averages\nwarnings.filterwarnings(\"error\")\n\n##################\n# CHECK SETTINGS #\n##################\n\n####################\n# HANDLE ARGUMENTS #\n####################\n\n#####################\n# DECLARE VARIABLES #\n#####################\n\nreadme_contents = '''\n# Awesome Lemmy Instances\n\nThis repo was created to help users migrate from reddit to lemmy (a federated reddit alternative).\n\nBecause lemmy is federated (like email), there are many different websites where you can register your new lemmy account. In general, it doesn't matter too much which server you register with. Just like with email, you can interact with users on other servers (eg hotmail, aol, gmail, etc).\n\nHowever, each server has their own local policies and configurations (for example, some lemmy instances disable the \"downvote\" button). The table below will help you compare each site to decide where to register your new lemmy account.\n\n### Terms\n\n * Instance = A lemmy instance is a website that runs the lemmy software\n * Community = Each instance has many communities. In reddit, **communities were called subreddits**.\n * NSFW = Not Safe For Work\n\n### Legend\n\n * **NU** \"Yes\" means that **New Users** can register accounts. \"No\" means that this instance is not accepting new account registrations at this time.\n * **NC** \"Yes\" means that you can create a **New Community**. \"No\" means that only admins can create new communities on this instance.\n * **Fed** \"Yes\" means that you can interact with other **federated** lemmy instances. \"No\" means that the instance is partially or fully siloed (you can only subscribe to communities on this one instance or other instances that are explicitly added to an allowlist)\n * **Adult** \"Yes\" means there's no **profanity filters** or blocking of **NSFW** content. \"No\" means that there are profanity filters or NSFW content is not allowed. Note: \"Yes\" does not mean all NSFW content is allowed. Each instance may block some types " }, { "role": "assistant", "content": "of NSFW content, such as pornography. Additionally, you can configure your account to hide NSFW content." } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "from fabric.api import *\nimpo" }, { "role": "assistant", "content": "rt fabric.contrib.project as project" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "):\n self._value = torch.nn.Parameter(torch.tensor(float(expr)))\n self._torch_func = lambda: self._value\n self._args = ()\n elif issubclass(expr.func, sympy.Rational):\n # This is some fraction fixed in the operator.\n self._value = float(expr)\n self._torch_func = lambda: self._value\n self._args = ()\n elif issubclass(expr.func, sympy.UnevaluatedExpr):\n if len(expr.args) != 1 or not issubclass(\n expr.args[0].func, sympy.Float\n ):\n raise ValueError(\n \"UnevaluatedExpr should only be used to wrap floats.\"\n )\n self.register_buffer(\"_value\", torch.tensor(float(expr.args[0])))\n self._torch_func = lambda: self._value\n self._args = ()\n elif issubclass(expr.func, sympy.Integer):\n # Can get here if expr is one of the Integer special cases,\n # e.g. NegativeOne\n self._value = int(expr)\n self._torch_func = lambda: self._value\n self._args = ()\n elif issubclass(expr.func, sympy.Symbol):\n self._name = expr.name\n self._torch_func = lambda value: value\n self._args = ((lambda memodict: memodict[expr.name]),)\n else:\n try:\n self._torch_func = _func_lookup[expr.func]\n except KeyError:\n raise KeyError(\n f\"Function {expr.func} was not found in Torch function mappings.\"\n \"Please add it to extra_torch_mappings in the format, e.g., \"\n \"{sympy.sqrt: torch.sqrt}.\"\n )\n args = []\n for arg in expr.args:\n try:\n arg_ = _memodict[arg]\n except KeyError:\n arg_ = type(self)(\n expr=arg,\n _memodict=_memodict,\n _func_lookup=_func_lookup,\n **kwargs,\n )\n _memodict[arg] = arg_\n args.append(arg_)\n self._args = torch.nn.ModuleList(args)\n\n def forward(self" }, { "role": "assistant", "content": ", memodict):" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "le_data: pd.DataFrame = pd.DataFrame()\n n_samples: int = 1000\n index: str = 'pytest'\n model_name: str = 'pytest-model'\n model = 'tfidf_truncatedsvd_kmeans'\n stop_words = 'english'\n max_df: float = 0.999\n min_df: float = 0.001\n n_components: int = 100\n n_clusters: int = 69\n ngram_range: Tuple[int, int] = (1, 1)\n random_state: int = 42\n include_title: bool = True\n include_abstract: bool = True\n include_keywords_major: bool = False\n include_keywords_minor: bool = False\n\n @classmethod\n def setup_class(cls) - None:\n # Clear the test model directory\n shutil.rmtree(os.path.join(get_models_dir(), cls.model_name), ignore_errors=True)\n\n # Sample some data\n cls.sample_data = sample_training_data(cls.index, random_state=42, n_samples=cls.n_samples, method='forward')['text']\n\n @classmethod\n def teardown_class(cls) - None:\n # Clear the test model directory\n shutil.rmtree(os.path.join(get_models_dir(), cls.model_name), ignore_errors=True)\n\n def teardown_method(self) - None:\n # Clear the test model directory\n shutil.rmtree(os.path.join(get_models_dir(), self.model_name), ignore_errors=True)\n\n def test_sample_data(self) - None:\n assert len(self.sample_data) == self.n_samples\n\n def test_create_default_simple_sklearn_pipeline_manager(self) - None:\n manager = ModelFactory.create(\n self.model,\n self.include_title,\n self.include_abstract,\n self.include_keywords_major,\n self.include_keywords_minor,\n stop_words=self.stop_words,\n max_df=self.max_df,\n min_df=self.min_df,\n n_components=self.n_components,\n n_clusters=self.n_clusters,\n ngram_range=self.ngram_range,\n random_state=None)\n\n assert manager is not None\n assert isinstance(manager.model, Pipeline)\n assert manager.random_state is None\n assert manager.preprocessing_args == {\n 'include_title': True,\n 'include_abstract': True,\n 'include_keywords_major': False,\n 'include_keywords_minor': False,\n }\n\n assert (manager.cluster_names.columns == ['name']).all()\n assert len(manager.cluster_names) == 0\n\n def test_create_custom_simple_sklearn_pipeline_manager(self) - None:\n manager = ModelFactory.create(\n self.model,\n self.include_title,\n self.include_abstract,\n True,\n self.include_keywords_minor,\n stop_words=self.stop_words,\n max_df=self.max_df,\n min_df=self.min_df,\n n_components=self.n_components,\n n_clusters=self.n_clusters,\n ngram_range=self.ngram_range,\n random_state=42)\n\n assert manager.random_state == 42\n assert manager.preprocessing_args == {\n 'include_title': True,\n 'include_abstract': True,\n 'include_keywords_major': True,\n 'include_keywords_minor': False,\n }\n\n def test_set_name(self) - None:\n manager = ModelFactory.create(\n self.model,\n self.include_title,\n self.include_abstract,\n self.include_keywords_major,\n self.include_keywords_minor,\n stop_words=self.stop_words,\n max_df=self.max_df,\n min_df=self.min_df,\n n_components=self.n_components,\n n_clusters=self.n_clusters,\n ngram_range=self.ngram_range,\n random_state=self.random_state)\n manager.set_name(self.model_name)\n\n assert manager._name == self.model_name\n\n def test_construct_predictions_index_name(self) - None:\n manager = ModelFactory.create(\n self.model,\n self.include_title,\n self.include_abstract,\n self.include_keywords_major,\n self.include_keywords_minor,\n stop_words=self.stop_words,\n max_df=self.max_df,\n min_df=self.min_df,\n n_components=self.n_components,\n n_clusters=self.n_clusters,\n ngram_range=self.ngram_range,\n random_state=self.random_state)\n manager.set_name(self.model_name)\n predictions_index_name = manager._construct_predictions_index_name(self.index)\n predictions_file_name = manager._construct_predictions_file_name(self.index)\n\n assert manager._name == self.model_name\n assert predictions_index_name == f'{self.index}_{manager._name}_predictions'\n assert predictions_file_name == f'{self.index}_predictions.json'\n\n def test_fit(self) - None:\n manager = ModelFactory.create(\n self.model,\n self.include_title,\n self.include_abstract,\n self.include_keywords_major,\n self.include_keywords_minor,\n stop_words=self.stop_words,\n max_df=self.max_df,\n min_df=self.min_df,\n n_components=self.n_components,\n n_clusters=self.n_clusters,\n ngram_range=self.ngram_range,\n random_state=self.random_state)\n\n manager.fit(self.sample_data)\n\n assert manager.model['clustering_kmeans'].labels_.shape == (self.n_samples,)\n assert len(manager.cluster_names) == self.n_clusters\n\n def test_predict(self) - None:\n manager = ModelFactory.create(\n self.model,\n self.include_title,\n self.include_abstract,\n self.include_keywords_major,\n self.include_keywords_minor,\n stop_words=self.stop_words,\n max_df=self.max_df,\n min_df=self.min_df,\n n_components=self.n_components,\n n_clusters=self.n_clusters,\n ngram_range=self.ngram_range,\n random_state=self.random_state)\n\n manager.fit(self.sample_data)\n predictions = manager.predict(self.sample_data)\n\n assert isinstance(predictions, np.ndarray)\n assert predictions.shape == (self.n_samples,)\n\n def test_transform(self) - None:\n manager = ModelFactory.create(\n self.model,\n self.include_title,\n self.include_abstract,\n self.include_keywords_major,\n self.include_keywords_minor,\n stop_words=self.stop_words,\n max_df=self.max_df,\n min_df=self.min_df,\n n_components=self.n_components,\n n_clusters=self.n_clusters,\n ngram_range=self.ngram_range,\n random_state=self.random_state)\n\n manager.fit(self.sample_data)\n transformed = manager.transform(self.sample_data, exclude_from='clustering')\n\n assert isinstance(transformed, np.ndarray)\n assert transformed.shape == (self.n_samples, self.n_components)\n\n transformed_with_kmeans = manager.transform(self.sample_data)\n\n assert isinstance(transformed_with_kmeans, np.ndarray)\n assert transformed_with_kmeans.shape == (self.n_samples, self.n_clusters)\n\n def test_save(self) - None:\n manager = ModelFactory.create(\n self.model,\n self.include_title,\n self.include_abstract,\n self.include_keywords_major,\n self.include_keywords_minor,\n stop_words=self.stop_words,\n max_df=self.max_df,\n min_df=self.min_df,\n n_components=self.n_components,\n n_clusters=self.n_clusters,\n ngram_range=self.ngram_range,\n random_state=self.random_state)\n\n manager.fit(self.sample_data)\n manager.save(self.model_name)\n\n assert os.path.exists(os.path.join(get_models_dir(), self.model_name, 'model.joblib'))\n assert os.path.exists(os.path.join(get_models_dir(), self.model_name, 'config.json'))\n assert os.path.exists(os.path.join(get_models_dir(), self.model_name, 'cluster_names.csv'))\n\n def test_save_only_model(self) - None:\n manager = ModelFactory.create(\n self.model,\n self.include_title,\n self.include_abstract,\n self.include_keywords_major,\n self.include_keywords_minor,\n stop_words=self.stop_words,\n max_df=self.max_df,\n min_df=self.min_df,\n n_components=self.n_components,\n n_clusters=self.n_clusters,\n ngram_range=self.ngram_range,\n random_state=self.random_state)\n\n manager.fit(self.sample_data)\n manager.save(self.model_name, save_only='model')\n\n assert os.path.exists(os.path.join(get_models_dir(), self.model_name, 'model.joblib'))\n assert not os.path.exists(os.path.join(get_models_dir(), self.model_name, 'config.json'))\n assert not os.path.exists(os.path.join(get_models_dir(), self.model_name, 'cluster_names.csv'))\n\n def test_load(self) - None:\n manager = ModelFactory.create(\n self.model,\n self.include_title,\n self.include_abstract,\n True,\n self.include_keywords_minor,\n stop_words=self.stop_words,\n max_df=self.max_df,\n min_df=self.min_df,\n n_components=self.n_components,\n n_clusters=self.n_clusters,\n ngram_range=self.ngram_range,\n random_state=self.random_state)\n\n manager.fit(self.sample_data)\n manager.save(self.model_name)\n\n manager_predictions = manager.model.predict(self.sample_data)\n manager_transformed = manager.model.transform(self.sample_data)\n\n loaded_manager = SimpleSklearnPipelineManager.load(self" }, { "role": "assistant", "content": ".model_name)\n\n loaded_manager_predictions = loaded_manager.model.predict(self.sample_data)\n loaded_manager_transformed = loaded_manager.model.transform(self.sample_data)\n\n assert isinstance(loaded_manager, SimpleSklearnPipelineManager)\n assert isinstance(loaded_manager.model, Pipeline)\n assert loaded_manager.random_state == 42\n assert loaded_manager.preprocessing_args == {\n 'include_title': True,\n 'include_abstract': True,\n 'include_keywords_major': True,\n 'include_keywords_minor': False,\n }\n\n assert (loaded_manager.cluster_names.columns == ['name']).all()\n assert len(loaded_manager.cluster_names) == self.n_clusters\n\n assert (loaded_manager_predictions == manager_predictions).all()\n assert (loaded_manager_transformed == manager_transformed).all()" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "from nlinec.data.preprocessing import combine_premise_hypothesis, construct_hypothesis, get_granularity, get_type, stringify_context\n\n\ndef test_stringify_context() - None:\n context = ['This', 'is', 'a', 'test', '.']\n\n assert stringify_context(context) == 'This is a test.'\n\n\ndef test_get_granularity() - None:\n assert get_granularity('/other') == 1\n assert get_granularity('/other/test') == 2\n assert get_granularity('/correct/horse/battery') == 3\n\n\ndef test_get_type() - None:\n assert get_type('/other') == 'other'\n assert get_type('/other/test') == 'test'\n assert get_type('/correct/horse/battery') == 'battery'\n assert get_type('/correct/horse/battery', granularity=1) == 'correct'\n assert get_type('/correct/horse/battery', granularity=2) == 'horse'\n assert get_type('/correct/horse/battery', granularity=4) is None\n\n\ndef test_construct_hypothesis() - None:\n entity = 'my_entity'\n type = 'my_type'\n\n assert construct_hypothesis(entity, type) == 'my_entity is a my_type.'\n\n\ndef test_combine_premise_hypothesis() - None:\n premise = 'This is a premise.'\n hypothesis = 'This is a hypothesis.'\n\n assert combine_premise_hypothesis(premise, hypothesis" }, { "role": "assistant", "content": ") == 'This is a premise./ssThis is a hypothesis.'\n" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": " return \"\", prompt_file\n\n if input.__contains__(\"show config\"):\n prompt_file.show_config()\n return \"config shown\", prompt_file\n\n # multi turn/single turn commands\n if input.__contains__(\"multi-turn\"):\n # start context\n if input.__contains__(\"start\"):\n if config['multi_turn'] == 'off':\n prompt_file.start_multi_turn()\n return \"multi turn mode on\", prompt_file\n \n return \"multi turn mode on\", prompt_file\n \n # stop context\n if input.__contains__(\"stop\"):\n prompt_file.stop_multi_turn()\n return \"multi turn mode off\", prompt_file\n \n # context file commands\n if input.__contains__(\"context\"):\n if input.__contains__(\"default\"):\n prompt_file.default_context()\n return \"stopped context\", prompt_file\n \n # show context n\n if input.__contains__(\"show\"):\n print('\\n')\n with open(prompt_file.file_name, 'r') as f:\n lines = f.readlines()\n lines = lines[6:] # skip headers\n \n line_numbers = 0\n if len(input.split()) 3:\n line_numbers = int(input.split()[3])\n \n if line_numbers != 0:\n for line in lines[-line_numbers:]:\n print('\\n# '+line, end='')\n else:\n print('\\n# '.join(lines))\n return \"context shown\", prompt_file\n \n # edit context\n if input.__contains__(\"view\"):\n # open the prompt file in text editor\n if config['shell'] != 'powershell':\n os.system('open {}'.format(prompt_file.file_path))\n else:\n os.system('start {}'.format(prompt_file.file_path))\n return \"context shown\", prompt_file\n\n # save context filename\n if input.__contains__(\"save\"):\n # save the current prompt file to" }, { "role": "assistant", "content": " a new file\n # if filename not specified use the current time (to avoid name conflicts)" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#\n\nimport torch\nfrom torch import nn\nimport numpy as np\nfrom utils.graphics_utils import getWorld2View2, getProjectionMatrix\n\nclass Camera(nn.Module):\n def __init__(self, colmap_id, R" }, { "role": "assistant", "content": ", T, FoVx, FoVy, image, gt_alpha_mask,\n image_name, uid,\n trans=np.array([0.0, 0.0, 0.0]), scale=1.0, data_device = \"cuda\"\n ):\n super(Camera, self).__init__()\n\n self.uid = uid\n self.colmap_id = colmap_id\n self.R = R\n self.T = T\n self.FoVx = FoVx\n self.FoVy = FoVy\n self.image_name = image_name" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "tImplementedError\n\n def to_python(self, value: t.Any) - t.Any:\n \"\"\"Convert the JSON representation back to the correct type. The tag\n will already be removed.\"\"\"\n raise NotImplementedError\n\n def tag(self, value: t.Any) - t.Any:\n \"\"\"Convert the value to a valid JSON type and add the tag structure\n around it.\"\"\"\n return {self.key: self.to_json(value)}\n\n\nclass TagDict(JSONTag):\n \"\"\"Tag for 1-item dicts whose only key matches a registered tag.\n\n Internally, the dict key is suffixed with `__`, and the suffix is removed\n when deserializing.\n \"\"\"\n\n __slots__ = ()\n key = \" di\"\n\n def check(self, value: t.Any) - bool:\n return (\n isinstance(value, dict)\n and len(value) == 1\n and next(iter(value)) in self.serializer.tags\n )\n\n def to_json(self, value: t.Any) - t.Any:\n key = next(iter(value))\n return {f\"{key}__\": self.serializer.tag(value[key])}\n\n def to_python(self, value: t.Any) - t.Any:\n key = next(iter(value))\n return {key[:-2]: value[key]}\n\n\nclass PassDict(JSONTag):\n __slots__ = ()\n\n def check(self, value: t.Any) - bool:\n return isinstance(value, dict)\n\n def to_json(self, value: t.Any) - t.Any:\n # JSON objects may only have string keys, so don't bother tagging the\n # key here.\n return {k: self.serializer.tag(v) for k, v in value.items()}\n\n tag = to_json\n\n\nclass TagTuple(JSONTag):\n __slots__ = ()\n key = \" t\"\n\n def check(self, value: t.Any) - bool:\n return isinstance(value, tuple)\n\n def to_json(self, value: t.Any) - t.Any:\n return [self.serializer.tag(item) for item in value]\n\n def to_python(self, value: t.Any) - t.Any:\n return tuple(value)\n\n\nclass PassList(JSONTag):\n __slots__ = ()\n\n def check(self, value: t.Any) - bool:\n return isinstance(value, list)\n\n def to_json(self, value: t.Any) - t.Any:\n return [self.serializer.tag(item) for item in value]\n\n tag = to_json\n\n\nclass TagBytes(JSONTag):\n __slots__ = ()\n key = \" b\"\n\n def check(self, value: t.Any) - bool:\n return isinstance(value, bytes)\n\n def to_json(self, value: t.Any) - t.Any:\n return b64encode(value).decode(\"ascii\")\n\n def to_python(self, value: t.Any) - t.Any:\n return b64decode(value)\n\n\nclass TagMarkup(JSONTag):\n \"\"\"Serialize anything matching the :class:`~markupsafe.Markup` API by\n having a ``__html__`` method to the result of that method. Always\n deserializes to an instance of :class:`~markupsafe.Markup`.\"\"\"\n\n __slots__ = ()\n key = \" m\"\n\n def check(self, value: t.Any) - bool:\n return callable(getattr(value, \"__html__\", None))\n\n def to_json(self, value: t.Any) - t.Any:\n return str(value.__html__())\n\n def to_python(self, value: t.Any) - t.Any:\n return Markup(value)\n\n\nclass TagUUID(JSONTag):\n __slots__ = ()\n key = \" u\"\n\n def check(self, value: t.Any) - bool:\n return isinstance(value, UUID)\n\n def to_json(self, value: t.Any) - t.Any:\n return value.hex\n\n def to_python(self, value: t.Any) - t.Any:\n return UUID(value)\n\n\nclass TagDateTime(JSONTag):\n __slots__ = ()\n key = \" d\"\n\n def check(self, value: t.Any) - bool:\n return isinstance(value, datetime)\n\n def to_json(self, value: t.Any) - t.Any:\n return http_date(value)\n\n def to_python(self, value: t.Any) - t.Any:\n return parse_date(value)\n\n\nclass TaggedJSONSerializer:\n \"\"\"Serializer that uses a tag system to compactly represent objects that\n are not JSON types. Passed as the intermediate serializer to\n :class:`itsdangerous.Serializer`.\n\n The following extra types are supported:\n\n * :class:`dict`\n * :class:`tuple`\n * :class:`bytes`\n * :class:`~markupsafe.Markup`\n * :class:`~uuid.UUID`\n * :class:`~datetime.datetime`\n \"\"\"\n\n __slots__ = (\"tags\", \"order\")\n\n #: Tag classes to bind when creating the serializer. Other tags can be\n #: added later using :meth:`~register`.\n default_tags = [\n TagDict,\n PassDict,\n TagTuple,\n PassList,\n TagBytes,\n TagMarkup,\n TagUUID,\n TagDateTime,\n ]\n\n def __init__(self) - None:\n self.tags: dict[str, JSONTag] = {}\n self.order: list[JSONTag] = []\n\n for cls in self.default_tags:\n self.register(cls)\n\n def register(\n self,\n tag_class: type[JSONTag],\n force: bool = False,\n index: int | None = None,\n ) - None:\n \"\"\"Register a new tag with this serializer.\n\n :param tag_class: tag class to register. Will be instantiated with this\n serializer instance.\n :param force: overwrite an existing tag. If false (default), a\n :exc:`KeyError` is raised.\n :param index: index to insert the new tag in the tag order. Useful when\n the new tag is a special case of an existing tag. If ``None``\n (default), the tag is appended to the end of the order.\n\n :raise KeyError: if the tag key is already registered and ``force`` is\n not true.\n \"\"\"\n tag = tag_class(self)\n key = tag.key\n\n if key is not None:\n if not force and key in self.tags:\n " }, { "role": "assistant", "content": "raise KeyError(f\"Tag '{key}' is already registered.\")" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# Al" }, { "role": "assistant", "content": "l rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use\n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact george.drettakis@inria.fr\n#" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "sult, expected)\n\n\n@pytest.mark.parametrize(\n \"header, expected_data\",\n [\n (\n 0,\n {\n \"Title\": [np.nan, \"A\", 1, 2, 3],\n \"Unnamed: 1\": [np.nan, \"B\", 4, 5, 6],\n \"Unnamed: 2\": [np.nan, \"C\", 7, 8, 9],\n },\n ),\n (2, {\"A\": [1, 2, 3], \"B\": [4, 5, 6], \"C\": [7, 8, 9]}),\n ],\n)\n@pytest.mark.parametrize(\n \"filename\", [\"dimension_missing\", \"dimension_small\", \"dimension_large\"]\n)\n# When read_only is None, use read_excel instead of a workbook\n@pytest.mark.parametrize(\"read_only\", [True, False, None])\ndef test_read_with_bad_dimension(\n datapath, ext, header, expected_data, filename, read_only\n):\n # GH 38956, 39001 - no/incorrect dimension information\n path = datapath(\"io\", \"data\", \"excel\", f\"{filename}{ext}\")\n if read_only is None:\n result = pd.read_excel(path, header=header)\n else:\n with contextlib.closing(\n openpyxl.load_workbook(path, read_only=read_only)\n ) as wb:\n result = pd.read_excel(wb, engine=\"openpyxl\", header=header)\n expected = DataFrame(expected_data)\n tm.assert_frame_equal(result, expected)\n\n\ndef test_append_mode_file(ext):\n # GH 39576\n df = DataFrame()\n\n with tm.ensure_clean(ext) as f:\n df.to_excel(f, engine=\"openpyxl\")\n\n with ExcelWriter(\n f, mode=\"a\", engine=\"openpyxl\", if_sheet_exists=\"new\"\n ) as writer:\n df.to_excel(writer)\n\n # make sure that zip files are not concatenated by making sure that\n # \"docProps/app.xml\" only occurs twice in the file\n data = Path(f).read_bytes()\n first = data.find(b\"docProps/app.xml\")\n second = data.find(b\"docProps/app.xml\", first + 1)\n third = data.find(b\"docProps/app.xml\", second + 1)\n assert second != -1 and third == -1\n\n\n# When read_only is None, use read_excel instead of a workbook\n@pytest.mark.parametrize(\"read_only\", [True, False, None])\ndef test_read_wi" }, { "role": "assistant", "content": "th_empty_trailing_rows(datapath, ext, read_only):\n # GH 39181\n path = datapath(\"io\", \"data\", \"excel\", f\"empty_trailing_rows{ext}\")\n if read_only is None:\n result = pd.read_excel(path)\n else:\n with contextlib.closing(\n openpyxl.load_workbook(path, read_only=read_only)\n ) as wb:\n result = pd.read_excel(wb, engine=\"openpyxl\")\n expected = DataFrame(\n {\n \"Title\": [np.nan, \"A\", 1, 2, 3],\n \"Unnamed: 1\": [np.nan, \"B\", 4, 5, 6],\n \"Unnamed: 2\": [np.nan, \"C\", 7, 8, 9],\n }\n )\n tm.assert_frame_equal(result, expected)" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": ".\n\n other: a number\n\n returns: new Pmf\n \"\"\"\n pmf = Pmf()\n for v1, p1 in self.Items():\n pmf.Set(v1 + other, p1)\n return pmf\n\n def __sub__(self, other):\n \"\"\"Computes the Pmf of the diff of values drawn from self and other.\n\n other: another Pmf\n\n returns: new Pmf\n \"\"\"\n try:\n return self.SubPmf(other)\n except AttributeError:\n return self.AddConstant(-other)\n\n def SubPmf(self, other):\n \"\"\"Computes the Pmf of the diff of values drawn from self and other.\n\n other: another Pmf\n\n returns: new Pmf\n \"\"\"\n pmf = Pmf()\n for v1, p1 in self.Items():\n for v2, p2 in other.Items():\n pmf.Incr(v1 - v2, p1 * p2)\n return pmf\n\n def __mul__(self, other):\n \"\"\"Computes the Pmf of the product of values drawn from self and other.\n\n other: another Pmf\n\n returns: new Pmf\n \"\"\"\n try:\n return self.MulPmf(other)\n except AttributeError:\n return self.MulConstant(other)\n\n def MulPmf(self, other):\n \"\"\"Computes the Pmf of the diff of values drawn from self and other.\n\n other: another Pmf\n\n returns: new Pmf\n \"\"\"\n pmf = Pmf()\n for v1, p1 in self.Items():\n for v2, p2 in other.Items():\n pmf.Incr(v1 * v2, p1 * p2)\n return pmf\n\n def MulConstant(self, other):\n \"\"\"Computes the Pmf of the product of a constant and values from self.\n\n other: a number\n\n returns: new Pmf\n \"\"\"\n pmf = Pmf()\n for v1, p1 in self.Items():\n pmf.Set(v1 * other, p1)\n return pmf\n\n def __div__(self, other):\n \"\"\"Computes the Pmf of the ratio of values drawn from self and other.\n\n other: another Pmf\n\n returns: new Pmf\n \"\"\"\n try:\n return self.DivPmf(other)\n except AttributeError:\n return self.MulConstant(1/other)\n\n __truediv__ = __div__\n\n def DivPmf(self, other):\n \"\"\"Computes the Pmf of the ratio of values drawn from self and other.\n\n other: another Pmf\n\n returns: new Pmf\n \"\"\"\n pmf = Pmf()\n for v1, p1 in self.Items():\n for v2, p2 in other.Items():\n pmf.Incr(v1 / v2, p1 * p2)\n return pmf\n\n def Max(self, k):\n \"\"\"Computes the CDF of the maximum of k selections from this dist.\n\n k: int\n\n returns: new Cdf\n \"\"\"\n cdf = self.MakeCdf()\n return cdf.Max(k)\n\n\nclass Joint(Pmf):\n \"\"\"Represents a joint distribution.\n\n The values are sequences (usually tuples)\n \"\"\"\n\n def Marginal(self, i, label=None):\n \"\"\"Gets the marginal distribution of the indicated variable.\n\n i: index of the variable we want\n\n Returns: Pmf\n \"\"\"\n pmf = Pmf(label=label)\n for vs, prob in self.Items():\n pmf.Incr(vs[i], prob)\n return pmf\n\n def Conditional(self, i, j, val, label=None):\n \"\"\"Gets the conditional distribution of the indicated variable.\n\n Distribution of vs[i], conditioned on vs[j] = val.\n\n i: index of the variable we want\n j: which variable is conditioned on\n val: the value the jth variable has to have\n\n Returns: Pmf\n \"\"\"\n pmf = Pmf(label=label)\n for vs, prob in self.Items():\n if vs[j] != val:\n continue\n pmf.Incr(vs[i], prob)\n\n pmf.Normalize()\n return pmf\n\n def MaxLikeInterval(self, percentage=90):\n \"\"\"Returns the maximum-likelihood credible interval.\n\n If percentage=90, computes a 90% CI containing the values\n with the highest likelihoods.\n\n percentage: float between 0 and 100\n\n Returns: list of values from the suite\n \"\"\"\n interval = []\n total = 0\n\n t = [(prob, val) for val, prob in self.Items()]\n t.sort(reverse=True)\n\n for prob, val in t:\n interval.append(val)\n total += prob\n if total = percentage / 100.0:\n break\n\n return interval\n\n\ndef MakeJoint(pmf1, pmf2):\n \"\"\"Joint distribution of values from pmf1 and pmf2.\n\n Assumes that the PMFs represent independent random variables.\n\n Args:\n pmf1: Pmf object\n pmf2: Pmf object\n\n Returns:\n Joint pmf of value pairs\n \"\"\"\n joint = Joint()\n for v1, p1 in pmf1.Items():\n for v2, p2 in pmf2.Items():\n joint.Set((v1, v2), p1 * p2)\n return joint\n\n\ndef MakeHistFromList(t, label=None):\n \"\"\"Makes a histogram from an unsorted sequence of values.\n\n Args:\n t: sequence of numbers\n label: string label for this histogram\n\n Returns:\n Hist object\n \"\"\"\n return Hist(t, label=label)\n\n\ndef MakeHistFromDict(d, label=None):\n \"\"\"Makes a histogram from a map from values to frequencies.\n\n Args:\n d: dictionary that maps values to frequencies\n label: string label for this histogram\n\n Returns:\n Hist object\n \"\"\"\n return Hist(d, label)\n\n\ndef MakePmfFromList(t, label=None):\n \"\"\"Makes a PMF from an unsorted sequence of values.\n\n Args:\n t: sequence of numbers\n label: string label for this PMF\n\n Returns:\n Pmf object\n \"\"\"\n return Pmf(t, label=label)\n\n\ndef MakePmfFromDict(d, label=None):\n \"\"\"Makes a PMF from a map from values to probabilities.\n\n Args:\n d: dictionary that maps values to probabilities\n label: string label for this PMF\n\n Returns:\n Pmf object\n \"\"\"\n return Pmf(d, label=label)\n\n\ndef MakePmfFromItems(t, label=None):\n \"\"\"Makes a PMF from a sequence of value-probability pairs\n\n Args:\n t: sequence of value-probability pairs\n label: string label for this PMF\n\n Returns:\n Pmf object\n \"\"\"\n return Pmf(dict(t), label=label)\n\n\ndef MakePmfFromHist(hist, label=None):\n \"\"\"Makes a normalized PMF from a Hist object.\n\n Args:\n hist: Hist object\n label: string label\n\n Returns:\n Pmf object\n \"\"\"\n if label is None:\n label = hist.label\n\n return Pmf(hist, label=label)\n\n\ndef MakeMixture(metapmf, label='mix'):\n \"\"\"Make a mixture distribution.\n\n Args:\n metapmf: Pmf that maps from Pmfs to probs.\n label: string label for the new Pmf.\n\n Returns: Pmf object.\n \"\"\"\n mix = Pmf(label=label)\n for pmf, p1 in metapmf.Items():\n for x, p2 in pmf.Items():\n mix.Incr(x, p1 * p2)\n return mix\n\n\ndef MakeUniformPmf(low, high, n):\n \"\"\"Make a uniform Pmf.\n\n low: lowest value (inclusive)\n high: highest value (inclusize)\n n: number of values\n \"\"\"\n pmf = Pmf()\n for x in np.linspace(low, high, n):\n pmf.Set(x, 1)\n pmf.Normalize()\n return pmf\n\n\nclass Cdf(object):\n \"\"\"Represents a cumulative distribution function.\n\n Attributes:\n xs: sequence of values\n ps: sequence of probabilities\n label: string used as a graph label.\n \"\"\"\n def __init__(self, obj=None, ps=None, label=None):\n \"\"\"Initializes.\n \n If ps is provided, obj must be the corresponding list of values.\n\n obj: Hist, Pmf, Cdf, Pdf, dict, pandas Series, list of pairs\n ps: list of cumulative probabilities\n label: string label\n \"\"\"\n self.label = label if label is not None else '_nolegend_'\n\n if isinstance(obj, (_DictWrapper, Cdf, Pdf)):\n if not label:\n self.label = label if label is not None else obj.label\n\n if obj is None:\n # caller does not provide obj, make an empty Cdf\n self.xs = np.asarray([])\n self.ps = np.asarray([])\n if ps is not None:\n logging.warning(\"Cdf: can't pass ps without also passing xs.\")\n return\n else:\n # if the caller provides xs and ps, just store them \n if ps is not None:\n if isinstance(ps, str):\n logging.warning(\"Cdf: ps can't be a string\")\n\n self.xs = np.asarray(obj)\n self.ps = np.asarray(ps)\n return\n\n # caller has provided just obj, not ps\n if isinstance(obj, Cdf):\n self.xs = copy.copy(obj.xs)\n self.ps = copy.copy(obj.ps)\n return\n\n if isinstance(obj, _DictWrapper):\n dw = obj\n else:\n dw = Hist(obj)\n\n if len(dw) == 0:\n self.xs = np.asarray([])\n self.ps = np.asarray([])\n return\n\n xs, freqs = zip(*sorted(dw.Items()))\n self.xs = np.asarray(xs)\n self.ps = np.cumsum(freqs, dtype=np.float)\n self.ps /= self.ps[-1]\n\n def __str__(self):\n return 'Cdf(%s, %s)' % (str(self.xs), str(self.ps))\n\n __repr__ = __str__\n\n def __len__(self):\n return len(self.xs)\n\n def __getitem__(self, x):\n return self.Prob(x)\n\n def __setitem__(self):\n raise UnimplementedMethodException()\n\n def __delitem__(self):\n raise UnimplementedMethodException()\n\n def __eq__(self, other):\n return np.all(self.xs == other.xs) and np.all(self.ps == other.ps)\n\n def Copy(self, label=None):\n \"\"\"Returns a copy of this Cdf.\n\n label: string label for the new Cdf\n \"\"\"\n if label is None:\n label = self.label\n return Cdf(list(self.xs), list(self.ps), label=label)\n\n def MakePmf(self, label=None):\n \"\"\"Makes a Pmf.\"\"\"\n if label is None:\n label = self.label\n return Pmf(self, label=label)\n\n def Values(self):\n \"\"\"Returns a sorted list of values.\n \"\"\"\n return self.xs\n\n def Items(self):\n \"\"\"Returns a sorted sequence o" }, { "role": "assistant", "content": "f (value, probability) pairs.\n\n Note: in Python3, returns an iterator.\n \"\"\"\n a = self.ps\n b = np.roll(a, 1)\n b[0] = 0\n return zip(self.xs, a-b)" } ]
[ { "role": "system", "content": "You are AutocompleteGPT, a useful AI autocomplete tool that provides code completions based on the user's code.\nYou are a precision-focused tool for code autocompletion, adept in languages like Python, JavaScript, C++, and SQL.\nPrecisely continue the code from the point of interruption and do not repeat or modify the original code, even if it is incorrect or the code interrupts in the middle of a line.\nYour code is well documented with comments and annotations, and you should provide a clear explanation of the code's purpose in your code completion.\nYour unique capability is to provide completions without altering, repeating, or commenting on the original code.\nYou offer only the necessary code to complete the snippet, ensuring the response is exclusively code, with no additional comments, explanations, or annotations.\nThis approach makes you an ideal assistant for users seeking straightforward and efficient code extensions, enhancing their work with accurate, logic-driven completions while maintaining the integrity and simplicity of the original input.\nYour response begins with the next characters of the line if the last line of the user'S code is incomplete, or the next line if the last line of the user's code is complete.\nYour application is a VSCode extension like GitHub Copilot, which provides seamless code completions based on the user's code at the point of interruption.\n" }, { "role": "user", "content": "# composite fields. In the meantime we take this practical approach to\n # solve a regression on 1.6 when the reverse manager in hidden\n # (related_name ends with a '+'). Refs #21410.\n # The check for len(...) == 1 is a special case that allows the query\n # to be join-less and smaller. Refs #21760.\n if remote_field.is_hidden() or len(self.field.foreign_related_fields) == 1:\n query = {\n \"%s__in\"\n % related_field.name: {instance_attr(inst)[0] for inst in instances}\n }\n else:\n query = {\"%s__in\" % self.field.related_query_name(): instances}\n queryset = queryset.filter(**query)\n\n # Since we're going to assign directly in the cache,\n # we must manage the reverse relation cache manually.\n if not remote_field.multiple:\n for rel_obj in queryset:\n instance = instances_dict[rel_obj_attr(rel_obj)]\n remote_field.set_cached_value(rel_obj, instance)\n return (\n queryset,\n rel_obj_attr,\n instance_attr,\n True,\n self.field.get_cache_name(),\n False,\n )\n\n def get_object(self, instance):\n qs = self.get_queryset(instance=instance)\n # Assuming the database enforces foreign keys, this won't fail.\n return qs.get(self.field.get_reverse_related_filter(instance))\n\n def __get__(self, instance, cls=None):\n \"\"\"\n Get the related instance through the forward relation.\n\n With the example above, when getting ``child.parent``:\n\n - ``self`` is the descriptor managing the ``parent`` attribute\n - ``instance`` is the ``child`` instance\n - ``cls`` is the ``Child`` class (we don't need it)\n \"\"\"\n if instance is None:\n return self\n\n # The related instance is loaded from the database and then cached\n # by the field on the model instance state. It can also be pre-cached\n # by the reverse accessor (ReverseOneToOneDescriptor).\n try:\n rel_obj = self.field.get_cached_value(instance)\n except KeyError:\n has_value = None not in self.field.get_local_related_value(instance)\n ancestor_link = (\n instance._meta.get_ancestor_link(self.field.model)\n if has_value\n else None\n )\n if ancestor_link and ancestor_link.is_cached(instance):\n # An ancestor link will exist if this field is defined on a\n # multi-table inheritance parent of the instance's class.\n ancestor = ancestor_link.get_cached_value(instance)\n # The value might be cached on an ancestor if the instance\n # originated from walking down the inheritance chain.\n rel_obj = self.field.get_cached_value(ancestor, default=None)\n else:\n rel_obj = None\n if rel_obj is None and has_value:\n rel_obj = self.get_object(instance)\n remote_field = self.field.remote_field\n # If this is a one-to-one relation, set the reverse accessor\n # cache on the related object to the current instance to avoid\n # an extra SQL query if it's accessed later on.\n if not remote_field.multiple:\n remote_field.set_cached_value(rel_obj, instance)\n self.field.set_cached_value(instance, rel_obj)\n\n if rel_obj is None and not self.field.null:\n raise self.RelatedObjectDoesNotExist(\n \"%s has no %s.\" % (self.field.model.__name__, self.field.name)\n )\n else:\n return rel_obj\n\n def __set__(self, instance, value):\n \"\"\"\n Set the related instance through the forward relation.\n\n With the example above, when setting ``child.parent = parent``:\n\n - ``self`` is the descriptor managing the ``parent`` attribute\n - ``instance`` is the ``child`` instance\n - ``value`` is the ``parent`` instance on the right of the equal sign\n \"\"\"\n # An object must be an instance of the related class.\n if value is not None and not isinstance(\n value, self.field.remote_field.model._meta.concrete_model\n ):\n raise ValueError(\n 'Cannot assign \"%r\": \"%s.%s\" must be a \"%s\" instance.'\n % (\n value,\n instance._meta.object_name,\n self.field.name,\n self.field.remote_field.model._meta.object_name,\n )\n )\n elif value is not None:\n if instance._state.db is None:\n instance._state.db = router.db_for_write(\n instance.__class__, instance=value\n )\n if value._state.db is None:\n value._state.db = router.db_for_write(\n value.__class__, instance=instance\n )\n if not router.allow_relation(value, instance):\n raise ValueError(\n 'Cannot assign \"%r\": the current database router prevents this '\n \"relation.\" % value\n )\n\n remote_field = self.field.remote_field\n # If we're setting the value of a OneToOneField to None, we need to clear\n # out the cache on any old related object. Otherwise, deleting the\n # previously-related object will also cause this object to be deleted,\n # which is wrong.\n if value is None:\n # Look up the previously-related object, which may still be available\n # since we've not yet cleared out the related field.\n # Use the cache directly, instead of the accessor; if we haven't\n # populated the cache, then we don't care - we're only accessing\n # the object to invalidate the accessor cache, so there's no\n # need to populate the cache just to expire it again.\n related = self.field.get_cached_value(instance, default=None)\n\n # If we've got an old related object, we need to clear out its\n # cache. This cache also might not exist if the related object\n # hasn't been accessed yet.\n if related is not None:\n remote_field.set_cached_value(related, None)\n\n for lh_field, rh_field in self.field.related_fields:\n setattr(instance, lh_field.attname, None)\n\n # Set the values of the related field.\n else:\n for lh_field, rh_field in self.field.related_fields:\n setattr(instance, lh_field.attname, getattr(value, rh_field.attname))\n\n # Set the related instance cache used by __get__ to avoid an SQL query\n # when accessing the attribute we just set.\n self.field.set_cached_value(instance, value)\n\n # If this is a one-to-one relation, set the reverse accessor cache on\n # the related object to the current instance to avoid an extra SQL\n # query if it's accessed later on.\n if value is not None and not remote_field.multiple:\n remote_field.set_cached_value(value, instance)\n\n def __reduce__(self):\n \"\"\"\n Pickling should return the instance attached by self.field on the\n model, not a new copy of that descriptor. Use getattr() to retrieve\n the instance directly from the model.\n \"\"\"\n return getattr, (self.field.model, self.field.name)\n\n\nclass ForwardOneToOneDescriptor(ForwardManyToOneDescriptor):\n \"\"\"\n Accessor to the related object on the forward side of a one-to-one relation.\n\n In the example::\n\n class Restaurant(Model):\n place = OneToOneField(Place, related_name='restaurant')\n\n ``Res" }, { "role": "assistant", "content": "taurant.place`` is a ``ForwardOneToOneDescriptor`` instance.\n \"\"\"" } ]