repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1
value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
coursera-dl/coursera-dl | coursera/api.py | CourseraOnDemand._extract_programming_immediate_instructions_text | def _extract_programming_immediate_instructions_text(self, element_id):
"""
Extract assignment text (instructions).
@param element_id: Element id to extract assignment instructions from.
@type element_id: str
@return: List of assignment text (instructions).
@rtype: [str... | python | def _extract_programming_immediate_instructions_text(self, element_id):
"""
Extract assignment text (instructions).
@param element_id: Element id to extract assignment instructions from.
@type element_id: str
@return: List of assignment text (instructions).
@rtype: [str... | [
"def",
"_extract_programming_immediate_instructions_text",
"(",
"self",
",",
"element_id",
")",
":",
"dom",
"=",
"get_page",
"(",
"self",
".",
"_session",
",",
"OPENCOURSE_PROGRAMMING_IMMEDIATE_INSTRUCTIOINS_URL",
",",
"json",
"=",
"True",
",",
"course_id",
"=",
"self... | Extract assignment text (instructions).
@param element_id: Element id to extract assignment instructions from.
@type element_id: str
@return: List of assignment text (instructions).
@rtype: [str] | [
"Extract",
"assignment",
"text",
"(",
"instructions",
")",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/api.py#L1394-L1410 | train |
coursera-dl/coursera-dl | coursera/api.py | CourseraOnDemand._extract_notebook_text | def _extract_notebook_text(self, element_id):
"""
Extract notebook text (instructions).
@param element_id: Element id to extract notebook links.
@type element_id: str
@return: Notebook URL.
@rtype: [str]
"""
headers = self._auth_headers_with_json()
... | python | def _extract_notebook_text(self, element_id):
"""
Extract notebook text (instructions).
@param element_id: Element id to extract notebook links.
@type element_id: str
@return: Notebook URL.
@rtype: [str]
"""
headers = self._auth_headers_with_json()
... | [
"def",
"_extract_notebook_text",
"(",
"self",
",",
"element_id",
")",
":",
"headers",
"=",
"self",
".",
"_auth_headers_with_json",
"(",
")",
"data",
"=",
"{",
"'courseId'",
":",
"self",
".",
"_course_id",
",",
"'learnerId'",
":",
"self",
".",
"_user_id",
","... | Extract notebook text (instructions).
@param element_id: Element id to extract notebook links.
@type element_id: str
@return: Notebook URL.
@rtype: [str] | [
"Extract",
"notebook",
"text",
"(",
"instructions",
")",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/api.py#L1412-L1436 | train |
coursera-dl/coursera-dl | coursera/api.py | CourseraOnDemand._extract_assignment_text | def _extract_assignment_text(self, element_id):
"""
Extract assignment text (instructions).
@param element_id: Element id to extract assignment instructions from.
@type element_id: str
@return: List of assignment text (instructions).
@rtype: [str]
"""
do... | python | def _extract_assignment_text(self, element_id):
"""
Extract assignment text (instructions).
@param element_id: Element id to extract assignment instructions from.
@type element_id: str
@return: List of assignment text (instructions).
@rtype: [str]
"""
do... | [
"def",
"_extract_assignment_text",
"(",
"self",
",",
"element_id",
")",
":",
"dom",
"=",
"get_page",
"(",
"self",
".",
"_session",
",",
"OPENCOURSE_PROGRAMMING_ASSIGNMENTS_URL",
",",
"json",
"=",
"True",
",",
"course_id",
"=",
"self",
".",
"_course_id",
",",
"... | Extract assignment text (instructions).
@param element_id: Element id to extract assignment instructions from.
@type element_id: str
@return: List of assignment text (instructions).
@rtype: [str] | [
"Extract",
"assignment",
"text",
"(",
"instructions",
")",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/api.py#L1438-L1455 | train |
coursera-dl/coursera-dl | coursera/api.py | CourseraOnDemand._extract_peer_assignment_text | def _extract_peer_assignment_text(self, element_id):
"""
Extract peer assignment text (instructions).
@param element_id: Element id to extract peer assignment instructions from.
@type element_id: str
@return: List of peer assignment text (instructions).
@rtype: [str]
... | python | def _extract_peer_assignment_text(self, element_id):
"""
Extract peer assignment text (instructions).
@param element_id: Element id to extract peer assignment instructions from.
@type element_id: str
@return: List of peer assignment text (instructions).
@rtype: [str]
... | [
"def",
"_extract_peer_assignment_text",
"(",
"self",
",",
"element_id",
")",
":",
"dom",
"=",
"get_page",
"(",
"self",
".",
"_session",
",",
"OPENCOURSE_PEER_ASSIGNMENT_INSTRUCTIONS",
",",
"json",
"=",
"True",
",",
"user_id",
"=",
"self",
".",
"_user_id",
",",
... | Extract peer assignment text (instructions).
@param element_id: Element id to extract peer assignment instructions from.
@type element_id: str
@return: List of peer assignment text (instructions).
@rtype: [str] | [
"Extract",
"peer",
"assignment",
"text",
"(",
"instructions",
")",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/api.py#L1457-L1492 | train |
coursera-dl/coursera-dl | coursera/api.py | CourseraOnDemand._extract_links_from_text | def _extract_links_from_text(self, text):
"""
Extract supplement links from the html text. Links may be provided
in two ways:
1. <a> tags with href attribute
2. <asset> tags with id attribute (requires additional request
to get the direct URL to the asset f... | python | def _extract_links_from_text(self, text):
"""
Extract supplement links from the html text. Links may be provided
in two ways:
1. <a> tags with href attribute
2. <asset> tags with id attribute (requires additional request
to get the direct URL to the asset f... | [
"def",
"_extract_links_from_text",
"(",
"self",
",",
"text",
")",
":",
"supplement_links",
"=",
"self",
".",
"_extract_links_from_a_tags_in_text",
"(",
"text",
")",
"extend_supplement_links",
"(",
"supplement_links",
",",
"self",
".",
"_extract_links_from_asset_tags_in_te... | Extract supplement links from the html text. Links may be provided
in two ways:
1. <a> tags with href attribute
2. <asset> tags with id attribute (requires additional request
to get the direct URL to the asset file)
@param text: HTML text.
@type text: str
... | [
"Extract",
"supplement",
"links",
"from",
"the",
"html",
"text",
".",
"Links",
"may",
"be",
"provided",
"in",
"two",
"ways",
":",
"1",
".",
"<a",
">",
"tags",
"with",
"href",
"attribute",
"2",
".",
"<asset",
">",
"tags",
"with",
"id",
"attribute",
"(",... | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/api.py#L1494-L1524 | train |
coursera-dl/coursera-dl | coursera/api.py | CourseraOnDemand._extract_links_from_asset_tags_in_text | def _extract_links_from_asset_tags_in_text(self, text):
"""
Scan the text and extract asset tags and links to corresponding
files.
@param text: Page text.
@type text: str
@return: @see CourseraOnDemand._extract_links_from_text
"""
# Extract asset tags fr... | python | def _extract_links_from_asset_tags_in_text(self, text):
"""
Scan the text and extract asset tags and links to corresponding
files.
@param text: Page text.
@type text: str
@return: @see CourseraOnDemand._extract_links_from_text
"""
# Extract asset tags fr... | [
"def",
"_extract_links_from_asset_tags_in_text",
"(",
"self",
",",
"text",
")",
":",
"# Extract asset tags from instructions text",
"asset_tags_map",
"=",
"self",
".",
"_extract_asset_tags",
"(",
"text",
")",
"ids",
"=",
"list",
"(",
"iterkeys",
"(",
"asset_tags_map",
... | Scan the text and extract asset tags and links to corresponding
files.
@param text: Page text.
@type text: str
@return: @see CourseraOnDemand._extract_links_from_text | [
"Scan",
"the",
"text",
"and",
"extract",
"asset",
"tags",
"and",
"links",
"to",
"corresponding",
"files",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/api.py#L1526-L1561 | train |
coursera-dl/coursera-dl | coursera/api.py | CourseraOnDemand._extract_links_from_a_tags_in_text | def _extract_links_from_a_tags_in_text(self, text):
"""
Extract supplement links from the html text that contains <a> tags
with href attribute.
@param text: HTML text.
@type text: str
@return: Dictionary with supplement links grouped by extension.
@rtype: {
... | python | def _extract_links_from_a_tags_in_text(self, text):
"""
Extract supplement links from the html text that contains <a> tags
with href attribute.
@param text: HTML text.
@type text: str
@return: Dictionary with supplement links grouped by extension.
@rtype: {
... | [
"def",
"_extract_links_from_a_tags_in_text",
"(",
"self",
",",
"text",
")",
":",
"soup",
"=",
"BeautifulSoup",
"(",
"text",
")",
"links",
"=",
"[",
"item",
"[",
"'href'",
"]",
".",
"strip",
"(",
")",
"for",
"item",
"in",
"soup",
".",
"find_all",
"(",
"... | Extract supplement links from the html text that contains <a> tags
with href attribute.
@param text: HTML text.
@type text: str
@return: Dictionary with supplement links grouped by extension.
@rtype: {
'<extension1>': [
('<link1>', '<title1>'),
... | [
"Extract",
"supplement",
"links",
"from",
"the",
"html",
"text",
"that",
"contains",
"<a",
">",
"tags",
"with",
"href",
"attribute",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/api.py#L1563-L1613 | train |
coursera-dl/coursera-dl | coursera/playlist.py | create_m3u_playlist | def create_m3u_playlist(section_dir):
"""
Create M3U playlist with contents of `section_dir`/*.mp4. The playlist
will be created in that directory.
@param section_dir: Path where to scan for *.mp4 files.
@type section_dir: str
"""
path_to_return = os.getcwd()
for (_path, subdirs, files... | python | def create_m3u_playlist(section_dir):
"""
Create M3U playlist with contents of `section_dir`/*.mp4. The playlist
will be created in that directory.
@param section_dir: Path where to scan for *.mp4 files.
@type section_dir: str
"""
path_to_return = os.getcwd()
for (_path, subdirs, files... | [
"def",
"create_m3u_playlist",
"(",
"section_dir",
")",
":",
"path_to_return",
"=",
"os",
".",
"getcwd",
"(",
")",
"for",
"(",
"_path",
",",
"subdirs",
",",
"files",
")",
"in",
"os",
".",
"walk",
"(",
"section_dir",
")",
":",
"os",
".",
"chdir",
"(",
... | Create M3U playlist with contents of `section_dir`/*.mp4. The playlist
will be created in that directory.
@param section_dir: Path where to scan for *.mp4 files.
@type section_dir: str | [
"Create",
"M3U",
"playlist",
"with",
"contents",
"of",
"section_dir",
"/",
"*",
".",
"mp4",
".",
"The",
"playlist",
"will",
"be",
"created",
"in",
"that",
"directory",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/playlist.py#L5-L25 | train |
coursera-dl/coursera-dl | coursera/extractors.py | CourseraExtractor.list_courses | def list_courses(self):
"""
List enrolled courses.
@return: List of enrolled courses.
@rtype: [str]
"""
course = CourseraOnDemand(session=self._session,
course_id=None,
course_name=None)
return c... | python | def list_courses(self):
"""
List enrolled courses.
@return: List of enrolled courses.
@rtype: [str]
"""
course = CourseraOnDemand(session=self._session,
course_id=None,
course_name=None)
return c... | [
"def",
"list_courses",
"(",
"self",
")",
":",
"course",
"=",
"CourseraOnDemand",
"(",
"session",
"=",
"self",
".",
"_session",
",",
"course_id",
"=",
"None",
",",
"course_name",
"=",
"None",
")",
"return",
"course",
".",
"list_courses",
"(",
")"
] | List enrolled courses.
@return: List of enrolled courses.
@rtype: [str] | [
"List",
"enrolled",
"courses",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/extractors.py#L34-L44 | train |
coursera-dl/coursera-dl | coursera/extractors.py | CourseraExtractor._get_on_demand_syllabus | def _get_on_demand_syllabus(self, class_name):
"""
Get the on-demand course listing webpage.
"""
url = OPENCOURSE_ONDEMAND_COURSE_MATERIALS_V2.format(
class_name=class_name)
page = get_page(self._session, url)
logging.debug('Downloaded %s (%d bytes)', url, le... | python | def _get_on_demand_syllabus(self, class_name):
"""
Get the on-demand course listing webpage.
"""
url = OPENCOURSE_ONDEMAND_COURSE_MATERIALS_V2.format(
class_name=class_name)
page = get_page(self._session, url)
logging.debug('Downloaded %s (%d bytes)', url, le... | [
"def",
"_get_on_demand_syllabus",
"(",
"self",
",",
"class_name",
")",
":",
"url",
"=",
"OPENCOURSE_ONDEMAND_COURSE_MATERIALS_V2",
".",
"format",
"(",
"class_name",
"=",
"class_name",
")",
"page",
"=",
"get_page",
"(",
"self",
".",
"_session",
",",
"url",
")",
... | Get the on-demand course listing webpage. | [
"Get",
"the",
"on",
"-",
"demand",
"course",
"listing",
"webpage",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/extractors.py#L61-L71 | train |
coursera-dl/coursera-dl | coursera/extractors.py | CourseraExtractor._parse_on_demand_syllabus | def _parse_on_demand_syllabus(self, course_name, page, reverse=False,
unrestricted_filenames=False,
subtitle_language='en',
video_resolution=None,
download_quizzes=False,
... | python | def _parse_on_demand_syllabus(self, course_name, page, reverse=False,
unrestricted_filenames=False,
subtitle_language='en',
video_resolution=None,
download_quizzes=False,
... | [
"def",
"_parse_on_demand_syllabus",
"(",
"self",
",",
"course_name",
",",
"page",
",",
"reverse",
"=",
"False",
",",
"unrestricted_filenames",
"=",
"False",
",",
"subtitle_language",
"=",
"'en'",
",",
"video_resolution",
"=",
"None",
",",
"download_quizzes",
"=",
... | Parse a Coursera on-demand course listing/syllabus page.
@return: Tuple of (bool, list), where bool indicates whether
there was at least on error while parsing syllabus, the list
is a list of parsed modules.
@rtype: (bool, list) | [
"Parse",
"a",
"Coursera",
"on",
"-",
"demand",
"course",
"listing",
"/",
"syllabus",
"page",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/extractors.py#L73-L239 | train |
coursera-dl/coursera-dl | coursera/workflow.py | _iter_modules | def _iter_modules(modules, class_name, path, ignored_formats, args):
"""
This huge function generates a hierarchy with hopefully more
clear structure of modules/sections/lectures.
"""
file_formats = args.file_formats
lecture_filter = args.lecture_filter
resource_filter = args.resource_filter... | python | def _iter_modules(modules, class_name, path, ignored_formats, args):
"""
This huge function generates a hierarchy with hopefully more
clear structure of modules/sections/lectures.
"""
file_formats = args.file_formats
lecture_filter = args.lecture_filter
resource_filter = args.resource_filter... | [
"def",
"_iter_modules",
"(",
"modules",
",",
"class_name",
",",
"path",
",",
"ignored_formats",
",",
"args",
")",
":",
"file_formats",
"=",
"args",
".",
"file_formats",
"lecture_filter",
"=",
"args",
".",
"lecture_filter",
"resource_filter",
"=",
"args",
".",
... | This huge function generates a hierarchy with hopefully more
clear structure of modules/sections/lectures. | [
"This",
"huge",
"function",
"generates",
"a",
"hierarchy",
"with",
"hopefully",
"more",
"clear",
"structure",
"of",
"modules",
"/",
"sections",
"/",
"lectures",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/workflow.py#L18-L97 | train |
coursera-dl/coursera-dl | coursera/workflow.py | _walk_modules | def _walk_modules(modules, class_name, path, ignored_formats, args):
"""
Helper generator that traverses modules in returns a flattened
iterator.
"""
for module in _iter_modules(modules=modules,
class_name=class_name,
path=path,
... | python | def _walk_modules(modules, class_name, path, ignored_formats, args):
"""
Helper generator that traverses modules in returns a flattened
iterator.
"""
for module in _iter_modules(modules=modules,
class_name=class_name,
path=path,
... | [
"def",
"_walk_modules",
"(",
"modules",
",",
"class_name",
",",
"path",
",",
"ignored_formats",
",",
"args",
")",
":",
"for",
"module",
"in",
"_iter_modules",
"(",
"modules",
"=",
"modules",
",",
"class_name",
"=",
"class_name",
",",
"path",
"=",
"path",
"... | Helper generator that traverses modules in returns a flattened
iterator. | [
"Helper",
"generator",
"that",
"traverses",
"modules",
"in",
"returns",
"a",
"flattened",
"iterator",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/workflow.py#L100-L113 | train |
coursera-dl/coursera-dl | coursera/workflow.py | CourseraDownloader._handle_resource | def _handle_resource(self, url, fmt, lecture_filename, callback, last_update):
"""
Handle resource. This function builds up resource file name and
downloads it if necessary.
@param url: URL of the resource.
@type url: str
@param fmt: Format of the resource (pdf, csv, et... | python | def _handle_resource(self, url, fmt, lecture_filename, callback, last_update):
"""
Handle resource. This function builds up resource file name and
downloads it if necessary.
@param url: URL of the resource.
@type url: str
@param fmt: Format of the resource (pdf, csv, et... | [
"def",
"_handle_resource",
"(",
"self",
",",
"url",
",",
"fmt",
",",
"lecture_filename",
",",
"callback",
",",
"last_update",
")",
":",
"overwrite",
"=",
"self",
".",
"_args",
".",
"overwrite",
"resume",
"=",
"self",
".",
"_args",
".",
"resume",
"skip_down... | Handle resource. This function builds up resource file name and
downloads it if necessary.
@param url: URL of the resource.
@type url: str
@param fmt: Format of the resource (pdf, csv, etc)
@type fmt: str
@param lecture_filename: File name of the lecture.
@type... | [
"Handle",
"resource",
".",
"This",
"function",
"builds",
"up",
"resource",
"file",
"name",
"and",
"downloads",
"it",
"if",
"necessary",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/workflow.py#L195-L246 | train |
coursera-dl/coursera-dl | coursera/formatting.py | get_lecture_filename | def get_lecture_filename(combined_section_lectures_nums,
section_dir,
secnum,
lecnum,
lecname,
title,
fmt):
"""
Prepare a destination lecture filename.
@para... | python | def get_lecture_filename(combined_section_lectures_nums,
section_dir,
secnum,
lecnum,
lecname,
title,
fmt):
"""
Prepare a destination lecture filename.
@para... | [
"def",
"get_lecture_filename",
"(",
"combined_section_lectures_nums",
",",
"section_dir",
",",
"secnum",
",",
"lecnum",
",",
"lecname",
",",
"title",
",",
"fmt",
")",
":",
"# FIXME: this is a quick and dirty solution to Filename too long",
"# problem. We need to think of a more... | Prepare a destination lecture filename.
@param combined_section_lectures_nums: Flag that indicates whether
section lectures should have combined numbering.
@type combined_section_lectures_nums: bool
@param section_dir: Path to current section directory.
@type section_dir: str
@param secnu... | [
"Prepare",
"a",
"destination",
"lecture",
"filename",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/formatting.py#L25-L76 | train |
coursera-dl/coursera-dl | coursera/downloaders.py | format_bytes | def format_bytes(bytes):
"""
Get human readable version of given bytes.
Ripped from https://github.com/rg3/youtube-dl
"""
if bytes is None:
return 'N/A'
if type(bytes) is str:
bytes = float(bytes)
if bytes == 0.0:
exponent = 0
else:
exponent = int(math.log... | python | def format_bytes(bytes):
"""
Get human readable version of given bytes.
Ripped from https://github.com/rg3/youtube-dl
"""
if bytes is None:
return 'N/A'
if type(bytes) is str:
bytes = float(bytes)
if bytes == 0.0:
exponent = 0
else:
exponent = int(math.log... | [
"def",
"format_bytes",
"(",
"bytes",
")",
":",
"if",
"bytes",
"is",
"None",
":",
"return",
"'N/A'",
"if",
"type",
"(",
"bytes",
")",
"is",
"str",
":",
"bytes",
"=",
"float",
"(",
"bytes",
")",
"if",
"bytes",
"==",
"0.0",
":",
"exponent",
"=",
"0",
... | Get human readable version of given bytes.
Ripped from https://github.com/rg3/youtube-dl | [
"Get",
"human",
"readable",
"version",
"of",
"given",
"bytes",
".",
"Ripped",
"from",
"https",
":",
"//",
"github",
".",
"com",
"/",
"rg3",
"/",
"youtube",
"-",
"dl"
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/downloaders.py#L214-L229 | train |
coursera-dl/coursera-dl | coursera/downloaders.py | get_downloader | def get_downloader(session, class_name, args):
"""
Decides which downloader to use.
"""
external = {
'wget': WgetDownloader,
'curl': CurlDownloader,
'aria2': Aria2Downloader,
'axel': AxelDownloader,
}
for bin, class_ in iteritems(external):
if getattr(ar... | python | def get_downloader(session, class_name, args):
"""
Decides which downloader to use.
"""
external = {
'wget': WgetDownloader,
'curl': CurlDownloader,
'aria2': Aria2Downloader,
'axel': AxelDownloader,
}
for bin, class_ in iteritems(external):
if getattr(ar... | [
"def",
"get_downloader",
"(",
"session",
",",
"class_name",
",",
"args",
")",
":",
"external",
"=",
"{",
"'wget'",
":",
"WgetDownloader",
",",
"'curl'",
":",
"CurlDownloader",
",",
"'aria2'",
":",
"Aria2Downloader",
",",
"'axel'",
":",
"AxelDownloader",
",",
... | Decides which downloader to use. | [
"Decides",
"which",
"downloader",
"to",
"use",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/downloaders.py#L389-L406 | train |
coursera-dl/coursera-dl | coursera/downloaders.py | Downloader.download | def download(self, url, filename, resume=False):
"""
Download the given url to the given file. When the download
is aborted by the user, the partially downloaded file is also removed.
"""
try:
self._start_download(url, filename, resume)
except KeyboardInterru... | python | def download(self, url, filename, resume=False):
"""
Download the given url to the given file. When the download
is aborted by the user, the partially downloaded file is also removed.
"""
try:
self._start_download(url, filename, resume)
except KeyboardInterru... | [
"def",
"download",
"(",
"self",
",",
"url",
",",
"filename",
",",
"resume",
"=",
"False",
")",
":",
"try",
":",
"self",
".",
"_start_download",
"(",
"url",
",",
"filename",
",",
"resume",
")",
"except",
"KeyboardInterrupt",
"as",
"e",
":",
"# keep the fi... | Download the given url to the given file. When the download
is aborted by the user, the partially downloaded file is also removed. | [
"Download",
"the",
"given",
"url",
"to",
"the",
"given",
"file",
".",
"When",
"the",
"download",
"is",
"aborted",
"by",
"the",
"user",
"the",
"partially",
"downloaded",
"file",
"is",
"also",
"removed",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/downloaders.py#L47-L64 | train |
coursera-dl/coursera-dl | coursera/downloaders.py | ExternalDownloader._prepare_cookies | def _prepare_cookies(self, command, url):
"""
Extract cookies from the requests session and add them to the command
"""
req = requests.models.Request()
req.method = 'GET'
req.url = url
cookie_values = requests.cookies.get_cookie_header(
self.session.... | python | def _prepare_cookies(self, command, url):
"""
Extract cookies from the requests session and add them to the command
"""
req = requests.models.Request()
req.method = 'GET'
req.url = url
cookie_values = requests.cookies.get_cookie_header(
self.session.... | [
"def",
"_prepare_cookies",
"(",
"self",
",",
"command",
",",
"url",
")",
":",
"req",
"=",
"requests",
".",
"models",
".",
"Request",
"(",
")",
"req",
".",
"method",
"=",
"'GET'",
"req",
".",
"url",
"=",
"url",
"cookie_values",
"=",
"requests",
".",
"... | Extract cookies from the requests session and add them to the command | [
"Extract",
"cookies",
"from",
"the",
"requests",
"session",
"and",
"add",
"them",
"to",
"the",
"command"
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/downloaders.py#L89-L102 | train |
coursera-dl/coursera-dl | coursera/downloaders.py | DownloadProgress.report_progress | def report_progress(self):
"""Report download progress."""
percent = self.calc_percent()
total = format_bytes(self._total)
speed = self.calc_speed()
total_speed_report = '{0} at {1}'.format(total, speed)
report = '\r{0: <56} {1: >30}'.format(percent, total_speed_report)... | python | def report_progress(self):
"""Report download progress."""
percent = self.calc_percent()
total = format_bytes(self._total)
speed = self.calc_speed()
total_speed_report = '{0} at {1}'.format(total, speed)
report = '\r{0: <56} {1: >30}'.format(percent, total_speed_report)... | [
"def",
"report_progress",
"(",
"self",
")",
":",
"percent",
"=",
"self",
".",
"calc_percent",
"(",
")",
"total",
"=",
"format_bytes",
"(",
"self",
".",
"_total",
")",
"speed",
"=",
"self",
".",
"calc_speed",
"(",
")",
"total_speed_report",
"=",
"'{0} at {1... | Report download progress. | [
"Report",
"download",
"progress",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/downloaders.py#L285-L299 | train |
coursera-dl/coursera-dl | coursera/parallel.py | AbstractDownloader._download_wrapper | def _download_wrapper(self, url, *args, **kwargs):
"""
Actual download call. Calls the underlying file downloader,
catches all exceptions and returns the result.
"""
try:
return url, self._file_downloader.download(url, *args, **kwargs)
except Exception as e:
... | python | def _download_wrapper(self, url, *args, **kwargs):
"""
Actual download call. Calls the underlying file downloader,
catches all exceptions and returns the result.
"""
try:
return url, self._file_downloader.download(url, *args, **kwargs)
except Exception as e:
... | [
"def",
"_download_wrapper",
"(",
"self",
",",
"url",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"url",
",",
"self",
".",
"_file_downloader",
".",
"download",
"(",
"url",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"... | Actual download call. Calls the underlying file downloader,
catches all exceptions and returns the result. | [
"Actual",
"download",
"call",
".",
"Calls",
"the",
"underlying",
"file",
"downloader",
"catches",
"all",
"exceptions",
"and",
"returns",
"the",
"result",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/parallel.py#L26-L35 | train |
coursera-dl/coursera-dl | coursera/credentials.py | get_config_paths | def get_config_paths(config_name): # pragma: no test
"""
Return a list of config files paths to try in order, given config file
name and possibly a user-specified path.
For Windows platforms, there are several paths that can be tried to
retrieve the netrc file. There is, however, no "standard way"... | python | def get_config_paths(config_name): # pragma: no test
"""
Return a list of config files paths to try in order, given config file
name and possibly a user-specified path.
For Windows platforms, there are several paths that can be tried to
retrieve the netrc file. There is, however, no "standard way"... | [
"def",
"get_config_paths",
"(",
"config_name",
")",
":",
"# pragma: no test",
"if",
"platform",
".",
"system",
"(",
")",
"!=",
"'Windows'",
":",
"return",
"[",
"None",
"]",
"# Now, we only treat the case of Windows",
"env_vars",
"=",
"[",
"[",
"\"HOME\"",
"]",
"... | Return a list of config files paths to try in order, given config file
name and possibly a user-specified path.
For Windows platforms, there are several paths that can be tried to
retrieve the netrc file. There is, however, no "standard way" of doing
things.
A brief recap of the situation (all fil... | [
"Return",
"a",
"list",
"of",
"config",
"files",
"paths",
"to",
"try",
"in",
"order",
"given",
"config",
"file",
"name",
"and",
"possibly",
"a",
"user",
"-",
"specified",
"path",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/credentials.py#L37-L110 | train |
coursera-dl/coursera-dl | coursera/credentials.py | authenticate_through_netrc | def authenticate_through_netrc(path=None):
"""
Return the tuple user / password given a path for the .netrc file.
Raises CredentialsError if no valid netrc file is found.
"""
errors = []
netrc_machine = 'coursera-dl'
paths = [path] if path else get_config_paths("netrc")
for path in path... | python | def authenticate_through_netrc(path=None):
"""
Return the tuple user / password given a path for the .netrc file.
Raises CredentialsError if no valid netrc file is found.
"""
errors = []
netrc_machine = 'coursera-dl'
paths = [path] if path else get_config_paths("netrc")
for path in path... | [
"def",
"authenticate_through_netrc",
"(",
"path",
"=",
"None",
")",
":",
"errors",
"=",
"[",
"]",
"netrc_machine",
"=",
"'coursera-dl'",
"paths",
"=",
"[",
"path",
"]",
"if",
"path",
"else",
"get_config_paths",
"(",
"\"netrc\"",
")",
"for",
"path",
"in",
"... | Return the tuple user / password given a path for the .netrc file.
Raises CredentialsError if no valid netrc file is found. | [
"Return",
"the",
"tuple",
"user",
"/",
"password",
"given",
"a",
"path",
"for",
"the",
".",
"netrc",
"file",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/credentials.py#L113-L138 | train |
coursera-dl/coursera-dl | coursera/credentials.py | get_credentials | def get_credentials(username=None, password=None, netrc=None, use_keyring=False):
"""
Return valid username, password tuple.
Raises CredentialsError if username or password is missing.
"""
if netrc:
path = None if netrc is True else netrc
return authenticate_through_netrc(path)
... | python | def get_credentials(username=None, password=None, netrc=None, use_keyring=False):
"""
Return valid username, password tuple.
Raises CredentialsError if username or password is missing.
"""
if netrc:
path = None if netrc is True else netrc
return authenticate_through_netrc(path)
... | [
"def",
"get_credentials",
"(",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"netrc",
"=",
"None",
",",
"use_keyring",
"=",
"False",
")",
":",
"if",
"netrc",
":",
"path",
"=",
"None",
"if",
"netrc",
"is",
"True",
"else",
"netrc",
"return"... | Return valid username, password tuple.
Raises CredentialsError if username or password is missing. | [
"Return",
"valid",
"username",
"password",
"tuple",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/credentials.py#L141-L164 | train |
pallets/werkzeug | src/werkzeug/wrappers/common_descriptors.py | CommonResponseDescriptorsMixin.mimetype | def mimetype(self):
"""The mimetype (content type without charset etc.)"""
ct = self.headers.get("content-type")
if ct:
return ct.split(";")[0].strip() | python | def mimetype(self):
"""The mimetype (content type without charset etc.)"""
ct = self.headers.get("content-type")
if ct:
return ct.split(";")[0].strip() | [
"def",
"mimetype",
"(",
"self",
")",
":",
"ct",
"=",
"self",
".",
"headers",
".",
"get",
"(",
"\"content-type\"",
")",
"if",
"ct",
":",
"return",
"ct",
".",
"split",
"(",
"\";\"",
")",
"[",
"0",
"]",
".",
"strip",
"(",
")"
] | The mimetype (content type without charset etc.) | [
"The",
"mimetype",
"(",
"content",
"type",
"without",
"charset",
"etc",
".",
")"
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/wrappers/common_descriptors.py#L136-L140 | train |
pallets/werkzeug | src/werkzeug/wrappers/common_descriptors.py | CommonResponseDescriptorsMixin.mimetype_params | def mimetype_params(self):
"""The mimetype parameters as dict. For example if the
content type is ``text/html; charset=utf-8`` the params would be
``{'charset': 'utf-8'}``.
.. versionadded:: 0.5
"""
def on_update(d):
self.headers["Content-Type"] = dump_optio... | python | def mimetype_params(self):
"""The mimetype parameters as dict. For example if the
content type is ``text/html; charset=utf-8`` the params would be
``{'charset': 'utf-8'}``.
.. versionadded:: 0.5
"""
def on_update(d):
self.headers["Content-Type"] = dump_optio... | [
"def",
"mimetype_params",
"(",
"self",
")",
":",
"def",
"on_update",
"(",
"d",
")",
":",
"self",
".",
"headers",
"[",
"\"Content-Type\"",
"]",
"=",
"dump_options_header",
"(",
"self",
".",
"mimetype",
",",
"d",
")",
"d",
"=",
"parse_options_header",
"(",
... | The mimetype parameters as dict. For example if the
content type is ``text/html; charset=utf-8`` the params would be
``{'charset': 'utf-8'}``.
.. versionadded:: 0.5 | [
"The",
"mimetype",
"parameters",
"as",
"dict",
".",
"For",
"example",
"if",
"the",
"content",
"type",
"is",
"text",
"/",
"html",
";",
"charset",
"=",
"utf",
"-",
"8",
"the",
"params",
"would",
"be",
"{",
"charset",
":",
"utf",
"-",
"8",
"}",
"."
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/wrappers/common_descriptors.py#L147-L159 | train |
pallets/werkzeug | examples/simplewiki/specialpages.py | page_index | def page_index(request):
"""Index of all pages."""
letters = {}
for page in Page.query.order_by(Page.name):
letters.setdefault(page.name.capitalize()[0], []).append(page)
return Response(
generate_template("page_index.html", letters=sorted(letters.items()))
) | python | def page_index(request):
"""Index of all pages."""
letters = {}
for page in Page.query.order_by(Page.name):
letters.setdefault(page.name.capitalize()[0], []).append(page)
return Response(
generate_template("page_index.html", letters=sorted(letters.items()))
) | [
"def",
"page_index",
"(",
"request",
")",
":",
"letters",
"=",
"{",
"}",
"for",
"page",
"in",
"Page",
".",
"query",
".",
"order_by",
"(",
"Page",
".",
"name",
")",
":",
"letters",
".",
"setdefault",
"(",
"page",
".",
"name",
".",
"capitalize",
"(",
... | Index of all pages. | [
"Index",
"of",
"all",
"pages",
"."
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/examples/simplewiki/specialpages.py#L20-L27 | train |
pallets/werkzeug | examples/simplewiki/specialpages.py | recent_changes | def recent_changes(request):
"""Display the recent changes."""
page = max(1, request.args.get("page", type=int))
query = RevisionedPage.query.order_by(RevisionedPage.revision_id.desc())
return Response(
generate_template(
"recent_changes.html",
pagination=Pagination(query... | python | def recent_changes(request):
"""Display the recent changes."""
page = max(1, request.args.get("page", type=int))
query = RevisionedPage.query.order_by(RevisionedPage.revision_id.desc())
return Response(
generate_template(
"recent_changes.html",
pagination=Pagination(query... | [
"def",
"recent_changes",
"(",
"request",
")",
":",
"page",
"=",
"max",
"(",
"1",
",",
"request",
".",
"args",
".",
"get",
"(",
"\"page\"",
",",
"type",
"=",
"int",
")",
")",
"query",
"=",
"RevisionedPage",
".",
"query",
".",
"order_by",
"(",
"Revisio... | Display the recent changes. | [
"Display",
"the",
"recent",
"changes",
"."
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/examples/simplewiki/specialpages.py#L30-L39 | train |
pallets/werkzeug | examples/manage-plnt.py | make_app | def make_app():
"""Helper function that creates a plnt app."""
from plnt import Plnt
database_uri = os.environ.get("PLNT_DATABASE_URI")
app = Plnt(database_uri or "sqlite:////tmp/plnt.db")
app.bind_to_context()
return app | python | def make_app():
"""Helper function that creates a plnt app."""
from plnt import Plnt
database_uri = os.environ.get("PLNT_DATABASE_URI")
app = Plnt(database_uri or "sqlite:////tmp/plnt.db")
app.bind_to_context()
return app | [
"def",
"make_app",
"(",
")",
":",
"from",
"plnt",
"import",
"Plnt",
"database_uri",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"\"PLNT_DATABASE_URI\"",
")",
"app",
"=",
"Plnt",
"(",
"database_uri",
"or",
"\"sqlite:////tmp/plnt.db\"",
")",
"app",
".",
"bind_... | Helper function that creates a plnt app. | [
"Helper",
"function",
"that",
"creates",
"a",
"plnt",
"app",
"."
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/examples/manage-plnt.py#L18-L25 | train |
pallets/werkzeug | examples/manage-plnt.py | initdb | def initdb():
"""Initialize the database"""
from plnt.database import Blog, session
make_app().init_database()
# and now fill in some python blogs everybody should read (shamelessly
# added my own blog too)
blogs = [
Blog(
"Armin Ronacher",
"http://lucumr.pocoo.o... | python | def initdb():
"""Initialize the database"""
from plnt.database import Blog, session
make_app().init_database()
# and now fill in some python blogs everybody should read (shamelessly
# added my own blog too)
blogs = [
Blog(
"Armin Ronacher",
"http://lucumr.pocoo.o... | [
"def",
"initdb",
"(",
")",
":",
"from",
"plnt",
".",
"database",
"import",
"Blog",
",",
"session",
"make_app",
"(",
")",
".",
"init_database",
"(",
")",
"# and now fill in some python blogs everybody should read (shamelessly",
"# added my own blog too)",
"blogs",
"=",
... | Initialize the database | [
"Initialize",
"the",
"database"
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/examples/manage-plnt.py#L34-L76 | train |
pallets/werkzeug | examples/manage-plnt.py | runserver | def runserver(hostname, port, no_reloader, debugger, no_evalex, threaded, processes):
"""Start a new development server."""
app = make_app()
reloader = not no_reloader
evalex = not no_evalex
run_simple(
hostname,
port,
app,
use_reloader=reloader,
use_debugger=... | python | def runserver(hostname, port, no_reloader, debugger, no_evalex, threaded, processes):
"""Start a new development server."""
app = make_app()
reloader = not no_reloader
evalex = not no_evalex
run_simple(
hostname,
port,
app,
use_reloader=reloader,
use_debugger=... | [
"def",
"runserver",
"(",
"hostname",
",",
"port",
",",
"no_reloader",
",",
"debugger",
",",
"no_evalex",
",",
"threaded",
",",
"processes",
")",
":",
"app",
"=",
"make_app",
"(",
")",
"reloader",
"=",
"not",
"no_reloader",
"evalex",
"=",
"not",
"no_evalex"... | Start a new development server. | [
"Start",
"a",
"new",
"development",
"server",
"."
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/examples/manage-plnt.py#L87-L101 | train |
pallets/werkzeug | src/werkzeug/datastructures.py | iter_multi_items | def iter_multi_items(mapping):
"""Iterates over the items of a mapping yielding keys and values
without dropping any from more complex structures.
"""
if isinstance(mapping, MultiDict):
for item in iteritems(mapping, multi=True):
yield item
elif isinstance(mapping, dict):
... | python | def iter_multi_items(mapping):
"""Iterates over the items of a mapping yielding keys and values
without dropping any from more complex structures.
"""
if isinstance(mapping, MultiDict):
for item in iteritems(mapping, multi=True):
yield item
elif isinstance(mapping, dict):
... | [
"def",
"iter_multi_items",
"(",
"mapping",
")",
":",
"if",
"isinstance",
"(",
"mapping",
",",
"MultiDict",
")",
":",
"for",
"item",
"in",
"iteritems",
"(",
"mapping",
",",
"multi",
"=",
"True",
")",
":",
"yield",
"item",
"elif",
"isinstance",
"(",
"mappi... | Iterates over the items of a mapping yielding keys and values
without dropping any from more complex structures. | [
"Iterates",
"over",
"the",
"items",
"of",
"a",
"mapping",
"yielding",
"keys",
"and",
"values",
"without",
"dropping",
"any",
"from",
"more",
"complex",
"structures",
"."
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/datastructures.py#L39-L55 | train |
pallets/werkzeug | src/werkzeug/datastructures.py | TypeConversionDict.get | def get(self, key, default=None, type=None):
"""Return the default value if the requested data doesn't exist.
If `type` is provided and is a callable it should convert the value,
return it or raise a :exc:`ValueError` if that is not possible. In
this case the function will return the de... | python | def get(self, key, default=None, type=None):
"""Return the default value if the requested data doesn't exist.
If `type` is provided and is a callable it should convert the value,
return it or raise a :exc:`ValueError` if that is not possible. In
this case the function will return the de... | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
",",
"type",
"=",
"None",
")",
":",
"try",
":",
"rv",
"=",
"self",
"[",
"key",
"]",
"except",
"KeyError",
":",
"return",
"default",
"if",
"type",
"is",
"not",
"None",
":",
"try",... | Return the default value if the requested data doesn't exist.
If `type` is provided and is a callable it should convert the value,
return it or raise a :exc:`ValueError` if that is not possible. In
this case the function will return the default as if the value was not
found:
>>... | [
"Return",
"the",
"default",
"value",
"if",
"the",
"requested",
"data",
"doesn",
"t",
"exist",
".",
"If",
"type",
"is",
"provided",
"and",
"is",
"a",
"callable",
"it",
"should",
"convert",
"the",
"value",
"return",
"it",
"or",
"raise",
"a",
":",
"exc",
... | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/datastructures.py#L292-L322 | train |
pallets/werkzeug | src/werkzeug/datastructures.py | _CacheControl._get_cache_value | def _get_cache_value(self, key, empty, type):
"""Used internally by the accessor properties."""
if type is bool:
return key in self
if key in self:
value = self[key]
if value is None:
return empty
elif type is not None:
... | python | def _get_cache_value(self, key, empty, type):
"""Used internally by the accessor properties."""
if type is bool:
return key in self
if key in self:
value = self[key]
if value is None:
return empty
elif type is not None:
... | [
"def",
"_get_cache_value",
"(",
"self",
",",
"key",
",",
"empty",
",",
"type",
")",
":",
"if",
"type",
"is",
"bool",
":",
"return",
"key",
"in",
"self",
"if",
"key",
"in",
"self",
":",
"value",
"=",
"self",
"[",
"key",
"]",
"if",
"value",
"is",
"... | Used internally by the accessor properties. | [
"Used",
"internally",
"by",
"the",
"accessor",
"properties",
"."
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/datastructures.py#L1914-L1927 | train |
pallets/werkzeug | src/werkzeug/datastructures.py | _CacheControl._set_cache_value | def _set_cache_value(self, key, value, type):
"""Used internally by the accessor properties."""
if type is bool:
if value:
self[key] = None
else:
self.pop(key, None)
else:
if value is None:
self.pop(key)
... | python | def _set_cache_value(self, key, value, type):
"""Used internally by the accessor properties."""
if type is bool:
if value:
self[key] = None
else:
self.pop(key, None)
else:
if value is None:
self.pop(key)
... | [
"def",
"_set_cache_value",
"(",
"self",
",",
"key",
",",
"value",
",",
"type",
")",
":",
"if",
"type",
"is",
"bool",
":",
"if",
"value",
":",
"self",
"[",
"key",
"]",
"=",
"None",
"else",
":",
"self",
".",
"pop",
"(",
"key",
",",
"None",
")",
"... | Used internally by the accessor properties. | [
"Used",
"internally",
"by",
"the",
"accessor",
"properties",
"."
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/datastructures.py#L1929-L1942 | train |
pallets/werkzeug | src/werkzeug/datastructures.py | HeaderSet.remove | def remove(self, header):
"""Remove a header from the set. This raises an :exc:`KeyError` if the
header is not in the set.
.. versionchanged:: 0.5
In older versions a :exc:`IndexError` was raised instead of a
:exc:`KeyError` if the object was missing.
:param he... | python | def remove(self, header):
"""Remove a header from the set. This raises an :exc:`KeyError` if the
header is not in the set.
.. versionchanged:: 0.5
In older versions a :exc:`IndexError` was raised instead of a
:exc:`KeyError` if the object was missing.
:param he... | [
"def",
"remove",
"(",
"self",
",",
"header",
")",
":",
"key",
"=",
"header",
".",
"lower",
"(",
")",
"if",
"key",
"not",
"in",
"self",
".",
"_set",
":",
"raise",
"KeyError",
"(",
"header",
")",
"self",
".",
"_set",
".",
"remove",
"(",
"key",
")",... | Remove a header from the set. This raises an :exc:`KeyError` if the
header is not in the set.
.. versionchanged:: 0.5
In older versions a :exc:`IndexError` was raised instead of a
:exc:`KeyError` if the object was missing.
:param header: the header to be removed. | [
"Remove",
"a",
"header",
"from",
"the",
"set",
".",
"This",
"raises",
"an",
":",
"exc",
":",
"KeyError",
"if",
"the",
"header",
"is",
"not",
"in",
"the",
"set",
"."
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/datastructures.py#L2045-L2064 | train |
pallets/werkzeug | src/werkzeug/datastructures.py | HeaderSet.update | def update(self, iterable):
"""Add all the headers from the iterable to the set.
:param iterable: updates the set with the items from the iterable.
"""
inserted_any = False
for header in iterable:
key = header.lower()
if key not in self._set:
... | python | def update(self, iterable):
"""Add all the headers from the iterable to the set.
:param iterable: updates the set with the items from the iterable.
"""
inserted_any = False
for header in iterable:
key = header.lower()
if key not in self._set:
... | [
"def",
"update",
"(",
"self",
",",
"iterable",
")",
":",
"inserted_any",
"=",
"False",
"for",
"header",
"in",
"iterable",
":",
"key",
"=",
"header",
".",
"lower",
"(",
")",
"if",
"key",
"not",
"in",
"self",
".",
"_set",
":",
"self",
".",
"_headers",
... | Add all the headers from the iterable to the set.
:param iterable: updates the set with the items from the iterable. | [
"Add",
"all",
"the",
"headers",
"from",
"the",
"iterable",
"to",
"the",
"set",
"."
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/datastructures.py#L2066-L2079 | train |
pallets/werkzeug | src/werkzeug/datastructures.py | HeaderSet.find | def find(self, header):
"""Return the index of the header in the set or return -1 if not found.
:param header: the header to be looked up.
"""
header = header.lower()
for idx, item in enumerate(self._headers):
if item.lower() == header:
return idx
... | python | def find(self, header):
"""Return the index of the header in the set or return -1 if not found.
:param header: the header to be looked up.
"""
header = header.lower()
for idx, item in enumerate(self._headers):
if item.lower() == header:
return idx
... | [
"def",
"find",
"(",
"self",
",",
"header",
")",
":",
"header",
"=",
"header",
".",
"lower",
"(",
")",
"for",
"idx",
",",
"item",
"in",
"enumerate",
"(",
"self",
".",
"_headers",
")",
":",
"if",
"item",
".",
"lower",
"(",
")",
"==",
"header",
":",... | Return the index of the header in the set or return -1 if not found.
:param header: the header to be looked up. | [
"Return",
"the",
"index",
"of",
"the",
"header",
"in",
"the",
"set",
"or",
"return",
"-",
"1",
"if",
"not",
"found",
"."
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/datastructures.py#L2091-L2100 | train |
pallets/werkzeug | src/werkzeug/datastructures.py | HeaderSet.index | def index(self, header):
"""Return the index of the header in the set or raise an
:exc:`IndexError`.
:param header: the header to be looked up.
"""
rv = self.find(header)
if rv < 0:
raise IndexError(header)
return rv | python | def index(self, header):
"""Return the index of the header in the set or raise an
:exc:`IndexError`.
:param header: the header to be looked up.
"""
rv = self.find(header)
if rv < 0:
raise IndexError(header)
return rv | [
"def",
"index",
"(",
"self",
",",
"header",
")",
":",
"rv",
"=",
"self",
".",
"find",
"(",
"header",
")",
"if",
"rv",
"<",
"0",
":",
"raise",
"IndexError",
"(",
"header",
")",
"return",
"rv"
] | Return the index of the header in the set or raise an
:exc:`IndexError`.
:param header: the header to be looked up. | [
"Return",
"the",
"index",
"of",
"the",
"header",
"in",
"the",
"set",
"or",
"raise",
"an",
":",
"exc",
":",
"IndexError",
"."
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/datastructures.py#L2102-L2111 | train |
pallets/werkzeug | src/werkzeug/datastructures.py | HeaderSet.clear | def clear(self):
"""Clear the set."""
self._set.clear()
del self._headers[:]
if self.on_update is not None:
self.on_update(self) | python | def clear(self):
"""Clear the set."""
self._set.clear()
del self._headers[:]
if self.on_update is not None:
self.on_update(self) | [
"def",
"clear",
"(",
"self",
")",
":",
"self",
".",
"_set",
".",
"clear",
"(",
")",
"del",
"self",
".",
"_headers",
"[",
":",
"]",
"if",
"self",
".",
"on_update",
"is",
"not",
"None",
":",
"self",
".",
"on_update",
"(",
"self",
")"
] | Clear the set. | [
"Clear",
"the",
"set",
"."
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/datastructures.py#L2113-L2118 | train |
pallets/werkzeug | src/werkzeug/datastructures.py | HeaderSet.as_set | def as_set(self, preserve_casing=False):
"""Return the set as real python set type. When calling this, all
the items are converted to lowercase and the ordering is lost.
:param preserve_casing: if set to `True` the items in the set returned
will have the origina... | python | def as_set(self, preserve_casing=False):
"""Return the set as real python set type. When calling this, all
the items are converted to lowercase and the ordering is lost.
:param preserve_casing: if set to `True` the items in the set returned
will have the origina... | [
"def",
"as_set",
"(",
"self",
",",
"preserve_casing",
"=",
"False",
")",
":",
"if",
"preserve_casing",
":",
"return",
"set",
"(",
"self",
".",
"_headers",
")",
"return",
"set",
"(",
"self",
".",
"_set",
")"
] | Return the set as real python set type. When calling this, all
the items are converted to lowercase and the ordering is lost.
:param preserve_casing: if set to `True` the items in the set returned
will have the original case like in the
:... | [
"Return",
"the",
"set",
"as",
"real",
"python",
"set",
"type",
".",
"When",
"calling",
"this",
"all",
"the",
"items",
"are",
"converted",
"to",
"lowercase",
"and",
"the",
"ordering",
"is",
"lost",
"."
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/datastructures.py#L2120-L2131 | train |
pallets/werkzeug | src/werkzeug/datastructures.py | ETags.as_set | def as_set(self, include_weak=False):
"""Convert the `ETags` object into a python set. Per default all the
weak etags are not part of this set."""
rv = set(self._strong)
if include_weak:
rv.update(self._weak)
return rv | python | def as_set(self, include_weak=False):
"""Convert the `ETags` object into a python set. Per default all the
weak etags are not part of this set."""
rv = set(self._strong)
if include_weak:
rv.update(self._weak)
return rv | [
"def",
"as_set",
"(",
"self",
",",
"include_weak",
"=",
"False",
")",
":",
"rv",
"=",
"set",
"(",
"self",
".",
"_strong",
")",
"if",
"include_weak",
":",
"rv",
".",
"update",
"(",
"self",
".",
"_weak",
")",
"return",
"rv"
] | Convert the `ETags` object into a python set. Per default all the
weak etags are not part of this set. | [
"Convert",
"the",
"ETags",
"object",
"into",
"a",
"python",
"set",
".",
"Per",
"default",
"all",
"the",
"weak",
"etags",
"are",
"not",
"part",
"of",
"this",
"set",
"."
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/datastructures.py#L2183-L2189 | train |
pallets/werkzeug | src/werkzeug/datastructures.py | ETags.contains_raw | def contains_raw(self, etag):
"""When passed a quoted tag it will check if this tag is part of the
set. If the tag is weak it is checked against weak and strong tags,
otherwise strong only."""
etag, weak = unquote_etag(etag)
if weak:
return self.contains_weak(etag)
... | python | def contains_raw(self, etag):
"""When passed a quoted tag it will check if this tag is part of the
set. If the tag is weak it is checked against weak and strong tags,
otherwise strong only."""
etag, weak = unquote_etag(etag)
if weak:
return self.contains_weak(etag)
... | [
"def",
"contains_raw",
"(",
"self",
",",
"etag",
")",
":",
"etag",
",",
"weak",
"=",
"unquote_etag",
"(",
"etag",
")",
"if",
"weak",
":",
"return",
"self",
".",
"contains_weak",
"(",
"etag",
")",
"return",
"self",
".",
"contains",
"(",
"etag",
")"
] | When passed a quoted tag it will check if this tag is part of the
set. If the tag is weak it is checked against weak and strong tags,
otherwise strong only. | [
"When",
"passed",
"a",
"quoted",
"tag",
"it",
"will",
"check",
"if",
"this",
"tag",
"is",
"part",
"of",
"the",
"set",
".",
"If",
"the",
"tag",
"is",
"weak",
"it",
"is",
"checked",
"against",
"weak",
"and",
"strong",
"tags",
"otherwise",
"strong",
"only... | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/datastructures.py#L2211-L2218 | train |
pallets/werkzeug | src/werkzeug/datastructures.py | ETags.to_header | def to_header(self):
"""Convert the etags set into a HTTP header string."""
if self.star_tag:
return "*"
return ", ".join(
['"%s"' % x for x in self._strong] + ['W/"%s"' % x for x in self._weak]
) | python | def to_header(self):
"""Convert the etags set into a HTTP header string."""
if self.star_tag:
return "*"
return ", ".join(
['"%s"' % x for x in self._strong] + ['W/"%s"' % x for x in self._weak]
) | [
"def",
"to_header",
"(",
"self",
")",
":",
"if",
"self",
".",
"star_tag",
":",
"return",
"\"*\"",
"return",
"\", \"",
".",
"join",
"(",
"[",
"'\"%s\"'",
"%",
"x",
"for",
"x",
"in",
"self",
".",
"_strong",
"]",
"+",
"[",
"'W/\"%s\"'",
"%",
"x",
"for... | Convert the etags set into a HTTP header string. | [
"Convert",
"the",
"etags",
"set",
"into",
"a",
"HTTP",
"header",
"string",
"."
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/datastructures.py#L2220-L2226 | train |
pallets/werkzeug | src/werkzeug/datastructures.py | IfRange.to_header | def to_header(self):
"""Converts the object back into an HTTP header."""
if self.date is not None:
return http_date(self.date)
if self.etag is not None:
return quote_etag(self.etag)
return "" | python | def to_header(self):
"""Converts the object back into an HTTP header."""
if self.date is not None:
return http_date(self.date)
if self.etag is not None:
return quote_etag(self.etag)
return "" | [
"def",
"to_header",
"(",
"self",
")",
":",
"if",
"self",
".",
"date",
"is",
"not",
"None",
":",
"return",
"http_date",
"(",
"self",
".",
"date",
")",
"if",
"self",
".",
"etag",
"is",
"not",
"None",
":",
"return",
"quote_etag",
"(",
"self",
".",
"et... | Converts the object back into an HTTP header. | [
"Converts",
"the",
"object",
"back",
"into",
"an",
"HTTP",
"header",
"."
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/datastructures.py#L2271-L2277 | train |
pallets/werkzeug | src/werkzeug/datastructures.py | Range.range_for_length | def range_for_length(self, length):
"""If the range is for bytes, the length is not None and there is
exactly one range and it is satisfiable it returns a ``(start, stop)``
tuple, otherwise `None`.
"""
if self.units != "bytes" or length is None or len(self.ranges) != 1:
... | python | def range_for_length(self, length):
"""If the range is for bytes, the length is not None and there is
exactly one range and it is satisfiable it returns a ``(start, stop)``
tuple, otherwise `None`.
"""
if self.units != "bytes" or length is None or len(self.ranges) != 1:
... | [
"def",
"range_for_length",
"(",
"self",
",",
"length",
")",
":",
"if",
"self",
".",
"units",
"!=",
"\"bytes\"",
"or",
"length",
"is",
"None",
"or",
"len",
"(",
"self",
".",
"ranges",
")",
"!=",
"1",
":",
"return",
"None",
"start",
",",
"end",
"=",
... | If the range is for bytes, the length is not None and there is
exactly one range and it is satisfiable it returns a ``(start, stop)``
tuple, otherwise `None`. | [
"If",
"the",
"range",
"is",
"for",
"bytes",
"the",
"length",
"is",
"not",
"None",
"and",
"there",
"is",
"exactly",
"one",
"range",
"and",
"it",
"is",
"satisfiable",
"it",
"returns",
"a",
"(",
"start",
"stop",
")",
"tuple",
"otherwise",
"None",
"."
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/datastructures.py#L2310-L2323 | train |
pallets/werkzeug | src/werkzeug/datastructures.py | Range.make_content_range | def make_content_range(self, length):
"""Creates a :class:`~werkzeug.datastructures.ContentRange` object
from the current range and given content length.
"""
rng = self.range_for_length(length)
if rng is not None:
return ContentRange(self.units, rng[0], rng[1], length... | python | def make_content_range(self, length):
"""Creates a :class:`~werkzeug.datastructures.ContentRange` object
from the current range and given content length.
"""
rng = self.range_for_length(length)
if rng is not None:
return ContentRange(self.units, rng[0], rng[1], length... | [
"def",
"make_content_range",
"(",
"self",
",",
"length",
")",
":",
"rng",
"=",
"self",
".",
"range_for_length",
"(",
"length",
")",
"if",
"rng",
"is",
"not",
"None",
":",
"return",
"ContentRange",
"(",
"self",
".",
"units",
",",
"rng",
"[",
"0",
"]",
... | Creates a :class:`~werkzeug.datastructures.ContentRange` object
from the current range and given content length. | [
"Creates",
"a",
":",
"class",
":",
"~werkzeug",
".",
"datastructures",
".",
"ContentRange",
"object",
"from",
"the",
"current",
"range",
"and",
"given",
"content",
"length",
"."
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/datastructures.py#L2325-L2331 | train |
pallets/werkzeug | src/werkzeug/datastructures.py | Range.to_header | def to_header(self):
"""Converts the object back into an HTTP header."""
ranges = []
for begin, end in self.ranges:
if end is None:
ranges.append("%s-" % begin if begin >= 0 else str(begin))
else:
ranges.append("%s-%s" % (begin, end - 1))
... | python | def to_header(self):
"""Converts the object back into an HTTP header."""
ranges = []
for begin, end in self.ranges:
if end is None:
ranges.append("%s-" % begin if begin >= 0 else str(begin))
else:
ranges.append("%s-%s" % (begin, end - 1))
... | [
"def",
"to_header",
"(",
"self",
")",
":",
"ranges",
"=",
"[",
"]",
"for",
"begin",
",",
"end",
"in",
"self",
".",
"ranges",
":",
"if",
"end",
"is",
"None",
":",
"ranges",
".",
"append",
"(",
"\"%s-\"",
"%",
"begin",
"if",
"begin",
">=",
"0",
"el... | Converts the object back into an HTTP header. | [
"Converts",
"the",
"object",
"back",
"into",
"an",
"HTTP",
"header",
"."
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/datastructures.py#L2333-L2341 | train |
pallets/werkzeug | src/werkzeug/datastructures.py | Range.to_content_range_header | def to_content_range_header(self, length):
"""Converts the object into `Content-Range` HTTP header,
based on given length
"""
range_for_length = self.range_for_length(length)
if range_for_length is not None:
return "%s %d-%d/%d" % (
self.units,
... | python | def to_content_range_header(self, length):
"""Converts the object into `Content-Range` HTTP header,
based on given length
"""
range_for_length = self.range_for_length(length)
if range_for_length is not None:
return "%s %d-%d/%d" % (
self.units,
... | [
"def",
"to_content_range_header",
"(",
"self",
",",
"length",
")",
":",
"range_for_length",
"=",
"self",
".",
"range_for_length",
"(",
"length",
")",
"if",
"range_for_length",
"is",
"not",
"None",
":",
"return",
"\"%s %d-%d/%d\"",
"%",
"(",
"self",
".",
"units... | Converts the object into `Content-Range` HTTP header,
based on given length | [
"Converts",
"the",
"object",
"into",
"Content",
"-",
"Range",
"HTTP",
"header",
"based",
"on",
"given",
"length"
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/datastructures.py#L2343-L2355 | train |
pallets/werkzeug | src/werkzeug/datastructures.py | WWWAuthenticate.set_digest | def set_digest(
self, realm, nonce, qop=("auth",), opaque=None, algorithm=None, stale=False
):
"""Clear the auth info and enable digest auth."""
d = {
"__auth_type__": "digest",
"realm": realm,
"nonce": nonce,
"qop": dump_header(qop),
}... | python | def set_digest(
self, realm, nonce, qop=("auth",), opaque=None, algorithm=None, stale=False
):
"""Clear the auth info and enable digest auth."""
d = {
"__auth_type__": "digest",
"realm": realm,
"nonce": nonce,
"qop": dump_header(qop),
}... | [
"def",
"set_digest",
"(",
"self",
",",
"realm",
",",
"nonce",
",",
"qop",
"=",
"(",
"\"auth\"",
",",
")",
",",
"opaque",
"=",
"None",
",",
"algorithm",
"=",
"None",
",",
"stale",
"=",
"False",
")",
":",
"d",
"=",
"{",
"\"__auth_type__\"",
":",
"\"d... | Clear the auth info and enable digest auth. | [
"Clear",
"the",
"auth",
"info",
"and",
"enable",
"digest",
"auth",
"."
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/datastructures.py#L2538-L2557 | train |
pallets/werkzeug | src/werkzeug/datastructures.py | WWWAuthenticate.to_header | def to_header(self):
"""Convert the stored values into a WWW-Authenticate header."""
d = dict(self)
auth_type = d.pop("__auth_type__", None) or "basic"
return "%s %s" % (
auth_type.title(),
", ".join(
[
"%s=%s"
... | python | def to_header(self):
"""Convert the stored values into a WWW-Authenticate header."""
d = dict(self)
auth_type = d.pop("__auth_type__", None) or "basic"
return "%s %s" % (
auth_type.title(),
", ".join(
[
"%s=%s"
... | [
"def",
"to_header",
"(",
"self",
")",
":",
"d",
"=",
"dict",
"(",
"self",
")",
"auth_type",
"=",
"d",
".",
"pop",
"(",
"\"__auth_type__\"",
",",
"None",
")",
"or",
"\"basic\"",
"return",
"\"%s %s\"",
"%",
"(",
"auth_type",
".",
"title",
"(",
")",
","... | Convert the stored values into a WWW-Authenticate header. | [
"Convert",
"the",
"stored",
"values",
"into",
"a",
"WWW",
"-",
"Authenticate",
"header",
"."
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/datastructures.py#L2559-L2577 | train |
pallets/werkzeug | src/werkzeug/datastructures.py | WWWAuthenticate.auth_property | def auth_property(name, doc=None): # noqa: B902
"""A static helper function for subclasses to add extra authentication
system properties onto a class::
class FooAuthenticate(WWWAuthenticate):
special_realm = auth_property('special_realm')
For more information have ... | python | def auth_property(name, doc=None): # noqa: B902
"""A static helper function for subclasses to add extra authentication
system properties onto a class::
class FooAuthenticate(WWWAuthenticate):
special_realm = auth_property('special_realm')
For more information have ... | [
"def",
"auth_property",
"(",
"name",
",",
"doc",
"=",
"None",
")",
":",
"# noqa: B902",
"def",
"_set_value",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"self",
".",
"pop",
"(",
"name",
",",
"None",
")",
"else",
":",
"sel... | A static helper function for subclasses to add extra authentication
system properties onto a class::
class FooAuthenticate(WWWAuthenticate):
special_realm = auth_property('special_realm')
For more information have a look at the sourcecode to see how the
regular prop... | [
"A",
"static",
"helper",
"function",
"for",
"subclasses",
"to",
"add",
"extra",
"authentication",
"system",
"properties",
"onto",
"a",
"class",
"::"
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/datastructures.py#L2585-L2602 | train |
pallets/werkzeug | src/werkzeug/datastructures.py | FileStorage.save | def save(self, dst, buffer_size=16384):
"""Save the file to a destination path or file object. If the
destination is a file object you have to close it yourself after the
call. The buffer size is the number of bytes held in memory during
the copy process. It defaults to 16KB.
... | python | def save(self, dst, buffer_size=16384):
"""Save the file to a destination path or file object. If the
destination is a file object you have to close it yourself after the
call. The buffer size is the number of bytes held in memory during
the copy process. It defaults to 16KB.
... | [
"def",
"save",
"(",
"self",
",",
"dst",
",",
"buffer_size",
"=",
"16384",
")",
":",
"from",
"shutil",
"import",
"copyfileobj",
"close_dst",
"=",
"False",
"if",
"isinstance",
"(",
"dst",
",",
"string_types",
")",
":",
"dst",
"=",
"open",
"(",
"dst",
","... | Save the file to a destination path or file object. If the
destination is a file object you have to close it yourself after the
call. The buffer size is the number of bytes held in memory during
the copy process. It defaults to 16KB.
For secure file saving also have a look at :func:`... | [
"Save",
"the",
"file",
"to",
"a",
"destination",
"path",
"or",
"file",
"object",
".",
"If",
"the",
"destination",
"is",
"a",
"file",
"object",
"you",
"have",
"to",
"close",
"it",
"yourself",
"after",
"the",
"call",
".",
"The",
"buffer",
"size",
"is",
"... | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/datastructures.py#L2766-L2790 | train |
pallets/werkzeug | src/werkzeug/wrappers/base_response.py | BaseResponse.force_type | def force_type(cls, response, environ=None):
"""Enforce that the WSGI response is a response object of the current
type. Werkzeug will use the :class:`BaseResponse` internally in many
situations like the exceptions. If you call :meth:`get_response` on an
exception you will get back a r... | python | def force_type(cls, response, environ=None):
"""Enforce that the WSGI response is a response object of the current
type. Werkzeug will use the :class:`BaseResponse` internally in many
situations like the exceptions. If you call :meth:`get_response` on an
exception you will get back a r... | [
"def",
"force_type",
"(",
"cls",
",",
"response",
",",
"environ",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"response",
",",
"BaseResponse",
")",
":",
"if",
"environ",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"\"cannot convert WSGI applicat... | Enforce that the WSGI response is a response object of the current
type. Werkzeug will use the :class:`BaseResponse` internally in many
situations like the exceptions. If you call :meth:`get_response` on an
exception you will get back a regular :class:`BaseResponse` object, even
if you... | [
"Enforce",
"that",
"the",
"WSGI",
"response",
"is",
"a",
"response",
"object",
"of",
"the",
"current",
"type",
".",
"Werkzeug",
"will",
"use",
"the",
":",
"class",
":",
"BaseResponse",
"internally",
"in",
"many",
"situations",
"like",
"the",
"exceptions",
".... | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/wrappers/base_response.py#L235-L271 | train |
pallets/werkzeug | src/werkzeug/wrappers/base_response.py | BaseResponse.from_app | def from_app(cls, app, environ, buffered=False):
"""Create a new response object from an application output. This
works best if you pass it an application that returns a generator all
the time. Sometimes applications may use the `write()` callable
returned by the `start_response` funct... | python | def from_app(cls, app, environ, buffered=False):
"""Create a new response object from an application output. This
works best if you pass it an application that returns a generator all
the time. Sometimes applications may use the `write()` callable
returned by the `start_response` funct... | [
"def",
"from_app",
"(",
"cls",
",",
"app",
",",
"environ",
",",
"buffered",
"=",
"False",
")",
":",
"return",
"cls",
"(",
"*",
"_run_wsgi_app",
"(",
"app",
",",
"environ",
",",
"buffered",
")",
")"
] | Create a new response object from an application output. This
works best if you pass it an application that returns a generator all
the time. Sometimes applications may use the `write()` callable
returned by the `start_response` function. This tries to resolve such
edge cases automati... | [
"Create",
"a",
"new",
"response",
"object",
"from",
"an",
"application",
"output",
".",
"This",
"works",
"best",
"if",
"you",
"pass",
"it",
"an",
"application",
"that",
"returns",
"a",
"generator",
"all",
"the",
"time",
".",
"Sometimes",
"applications",
"may... | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/wrappers/base_response.py#L274-L287 | train |
pallets/werkzeug | src/werkzeug/wrappers/base_response.py | BaseResponse.calculate_content_length | def calculate_content_length(self):
"""Returns the content length if available or `None` otherwise."""
try:
self._ensure_sequence()
except RuntimeError:
return None
return sum(len(x) for x in self.iter_encoded()) | python | def calculate_content_length(self):
"""Returns the content length if available or `None` otherwise."""
try:
self._ensure_sequence()
except RuntimeError:
return None
return sum(len(x) for x in self.iter_encoded()) | [
"def",
"calculate_content_length",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"_ensure_sequence",
"(",
")",
"except",
"RuntimeError",
":",
"return",
"None",
"return",
"sum",
"(",
"len",
"(",
"x",
")",
"for",
"x",
"in",
"self",
".",
"iter_encoded",
"... | Returns the content length if available or `None` otherwise. | [
"Returns",
"the",
"content",
"length",
"if",
"available",
"or",
"None",
"otherwise",
"."
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/wrappers/base_response.py#L366-L372 | train |
pallets/werkzeug | src/werkzeug/wrappers/base_response.py | BaseResponse.make_sequence | def make_sequence(self):
"""Converts the response iterator in a list. By default this happens
automatically if required. If `implicit_sequence_conversion` is
disabled, this method is not automatically called and some properties
might raise exceptions. This also encodes all the items.
... | python | def make_sequence(self):
"""Converts the response iterator in a list. By default this happens
automatically if required. If `implicit_sequence_conversion` is
disabled, this method is not automatically called and some properties
might raise exceptions. This also encodes all the items.
... | [
"def",
"make_sequence",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_sequence",
":",
"# if we consume an iterable we have to ensure that the close",
"# method of the iterable is called if available when we tear",
"# down the response",
"close",
"=",
"getattr",
"(",
"sel... | Converts the response iterator in a list. By default this happens
automatically if required. If `implicit_sequence_conversion` is
disabled, this method is not automatically called and some properties
might raise exceptions. This also encodes all the items.
.. versionadded:: 0.6 | [
"Converts",
"the",
"response",
"iterator",
"in",
"a",
"list",
".",
"By",
"default",
"this",
"happens",
"automatically",
"if",
"required",
".",
"If",
"implicit_sequence_conversion",
"is",
"disabled",
"this",
"method",
"is",
"not",
"automatically",
"called",
"and",
... | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/wrappers/base_response.py#L399-L414 | train |
pallets/werkzeug | src/werkzeug/wrappers/base_response.py | BaseResponse.set_cookie | def set_cookie(
self,
key,
value="",
max_age=None,
expires=None,
path="/",
domain=None,
secure=False,
httponly=False,
samesite=None,
):
"""Sets a cookie. The parameters are the same as in the cookie `Morsel`
object in th... | python | def set_cookie(
self,
key,
value="",
max_age=None,
expires=None,
path="/",
domain=None,
secure=False,
httponly=False,
samesite=None,
):
"""Sets a cookie. The parameters are the same as in the cookie `Morsel`
object in th... | [
"def",
"set_cookie",
"(",
"self",
",",
"key",
",",
"value",
"=",
"\"\"",
",",
"max_age",
"=",
"None",
",",
"expires",
"=",
"None",
",",
"path",
"=",
"\"/\"",
",",
"domain",
"=",
"None",
",",
"secure",
"=",
"False",
",",
"httponly",
"=",
"False",
",... | Sets a cookie. The parameters are the same as in the cookie `Morsel`
object in the Python standard library but it accepts unicode data, too.
A warning is raised if the size of the cookie header exceeds
:attr:`max_cookie_size`, but the header will still be set.
:param key: the key (name... | [
"Sets",
"a",
"cookie",
".",
"The",
"parameters",
"are",
"the",
"same",
"as",
"in",
"the",
"cookie",
"Morsel",
"object",
"in",
"the",
"Python",
"standard",
"library",
"but",
"it",
"accepts",
"unicode",
"data",
"too",
"."
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/wrappers/base_response.py#L429-L483 | train |
pallets/werkzeug | src/werkzeug/wrappers/base_response.py | BaseResponse.close | def close(self):
"""Close the wrapped response if possible. You can also use the object
in a with statement which will automatically close it.
.. versionadded:: 0.9
Can now be used in a with statement.
"""
if hasattr(self.response, "close"):
self.response... | python | def close(self):
"""Close the wrapped response if possible. You can also use the object
in a with statement which will automatically close it.
.. versionadded:: 0.9
Can now be used in a with statement.
"""
if hasattr(self.response, "close"):
self.response... | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
".",
"response",
",",
"\"close\"",
")",
":",
"self",
".",
"response",
".",
"close",
"(",
")",
"for",
"func",
"in",
"self",
".",
"_on_close",
":",
"func",
"(",
")"
] | Close the wrapped response if possible. You can also use the object
in a with statement which will automatically close it.
.. versionadded:: 0.9
Can now be used in a with statement. | [
"Close",
"the",
"wrapped",
"response",
"if",
"possible",
".",
"You",
"can",
"also",
"use",
"the",
"object",
"in",
"a",
"with",
"statement",
"which",
"will",
"automatically",
"close",
"it",
"."
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/wrappers/base_response.py#L522-L532 | train |
pallets/werkzeug | src/werkzeug/wrappers/base_response.py | BaseResponse.get_wsgi_headers | def get_wsgi_headers(self, environ):
"""This is automatically called right before the response is started
and returns headers modified for the given environment. It returns a
copy of the headers from the response with some modifications applied
if necessary.
For example the loc... | python | def get_wsgi_headers(self, environ):
"""This is automatically called right before the response is started
and returns headers modified for the given environment. It returns a
copy of the headers from the response with some modifications applied
if necessary.
For example the loc... | [
"def",
"get_wsgi_headers",
"(",
"self",
",",
"environ",
")",
":",
"headers",
"=",
"Headers",
"(",
"self",
".",
"headers",
")",
"location",
"=",
"None",
"content_location",
"=",
"None",
"content_length",
"=",
"None",
"status",
"=",
"self",
".",
"status_code",... | This is automatically called right before the response is started
and returns headers modified for the given environment. It returns a
copy of the headers from the response with some modifications applied
if necessary.
For example the location header (if present) is joined with the roo... | [
"This",
"is",
"automatically",
"called",
"right",
"before",
"the",
"response",
"is",
"started",
"and",
"returns",
"headers",
"modified",
"for",
"the",
"given",
"environment",
".",
"It",
"returns",
"a",
"copy",
"of",
"the",
"headers",
"from",
"the",
"response",... | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/wrappers/base_response.py#L553-L644 | train |
pallets/werkzeug | src/werkzeug/wrappers/base_response.py | BaseResponse.get_wsgi_response | def get_wsgi_response(self, environ):
"""Returns the final WSGI response as tuple. The first item in
the tuple is the application iterator, the second the status and
the third the list of headers. The response returned is created
specially for the given environment. For example if the... | python | def get_wsgi_response(self, environ):
"""Returns the final WSGI response as tuple. The first item in
the tuple is the application iterator, the second the status and
the third the list of headers. The response returned is created
specially for the given environment. For example if the... | [
"def",
"get_wsgi_response",
"(",
"self",
",",
"environ",
")",
":",
"headers",
"=",
"self",
".",
"get_wsgi_headers",
"(",
"environ",
")",
"app_iter",
"=",
"self",
".",
"get_app_iter",
"(",
"environ",
")",
"return",
"app_iter",
",",
"self",
".",
"status",
",... | Returns the final WSGI response as tuple. The first item in
the tuple is the application iterator, the second the status and
the third the list of headers. The response returned is created
specially for the given environment. For example if the request
method in the WSGI environment i... | [
"Returns",
"the",
"final",
"WSGI",
"response",
"as",
"tuple",
".",
"The",
"first",
"item",
"in",
"the",
"tuple",
"is",
"the",
"application",
"iterator",
"the",
"second",
"the",
"status",
"and",
"the",
"third",
"the",
"list",
"of",
"headers",
".",
"The",
... | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/wrappers/base_response.py#L675-L690 | train |
pallets/werkzeug | src/werkzeug/security.py | pbkdf2_bin | def pbkdf2_bin(
data, salt, iterations=DEFAULT_PBKDF2_ITERATIONS, keylen=None, hashfunc=None
):
"""Returns a binary digest for the PBKDF2 hash algorithm of `data`
with the given `salt`. It iterates `iterations` times and produces a
key of `keylen` bytes. By default, SHA-256 is used as hash function;
... | python | def pbkdf2_bin(
data, salt, iterations=DEFAULT_PBKDF2_ITERATIONS, keylen=None, hashfunc=None
):
"""Returns a binary digest for the PBKDF2 hash algorithm of `data`
with the given `salt`. It iterates `iterations` times and produces a
key of `keylen` bytes. By default, SHA-256 is used as hash function;
... | [
"def",
"pbkdf2_bin",
"(",
"data",
",",
"salt",
",",
"iterations",
"=",
"DEFAULT_PBKDF2_ITERATIONS",
",",
"keylen",
"=",
"None",
",",
"hashfunc",
"=",
"None",
")",
":",
"if",
"not",
"hashfunc",
":",
"hashfunc",
"=",
"\"sha256\"",
"data",
"=",
"to_bytes",
"(... | Returns a binary digest for the PBKDF2 hash algorithm of `data`
with the given `salt`. It iterates `iterations` times and produces a
key of `keylen` bytes. By default, SHA-256 is used as hash function;
a different hashlib `hashfunc` can be provided.
.. versionadded:: 0.9
:param data: the data to d... | [
"Returns",
"a",
"binary",
"digest",
"for",
"the",
"PBKDF2",
"hash",
"algorithm",
"of",
"data",
"with",
"the",
"given",
"salt",
".",
"It",
"iterates",
"iterations",
"times",
"and",
"produces",
"a",
"key",
"of",
"keylen",
"bytes",
".",
"By",
"default",
"SHA"... | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/security.py#L57-L87 | train |
pallets/werkzeug | src/werkzeug/security.py | _hash_internal | def _hash_internal(method, salt, password):
"""Internal password hash helper. Supports plaintext without salt,
unsalted and salted passwords. In case salted passwords are used
hmac is used.
"""
if method == "plain":
return password, method
if isinstance(password, text_type):
p... | python | def _hash_internal(method, salt, password):
"""Internal password hash helper. Supports plaintext without salt,
unsalted and salted passwords. In case salted passwords are used
hmac is used.
"""
if method == "plain":
return password, method
if isinstance(password, text_type):
p... | [
"def",
"_hash_internal",
"(",
"method",
",",
"salt",
",",
"password",
")",
":",
"if",
"method",
"==",
"\"plain\"",
":",
"return",
"password",
",",
"method",
"if",
"isinstance",
"(",
"password",
",",
"text_type",
")",
":",
"password",
"=",
"password",
".",
... | Internal password hash helper. Supports plaintext without salt,
unsalted and salted passwords. In case salted passwords are used
hmac is used. | [
"Internal",
"password",
"hash",
"helper",
".",
"Supports",
"plaintext",
"without",
"salt",
"unsalted",
"and",
"salted",
"passwords",
".",
"In",
"case",
"salted",
"passwords",
"are",
"used",
"hmac",
"is",
"used",
"."
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/security.py#L127-L161 | train |
pallets/werkzeug | src/werkzeug/security.py | safe_join | def safe_join(directory, *pathnames):
"""Safely join `directory` and one or more untrusted `pathnames`. If this
cannot be done, this function returns ``None``.
:param directory: the base directory.
:param pathnames: the untrusted pathnames relative to that directory.
"""
parts = [directory]
... | python | def safe_join(directory, *pathnames):
"""Safely join `directory` and one or more untrusted `pathnames`. If this
cannot be done, this function returns ``None``.
:param directory: the base directory.
:param pathnames: the untrusted pathnames relative to that directory.
"""
parts = [directory]
... | [
"def",
"safe_join",
"(",
"directory",
",",
"*",
"pathnames",
")",
":",
"parts",
"=",
"[",
"directory",
"]",
"for",
"filename",
"in",
"pathnames",
":",
"if",
"filename",
"!=",
"\"\"",
":",
"filename",
"=",
"posixpath",
".",
"normpath",
"(",
"filename",
")... | Safely join `directory` and one or more untrusted `pathnames`. If this
cannot be done, this function returns ``None``.
:param directory: the base directory.
:param pathnames: the untrusted pathnames relative to that directory. | [
"Safely",
"join",
"directory",
"and",
"one",
"or",
"more",
"untrusted",
"pathnames",
".",
"If",
"this",
"cannot",
"be",
"done",
"this",
"function",
"returns",
"None",
"."
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/security.py#L224-L241 | train |
pallets/werkzeug | src/werkzeug/serving.py | generate_adhoc_ssl_context | def generate_adhoc_ssl_context():
"""Generates an adhoc SSL context for the development server."""
crypto = _get_openssl_crypto_module()
import tempfile
import atexit
cert, pkey = generate_adhoc_ssl_pair()
cert_handle, cert_file = tempfile.mkstemp()
pkey_handle, pkey_file = tempfile.mkstemp... | python | def generate_adhoc_ssl_context():
"""Generates an adhoc SSL context for the development server."""
crypto = _get_openssl_crypto_module()
import tempfile
import atexit
cert, pkey = generate_adhoc_ssl_pair()
cert_handle, cert_file = tempfile.mkstemp()
pkey_handle, pkey_file = tempfile.mkstemp... | [
"def",
"generate_adhoc_ssl_context",
"(",
")",
":",
"crypto",
"=",
"_get_openssl_crypto_module",
"(",
")",
"import",
"tempfile",
"import",
"atexit",
"cert",
",",
"pkey",
"=",
"generate_adhoc_ssl_pair",
"(",
")",
"cert_handle",
",",
"cert_file",
"=",
"tempfile",
".... | Generates an adhoc SSL context for the development server. | [
"Generates",
"an",
"adhoc",
"SSL",
"context",
"for",
"the",
"development",
"server",
"."
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/serving.py#L532-L549 | train |
pallets/werkzeug | src/werkzeug/serving.py | load_ssl_context | def load_ssl_context(cert_file, pkey_file=None, protocol=None):
"""Loads SSL context from cert/private key files and optional protocol.
Many parameters are directly taken from the API of
:py:class:`ssl.SSLContext`.
:param cert_file: Path of the certificate to use.
:param pkey_file: Path of the priv... | python | def load_ssl_context(cert_file, pkey_file=None, protocol=None):
"""Loads SSL context from cert/private key files and optional protocol.
Many parameters are directly taken from the API of
:py:class:`ssl.SSLContext`.
:param cert_file: Path of the certificate to use.
:param pkey_file: Path of the priv... | [
"def",
"load_ssl_context",
"(",
"cert_file",
",",
"pkey_file",
"=",
"None",
",",
"protocol",
"=",
"None",
")",
":",
"if",
"protocol",
"is",
"None",
":",
"protocol",
"=",
"ssl",
".",
"PROTOCOL_SSLv23",
"ctx",
"=",
"_SSLContext",
"(",
"protocol",
")",
"ctx",... | Loads SSL context from cert/private key files and optional protocol.
Many parameters are directly taken from the API of
:py:class:`ssl.SSLContext`.
:param cert_file: Path of the certificate to use.
:param pkey_file: Path of the private key to use. If not given, the key
will be obt... | [
"Loads",
"SSL",
"context",
"from",
"cert",
"/",
"private",
"key",
"files",
"and",
"optional",
"protocol",
".",
"Many",
"parameters",
"are",
"directly",
"taken",
"from",
"the",
"API",
"of",
":",
"py",
":",
"class",
":",
"ssl",
".",
"SSLContext",
"."
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/serving.py#L552-L567 | train |
pallets/werkzeug | src/werkzeug/serving.py | is_ssl_error | def is_ssl_error(error=None):
"""Checks if the given error (or the current one) is an SSL error."""
exc_types = (ssl.SSLError,)
try:
from OpenSSL.SSL import Error
exc_types += (Error,)
except ImportError:
pass
if error is None:
error = sys.exc_info()[1]
return i... | python | def is_ssl_error(error=None):
"""Checks if the given error (or the current one) is an SSL error."""
exc_types = (ssl.SSLError,)
try:
from OpenSSL.SSL import Error
exc_types += (Error,)
except ImportError:
pass
if error is None:
error = sys.exc_info()[1]
return i... | [
"def",
"is_ssl_error",
"(",
"error",
"=",
"None",
")",
":",
"exc_types",
"=",
"(",
"ssl",
".",
"SSLError",
",",
")",
"try",
":",
"from",
"OpenSSL",
".",
"SSL",
"import",
"Error",
"exc_types",
"+=",
"(",
"Error",
",",
")",
"except",
"ImportError",
":",
... | Checks if the given error (or the current one) is an SSL error. | [
"Checks",
"if",
"the",
"given",
"error",
"(",
"or",
"the",
"current",
"one",
")",
"is",
"an",
"SSL",
"error",
"."
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/serving.py#L596-L608 | train |
pallets/werkzeug | src/werkzeug/serving.py | select_address_family | def select_address_family(host, port):
"""Return ``AF_INET4``, ``AF_INET6``, or ``AF_UNIX`` depending on
the host and port."""
# disabled due to problems with current ipv6 implementations
# and various operating systems. Probably this code also is
# not supposed to work, but I can't come up with an... | python | def select_address_family(host, port):
"""Return ``AF_INET4``, ``AF_INET6``, or ``AF_UNIX`` depending on
the host and port."""
# disabled due to problems with current ipv6 implementations
# and various operating systems. Probably this code also is
# not supposed to work, but I can't come up with an... | [
"def",
"select_address_family",
"(",
"host",
",",
"port",
")",
":",
"# disabled due to problems with current ipv6 implementations",
"# and various operating systems. Probably this code also is",
"# not supposed to work, but I can't come up with any other",
"# ways to implement this.",
"# tr... | Return ``AF_INET4``, ``AF_INET6``, or ``AF_UNIX`` depending on
the host and port. | [
"Return",
"AF_INET4",
"AF_INET6",
"or",
"AF_UNIX",
"depending",
"on",
"the",
"host",
"and",
"port",
"."
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/serving.py#L611-L630 | train |
pallets/werkzeug | src/werkzeug/serving.py | get_sockaddr | def get_sockaddr(host, port, family):
"""Return a fully qualified socket address that can be passed to
:func:`socket.bind`."""
if family == af_unix:
return host.split("://", 1)[1]
try:
res = socket.getaddrinfo(
host, port, family, socket.SOCK_STREAM, socket.IPPROTO_TCP
... | python | def get_sockaddr(host, port, family):
"""Return a fully qualified socket address that can be passed to
:func:`socket.bind`."""
if family == af_unix:
return host.split("://", 1)[1]
try:
res = socket.getaddrinfo(
host, port, family, socket.SOCK_STREAM, socket.IPPROTO_TCP
... | [
"def",
"get_sockaddr",
"(",
"host",
",",
"port",
",",
"family",
")",
":",
"if",
"family",
"==",
"af_unix",
":",
"return",
"host",
".",
"split",
"(",
"\"://\"",
",",
"1",
")",
"[",
"1",
"]",
"try",
":",
"res",
"=",
"socket",
".",
"getaddrinfo",
"(",... | Return a fully qualified socket address that can be passed to
:func:`socket.bind`. | [
"Return",
"a",
"fully",
"qualified",
"socket",
"address",
"that",
"can",
"be",
"passed",
"to",
":",
"func",
":",
"socket",
".",
"bind",
"."
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/serving.py#L633-L644 | train |
pallets/werkzeug | src/werkzeug/serving.py | run_simple | def run_simple(
hostname,
port,
application,
use_reloader=False,
use_debugger=False,
use_evalex=True,
extra_files=None,
reloader_interval=1,
reloader_type="auto",
threaded=False,
processes=1,
request_handler=None,
static_files=None,
passthrough_errors=False,
s... | python | def run_simple(
hostname,
port,
application,
use_reloader=False,
use_debugger=False,
use_evalex=True,
extra_files=None,
reloader_interval=1,
reloader_type="auto",
threaded=False,
processes=1,
request_handler=None,
static_files=None,
passthrough_errors=False,
s... | [
"def",
"run_simple",
"(",
"hostname",
",",
"port",
",",
"application",
",",
"use_reloader",
"=",
"False",
",",
"use_debugger",
"=",
"False",
",",
"use_evalex",
"=",
"True",
",",
"extra_files",
"=",
"None",
",",
"reloader_interval",
"=",
"1",
",",
"reloader_t... | Start a WSGI application. Optional features include a reloader,
multithreading and fork support.
This function has a command-line interface too::
python -m werkzeug.serving --help
.. versionadded:: 0.5
`static_files` was added to simplify serving of static files as well
as `passthro... | [
"Start",
"a",
"WSGI",
"application",
".",
"Optional",
"features",
"include",
"a",
"reloader",
"multithreading",
"and",
"fork",
"support",
"."
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/serving.py#L814-L990 | train |
pallets/werkzeug | src/werkzeug/serving.py | main | def main():
"""A simple command-line interface for :py:func:`run_simple`."""
# in contrast to argparse, this works at least under Python < 2.7
import optparse
from .utils import import_string
parser = optparse.OptionParser(usage="Usage: %prog [options] app_module:app_object")
parser.add_option... | python | def main():
"""A simple command-line interface for :py:func:`run_simple`."""
# in contrast to argparse, this works at least under Python < 2.7
import optparse
from .utils import import_string
parser = optparse.OptionParser(usage="Usage: %prog [options] app_module:app_object")
parser.add_option... | [
"def",
"main",
"(",
")",
":",
"# in contrast to argparse, this works at least under Python < 2.7",
"import",
"optparse",
"from",
".",
"utils",
"import",
"import_string",
"parser",
"=",
"optparse",
".",
"OptionParser",
"(",
"usage",
"=",
"\"Usage: %prog [options] app_module:... | A simple command-line interface for :py:func:`run_simple`. | [
"A",
"simple",
"command",
"-",
"line",
"interface",
"for",
":",
"py",
":",
"func",
":",
"run_simple",
"."
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/serving.py#L1001-L1051 | train |
pallets/werkzeug | src/werkzeug/serving.py | WSGIRequestHandler.handle | def handle(self):
"""Handles a request ignoring dropped connections."""
rv = None
try:
rv = BaseHTTPRequestHandler.handle(self)
except (_ConnectionError, socket.timeout) as e:
self.connection_dropped(e)
except Exception as e:
if self.server.ssl... | python | def handle(self):
"""Handles a request ignoring dropped connections."""
rv = None
try:
rv = BaseHTTPRequestHandler.handle(self)
except (_ConnectionError, socket.timeout) as e:
self.connection_dropped(e)
except Exception as e:
if self.server.ssl... | [
"def",
"handle",
"(",
"self",
")",
":",
"rv",
"=",
"None",
"try",
":",
"rv",
"=",
"BaseHTTPRequestHandler",
".",
"handle",
"(",
"self",
")",
"except",
"(",
"_ConnectionError",
",",
"socket",
".",
"timeout",
")",
"as",
"e",
":",
"self",
".",
"connection... | Handles a request ignoring dropped connections. | [
"Handles",
"a",
"request",
"ignoring",
"dropped",
"connections",
"."
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/serving.py#L321-L333 | train |
pallets/werkzeug | src/werkzeug/serving.py | WSGIRequestHandler.initiate_shutdown | def initiate_shutdown(self):
"""A horrible, horrible way to kill the server for Python 2.6 and
later. It's the best we can do.
"""
# Windows does not provide SIGKILL, go with SIGTERM then.
sig = getattr(signal, "SIGKILL", signal.SIGTERM)
# reloader active
if is_r... | python | def initiate_shutdown(self):
"""A horrible, horrible way to kill the server for Python 2.6 and
later. It's the best we can do.
"""
# Windows does not provide SIGKILL, go with SIGTERM then.
sig = getattr(signal, "SIGKILL", signal.SIGTERM)
# reloader active
if is_r... | [
"def",
"initiate_shutdown",
"(",
"self",
")",
":",
"# Windows does not provide SIGKILL, go with SIGTERM then.",
"sig",
"=",
"getattr",
"(",
"signal",
",",
"\"SIGKILL\"",
",",
"signal",
".",
"SIGTERM",
")",
"# reloader active",
"if",
"is_running_from_reloader",
"(",
")",... | A horrible, horrible way to kill the server for Python 2.6 and
later. It's the best we can do. | [
"A",
"horrible",
"horrible",
"way",
"to",
"kill",
"the",
"server",
"for",
"Python",
"2",
".",
"6",
"and",
"later",
".",
"It",
"s",
"the",
"best",
"we",
"can",
"do",
"."
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/serving.py#L335-L347 | train |
pallets/werkzeug | src/werkzeug/serving.py | WSGIRequestHandler.handle_one_request | def handle_one_request(self):
"""Handle a single HTTP request."""
self.raw_requestline = self.rfile.readline()
if not self.raw_requestline:
self.close_connection = 1
elif self.parse_request():
return self.run_wsgi() | python | def handle_one_request(self):
"""Handle a single HTTP request."""
self.raw_requestline = self.rfile.readline()
if not self.raw_requestline:
self.close_connection = 1
elif self.parse_request():
return self.run_wsgi() | [
"def",
"handle_one_request",
"(",
"self",
")",
":",
"self",
".",
"raw_requestline",
"=",
"self",
".",
"rfile",
".",
"readline",
"(",
")",
"if",
"not",
"self",
".",
"raw_requestline",
":",
"self",
".",
"close_connection",
"=",
"1",
"elif",
"self",
".",
"p... | Handle a single HTTP request. | [
"Handle",
"a",
"single",
"HTTP",
"request",
"."
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/serving.py#L354-L360 | train |
pallets/werkzeug | src/werkzeug/serving.py | WSGIRequestHandler.send_response | def send_response(self, code, message=None):
"""Send the response header and log the response code."""
self.log_request(code)
if message is None:
message = code in self.responses and self.responses[code][0] or ""
if self.request_version != "HTTP/0.9":
hdr = "%s %d... | python | def send_response(self, code, message=None):
"""Send the response header and log the response code."""
self.log_request(code)
if message is None:
message = code in self.responses and self.responses[code][0] or ""
if self.request_version != "HTTP/0.9":
hdr = "%s %d... | [
"def",
"send_response",
"(",
"self",
",",
"code",
",",
"message",
"=",
"None",
")",
":",
"self",
".",
"log_request",
"(",
"code",
")",
"if",
"message",
"is",
"None",
":",
"message",
"=",
"code",
"in",
"self",
".",
"responses",
"and",
"self",
".",
"re... | Send the response header and log the response code. | [
"Send",
"the",
"response",
"header",
"and",
"log",
"the",
"response",
"code",
"."
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/serving.py#L362-L369 | train |
pallets/werkzeug | src/werkzeug/serving.py | WSGIRequestHandler.get_header_items | def get_header_items(self):
"""
Get an iterable list of key/value pairs representing headers.
This function provides Python 2/3 compatibility as related to the
parsing of request headers. Python 2.7 is not compliant with
RFC 3875 Section 4.1.18 which requires multiple values for... | python | def get_header_items(self):
"""
Get an iterable list of key/value pairs representing headers.
This function provides Python 2/3 compatibility as related to the
parsing of request headers. Python 2.7 is not compliant with
RFC 3875 Section 4.1.18 which requires multiple values for... | [
"def",
"get_header_items",
"(",
"self",
")",
":",
"if",
"PY2",
":",
"# For Python 2, process the headers manually according to",
"# W3C RFC 2616 Section 4.2.",
"items",
"=",
"[",
"]",
"for",
"header",
"in",
"self",
".",
"headers",
".",
"headers",
":",
"# Remove \"\\n\... | Get an iterable list of key/value pairs representing headers.
This function provides Python 2/3 compatibility as related to the
parsing of request headers. Python 2.7 is not compliant with
RFC 3875 Section 4.1.18 which requires multiple values for headers
to be provided. This function w... | [
"Get",
"an",
"iterable",
"list",
"of",
"key",
"/",
"value",
"pairs",
"representing",
"headers",
"."
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/serving.py#L430-L460 | train |
pallets/werkzeug | src/werkzeug/_internal.py | _has_level_handler | def _has_level_handler(logger):
"""Check if there is a handler in the logging chain that will handle
the given logger's effective level.
"""
level = logger.getEffectiveLevel()
current = logger
while current:
if any(handler.level <= level for handler in current.handlers):
ret... | python | def _has_level_handler(logger):
"""Check if there is a handler in the logging chain that will handle
the given logger's effective level.
"""
level = logger.getEffectiveLevel()
current = logger
while current:
if any(handler.level <= level for handler in current.handlers):
ret... | [
"def",
"_has_level_handler",
"(",
"logger",
")",
":",
"level",
"=",
"logger",
".",
"getEffectiveLevel",
"(",
")",
"current",
"=",
"logger",
"while",
"current",
":",
"if",
"any",
"(",
"handler",
".",
"level",
"<=",
"level",
"for",
"handler",
"in",
"current"... | Check if there is a handler in the logging chain that will handle
the given logger's effective level. | [
"Check",
"if",
"there",
"is",
"a",
"handler",
"in",
"the",
"logging",
"chain",
"that",
"will",
"handle",
"the",
"given",
"logger",
"s",
"effective",
"level",
"."
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/_internal.py#L75-L91 | train |
pallets/werkzeug | src/werkzeug/_internal.py | _log | def _log(type, message, *args, **kwargs):
"""Log a message to the 'werkzeug' logger.
The logger is created the first time it is needed. If there is no
level set, it is set to :data:`logging.INFO`. If there is no handler
for the logger's effective level, a :class:`logging.StreamHandler`
is added.
... | python | def _log(type, message, *args, **kwargs):
"""Log a message to the 'werkzeug' logger.
The logger is created the first time it is needed. If there is no
level set, it is set to :data:`logging.INFO`. If there is no handler
for the logger's effective level, a :class:`logging.StreamHandler`
is added.
... | [
"def",
"_log",
"(",
"type",
",",
"message",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"global",
"_logger",
"if",
"_logger",
"is",
"None",
":",
"_logger",
"=",
"logging",
".",
"getLogger",
"(",
"\"werkzeug\"",
")",
"if",
"_logger",
".",
"le... | Log a message to the 'werkzeug' logger.
The logger is created the first time it is needed. If there is no
level set, it is set to :data:`logging.INFO`. If there is no handler
for the logger's effective level, a :class:`logging.StreamHandler`
is added. | [
"Log",
"a",
"message",
"to",
"the",
"werkzeug",
"logger",
"."
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/_internal.py#L94-L113 | train |
pallets/werkzeug | src/werkzeug/_internal.py | _parse_signature | def _parse_signature(func):
"""Return a signature object for the function."""
if hasattr(func, "im_func"):
func = func.im_func
# if we have a cached validator for this function, return it
parse = _signature_cache.get(func)
if parse is not None:
return parse
# inspect the functi... | python | def _parse_signature(func):
"""Return a signature object for the function."""
if hasattr(func, "im_func"):
func = func.im_func
# if we have a cached validator for this function, return it
parse = _signature_cache.get(func)
if parse is not None:
return parse
# inspect the functi... | [
"def",
"_parse_signature",
"(",
"func",
")",
":",
"if",
"hasattr",
"(",
"func",
",",
"\"im_func\"",
")",
":",
"func",
"=",
"func",
".",
"im_func",
"# if we have a cached validator for this function, return it",
"parse",
"=",
"_signature_cache",
".",
"get",
"(",
"f... | Return a signature object for the function. | [
"Return",
"a",
"signature",
"object",
"for",
"the",
"function",
"."
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/_internal.py#L116-L191 | train |
pallets/werkzeug | src/werkzeug/_internal.py | _date_to_unix | def _date_to_unix(arg):
"""Converts a timetuple, integer or datetime object into the seconds from
epoch in utc.
"""
if isinstance(arg, datetime):
arg = arg.utctimetuple()
elif isinstance(arg, integer_types + (float,)):
return int(arg)
year, month, day, hour, minute, second = arg[... | python | def _date_to_unix(arg):
"""Converts a timetuple, integer or datetime object into the seconds from
epoch in utc.
"""
if isinstance(arg, datetime):
arg = arg.utctimetuple()
elif isinstance(arg, integer_types + (float,)):
return int(arg)
year, month, day, hour, minute, second = arg[... | [
"def",
"_date_to_unix",
"(",
"arg",
")",
":",
"if",
"isinstance",
"(",
"arg",
",",
"datetime",
")",
":",
"arg",
"=",
"arg",
".",
"utctimetuple",
"(",
")",
"elif",
"isinstance",
"(",
"arg",
",",
"integer_types",
"+",
"(",
"float",
",",
")",
")",
":",
... | Converts a timetuple, integer or datetime object into the seconds from
epoch in utc. | [
"Converts",
"a",
"timetuple",
"integer",
"or",
"datetime",
"object",
"into",
"the",
"seconds",
"from",
"epoch",
"in",
"utc",
"."
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/_internal.py#L194-L207 | train |
pallets/werkzeug | src/werkzeug/_internal.py | _cookie_parse_impl | def _cookie_parse_impl(b):
"""Lowlevel cookie parsing facility that operates on bytes."""
i = 0
n = len(b)
while i < n:
match = _cookie_re.search(b + b";", i)
if not match:
break
key = match.group("key").strip()
value = match.group("val") or b""
i = ... | python | def _cookie_parse_impl(b):
"""Lowlevel cookie parsing facility that operates on bytes."""
i = 0
n = len(b)
while i < n:
match = _cookie_re.search(b + b";", i)
if not match:
break
key = match.group("key").strip()
value = match.group("val") or b""
i = ... | [
"def",
"_cookie_parse_impl",
"(",
"b",
")",
":",
"i",
"=",
"0",
"n",
"=",
"len",
"(",
"b",
")",
"while",
"i",
"<",
"n",
":",
"match",
"=",
"_cookie_re",
".",
"search",
"(",
"b",
"+",
"b\";\"",
",",
"i",
")",
"if",
"not",
"match",
":",
"break",
... | Lowlevel cookie parsing facility that operates on bytes. | [
"Lowlevel",
"cookie",
"parsing",
"facility",
"that",
"operates",
"on",
"bytes",
"."
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/_internal.py#L315-L329 | train |
pallets/werkzeug | src/werkzeug/_internal.py | _easteregg | def _easteregg(app=None):
"""Like the name says. But who knows how it works?"""
def bzzzzzzz(gyver):
import base64
import zlib
return zlib.decompress(base64.b64decode(gyver)).decode("ascii")
gyver = u"\n".join(
[
x + (77 - len(x)) * u" "
for x in b... | python | def _easteregg(app=None):
"""Like the name says. But who knows how it works?"""
def bzzzzzzz(gyver):
import base64
import zlib
return zlib.decompress(base64.b64decode(gyver)).decode("ascii")
gyver = u"\n".join(
[
x + (77 - len(x)) * u" "
for x in b... | [
"def",
"_easteregg",
"(",
"app",
"=",
"None",
")",
":",
"def",
"bzzzzzzz",
"(",
"gyver",
")",
":",
"import",
"base64",
"import",
"zlib",
"return",
"zlib",
".",
"decompress",
"(",
"base64",
".",
"b64decode",
"(",
"gyver",
")",
")",
".",
"decode",
"(",
... | Like the name says. But who knows how it works? | [
"Like",
"the",
"name",
"says",
".",
"But",
"who",
"knows",
"how",
"it",
"works?"
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/_internal.py#L391-L473 | train |
pallets/werkzeug | src/werkzeug/debug/__init__.py | get_pin_and_cookie_name | def get_pin_and_cookie_name(app):
"""Given an application object this returns a semi-stable 9 digit pin
code and a random key. The hope is that this is stable between
restarts to not make debugging particularly frustrating. If the pin
was forcefully disabled this returns `None`.
Second item in th... | python | def get_pin_and_cookie_name(app):
"""Given an application object this returns a semi-stable 9 digit pin
code and a random key. The hope is that this is stable between
restarts to not make debugging particularly frustrating. If the pin
was forcefully disabled this returns `None`.
Second item in th... | [
"def",
"get_pin_and_cookie_name",
"(",
"app",
")",
":",
"pin",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"\"WERKZEUG_DEBUG_PIN\"",
")",
"rv",
"=",
"None",
"num",
"=",
"None",
"# Pin was explicitly disabled",
"if",
"pin",
"==",
"\"off\"",
":",
"return",
"No... | Given an application object this returns a semi-stable 9 digit pin
code and a random key. The hope is that this is stable between
restarts to not make debugging particularly frustrating. If the pin
was forcefully disabled this returns `None`.
Second item in the resulting tuple is the cookie name for ... | [
"Given",
"an",
"application",
"object",
"this",
"returns",
"a",
"semi",
"-",
"stable",
"9",
"digit",
"pin",
"code",
"and",
"a",
"random",
"key",
".",
"The",
"hope",
"is",
"that",
"this",
"is",
"stable",
"between",
"restarts",
"to",
"not",
"make",
"debugg... | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/debug/__init__.py#L120-L200 | train |
pallets/werkzeug | src/werkzeug/debug/__init__.py | DebuggedApplication.pin_cookie_name | def pin_cookie_name(self):
"""The name of the pin cookie."""
if not hasattr(self, "_pin_cookie"):
self._pin, self._pin_cookie = get_pin_and_cookie_name(self.app)
return self._pin_cookie | python | def pin_cookie_name(self):
"""The name of the pin cookie."""
if not hasattr(self, "_pin_cookie"):
self._pin, self._pin_cookie = get_pin_and_cookie_name(self.app)
return self._pin_cookie | [
"def",
"pin_cookie_name",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"\"_pin_cookie\"",
")",
":",
"self",
".",
"_pin",
",",
"self",
".",
"_pin_cookie",
"=",
"get_pin_and_cookie_name",
"(",
"self",
".",
"app",
")",
"return",
"self",
... | The name of the pin cookie. | [
"The",
"name",
"of",
"the",
"pin",
"cookie",
"."
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/debug/__init__.py#L278-L282 | train |
pallets/werkzeug | src/werkzeug/debug/__init__.py | DebuggedApplication.execute_command | def execute_command(self, request, command, frame):
"""Execute a command in a console."""
return Response(frame.console.eval(command), mimetype="text/html") | python | def execute_command(self, request, command, frame):
"""Execute a command in a console."""
return Response(frame.console.eval(command), mimetype="text/html") | [
"def",
"execute_command",
"(",
"self",
",",
"request",
",",
"command",
",",
"frame",
")",
":",
"return",
"Response",
"(",
"frame",
".",
"console",
".",
"eval",
"(",
"command",
")",
",",
"mimetype",
"=",
"\"text/html\"",
")"
] | Execute a command in a console. | [
"Execute",
"a",
"command",
"in",
"a",
"console",
"."
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/debug/__init__.py#L333-L335 | train |
pallets/werkzeug | src/werkzeug/debug/__init__.py | DebuggedApplication.display_console | def display_console(self, request):
"""Display a standalone shell."""
if 0 not in self.frames:
if self.console_init_func is None:
ns = {}
else:
ns = dict(self.console_init_func())
ns.setdefault("app", self.app)
self.frames[0... | python | def display_console(self, request):
"""Display a standalone shell."""
if 0 not in self.frames:
if self.console_init_func is None:
ns = {}
else:
ns = dict(self.console_init_func())
ns.setdefault("app", self.app)
self.frames[0... | [
"def",
"display_console",
"(",
"self",
",",
"request",
")",
":",
"if",
"0",
"not",
"in",
"self",
".",
"frames",
":",
"if",
"self",
".",
"console_init_func",
"is",
"None",
":",
"ns",
"=",
"{",
"}",
"else",
":",
"ns",
"=",
"dict",
"(",
"self",
".",
... | Display a standalone shell. | [
"Display",
"a",
"standalone",
"shell",
"."
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/debug/__init__.py#L337-L350 | train |
pallets/werkzeug | src/werkzeug/debug/__init__.py | DebuggedApplication.get_resource | def get_resource(self, request, filename):
"""Return a static resource from the shared folder."""
filename = join("shared", basename(filename))
try:
data = pkgutil.get_data(__package__, filename)
except OSError:
data = None
if data is not None:
... | python | def get_resource(self, request, filename):
"""Return a static resource from the shared folder."""
filename = join("shared", basename(filename))
try:
data = pkgutil.get_data(__package__, filename)
except OSError:
data = None
if data is not None:
... | [
"def",
"get_resource",
"(",
"self",
",",
"request",
",",
"filename",
")",
":",
"filename",
"=",
"join",
"(",
"\"shared\"",
",",
"basename",
"(",
"filename",
")",
")",
"try",
":",
"data",
"=",
"pkgutil",
".",
"get_data",
"(",
"__package__",
",",
"filename... | Return a static resource from the shared folder. | [
"Return",
"a",
"static",
"resource",
"from",
"the",
"shared",
"folder",
"."
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/debug/__init__.py#L357-L367 | train |
pallets/werkzeug | src/werkzeug/debug/__init__.py | DebuggedApplication.check_pin_trust | def check_pin_trust(self, environ):
"""Checks if the request passed the pin test. This returns `True` if the
request is trusted on a pin/cookie basis and returns `False` if not.
Additionally if the cookie's stored pin hash is wrong it will return
`None` so that appropriate action can be... | python | def check_pin_trust(self, environ):
"""Checks if the request passed the pin test. This returns `True` if the
request is trusted on a pin/cookie basis and returns `False` if not.
Additionally if the cookie's stored pin hash is wrong it will return
`None` so that appropriate action can be... | [
"def",
"check_pin_trust",
"(",
"self",
",",
"environ",
")",
":",
"if",
"self",
".",
"pin",
"is",
"None",
":",
"return",
"True",
"val",
"=",
"parse_cookie",
"(",
"environ",
")",
".",
"get",
"(",
"self",
".",
"pin_cookie_name",
")",
"if",
"not",
"val",
... | Checks if the request passed the pin test. This returns `True` if the
request is trusted on a pin/cookie basis and returns `False` if not.
Additionally if the cookie's stored pin hash is wrong it will return
`None` so that appropriate action can be taken. | [
"Checks",
"if",
"the",
"request",
"passed",
"the",
"pin",
"test",
".",
"This",
"returns",
"True",
"if",
"the",
"request",
"is",
"trusted",
"on",
"a",
"pin",
"/",
"cookie",
"basis",
"and",
"returns",
"False",
"if",
"not",
".",
"Additionally",
"if",
"the",... | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/debug/__init__.py#L369-L385 | train |
pallets/werkzeug | src/werkzeug/debug/__init__.py | DebuggedApplication.pin_auth | def pin_auth(self, request):
"""Authenticates with the pin."""
exhausted = False
auth = False
trust = self.check_pin_trust(request.environ)
# If the trust return value is `None` it means that the cookie is
# set but the stored pin hash value is bad. This means that the
... | python | def pin_auth(self, request):
"""Authenticates with the pin."""
exhausted = False
auth = False
trust = self.check_pin_trust(request.environ)
# If the trust return value is `None` it means that the cookie is
# set but the stored pin hash value is bad. This means that the
... | [
"def",
"pin_auth",
"(",
"self",
",",
"request",
")",
":",
"exhausted",
"=",
"False",
"auth",
"=",
"False",
"trust",
"=",
"self",
".",
"check_pin_trust",
"(",
"request",
".",
"environ",
")",
"# If the trust return value is `None` it means that the cookie is",
"# set ... | Authenticates with the pin. | [
"Authenticates",
"with",
"the",
"pin",
"."
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/debug/__init__.py#L391-L436 | train |
pallets/werkzeug | src/werkzeug/debug/__init__.py | DebuggedApplication.log_pin_request | def log_pin_request(self):
"""Log the pin if needed."""
if self.pin_logging and self.pin is not None:
_log(
"info", " * To enable the debugger you need to enter the security pin:"
)
_log("info", " * Debugger pin code: %s" % self.pin)
return Res... | python | def log_pin_request(self):
"""Log the pin if needed."""
if self.pin_logging and self.pin is not None:
_log(
"info", " * To enable the debugger you need to enter the security pin:"
)
_log("info", " * Debugger pin code: %s" % self.pin)
return Res... | [
"def",
"log_pin_request",
"(",
"self",
")",
":",
"if",
"self",
".",
"pin_logging",
"and",
"self",
".",
"pin",
"is",
"not",
"None",
":",
"_log",
"(",
"\"info\"",
",",
"\" * To enable the debugger you need to enter the security pin:\"",
")",
"_log",
"(",
"\"info\"",... | Log the pin if needed. | [
"Log",
"the",
"pin",
"if",
"needed",
"."
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/debug/__init__.py#L438-L445 | train |
pallets/werkzeug | src/werkzeug/http.py | unquote_header_value | def unquote_header_value(value, is_filename=False):
r"""Unquotes a header value. (Reversal of :func:`quote_header_value`).
This does not use the real unquoting but what browsers are actually
using for quoting.
.. versionadded:: 0.5
:param value: the header value to unquote.
"""
if value a... | python | def unquote_header_value(value, is_filename=False):
r"""Unquotes a header value. (Reversal of :func:`quote_header_value`).
This does not use the real unquoting but what browsers are actually
using for quoting.
.. versionadded:: 0.5
:param value: the header value to unquote.
"""
if value a... | [
"def",
"unquote_header_value",
"(",
"value",
",",
"is_filename",
"=",
"False",
")",
":",
"if",
"value",
"and",
"value",
"[",
"0",
"]",
"==",
"value",
"[",
"-",
"1",
"]",
"==",
"'\"'",
":",
"# this is not the real unquoting, but fixing this so that the",
"# RFC i... | r"""Unquotes a header value. (Reversal of :func:`quote_header_value`).
This does not use the real unquoting but what browsers are actually
using for quoting.
.. versionadded:: 0.5
:param value: the header value to unquote. | [
"r",
"Unquotes",
"a",
"header",
"value",
".",
"(",
"Reversal",
"of",
":",
"func",
":",
"quote_header_value",
")",
".",
"This",
"does",
"not",
"use",
"the",
"real",
"unquoting",
"but",
"what",
"browsers",
"are",
"actually",
"using",
"for",
"quoting",
"."
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/http.py#L235-L258 | train |
pallets/werkzeug | src/werkzeug/http.py | dump_options_header | def dump_options_header(header, options):
"""The reverse function to :func:`parse_options_header`.
:param header: the header to dump
:param options: a dict of options to append.
"""
segments = []
if header is not None:
segments.append(header)
for key, value in iteritems(options):
... | python | def dump_options_header(header, options):
"""The reverse function to :func:`parse_options_header`.
:param header: the header to dump
:param options: a dict of options to append.
"""
segments = []
if header is not None:
segments.append(header)
for key, value in iteritems(options):
... | [
"def",
"dump_options_header",
"(",
"header",
",",
"options",
")",
":",
"segments",
"=",
"[",
"]",
"if",
"header",
"is",
"not",
"None",
":",
"segments",
".",
"append",
"(",
"header",
")",
"for",
"key",
",",
"value",
"in",
"iteritems",
"(",
"options",
")... | The reverse function to :func:`parse_options_header`.
:param header: the header to dump
:param options: a dict of options to append. | [
"The",
"reverse",
"function",
"to",
":",
"func",
":",
"parse_options_header",
"."
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/http.py#L261-L275 | train |
pallets/werkzeug | src/werkzeug/http.py | dump_header | def dump_header(iterable, allow_token=True):
"""Dump an HTTP header again. This is the reversal of
:func:`parse_list_header`, :func:`parse_set_header` and
:func:`parse_dict_header`. This also quotes strings that include an
equals sign unless you pass it as dict of key, value pairs.
>>> dump_heade... | python | def dump_header(iterable, allow_token=True):
"""Dump an HTTP header again. This is the reversal of
:func:`parse_list_header`, :func:`parse_set_header` and
:func:`parse_dict_header`. This also quotes strings that include an
equals sign unless you pass it as dict of key, value pairs.
>>> dump_heade... | [
"def",
"dump_header",
"(",
"iterable",
",",
"allow_token",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"iterable",
",",
"dict",
")",
":",
"items",
"=",
"[",
"]",
"for",
"key",
",",
"value",
"in",
"iteritems",
"(",
"iterable",
")",
":",
"if",
"val... | Dump an HTTP header again. This is the reversal of
:func:`parse_list_header`, :func:`parse_set_header` and
:func:`parse_dict_header`. This also quotes strings that include an
equals sign unless you pass it as dict of key, value pairs.
>>> dump_header({'foo': 'bar baz'})
'foo="bar baz"'
>>> du... | [
"Dump",
"an",
"HTTP",
"header",
"again",
".",
"This",
"is",
"the",
"reversal",
"of",
":",
"func",
":",
"parse_list_header",
":",
"func",
":",
"parse_set_header",
"and",
":",
"func",
":",
"parse_dict_header",
".",
"This",
"also",
"quotes",
"strings",
"that",
... | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/http.py#L278-L304 | train |
pallets/werkzeug | src/werkzeug/http.py | parse_dict_header | def parse_dict_header(value, cls=dict):
"""Parse lists of key, value pairs as described by RFC 2068 Section 2 and
convert them into a python dict (or any other mapping object created from
the type with a dict like interface provided by the `cls` argument):
>>> d = parse_dict_header('foo="is a fish", ba... | python | def parse_dict_header(value, cls=dict):
"""Parse lists of key, value pairs as described by RFC 2068 Section 2 and
convert them into a python dict (or any other mapping object created from
the type with a dict like interface provided by the `cls` argument):
>>> d = parse_dict_header('foo="is a fish", ba... | [
"def",
"parse_dict_header",
"(",
"value",
",",
"cls",
"=",
"dict",
")",
":",
"result",
"=",
"cls",
"(",
")",
"if",
"not",
"isinstance",
"(",
"value",
",",
"text_type",
")",
":",
"# XXX: validate",
"value",
"=",
"bytes_to_wsgi",
"(",
"value",
")",
"for",
... | Parse lists of key, value pairs as described by RFC 2068 Section 2 and
convert them into a python dict (or any other mapping object created from
the type with a dict like interface provided by the `cls` argument):
>>> d = parse_dict_header('foo="is a fish", bar="as well"')
>>> type(d) is dict
True
... | [
"Parse",
"lists",
"of",
"key",
"value",
"pairs",
"as",
"described",
"by",
"RFC",
"2068",
"Section",
"2",
"and",
"convert",
"them",
"into",
"a",
"python",
"dict",
"(",
"or",
"any",
"other",
"mapping",
"object",
"created",
"from",
"the",
"type",
"with",
"a... | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/http.py#L337-L375 | train |
pallets/werkzeug | src/werkzeug/http.py | parse_options_header | def parse_options_header(value, multiple=False):
"""Parse a ``Content-Type`` like header into a tuple with the content
type and the options:
>>> parse_options_header('text/html; charset=utf8')
('text/html', {'charset': 'utf8'})
This should not be used to parse ``Cache-Control`` like headers that u... | python | def parse_options_header(value, multiple=False):
"""Parse a ``Content-Type`` like header into a tuple with the content
type and the options:
>>> parse_options_header('text/html; charset=utf8')
('text/html', {'charset': 'utf8'})
This should not be used to parse ``Cache-Control`` like headers that u... | [
"def",
"parse_options_header",
"(",
"value",
",",
"multiple",
"=",
"False",
")",
":",
"if",
"not",
"value",
":",
"return",
"\"\"",
",",
"{",
"}",
"result",
"=",
"[",
"]",
"value",
"=",
"\",\"",
"+",
"value",
".",
"replace",
"(",
"\"\\n\"",
",",
"\",\... | Parse a ``Content-Type`` like header into a tuple with the content
type and the options:
>>> parse_options_header('text/html; charset=utf8')
('text/html', {'charset': 'utf8'})
This should not be used to parse ``Cache-Control`` like headers that use
a slightly different format. For these headers u... | [
"Parse",
"a",
"Content",
"-",
"Type",
"like",
"header",
"into",
"a",
"tuple",
"with",
"the",
"content",
"type",
"and",
"the",
"options",
":"
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/http.py#L378-L447 | train |
pallets/werkzeug | src/werkzeug/http.py | parse_accept_header | def parse_accept_header(value, cls=None):
"""Parses an HTTP Accept-* header. This does not implement a complete
valid algorithm but one that supports at least value and quality
extraction.
Returns a new :class:`Accept` object (basically a list of ``(value, quality)``
tuples sorted by the quality w... | python | def parse_accept_header(value, cls=None):
"""Parses an HTTP Accept-* header. This does not implement a complete
valid algorithm but one that supports at least value and quality
extraction.
Returns a new :class:`Accept` object (basically a list of ``(value, quality)``
tuples sorted by the quality w... | [
"def",
"parse_accept_header",
"(",
"value",
",",
"cls",
"=",
"None",
")",
":",
"if",
"cls",
"is",
"None",
":",
"cls",
"=",
"Accept",
"if",
"not",
"value",
":",
"return",
"cls",
"(",
"None",
")",
"result",
"=",
"[",
"]",
"for",
"match",
"in",
"_acce... | Parses an HTTP Accept-* header. This does not implement a complete
valid algorithm but one that supports at least value and quality
extraction.
Returns a new :class:`Accept` object (basically a list of ``(value, quality)``
tuples sorted by the quality with some additional accessor methods).
The s... | [
"Parses",
"an",
"HTTP",
"Accept",
"-",
"*",
"header",
".",
"This",
"does",
"not",
"implement",
"a",
"complete",
"valid",
"algorithm",
"but",
"one",
"that",
"supports",
"at",
"least",
"value",
"and",
"quality",
"extraction",
"."
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/http.py#L450-L480 | train |
pallets/werkzeug | src/werkzeug/http.py | parse_cache_control_header | def parse_cache_control_header(value, on_update=None, cls=None):
"""Parse a cache control header. The RFC differs between response and
request cache control, this method does not. It's your responsibility
to not use the wrong control statements.
.. versionadded:: 0.5
The `cls` was added. If n... | python | def parse_cache_control_header(value, on_update=None, cls=None):
"""Parse a cache control header. The RFC differs between response and
request cache control, this method does not. It's your responsibility
to not use the wrong control statements.
.. versionadded:: 0.5
The `cls` was added. If n... | [
"def",
"parse_cache_control_header",
"(",
"value",
",",
"on_update",
"=",
"None",
",",
"cls",
"=",
"None",
")",
":",
"if",
"cls",
"is",
"None",
":",
"cls",
"=",
"RequestCacheControl",
"if",
"not",
"value",
":",
"return",
"cls",
"(",
"None",
",",
"on_upda... | Parse a cache control header. The RFC differs between response and
request cache control, this method does not. It's your responsibility
to not use the wrong control statements.
.. versionadded:: 0.5
The `cls` was added. If not specified an immutable
:class:`~werkzeug.datastructures.Reques... | [
"Parse",
"a",
"cache",
"control",
"header",
".",
"The",
"RFC",
"differs",
"between",
"response",
"and",
"request",
"cache",
"control",
"this",
"method",
"does",
"not",
".",
"It",
"s",
"your",
"responsibility",
"to",
"not",
"use",
"the",
"wrong",
"control",
... | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/http.py#L483-L504 | train |
pallets/werkzeug | src/werkzeug/http.py | parse_set_header | def parse_set_header(value, on_update=None):
"""Parse a set-like header and return a
:class:`~werkzeug.datastructures.HeaderSet` object:
>>> hs = parse_set_header('token, "quoted value"')
The return value is an object that treats the items case-insensitively
and keeps the order of the items:
... | python | def parse_set_header(value, on_update=None):
"""Parse a set-like header and return a
:class:`~werkzeug.datastructures.HeaderSet` object:
>>> hs = parse_set_header('token, "quoted value"')
The return value is an object that treats the items case-insensitively
and keeps the order of the items:
... | [
"def",
"parse_set_header",
"(",
"value",
",",
"on_update",
"=",
"None",
")",
":",
"if",
"not",
"value",
":",
"return",
"HeaderSet",
"(",
"None",
",",
"on_update",
")",
"return",
"HeaderSet",
"(",
"parse_list_header",
"(",
"value",
")",
",",
"on_update",
")... | Parse a set-like header and return a
:class:`~werkzeug.datastructures.HeaderSet` object:
>>> hs = parse_set_header('token, "quoted value"')
The return value is an object that treats the items case-insensitively
and keeps the order of the items:
>>> 'TOKEN' in hs
True
>>> hs.index('quoted ... | [
"Parse",
"a",
"set",
"-",
"like",
"header",
"and",
"return",
"a",
":",
"class",
":",
"~werkzeug",
".",
"datastructures",
".",
"HeaderSet",
"object",
":"
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/http.py#L507-L534 | train |
pallets/werkzeug | src/werkzeug/http.py | parse_authorization_header | def parse_authorization_header(value):
"""Parse an HTTP basic/digest authorization header transmitted by the web
browser. The return value is either `None` if the header was invalid or
not given, otherwise an :class:`~werkzeug.datastructures.Authorization`
object.
:param value: the authorization h... | python | def parse_authorization_header(value):
"""Parse an HTTP basic/digest authorization header transmitted by the web
browser. The return value is either `None` if the header was invalid or
not given, otherwise an :class:`~werkzeug.datastructures.Authorization`
object.
:param value: the authorization h... | [
"def",
"parse_authorization_header",
"(",
"value",
")",
":",
"if",
"not",
"value",
":",
"return",
"value",
"=",
"wsgi_to_bytes",
"(",
"value",
")",
"try",
":",
"auth_type",
",",
"auth_info",
"=",
"value",
".",
"split",
"(",
"None",
",",
"1",
")",
"auth_t... | Parse an HTTP basic/digest authorization header transmitted by the web
browser. The return value is either `None` if the header was invalid or
not given, otherwise an :class:`~werkzeug.datastructures.Authorization`
object.
:param value: the authorization header to parse.
:return: a :class:`~werkze... | [
"Parse",
"an",
"HTTP",
"basic",
"/",
"digest",
"authorization",
"header",
"transmitted",
"by",
"the",
"web",
"browser",
".",
"The",
"return",
"value",
"is",
"either",
"None",
"if",
"the",
"header",
"was",
"invalid",
"or",
"not",
"given",
"otherwise",
"an",
... | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/http.py#L537-L574 | train |
pallets/werkzeug | src/werkzeug/http.py | parse_www_authenticate_header | def parse_www_authenticate_header(value, on_update=None):
"""Parse an HTTP WWW-Authenticate header into a
:class:`~werkzeug.datastructures.WWWAuthenticate` object.
:param value: a WWW-Authenticate header to parse.
:param on_update: an optional callable that is called every time a value
... | python | def parse_www_authenticate_header(value, on_update=None):
"""Parse an HTTP WWW-Authenticate header into a
:class:`~werkzeug.datastructures.WWWAuthenticate` object.
:param value: a WWW-Authenticate header to parse.
:param on_update: an optional callable that is called every time a value
... | [
"def",
"parse_www_authenticate_header",
"(",
"value",
",",
"on_update",
"=",
"None",
")",
":",
"if",
"not",
"value",
":",
"return",
"WWWAuthenticate",
"(",
"on_update",
"=",
"on_update",
")",
"try",
":",
"auth_type",
",",
"auth_info",
"=",
"value",
".",
"spl... | Parse an HTTP WWW-Authenticate header into a
:class:`~werkzeug.datastructures.WWWAuthenticate` object.
:param value: a WWW-Authenticate header to parse.
:param on_update: an optional callable that is called every time a value
on the :class:`~werkzeug.datastructures.WWWAuthenticate`
... | [
"Parse",
"an",
"HTTP",
"WWW",
"-",
"Authenticate",
"header",
"into",
"a",
":",
"class",
":",
"~werkzeug",
".",
"datastructures",
".",
"WWWAuthenticate",
"object",
"."
] | a220671d66755a94630a212378754bb432811158 | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/http.py#L577-L594 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.