{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef update(self, gist, content):\n # abort if content is False\n if content is False:\n return False\n\n # request\n url = self._api_url(\"gists\", gist.get(\"id\"))\n data = {\"files\": {self.filename: {\"content\": content}}}\n self.output(\"Sending contents of {} to {}\".format(self.file_path, url))\n response = self.requests.patch(url, data=dumps(data))\n\n # error\n if response.status_code != 200:\n self.oops(\"Could not update \" + gist.get(\"description\"))\n self.oops(\"PATCH request returned \" + str(response.status_code))\n return False\n\n # success\n self.yeah(\"Done!\")\n self.hey(\"The URL to this Gist is: {}\".format(gist[\"url\"]))\n return True", "response": "Updates the contents of a gist at GitHub."} {"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef create(self, content, **kwargs):\n # abort if content is False\n if content is False:\n return False\n\n # set new gist\n public = bool(kwargs.get(\"public\", True))\n data = {\n \"description\": self.filename,\n \"public\": public,\n \"files\": {self.filename: {\"content\": content}},\n }\n\n # send request\n url = self._api_url(\"gists\")\n self.output(\"Sending contents of {} to {}\".format(self.file_path, url))\n response = self.requests.post(url, data=dumps(data))\n\n # error\n if response.status_code != 201:\n self.oops(\"Could not create \" + self.filename)\n self.oops(\"POST request returned \" + str(response.status_code))\n return False\n\n # parse created gist\n gist = self._parse_gist(response.json())\n\n # success\n self.yeah(\"Done!\")\n self.hey(\"The URL to this Gist is: {}\".format(gist[\"url\"]))\n return True", "response": "Create a new gist."} {"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nasks user which gist to use in case of more than one gist matching the instance filename.", "response": "def _ask_which_gist(self, matches):\n \"\"\"\n Asks user which gist to use in case of more than one gist matching the\n instance filename.\n :param matches: (list) of dictioaries generated within select_gists()\n :return: (dict) of the selected gist\n \"\"\"\n # ask user which gist to use\n self.hey(\"Use {} from which gist?\".format(self.filename))\n for count, gist in enumerate(matches, 1):\n self.hey(\"[{}] {}\".format(count, gist.get(\"description\")))\n\n # get the gist index\n selected = False\n while not selected:\n gist_index = prompt(\"Type the number: \", type=int) - 1\n try:\n selected = matches[gist_index]\n except IndexError:\n self.oops(\"Invalid number, please try again.\")\n\n self.output(\"Using `{}` Gist\".format(selected[\"description\"]))\n return selected"} {"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nreceive a gist dict and parse it to GetGist", "response": "def _parse_gist(gist):\n \"\"\"Receive a gist (dict) and parse it to GetGist\"\"\"\n\n # parse files\n files = list()\n file_names = sorted(filename for filename in gist[\"files\"].keys())\n for name in file_names:\n files.append(\n dict(filename=name, raw_url=gist[\"files\"][name].get(\"raw_url\"))\n )\n\n # parse description\n description = gist[\"description\"]\n if not description:\n names = sorted(f.get(\"filename\") for f in files)\n description = names.pop(0)\n\n return dict(\n description=description,\n id=gist.get(\"id\"),\n files=files,\n url=gist.get(\"html_url\"),\n )"} {"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef indent(self, message):\n indent = self.indent_char * self.indent_size\n return indent + message", "response": "Sets the indent for standardized output\n "} {"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef get(self, url, params=None, **kwargs):\n return requests.get(url, params=params, headers=self.add_headers(**kwargs))", "response": "Encapsulte requests. get to use this class instance header"} {"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef patch(self, url, data=None, **kwargs):\n return requests.patch(url, data=data, headers=self.add_headers(**kwargs))", "response": "Encapsulte requests. patch to use this class instance header"} {"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef post(self, url, data=None, **kwargs):\n return requests.post(url, data=data, headers=self.add_headers(**kwargs))", "response": "Encapsulte requests. post to use this class instance header"} {"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef save(self, content):\n # backup existing file if needed\n if os.path.exists(self.file_path) and not self.assume_yes:\n message = \"Overwrite existing {}? (y/n) \"\n if not confirm(message.format(self.filename)):\n self.backup()\n\n # write file\n self.output(\"Saving \" + self.filename)\n with open(self.file_path, \"wb\") as handler:\n if not isinstance(content, bytes):\n content = bytes(content, \"utf-8\")\n handler.write(content)\n self.yeah(\"Done!\")", "response": "Save any given content to the instance file."} {"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef backup(self):\n count = 0\n name = \"{}.bkp\".format(self.filename)\n backup = os.path.join(self.cwd, name)\n while os.path.exists(backup):\n count += 1\n name = \"{}.bkp{}\".format(self.filename, count)\n backup = os.path.join(self.cwd, name)\n self.hey(\"Moving existing {} to {}\".format(self.filename, name))\n os.rename(os.path.join(self.cwd, self.filename), backup)", "response": "Backups files with the same name of the instance filename"} {"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nread the contents of a file in the local file system.", "response": "def read(self, file_path=None):\n \"\"\"\n Read the contents of a file.\n :param filename: (str) path to a file in the local file system\n :return: (str) contents of the file, or (False) if not found/not file\n \"\"\"\n if not file_path:\n file_path = self.file_path\n\n # abort if the file path does not exist\n if not os.path.exists(file_path):\n self.oops(\"Sorry, but {} does not exist\".format(file_path))\n return False\n\n # abort if the file path is not a file\n if not os.path.isfile(file_path):\n self.oops(\"Sorry, but {} is not a file\".format(file_path))\n return False\n\n with open(file_path) as handler:\n return handler.read()"} {"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef str_matcher(mode):\r\n\r\n def f_raw(inp_str, pos):\r\n return unique_literal_cache_pool[mode] if inp_str.startswith(mode, pos) else None\r\n\r\n def f_collection(inp_str, pos):\r\n for each in mode:\r\n if inp_str.startswith(each, pos):\r\n return unique_literal_cache_pool[each]\r\n return None\r\n\r\n if isinstance(mode, str):\r\n return f_raw\r\n\r\n if len(mode) is 1:\r\n mode = mode[0]\r\n return f_raw\r\n\r\n return f_collection", "response": "Returns a function that returns a list of tokens that match the input string."} {"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef regex_matcher(regex_pat):\r\n if isinstance(regex_pat, str):\r\n regex_pat = re.compile(regex_pat)\r\n\r\n def f(inp_str, pos):\r\n m = regex_pat.match(inp_str, pos)\r\n return m.group() if m else None\r\n\r\n return f", "response": "generate token names cache\r\n generate token names"} {"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef ast_for_stmts(self, stmts: T) -> None:\r\n if not stmts:\r\n raise ValueError('no ast found!')\r\n head, *equals = stmts\r\n\r\n if head.name is NameEnum.TokenDef:\r\n self.ast_for_token_def(head)\r\n elif head.name is NameEnum.TokenIgnore:\r\n self.ast_for_token_ignore(head)\r\n else:\r\n self.ast_for_equals(head)\r\n\r\n for each in equals:\r\n self.ast_for_equals(each)\r\n\r\n # if every combined parser can reach any other combined, \r\n # just take any of them and compile it!\r\n if not self.compile_helper.alone and self._current__combined_parser_name:\r\n self.compile_helper.alone.add(self._current__combined_parser_name)", "response": "Add the ast for the given list of statements."} {"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef _request(self, method, resource_uri, **kwargs):\n data = kwargs.get('data')\n response = method(self.API_BASE_URL + resource_uri,\n json=data, headers=self.headers)\n response.raise_for_status()\n return response.json()", "response": "Perform a method on a resource."} {"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\ngetting a resource s nacms.", "response": "def get(self, endpoint, **kwargs):\n \"\"\"Get a resource.\n\n Args:\n endpoint: resource endpoint.\n \"\"\"\n return self._request(requests.get, endpoint, **kwargs)"} {"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\ncreate a resource. Args: endpoint: resource endpoint.", "response": "def post(self, endpoint, **kwargs):\n \"\"\"Create a resource.\n\n Args:\n endpoint: resource endpoint.\n \"\"\"\n return self._request(requests.post, endpoint, **kwargs)"} {"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef put(self, endpoint, **kwargs):\n return self._request(requests.put, endpoint, **kwargs)", "response": "Update a resource s nacms."} {"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\ntake Slack formatted text and returns HTML.", "response": "def render(txt):\n \"\"\"\n Accepts Slack formatted text and returns HTML.\n \"\"\"\n\n # Removing links to other channels\n txt = re.sub(r'<#[^\\|]*\\|(.*)>', r'#\\g<1>', txt)\n\n # Removing links to other users\n txt = re.sub(r'<(@.*)>', r'\\g<1>', txt)\n\n # handle named hyperlinks\n txt = re.sub(r'<([^\\|]*)\\|([^\\|]*)>', r'\" target=\"blank\">\\g<2>', txt)\n\n # handle unnamed hyperlinks\n txt = re.sub(r'<([^a|/a].*)>', r'\" target=\"blank\">\\g<1>', txt)\n\n # handle ordered and unordered lists\n for delimeter in LIST_DELIMITERS:\n slack_tag = delimeter\n class_name = LIST_DELIMITERS[delimeter]\n\n # Wrap any lines that start with the slack_tag in
\n list_regex = u'(?:^|\\n){}\\s?(.*)'.format(slack_tag)\n list_repl = r'\\g<2>', txt, flags=re.DOTALL)\n txt = re.sub(u'(?:^|\\n)>\\s?(.*)\\n?', r'
\\g<1>', txt)\n\n # handle code blocks\n txt = re.sub(r'```\\n?(.*)```', r'
\\g<1>', txt, flags=re.DOTALL)\n txt = re.sub(r'\\n()', r'\\g<1>', txt)\n\n # handle bolding, italics, and strikethrough\n for wrapper in FORMATTERS:\n slack_tag = wrapper\n html_tag = FORMATTERS[wrapper]\n\n # Grab all text in formatted characters on the same line unless escaped\n regex = r'(?\\g<1>{t}>'.format(t=html_tag)\n txt = re.sub(regex, repl, txt)\n\n # convert line breaks\n txt = txt.replace('\\n', '
'\n self.current_parent_element['tag'] = 'p'\n self.cleaned_html += '<{}'.format(tag)\n\n for attr in sorted(attrs_dict.keys()):\n self.cleaned_html += ' {k}=\"{v}\"'.format(\n k=attr,\n v=attrs_dict[attr]\n )\n\n self.cleaned_html += '>'"} {"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\ncall by HTMLParser. feed when an end tag is found.", "response": "def handle_endtag(self, tag):\n \"\"\"\n Called by HTMLParser.feed when an end tag is found.\n \"\"\"\n if tag in PARENT_ELEMENTS:\n self.current_parent_element['tag'] = ''\n self.current_parent_element['attrs'] = ''\n\n if tag == 'li':\n self.parsing_li = True\n if tag != 'br':\n self.cleaned_html += '{}>'.format(tag)"} {"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef handle_data(self, data):\n if self.current_parent_element['tag'] == '':\n self.cleaned_html += '
'\n self.current_parent_element['tag'] = 'p'\n\n self.cleaned_html += data", "response": "Called by HTMLParser. feed when text is found."} {"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nremoves formatting tags added to pre elements.", "response": "def _remove_pre_formatting(self):\n \"\"\"\n Removes formatting tags added to pre elements.\n \"\"\"\n preformatted_wrappers = [\n 'pre',\n 'code'\n ]\n\n for wrapper in preformatted_wrappers:\n for formatter in FORMATTERS:\n tag = FORMATTERS[formatter]\n character = formatter\n\n regex = r'(<{w}>.*)<{t}>(.*){t}>(.*{w}>)'.format(\n t=tag,\n w=wrapper\n )\n repl = r'\\g<1>{c}\\g<2>{c}\\g<3>'.format(c=character)\n self.cleaned_html = re.sub(regex, repl, self.cleaned_html)"} {"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef clean(self):\n # Calls handle_starttag, handle_endtag, and handle_data\n self.feed()\n\n # Clean up any parent tags left open\n if self.current_parent_element['tag'] != '':\n self.cleaned_html += '{}>'.format(self.current_parent_element['tag'])\n\n # Remove empty
added after lists\n self.cleaned_html = re.sub(r'([u|o]l>)
', r'\\g<1>', self.cleaned_html)\n\n self._remove_pre_formatting()\n\n return self.cleaned_html", "response": "Cleans up any problematic HTML."} {"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef render_author(**kwargs):\n html = ''\n\n author_link = kwargs.get('author_link', None)\n if author_link:\n html += '{author_name}'.format(\n author_link=author_link,\n author_name=author_name\n )\n else:\n html += author_name\n\n html += '
'\n\n author_handle = kwargs.get('author_handle', None)\n if author_handle:\n html += '{}
'.format(author_handle)\n\n html += '