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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
pulumi/pulumi | sdk/python/lib/pulumi/runtime/known_types.py | remote_asset | def remote_asset(class_obj: type) -> type:
"""
Decorator to annotate the RemoteAsset class. Registers the decorated class
as the RemoteAsset known type.
"""
assert isinstance(class_obj, type), "class_obj is not a Class"
global _remote_asset_resource_type
_remote_asset_resource_type = class_o... | python | def remote_asset(class_obj: type) -> type:
"""
Decorator to annotate the RemoteAsset class. Registers the decorated class
as the RemoteAsset known type.
"""
assert isinstance(class_obj, type), "class_obj is not a Class"
global _remote_asset_resource_type
_remote_asset_resource_type = class_o... | [
"def",
"remote_asset",
"(",
"class_obj",
":",
"type",
")",
"->",
"type",
":",
"assert",
"isinstance",
"(",
"class_obj",
",",
"type",
")",
",",
"\"class_obj is not a Class\"",
"global",
"_remote_asset_resource_type",
"_remote_asset_resource_type",
"=",
"class_obj",
"re... | Decorator to annotate the RemoteAsset class. Registers the decorated class
as the RemoteAsset known type. | [
"Decorator",
"to",
"annotate",
"the",
"RemoteAsset",
"class",
".",
"Registers",
"the",
"decorated",
"class",
"as",
"the",
"RemoteAsset",
"known",
"type",
"."
] | 95d51efe6ab9a533838b6d83aa240b5f912e72aa | https://github.com/pulumi/pulumi/blob/95d51efe6ab9a533838b6d83aa240b5f912e72aa/sdk/python/lib/pulumi/runtime/known_types.py#L99-L107 | train |
pulumi/pulumi | sdk/python/lib/pulumi/runtime/known_types.py | archive | def archive(class_obj: type) -> type:
"""
Decorator to annotate the Archive class. Registers the decorated class
as the Archive known type.
"""
assert isinstance(class_obj, type), "class_obj is not a Class"
global _archive_resource_type
_archive_resource_type = class_obj
return class_obj | python | def archive(class_obj: type) -> type:
"""
Decorator to annotate the Archive class. Registers the decorated class
as the Archive known type.
"""
assert isinstance(class_obj, type), "class_obj is not a Class"
global _archive_resource_type
_archive_resource_type = class_obj
return class_obj | [
"def",
"archive",
"(",
"class_obj",
":",
"type",
")",
"->",
"type",
":",
"assert",
"isinstance",
"(",
"class_obj",
",",
"type",
")",
",",
"\"class_obj is not a Class\"",
"global",
"_archive_resource_type",
"_archive_resource_type",
"=",
"class_obj",
"return",
"class... | Decorator to annotate the Archive class. Registers the decorated class
as the Archive known type. | [
"Decorator",
"to",
"annotate",
"the",
"Archive",
"class",
".",
"Registers",
"the",
"decorated",
"class",
"as",
"the",
"Archive",
"known",
"type",
"."
] | 95d51efe6ab9a533838b6d83aa240b5f912e72aa | https://github.com/pulumi/pulumi/blob/95d51efe6ab9a533838b6d83aa240b5f912e72aa/sdk/python/lib/pulumi/runtime/known_types.py#L110-L118 | train |
pulumi/pulumi | sdk/python/lib/pulumi/runtime/known_types.py | asset_archive | def asset_archive(class_obj: type) -> type:
"""
Decorator to annotate the AssetArchive class. Registers the decorated class
as the AssetArchive known type.
"""
assert isinstance(class_obj, type), "class_obj is not a Class"
global _asset_archive_resource_type
_asset_archive_resource_type = cl... | python | def asset_archive(class_obj: type) -> type:
"""
Decorator to annotate the AssetArchive class. Registers the decorated class
as the AssetArchive known type.
"""
assert isinstance(class_obj, type), "class_obj is not a Class"
global _asset_archive_resource_type
_asset_archive_resource_type = cl... | [
"def",
"asset_archive",
"(",
"class_obj",
":",
"type",
")",
"->",
"type",
":",
"assert",
"isinstance",
"(",
"class_obj",
",",
"type",
")",
",",
"\"class_obj is not a Class\"",
"global",
"_asset_archive_resource_type",
"_asset_archive_resource_type",
"=",
"class_obj",
... | Decorator to annotate the AssetArchive class. Registers the decorated class
as the AssetArchive known type. | [
"Decorator",
"to",
"annotate",
"the",
"AssetArchive",
"class",
".",
"Registers",
"the",
"decorated",
"class",
"as",
"the",
"AssetArchive",
"known",
"type",
"."
] | 95d51efe6ab9a533838b6d83aa240b5f912e72aa | https://github.com/pulumi/pulumi/blob/95d51efe6ab9a533838b6d83aa240b5f912e72aa/sdk/python/lib/pulumi/runtime/known_types.py#L121-L129 | train |
pulumi/pulumi | sdk/python/lib/pulumi/runtime/known_types.py | file_archive | def file_archive(class_obj: type) -> type:
"""
Decorator to annotate the FileArchive class. Registers the decorated class
as the FileArchive known type.
"""
assert isinstance(class_obj, type), "class_obj is not a Class"
global _file_archive_resource_type
_file_archive_resource_type = class_o... | python | def file_archive(class_obj: type) -> type:
"""
Decorator to annotate the FileArchive class. Registers the decorated class
as the FileArchive known type.
"""
assert isinstance(class_obj, type), "class_obj is not a Class"
global _file_archive_resource_type
_file_archive_resource_type = class_o... | [
"def",
"file_archive",
"(",
"class_obj",
":",
"type",
")",
"->",
"type",
":",
"assert",
"isinstance",
"(",
"class_obj",
",",
"type",
")",
",",
"\"class_obj is not a Class\"",
"global",
"_file_archive_resource_type",
"_file_archive_resource_type",
"=",
"class_obj",
"re... | Decorator to annotate the FileArchive class. Registers the decorated class
as the FileArchive known type. | [
"Decorator",
"to",
"annotate",
"the",
"FileArchive",
"class",
".",
"Registers",
"the",
"decorated",
"class",
"as",
"the",
"FileArchive",
"known",
"type",
"."
] | 95d51efe6ab9a533838b6d83aa240b5f912e72aa | https://github.com/pulumi/pulumi/blob/95d51efe6ab9a533838b6d83aa240b5f912e72aa/sdk/python/lib/pulumi/runtime/known_types.py#L132-L140 | train |
pulumi/pulumi | sdk/python/lib/pulumi/runtime/known_types.py | remote_archive | def remote_archive(class_obj: type) -> type:
"""
Decorator to annotate the RemoteArchive class. Registers the decorated class
as the RemoteArchive known type.
"""
assert isinstance(class_obj, type), "class_obj is not a Class"
global _remote_archive_resource_type
_remote_archive_resource_type... | python | def remote_archive(class_obj: type) -> type:
"""
Decorator to annotate the RemoteArchive class. Registers the decorated class
as the RemoteArchive known type.
"""
assert isinstance(class_obj, type), "class_obj is not a Class"
global _remote_archive_resource_type
_remote_archive_resource_type... | [
"def",
"remote_archive",
"(",
"class_obj",
":",
"type",
")",
"->",
"type",
":",
"assert",
"isinstance",
"(",
"class_obj",
",",
"type",
")",
",",
"\"class_obj is not a Class\"",
"global",
"_remote_archive_resource_type",
"_remote_archive_resource_type",
"=",
"class_obj",... | Decorator to annotate the RemoteArchive class. Registers the decorated class
as the RemoteArchive known type. | [
"Decorator",
"to",
"annotate",
"the",
"RemoteArchive",
"class",
".",
"Registers",
"the",
"decorated",
"class",
"as",
"the",
"RemoteArchive",
"known",
"type",
"."
] | 95d51efe6ab9a533838b6d83aa240b5f912e72aa | https://github.com/pulumi/pulumi/blob/95d51efe6ab9a533838b6d83aa240b5f912e72aa/sdk/python/lib/pulumi/runtime/known_types.py#L143-L151 | train |
pulumi/pulumi | sdk/python/lib/pulumi/runtime/known_types.py | custom_resource | def custom_resource(class_obj: type) -> type:
"""
Decorator to annotate the CustomResource class. Registers the decorated class
as the CustomResource known type.
"""
assert isinstance(class_obj, type), "class_obj is not a Class"
global _custom_resource_type
_custom_resource_type = class_obj
... | python | def custom_resource(class_obj: type) -> type:
"""
Decorator to annotate the CustomResource class. Registers the decorated class
as the CustomResource known type.
"""
assert isinstance(class_obj, type), "class_obj is not a Class"
global _custom_resource_type
_custom_resource_type = class_obj
... | [
"def",
"custom_resource",
"(",
"class_obj",
":",
"type",
")",
"->",
"type",
":",
"assert",
"isinstance",
"(",
"class_obj",
",",
"type",
")",
",",
"\"class_obj is not a Class\"",
"global",
"_custom_resource_type",
"_custom_resource_type",
"=",
"class_obj",
"return",
... | Decorator to annotate the CustomResource class. Registers the decorated class
as the CustomResource known type. | [
"Decorator",
"to",
"annotate",
"the",
"CustomResource",
"class",
".",
"Registers",
"the",
"decorated",
"class",
"as",
"the",
"CustomResource",
"known",
"type",
"."
] | 95d51efe6ab9a533838b6d83aa240b5f912e72aa | https://github.com/pulumi/pulumi/blob/95d51efe6ab9a533838b6d83aa240b5f912e72aa/sdk/python/lib/pulumi/runtime/known_types.py#L154-L162 | train |
pulumi/pulumi | sdk/python/lib/pulumi/log.py | debug | def debug(msg: str, resource: Optional['Resource'] = None, stream_id: Optional[int] = None) -> None:
"""
Logs a message to the Pulumi CLI's debug channel, associating it with a resource
and stream_id if provided.
:param str msg: The message to send to the Pulumi CLI.
:param Optional[Resource] resou... | python | def debug(msg: str, resource: Optional['Resource'] = None, stream_id: Optional[int] = None) -> None:
"""
Logs a message to the Pulumi CLI's debug channel, associating it with a resource
and stream_id if provided.
:param str msg: The message to send to the Pulumi CLI.
:param Optional[Resource] resou... | [
"def",
"debug",
"(",
"msg",
":",
"str",
",",
"resource",
":",
"Optional",
"[",
"'Resource'",
"]",
"=",
"None",
",",
"stream_id",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
")",
"->",
"None",
":",
"engine",
"=",
"get_engine",
"(",
")",
"if",
"en... | Logs a message to the Pulumi CLI's debug channel, associating it with a resource
and stream_id if provided.
:param str msg: The message to send to the Pulumi CLI.
:param Optional[Resource] resource: If provided, associate this message with the given resource in the Pulumi CLI.
:param Optional[int] stre... | [
"Logs",
"a",
"message",
"to",
"the",
"Pulumi",
"CLI",
"s",
"debug",
"channel",
"associating",
"it",
"with",
"a",
"resource",
"and",
"stream_id",
"if",
"provided",
"."
] | 95d51efe6ab9a533838b6d83aa240b5f912e72aa | https://github.com/pulumi/pulumi/blob/95d51efe6ab9a533838b6d83aa240b5f912e72aa/sdk/python/lib/pulumi/log.py#L29-L42 | train |
pulumi/pulumi | sdk/python/lib/pulumi/log.py | info | def info(msg: str, resource: Optional['Resource'] = None, stream_id: Optional[int] = None) -> None:
"""
Logs a message to the Pulumi CLI's info channel, associating it with a resource
and stream_id if provided.
:param str msg: The message to send to the Pulumi CLI.
:param Optional[Resource] resourc... | python | def info(msg: str, resource: Optional['Resource'] = None, stream_id: Optional[int] = None) -> None:
"""
Logs a message to the Pulumi CLI's info channel, associating it with a resource
and stream_id if provided.
:param str msg: The message to send to the Pulumi CLI.
:param Optional[Resource] resourc... | [
"def",
"info",
"(",
"msg",
":",
"str",
",",
"resource",
":",
"Optional",
"[",
"'Resource'",
"]",
"=",
"None",
",",
"stream_id",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
")",
"->",
"None",
":",
"engine",
"=",
"get_engine",
"(",
")",
"if",
"eng... | Logs a message to the Pulumi CLI's info channel, associating it with a resource
and stream_id if provided.
:param str msg: The message to send to the Pulumi CLI.
:param Optional[Resource] resource: If provided, associate this message with the given resource in the Pulumi CLI.
:param Optional[int] strea... | [
"Logs",
"a",
"message",
"to",
"the",
"Pulumi",
"CLI",
"s",
"info",
"channel",
"associating",
"it",
"with",
"a",
"resource",
"and",
"stream_id",
"if",
"provided",
"."
] | 95d51efe6ab9a533838b6d83aa240b5f912e72aa | https://github.com/pulumi/pulumi/blob/95d51efe6ab9a533838b6d83aa240b5f912e72aa/sdk/python/lib/pulumi/log.py#L45-L58 | train |
pulumi/pulumi | sdk/python/lib/pulumi/log.py | warn | def warn(msg: str, resource: Optional['Resource'] = None, stream_id: Optional[int] = None) -> None:
"""
Logs a message to the Pulumi CLI's warning channel, associating it with a resource
and stream_id if provided.
:param str msg: The message to send to the Pulumi CLI.
:param Optional[Resource] reso... | python | def warn(msg: str, resource: Optional['Resource'] = None, stream_id: Optional[int] = None) -> None:
"""
Logs a message to the Pulumi CLI's warning channel, associating it with a resource
and stream_id if provided.
:param str msg: The message to send to the Pulumi CLI.
:param Optional[Resource] reso... | [
"def",
"warn",
"(",
"msg",
":",
"str",
",",
"resource",
":",
"Optional",
"[",
"'Resource'",
"]",
"=",
"None",
",",
"stream_id",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
")",
"->",
"None",
":",
"engine",
"=",
"get_engine",
"(",
")",
"if",
"eng... | Logs a message to the Pulumi CLI's warning channel, associating it with a resource
and stream_id if provided.
:param str msg: The message to send to the Pulumi CLI.
:param Optional[Resource] resource: If provided, associate this message with the given resource in the Pulumi CLI.
:param Optional[int] st... | [
"Logs",
"a",
"message",
"to",
"the",
"Pulumi",
"CLI",
"s",
"warning",
"channel",
"associating",
"it",
"with",
"a",
"resource",
"and",
"stream_id",
"if",
"provided",
"."
] | 95d51efe6ab9a533838b6d83aa240b5f912e72aa | https://github.com/pulumi/pulumi/blob/95d51efe6ab9a533838b6d83aa240b5f912e72aa/sdk/python/lib/pulumi/log.py#L61-L74 | train |
pulumi/pulumi | sdk/python/lib/pulumi/log.py | error | def error(msg: str, resource: Optional['Resource'] = None, stream_id: Optional[int] = None):
"""
Logs a message to the Pulumi CLI's error channel, associating it with a resource
and stream_id if provided.
:param str msg: The message to send to the Pulumi CLI.
:param Optional[Resource] resource: If ... | python | def error(msg: str, resource: Optional['Resource'] = None, stream_id: Optional[int] = None):
"""
Logs a message to the Pulumi CLI's error channel, associating it with a resource
and stream_id if provided.
:param str msg: The message to send to the Pulumi CLI.
:param Optional[Resource] resource: If ... | [
"def",
"error",
"(",
"msg",
":",
"str",
",",
"resource",
":",
"Optional",
"[",
"'Resource'",
"]",
"=",
"None",
",",
"stream_id",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
")",
":",
"engine",
"=",
"get_engine",
"(",
")",
"if",
"engine",
"is",
"... | Logs a message to the Pulumi CLI's error channel, associating it with a resource
and stream_id if provided.
:param str msg: The message to send to the Pulumi CLI.
:param Optional[Resource] resource: If provided, associate this message with the given resource in the Pulumi CLI.
:param Optional[int] stre... | [
"Logs",
"a",
"message",
"to",
"the",
"Pulumi",
"CLI",
"s",
"error",
"channel",
"associating",
"it",
"with",
"a",
"resource",
"and",
"stream_id",
"if",
"provided",
"."
] | 95d51efe6ab9a533838b6d83aa240b5f912e72aa | https://github.com/pulumi/pulumi/blob/95d51efe6ab9a533838b6d83aa240b5f912e72aa/sdk/python/lib/pulumi/log.py#L77-L90 | train |
pulumi/pulumi | sdk/python/lib/pulumi/runtime/config.py | get_config_env | def get_config_env() -> Dict[str, Any]:
"""
Returns the environment map that will be used for config checking when variables aren't set.
"""
if 'PULUMI_CONFIG' in os.environ:
env_config = os.environ['PULUMI_CONFIG']
return json.loads(env_config)
return dict() | python | def get_config_env() -> Dict[str, Any]:
"""
Returns the environment map that will be used for config checking when variables aren't set.
"""
if 'PULUMI_CONFIG' in os.environ:
env_config = os.environ['PULUMI_CONFIG']
return json.loads(env_config)
return dict() | [
"def",
"get_config_env",
"(",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"if",
"'PULUMI_CONFIG'",
"in",
"os",
".",
"environ",
":",
"env_config",
"=",
"os",
".",
"environ",
"[",
"'PULUMI_CONFIG'",
"]",
"return",
"json",
".",
"loads",
"(",
"env... | Returns the environment map that will be used for config checking when variables aren't set. | [
"Returns",
"the",
"environment",
"map",
"that",
"will",
"be",
"used",
"for",
"config",
"checking",
"when",
"variables",
"aren",
"t",
"set",
"."
] | 95d51efe6ab9a533838b6d83aa240b5f912e72aa | https://github.com/pulumi/pulumi/blob/95d51efe6ab9a533838b6d83aa240b5f912e72aa/sdk/python/lib/pulumi/runtime/config.py#L34-L41 | train |
pulumi/pulumi | sdk/python/lib/pulumi/runtime/config.py | get_config_env_key | def get_config_env_key(k: str) -> str:
"""
Returns a scrubbed environment variable key, PULUMI_CONFIG_<k>, that can be used for
setting explicit varaibles. This is unlike PULUMI_CONFIG which is just a JSON-serialized bag.
"""
env_key = ''
for c in k:
if c == '_' or 'A' <= c <= 'Z' or '0... | python | def get_config_env_key(k: str) -> str:
"""
Returns a scrubbed environment variable key, PULUMI_CONFIG_<k>, that can be used for
setting explicit varaibles. This is unlike PULUMI_CONFIG which is just a JSON-serialized bag.
"""
env_key = ''
for c in k:
if c == '_' or 'A' <= c <= 'Z' or '0... | [
"def",
"get_config_env_key",
"(",
"k",
":",
"str",
")",
"->",
"str",
":",
"env_key",
"=",
"''",
"for",
"c",
"in",
"k",
":",
"if",
"c",
"==",
"'_'",
"or",
"'A'",
"<=",
"c",
"<=",
"'Z'",
"or",
"'0'",
"<=",
"c",
"<=",
"'9'",
":",
"env_key",
"+=",
... | Returns a scrubbed environment variable key, PULUMI_CONFIG_<k>, that can be used for
setting explicit varaibles. This is unlike PULUMI_CONFIG which is just a JSON-serialized bag. | [
"Returns",
"a",
"scrubbed",
"environment",
"variable",
"key",
"PULUMI_CONFIG_<k",
">",
"that",
"can",
"be",
"used",
"for",
"setting",
"explicit",
"varaibles",
".",
"This",
"is",
"unlike",
"PULUMI_CONFIG",
"which",
"is",
"just",
"a",
"JSON",
"-",
"serialized",
... | 95d51efe6ab9a533838b6d83aa240b5f912e72aa | https://github.com/pulumi/pulumi/blob/95d51efe6ab9a533838b6d83aa240b5f912e72aa/sdk/python/lib/pulumi/runtime/config.py#L44-L57 | train |
pulumi/pulumi | sdk/python/lib/pulumi/runtime/config.py | get_config | def get_config(k: str) -> Any:
"""
Returns a configuration variable's value or None if it is unset.
"""
# If the config has been set explicitly, use it.
if k in list(CONFIG.keys()):
return CONFIG[k]
# If there is a specific PULUMI_CONFIG_<k> environment variable, use it.
env_key = g... | python | def get_config(k: str) -> Any:
"""
Returns a configuration variable's value or None if it is unset.
"""
# If the config has been set explicitly, use it.
if k in list(CONFIG.keys()):
return CONFIG[k]
# If there is a specific PULUMI_CONFIG_<k> environment variable, use it.
env_key = g... | [
"def",
"get_config",
"(",
"k",
":",
"str",
")",
"->",
"Any",
":",
"# If the config has been set explicitly, use it.",
"if",
"k",
"in",
"list",
"(",
"CONFIG",
".",
"keys",
"(",
")",
")",
":",
"return",
"CONFIG",
"[",
"k",
"]",
"# If there is a specific PULUMI_C... | Returns a configuration variable's value or None if it is unset. | [
"Returns",
"a",
"configuration",
"variable",
"s",
"value",
"or",
"None",
"if",
"it",
"is",
"unset",
"."
] | 95d51efe6ab9a533838b6d83aa240b5f912e72aa | https://github.com/pulumi/pulumi/blob/95d51efe6ab9a533838b6d83aa240b5f912e72aa/sdk/python/lib/pulumi/runtime/config.py#L60-L78 | train |
pulumi/pulumi | sdk/python/lib/pulumi/runtime/stack.py | run_in_stack | async def run_in_stack(func: Callable):
"""
Run the given function inside of a new stack resource. This ensures that any stack export calls will end
up as output properties on the resulting stack component in the checkpoint file. This is meant for internal
runtime use only and is used by the Python SD... | python | async def run_in_stack(func: Callable):
"""
Run the given function inside of a new stack resource. This ensures that any stack export calls will end
up as output properties on the resulting stack component in the checkpoint file. This is meant for internal
runtime use only and is used by the Python SD... | [
"async",
"def",
"run_in_stack",
"(",
"func",
":",
"Callable",
")",
":",
"try",
":",
"Stack",
"(",
"func",
")",
"# If an exception occurred when doing an RPC, this await will propegate the exception",
"# to the main thread.",
"await",
"RPC_MANAGER",
".",
"unhandled_exeception"... | Run the given function inside of a new stack resource. This ensures that any stack export calls will end
up as output properties on the resulting stack component in the checkpoint file. This is meant for internal
runtime use only and is used by the Python SDK entrypoint program. | [
"Run",
"the",
"given",
"function",
"inside",
"of",
"a",
"new",
"stack",
"resource",
".",
"This",
"ensures",
"that",
"any",
"stack",
"export",
"calls",
"will",
"end",
"up",
"as",
"output",
"properties",
"on",
"the",
"resulting",
"stack",
"component",
"in",
... | 95d51efe6ab9a533838b6d83aa240b5f912e72aa | https://github.com/pulumi/pulumi/blob/95d51efe6ab9a533838b6d83aa240b5f912e72aa/sdk/python/lib/pulumi/runtime/stack.py#L27-L70 | train |
pulumi/pulumi | sdk/python/lib/pulumi/runtime/stack.py | Stack.output | def output(self, name: str, value: Any):
"""
Export a stack output with a given name and value.
"""
self.outputs[name] = value | python | def output(self, name: str, value: Any):
"""
Export a stack output with a given name and value.
"""
self.outputs[name] = value | [
"def",
"output",
"(",
"self",
",",
"name",
":",
"str",
",",
"value",
":",
"Any",
")",
":",
"self",
".",
"outputs",
"[",
"name",
"]",
"=",
"value"
] | Export a stack output with a given name and value. | [
"Export",
"a",
"stack",
"output",
"with",
"a",
"given",
"name",
"and",
"value",
"."
] | 95d51efe6ab9a533838b6d83aa240b5f912e72aa | https://github.com/pulumi/pulumi/blob/95d51efe6ab9a533838b6d83aa240b5f912e72aa/sdk/python/lib/pulumi/runtime/stack.py#L98-L102 | train |
pulumi/pulumi | sdk/python/lib/pulumi/runtime/invoke.py | invoke | def invoke(tok: str, props: Inputs, opts: InvokeOptions = None) -> Awaitable[Any]:
"""
invoke dynamically invokes the function, tok, which is offered by a provider plugin. The inputs
can be a bag of computed values (Ts or Awaitable[T]s), and the result is a Awaitable[Any] that
resolves when the invoke ... | python | def invoke(tok: str, props: Inputs, opts: InvokeOptions = None) -> Awaitable[Any]:
"""
invoke dynamically invokes the function, tok, which is offered by a provider plugin. The inputs
can be a bag of computed values (Ts or Awaitable[T]s), and the result is a Awaitable[Any] that
resolves when the invoke ... | [
"def",
"invoke",
"(",
"tok",
":",
"str",
",",
"props",
":",
"Inputs",
",",
"opts",
":",
"InvokeOptions",
"=",
"None",
")",
"->",
"Awaitable",
"[",
"Any",
"]",
":",
"log",
".",
"debug",
"(",
"f\"Invoking function: tok={tok}\"",
")",
"if",
"opts",
"is",
... | invoke dynamically invokes the function, tok, which is offered by a provider plugin. The inputs
can be a bag of computed values (Ts or Awaitable[T]s), and the result is a Awaitable[Any] that
resolves when the invoke finishes. | [
"invoke",
"dynamically",
"invokes",
"the",
"function",
"tok",
"which",
"is",
"offered",
"by",
"a",
"provider",
"plugin",
".",
"The",
"inputs",
"can",
"be",
"a",
"bag",
"of",
"computed",
"values",
"(",
"Ts",
"or",
"Awaitable",
"[",
"T",
"]",
"s",
")",
"... | 95d51efe6ab9a533838b6d83aa240b5f912e72aa | https://github.com/pulumi/pulumi/blob/95d51efe6ab9a533838b6d83aa240b5f912e72aa/sdk/python/lib/pulumi/runtime/invoke.py#L28-L86 | train |
pulumi/pulumi | sdk/python/lib/pulumi/resource.py | export | def export(name: str, value: Any):
"""
Exports a named stack output.
:param str name: The name to assign to this output.
:param Any value: The value of this output.
"""
stack = get_root_resource()
if stack is not None:
stack.output(name, value) | python | def export(name: str, value: Any):
"""
Exports a named stack output.
:param str name: The name to assign to this output.
:param Any value: The value of this output.
"""
stack = get_root_resource()
if stack is not None:
stack.output(name, value) | [
"def",
"export",
"(",
"name",
":",
"str",
",",
"value",
":",
"Any",
")",
":",
"stack",
"=",
"get_root_resource",
"(",
")",
"if",
"stack",
"is",
"not",
"None",
":",
"stack",
".",
"output",
"(",
"name",
",",
"value",
")"
] | Exports a named stack output.
:param str name: The name to assign to this output.
:param Any value: The value of this output. | [
"Exports",
"a",
"named",
"stack",
"output",
"."
] | 95d51efe6ab9a533838b6d83aa240b5f912e72aa | https://github.com/pulumi/pulumi/blob/95d51efe6ab9a533838b6d83aa240b5f912e72aa/sdk/python/lib/pulumi/resource.py#L321-L330 | train |
pulumi/pulumi | sdk/python/lib/pulumi/resource.py | Resource.get_provider | def get_provider(self, module_member: str) -> Optional['ProviderResource']:
"""
Fetches the provider for the given module member, if this resource has been provided a specific
provider for the given module member.
Returns None if no provider was provided.
:param str module_memb... | python | def get_provider(self, module_member: str) -> Optional['ProviderResource']:
"""
Fetches the provider for the given module member, if this resource has been provided a specific
provider for the given module member.
Returns None if no provider was provided.
:param str module_memb... | [
"def",
"get_provider",
"(",
"self",
",",
"module_member",
":",
"str",
")",
"->",
"Optional",
"[",
"'ProviderResource'",
"]",
":",
"components",
"=",
"module_member",
".",
"split",
"(",
"\":\"",
")",
"if",
"len",
"(",
"components",
")",
"!=",
"3",
":",
"r... | Fetches the provider for the given module member, if this resource has been provided a specific
provider for the given module member.
Returns None if no provider was provided.
:param str module_member: The requested module member.
:return: The :class:`ProviderResource` associated with ... | [
"Fetches",
"the",
"provider",
"for",
"the",
"given",
"module",
"member",
"if",
"this",
"resource",
"has",
"been",
"provided",
"a",
"specific",
"provider",
"for",
"the",
"given",
"module",
"member",
"."
] | 95d51efe6ab9a533838b6d83aa240b5f912e72aa | https://github.com/pulumi/pulumi/blob/95d51efe6ab9a533838b6d83aa240b5f912e72aa/sdk/python/lib/pulumi/resource.py#L215-L231 | train |
pytorch/ignite | ignite/engine/engine.py | Engine.add_event_handler | def add_event_handler(self, event_name, handler, *args, **kwargs):
"""Add an event handler to be executed when the specified event is fired.
Args:
event_name: An event to attach the handler to. Valid events are from :class:`~ignite.engine.Events`
or any `event_name` added by... | python | def add_event_handler(self, event_name, handler, *args, **kwargs):
"""Add an event handler to be executed when the specified event is fired.
Args:
event_name: An event to attach the handler to. Valid events are from :class:`~ignite.engine.Events`
or any `event_name` added by... | [
"def",
"add_event_handler",
"(",
"self",
",",
"event_name",
",",
"handler",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"event_name",
"not",
"in",
"self",
".",
"_allowed_events",
":",
"self",
".",
"_logger",
".",
"error",
"(",
"\"attempt t... | Add an event handler to be executed when the specified event is fired.
Args:
event_name: An event to attach the handler to. Valid events are from :class:`~ignite.engine.Events`
or any `event_name` added by :meth:`~ignite.engine.Engine.register_events`.
handler (callable)... | [
"Add",
"an",
"event",
"handler",
"to",
"be",
"executed",
"when",
"the",
"specified",
"event",
"is",
"fired",
"."
] | a96bd07cb58822cfb39fd81765135712f1db41ca | https://github.com/pytorch/ignite/blob/a96bd07cb58822cfb39fd81765135712f1db41ca/ignite/engine/engine.py#L122-L159 | train |
pytorch/ignite | ignite/engine/engine.py | Engine.has_event_handler | def has_event_handler(self, handler, event_name=None):
"""Check if the specified event has the specified handler.
Args:
handler (callable): the callable event handler.
event_name: The event the handler attached to. Set this
to ``None`` to search all events.
... | python | def has_event_handler(self, handler, event_name=None):
"""Check if the specified event has the specified handler.
Args:
handler (callable): the callable event handler.
event_name: The event the handler attached to. Set this
to ``None`` to search all events.
... | [
"def",
"has_event_handler",
"(",
"self",
",",
"handler",
",",
"event_name",
"=",
"None",
")",
":",
"if",
"event_name",
"is",
"not",
"None",
":",
"if",
"event_name",
"not",
"in",
"self",
".",
"_event_handlers",
":",
"return",
"False",
"events",
"=",
"[",
... | Check if the specified event has the specified handler.
Args:
handler (callable): the callable event handler.
event_name: The event the handler attached to. Set this
to ``None`` to search all events. | [
"Check",
"if",
"the",
"specified",
"event",
"has",
"the",
"specified",
"handler",
"."
] | a96bd07cb58822cfb39fd81765135712f1db41ca | https://github.com/pytorch/ignite/blob/a96bd07cb58822cfb39fd81765135712f1db41ca/ignite/engine/engine.py#L161-L179 | train |
pytorch/ignite | ignite/engine/engine.py | Engine.remove_event_handler | def remove_event_handler(self, handler, event_name):
"""Remove event handler `handler` from registered handlers of the engine
Args:
handler (callable): the callable event handler that should be removed
event_name: The event the handler attached to.
"""
if event_... | python | def remove_event_handler(self, handler, event_name):
"""Remove event handler `handler` from registered handlers of the engine
Args:
handler (callable): the callable event handler that should be removed
event_name: The event the handler attached to.
"""
if event_... | [
"def",
"remove_event_handler",
"(",
"self",
",",
"handler",
",",
"event_name",
")",
":",
"if",
"event_name",
"not",
"in",
"self",
".",
"_event_handlers",
":",
"raise",
"ValueError",
"(",
"\"Input event name '{}' does not exist\"",
".",
"format",
"(",
"event_name",
... | Remove event handler `handler` from registered handlers of the engine
Args:
handler (callable): the callable event handler that should be removed
event_name: The event the handler attached to. | [
"Remove",
"event",
"handler",
"handler",
"from",
"registered",
"handlers",
"of",
"the",
"engine"
] | a96bd07cb58822cfb39fd81765135712f1db41ca | https://github.com/pytorch/ignite/blob/a96bd07cb58822cfb39fd81765135712f1db41ca/ignite/engine/engine.py#L181-L196 | train |
pytorch/ignite | ignite/engine/engine.py | Engine.on | def on(self, event_name, *args, **kwargs):
"""Decorator shortcut for add_event_handler.
Args:
event_name: An event to attach the handler to. Valid events are from :class:`~ignite.engine.Events` or
any `event_name` added by :meth:`~ignite.engine.Engine.register_events`.
... | python | def on(self, event_name, *args, **kwargs):
"""Decorator shortcut for add_event_handler.
Args:
event_name: An event to attach the handler to. Valid events are from :class:`~ignite.engine.Events` or
any `event_name` added by :meth:`~ignite.engine.Engine.register_events`.
... | [
"def",
"on",
"(",
"self",
",",
"event_name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"self",
".",
"add_event_handler",
"(",
"event_name",
",",
"f",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")... | Decorator shortcut for add_event_handler.
Args:
event_name: An event to attach the handler to. Valid events are from :class:`~ignite.engine.Events` or
any `event_name` added by :meth:`~ignite.engine.Engine.register_events`.
*args: optional args to be passed to `handler`.... | [
"Decorator",
"shortcut",
"for",
"add_event_handler",
"."
] | a96bd07cb58822cfb39fd81765135712f1db41ca | https://github.com/pytorch/ignite/blob/a96bd07cb58822cfb39fd81765135712f1db41ca/ignite/engine/engine.py#L224-L237 | train |
pytorch/ignite | ignite/engine/engine.py | Engine._fire_event | def _fire_event(self, event_name, *event_args, **event_kwargs):
"""Execute all the handlers associated with given event.
This method executes all handlers associated with the event
`event_name`. Optional positional and keyword arguments can be used to
pass arguments to **all** handlers ... | python | def _fire_event(self, event_name, *event_args, **event_kwargs):
"""Execute all the handlers associated with given event.
This method executes all handlers associated with the event
`event_name`. Optional positional and keyword arguments can be used to
pass arguments to **all** handlers ... | [
"def",
"_fire_event",
"(",
"self",
",",
"event_name",
",",
"*",
"event_args",
",",
"*",
"*",
"event_kwargs",
")",
":",
"if",
"event_name",
"in",
"self",
".",
"_allowed_events",
":",
"self",
".",
"_logger",
".",
"debug",
"(",
"\"firing handlers for event %s \""... | Execute all the handlers associated with given event.
This method executes all handlers associated with the event
`event_name`. Optional positional and keyword arguments can be used to
pass arguments to **all** handlers added with this event. These
aguments updates arguments passed usin... | [
"Execute",
"all",
"the",
"handlers",
"associated",
"with",
"given",
"event",
"."
] | a96bd07cb58822cfb39fd81765135712f1db41ca | https://github.com/pytorch/ignite/blob/a96bd07cb58822cfb39fd81765135712f1db41ca/ignite/engine/engine.py#L239-L259 | train |
pytorch/ignite | ignite/engine/engine.py | Engine.run | def run(self, data, max_epochs=1):
"""Runs the process_function over the passed data.
Args:
data (Iterable): Collection of batches allowing repeated iteration (e.g., list or `DataLoader`).
max_epochs (int, optional): max epochs to run for (default: 1).
Returns:
... | python | def run(self, data, max_epochs=1):
"""Runs the process_function over the passed data.
Args:
data (Iterable): Collection of batches allowing repeated iteration (e.g., list or `DataLoader`).
max_epochs (int, optional): max epochs to run for (default: 1).
Returns:
... | [
"def",
"run",
"(",
"self",
",",
"data",
",",
"max_epochs",
"=",
"1",
")",
":",
"self",
".",
"state",
"=",
"State",
"(",
"dataloader",
"=",
"data",
",",
"epoch",
"=",
"0",
",",
"max_epochs",
"=",
"max_epochs",
",",
"metrics",
"=",
"{",
"}",
")",
"... | Runs the process_function over the passed data.
Args:
data (Iterable): Collection of batches allowing repeated iteration (e.g., list or `DataLoader`).
max_epochs (int, optional): max epochs to run for (default: 1).
Returns:
State: output state. | [
"Runs",
"the",
"process_function",
"over",
"the",
"passed",
"data",
"."
] | a96bd07cb58822cfb39fd81765135712f1db41ca | https://github.com/pytorch/ignite/blob/a96bd07cb58822cfb39fd81765135712f1db41ca/ignite/engine/engine.py#L326-L361 | train |
pytorch/ignite | ignite/metrics/confusion_matrix.py | IoU | def IoU(cm, ignore_index=None):
"""Calculates Intersection over Union
Args:
cm (ConfusionMatrix): instance of confusion matrix metric
ignore_index (int, optional): index to ignore, e.g. background index
Returns:
MetricsLambda
Examples:
.. code-block:: python
trai... | python | def IoU(cm, ignore_index=None):
"""Calculates Intersection over Union
Args:
cm (ConfusionMatrix): instance of confusion matrix metric
ignore_index (int, optional): index to ignore, e.g. background index
Returns:
MetricsLambda
Examples:
.. code-block:: python
trai... | [
"def",
"IoU",
"(",
"cm",
",",
"ignore_index",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"cm",
",",
"ConfusionMatrix",
")",
":",
"raise",
"TypeError",
"(",
"\"Argument cm should be instance of ConfusionMatrix, but given {}\"",
".",
"format",
"(",
"type... | Calculates Intersection over Union
Args:
cm (ConfusionMatrix): instance of confusion matrix metric
ignore_index (int, optional): index to ignore, e.g. background index
Returns:
MetricsLambda
Examples:
.. code-block:: python
train_evaluator = ...
cm = Confusi... | [
"Calculates",
"Intersection",
"over",
"Union"
] | a96bd07cb58822cfb39fd81765135712f1db41ca | https://github.com/pytorch/ignite/blob/a96bd07cb58822cfb39fd81765135712f1db41ca/ignite/metrics/confusion_matrix.py#L105-L150 | train |
pytorch/ignite | ignite/metrics/confusion_matrix.py | cmAccuracy | def cmAccuracy(cm):
"""
Calculates accuracy using :class:`~ignite.metrics.ConfusionMatrix` metric.
Args:
cm (ConfusionMatrix): instance of confusion matrix metric
Returns:
MetricsLambda
"""
# Increase floating point precision
cm = cm.type(torch.float64)
return cm.diag().... | python | def cmAccuracy(cm):
"""
Calculates accuracy using :class:`~ignite.metrics.ConfusionMatrix` metric.
Args:
cm (ConfusionMatrix): instance of confusion matrix metric
Returns:
MetricsLambda
"""
# Increase floating point precision
cm = cm.type(torch.float64)
return cm.diag().... | [
"def",
"cmAccuracy",
"(",
"cm",
")",
":",
"# Increase floating point precision",
"cm",
"=",
"cm",
".",
"type",
"(",
"torch",
".",
"float64",
")",
"return",
"cm",
".",
"diag",
"(",
")",
".",
"sum",
"(",
")",
"/",
"(",
"cm",
".",
"sum",
"(",
")",
"+"... | Calculates accuracy using :class:`~ignite.metrics.ConfusionMatrix` metric.
Args:
cm (ConfusionMatrix): instance of confusion matrix metric
Returns:
MetricsLambda | [
"Calculates",
"accuracy",
"using",
":",
"class",
":",
"~ignite",
".",
"metrics",
".",
"ConfusionMatrix",
"metric",
".",
"Args",
":",
"cm",
"(",
"ConfusionMatrix",
")",
":",
"instance",
"of",
"confusion",
"matrix",
"metric"
] | a96bd07cb58822cfb39fd81765135712f1db41ca | https://github.com/pytorch/ignite/blob/a96bd07cb58822cfb39fd81765135712f1db41ca/ignite/metrics/confusion_matrix.py#L180-L191 | train |
pytorch/ignite | ignite/metrics/confusion_matrix.py | cmPrecision | def cmPrecision(cm, average=True):
"""
Calculates precision using :class:`~ignite.metrics.ConfusionMatrix` metric.
Args:
cm (ConfusionMatrix): instance of confusion matrix metric
average (bool, optional): if True metric value is averaged over all classes
Returns:
MetricsLambda
... | python | def cmPrecision(cm, average=True):
"""
Calculates precision using :class:`~ignite.metrics.ConfusionMatrix` metric.
Args:
cm (ConfusionMatrix): instance of confusion matrix metric
average (bool, optional): if True metric value is averaged over all classes
Returns:
MetricsLambda
... | [
"def",
"cmPrecision",
"(",
"cm",
",",
"average",
"=",
"True",
")",
":",
"# Increase floating point precision",
"cm",
"=",
"cm",
".",
"type",
"(",
"torch",
".",
"float64",
")",
"precision",
"=",
"cm",
".",
"diag",
"(",
")",
"/",
"(",
"cm",
".",
"sum",
... | Calculates precision using :class:`~ignite.metrics.ConfusionMatrix` metric.
Args:
cm (ConfusionMatrix): instance of confusion matrix metric
average (bool, optional): if True metric value is averaged over all classes
Returns:
MetricsLambda | [
"Calculates",
"precision",
"using",
":",
"class",
":",
"~ignite",
".",
"metrics",
".",
"ConfusionMatrix",
"metric",
".",
"Args",
":",
"cm",
"(",
"ConfusionMatrix",
")",
":",
"instance",
"of",
"confusion",
"matrix",
"metric",
"average",
"(",
"bool",
"optional",... | a96bd07cb58822cfb39fd81765135712f1db41ca | https://github.com/pytorch/ignite/blob/a96bd07cb58822cfb39fd81765135712f1db41ca/ignite/metrics/confusion_matrix.py#L194-L209 | train |
pytorch/ignite | ignite/metrics/confusion_matrix.py | cmRecall | def cmRecall(cm, average=True):
"""
Calculates recall using :class:`~ignite.metrics.ConfusionMatrix` metric.
Args:
cm (ConfusionMatrix): instance of confusion matrix metric
average (bool, optional): if True metric value is averaged over all classes
Returns:
MetricsLambda
"""
... | python | def cmRecall(cm, average=True):
"""
Calculates recall using :class:`~ignite.metrics.ConfusionMatrix` metric.
Args:
cm (ConfusionMatrix): instance of confusion matrix metric
average (bool, optional): if True metric value is averaged over all classes
Returns:
MetricsLambda
"""
... | [
"def",
"cmRecall",
"(",
"cm",
",",
"average",
"=",
"True",
")",
":",
"# Increase floating point precision",
"cm",
"=",
"cm",
".",
"type",
"(",
"torch",
".",
"float64",
")",
"recall",
"=",
"cm",
".",
"diag",
"(",
")",
"/",
"(",
"cm",
".",
"sum",
"(",
... | Calculates recall using :class:`~ignite.metrics.ConfusionMatrix` metric.
Args:
cm (ConfusionMatrix): instance of confusion matrix metric
average (bool, optional): if True metric value is averaged over all classes
Returns:
MetricsLambda | [
"Calculates",
"recall",
"using",
":",
"class",
":",
"~ignite",
".",
"metrics",
".",
"ConfusionMatrix",
"metric",
".",
"Args",
":",
"cm",
"(",
"ConfusionMatrix",
")",
":",
"instance",
"of",
"confusion",
"matrix",
"metric",
"average",
"(",
"bool",
"optional",
... | a96bd07cb58822cfb39fd81765135712f1db41ca | https://github.com/pytorch/ignite/blob/a96bd07cb58822cfb39fd81765135712f1db41ca/ignite/metrics/confusion_matrix.py#L212-L227 | train |
pytorch/ignite | ignite/utils.py | convert_tensor | def convert_tensor(input_, device=None, non_blocking=False):
"""Move tensors to relevant device."""
def _func(tensor):
return tensor.to(device=device, non_blocking=non_blocking) if device else tensor
return apply_to_tensor(input_, _func) | python | def convert_tensor(input_, device=None, non_blocking=False):
"""Move tensors to relevant device."""
def _func(tensor):
return tensor.to(device=device, non_blocking=non_blocking) if device else tensor
return apply_to_tensor(input_, _func) | [
"def",
"convert_tensor",
"(",
"input_",
",",
"device",
"=",
"None",
",",
"non_blocking",
"=",
"False",
")",
":",
"def",
"_func",
"(",
"tensor",
")",
":",
"return",
"tensor",
".",
"to",
"(",
"device",
"=",
"device",
",",
"non_blocking",
"=",
"non_blocking... | Move tensors to relevant device. | [
"Move",
"tensors",
"to",
"relevant",
"device",
"."
] | a96bd07cb58822cfb39fd81765135712f1db41ca | https://github.com/pytorch/ignite/blob/a96bd07cb58822cfb39fd81765135712f1db41ca/ignite/utils.py#L14-L19 | train |
pytorch/ignite | ignite/utils.py | apply_to_type | def apply_to_type(input_, input_type, func):
"""Apply a function on a object of `input_type` or mapping, or sequence of objects of `input_type`.
"""
if isinstance(input_, input_type):
return func(input_)
elif isinstance(input_, string_classes):
return input_
elif isinstance(input_, c... | python | def apply_to_type(input_, input_type, func):
"""Apply a function on a object of `input_type` or mapping, or sequence of objects of `input_type`.
"""
if isinstance(input_, input_type):
return func(input_)
elif isinstance(input_, string_classes):
return input_
elif isinstance(input_, c... | [
"def",
"apply_to_type",
"(",
"input_",
",",
"input_type",
",",
"func",
")",
":",
"if",
"isinstance",
"(",
"input_",
",",
"input_type",
")",
":",
"return",
"func",
"(",
"input_",
")",
"elif",
"isinstance",
"(",
"input_",
",",
"string_classes",
")",
":",
"... | Apply a function on a object of `input_type` or mapping, or sequence of objects of `input_type`. | [
"Apply",
"a",
"function",
"on",
"a",
"object",
"of",
"input_type",
"or",
"mapping",
"or",
"sequence",
"of",
"objects",
"of",
"input_type",
"."
] | a96bd07cb58822cfb39fd81765135712f1db41ca | https://github.com/pytorch/ignite/blob/a96bd07cb58822cfb39fd81765135712f1db41ca/ignite/utils.py#L28-L41 | train |
pytorch/ignite | ignite/utils.py | to_onehot | def to_onehot(indices, num_classes):
"""Convert a tensor of indices of any shape `(N, ...)` to a
tensor of one-hot indicators of shape `(N, num_classes, ...)`.
"""
onehot = torch.zeros(indices.shape[0], num_classes, *indices.shape[1:], device=indices.device)
return onehot.scatter_(1, indices.unsquee... | python | def to_onehot(indices, num_classes):
"""Convert a tensor of indices of any shape `(N, ...)` to a
tensor of one-hot indicators of shape `(N, num_classes, ...)`.
"""
onehot = torch.zeros(indices.shape[0], num_classes, *indices.shape[1:], device=indices.device)
return onehot.scatter_(1, indices.unsquee... | [
"def",
"to_onehot",
"(",
"indices",
",",
"num_classes",
")",
":",
"onehot",
"=",
"torch",
".",
"zeros",
"(",
"indices",
".",
"shape",
"[",
"0",
"]",
",",
"num_classes",
",",
"*",
"indices",
".",
"shape",
"[",
"1",
":",
"]",
",",
"device",
"=",
"ind... | Convert a tensor of indices of any shape `(N, ...)` to a
tensor of one-hot indicators of shape `(N, num_classes, ...)`. | [
"Convert",
"a",
"tensor",
"of",
"indices",
"of",
"any",
"shape",
"(",
"N",
"...",
")",
"to",
"a",
"tensor",
"of",
"one",
"-",
"hot",
"indicators",
"of",
"shape",
"(",
"N",
"num_classes",
"...",
")",
"."
] | a96bd07cb58822cfb39fd81765135712f1db41ca | https://github.com/pytorch/ignite/blob/a96bd07cb58822cfb39fd81765135712f1db41ca/ignite/utils.py#L44-L49 | train |
pytorch/ignite | ignite/contrib/handlers/tqdm_logger.py | ProgressBar.attach | def attach(self, engine, metric_names=None, output_transform=None,
event_name=Events.ITERATION_COMPLETED,
closing_event_name=Events.EPOCH_COMPLETED):
"""
Attaches the progress bar to an engine object.
Args:
engine (Engine): engine object.
me... | python | def attach(self, engine, metric_names=None, output_transform=None,
event_name=Events.ITERATION_COMPLETED,
closing_event_name=Events.EPOCH_COMPLETED):
"""
Attaches the progress bar to an engine object.
Args:
engine (Engine): engine object.
me... | [
"def",
"attach",
"(",
"self",
",",
"engine",
",",
"metric_names",
"=",
"None",
",",
"output_transform",
"=",
"None",
",",
"event_name",
"=",
"Events",
".",
"ITERATION_COMPLETED",
",",
"closing_event_name",
"=",
"Events",
".",
"EPOCH_COMPLETED",
")",
":",
"desc... | Attaches the progress bar to an engine object.
Args:
engine (Engine): engine object.
metric_names (list, optional): list of the metrics names to log as the bar progresses
output_transform (callable, optional): a function to select what you want to print from the engine's
... | [
"Attaches",
"the",
"progress",
"bar",
"to",
"an",
"engine",
"object",
"."
] | a96bd07cb58822cfb39fd81765135712f1db41ca | https://github.com/pytorch/ignite/blob/a96bd07cb58822cfb39fd81765135712f1db41ca/ignite/contrib/handlers/tqdm_logger.py#L137-L167 | train |
pytorch/ignite | ignite/contrib/engines/tbptt.py | create_supervised_tbptt_trainer | def create_supervised_tbptt_trainer(
model,
optimizer,
loss_fn,
tbtt_step,
dim=0,
device=None,
non_blocking=False,
prepare_batch=_prepare_batch
):
"""Create a trainer for truncated backprop through time supervised models.
Training recurrent model on long sequences is computation... | python | def create_supervised_tbptt_trainer(
model,
optimizer,
loss_fn,
tbtt_step,
dim=0,
device=None,
non_blocking=False,
prepare_batch=_prepare_batch
):
"""Create a trainer for truncated backprop through time supervised models.
Training recurrent model on long sequences is computation... | [
"def",
"create_supervised_tbptt_trainer",
"(",
"model",
",",
"optimizer",
",",
"loss_fn",
",",
"tbtt_step",
",",
"dim",
"=",
"0",
",",
"device",
"=",
"None",
",",
"non_blocking",
"=",
"False",
",",
"prepare_batch",
"=",
"_prepare_batch",
")",
":",
"if",
"dev... | Create a trainer for truncated backprop through time supervised models.
Training recurrent model on long sequences is computationally intensive as
it requires to process the whole sequence before getting a gradient.
However, when the training loss is computed over many outputs
(`X to many <https://karp... | [
"Create",
"a",
"trainer",
"for",
"truncated",
"backprop",
"through",
"time",
"supervised",
"models",
"."
] | a96bd07cb58822cfb39fd81765135712f1db41ca | https://github.com/pytorch/ignite/blob/a96bd07cb58822cfb39fd81765135712f1db41ca/ignite/contrib/engines/tbptt.py#L31-L109 | train |
pytorch/ignite | ignite/engine/__init__.py | _prepare_batch | def _prepare_batch(batch, device=None, non_blocking=False):
"""Prepare batch for training: pass to a device with options.
"""
x, y = batch
return (convert_tensor(x, device=device, non_blocking=non_blocking),
convert_tensor(y, device=device, non_blocking=non_blocking)) | python | def _prepare_batch(batch, device=None, non_blocking=False):
"""Prepare batch for training: pass to a device with options.
"""
x, y = batch
return (convert_tensor(x, device=device, non_blocking=non_blocking),
convert_tensor(y, device=device, non_blocking=non_blocking)) | [
"def",
"_prepare_batch",
"(",
"batch",
",",
"device",
"=",
"None",
",",
"non_blocking",
"=",
"False",
")",
":",
"x",
",",
"y",
"=",
"batch",
"return",
"(",
"convert_tensor",
"(",
"x",
",",
"device",
"=",
"device",
",",
"non_blocking",
"=",
"non_blocking"... | Prepare batch for training: pass to a device with options. | [
"Prepare",
"batch",
"for",
"training",
":",
"pass",
"to",
"a",
"device",
"with",
"options",
"."
] | a96bd07cb58822cfb39fd81765135712f1db41ca | https://github.com/pytorch/ignite/blob/a96bd07cb58822cfb39fd81765135712f1db41ca/ignite/engine/__init__.py#L7-L13 | train |
pytorch/ignite | ignite/engine/__init__.py | create_supervised_trainer | def create_supervised_trainer(model, optimizer, loss_fn,
device=None, non_blocking=False,
prepare_batch=_prepare_batch,
output_transform=lambda x, y, y_pred, loss: loss.item()):
"""
Factory function for creating a trainer ... | python | def create_supervised_trainer(model, optimizer, loss_fn,
device=None, non_blocking=False,
prepare_batch=_prepare_batch,
output_transform=lambda x, y, y_pred, loss: loss.item()):
"""
Factory function for creating a trainer ... | [
"def",
"create_supervised_trainer",
"(",
"model",
",",
"optimizer",
",",
"loss_fn",
",",
"device",
"=",
"None",
",",
"non_blocking",
"=",
"False",
",",
"prepare_batch",
"=",
"_prepare_batch",
",",
"output_transform",
"=",
"lambda",
"x",
",",
"y",
",",
"y_pred"... | Factory function for creating a trainer for supervised models.
Args:
model (`torch.nn.Module`): the model to train.
optimizer (`torch.optim.Optimizer`): the optimizer to use.
loss_fn (torch.nn loss function): the loss function to use.
device (str, optional): device type specificatio... | [
"Factory",
"function",
"for",
"creating",
"a",
"trainer",
"for",
"supervised",
"models",
"."
] | a96bd07cb58822cfb39fd81765135712f1db41ca | https://github.com/pytorch/ignite/blob/a96bd07cb58822cfb39fd81765135712f1db41ca/ignite/engine/__init__.py#L16-L55 | train |
pytorch/ignite | ignite/engine/__init__.py | create_supervised_evaluator | def create_supervised_evaluator(model, metrics=None,
device=None, non_blocking=False,
prepare_batch=_prepare_batch,
output_transform=lambda x, y, y_pred: (y_pred, y,)):
"""
Factory function for creating an evaluator ... | python | def create_supervised_evaluator(model, metrics=None,
device=None, non_blocking=False,
prepare_batch=_prepare_batch,
output_transform=lambda x, y, y_pred: (y_pred, y,)):
"""
Factory function for creating an evaluator ... | [
"def",
"create_supervised_evaluator",
"(",
"model",
",",
"metrics",
"=",
"None",
",",
"device",
"=",
"None",
",",
"non_blocking",
"=",
"False",
",",
"prepare_batch",
"=",
"_prepare_batch",
",",
"output_transform",
"=",
"lambda",
"x",
",",
"y",
",",
"y_pred",
... | Factory function for creating an evaluator for supervised models.
Args:
model (`torch.nn.Module`): the model to train.
metrics (dict of str - :class:`~ignite.metrics.Metric`): a map of metric names to Metrics.
device (str, optional): device type specification (default: None).
Ap... | [
"Factory",
"function",
"for",
"creating",
"an",
"evaluator",
"for",
"supervised",
"models",
"."
] | a96bd07cb58822cfb39fd81765135712f1db41ca | https://github.com/pytorch/ignite/blob/a96bd07cb58822cfb39fd81765135712f1db41ca/ignite/engine/__init__.py#L58-L101 | train |
pytorch/ignite | ignite/contrib/handlers/param_scheduler.py | create_lr_scheduler_with_warmup | def create_lr_scheduler_with_warmup(lr_scheduler, warmup_start_value, warmup_end_value, warmup_duration,
save_history=False,
output_simulated_values=None):
"""
Helper method to create a LR scheduler with a linear warm-up.
Args:
... | python | def create_lr_scheduler_with_warmup(lr_scheduler, warmup_start_value, warmup_end_value, warmup_duration,
save_history=False,
output_simulated_values=None):
"""
Helper method to create a LR scheduler with a linear warm-up.
Args:
... | [
"def",
"create_lr_scheduler_with_warmup",
"(",
"lr_scheduler",
",",
"warmup_start_value",
",",
"warmup_end_value",
",",
"warmup_duration",
",",
"save_history",
"=",
"False",
",",
"output_simulated_values",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"lr_sch... | Helper method to create a LR scheduler with a linear warm-up.
Args:
lr_scheduler (ParamScheduler or subclass of `torch.optim.lr_scheduler._LRScheduler`): LR scheduler after
the warm-up.
warmup_start_value (float): LR start value of the warm-up phase.
warmup_end_value (float): LR... | [
"Helper",
"method",
"to",
"create",
"a",
"LR",
"scheduler",
"with",
"a",
"linear",
"warm",
"-",
"up",
"."
] | a96bd07cb58822cfb39fd81765135712f1db41ca | https://github.com/pytorch/ignite/blob/a96bd07cb58822cfb39fd81765135712f1db41ca/ignite/contrib/handlers/param_scheduler.py#L501-L565 | train |
pytorch/ignite | ignite/contrib/handlers/param_scheduler.py | ParamScheduler.simulate_values | def simulate_values(cls, num_events, **scheduler_kwargs):
"""Method to simulate scheduled values during num_events events.
Args:
num_events (int): number of events during the simulation.
**scheduler_kwargs : parameter scheduler configuration kwargs.
Returns:
... | python | def simulate_values(cls, num_events, **scheduler_kwargs):
"""Method to simulate scheduled values during num_events events.
Args:
num_events (int): number of events during the simulation.
**scheduler_kwargs : parameter scheduler configuration kwargs.
Returns:
... | [
"def",
"simulate_values",
"(",
"cls",
",",
"num_events",
",",
"*",
"*",
"scheduler_kwargs",
")",
":",
"keys_to_remove",
"=",
"[",
"'optimizer'",
",",
"'save_history'",
"]",
"for",
"key",
"in",
"keys_to_remove",
":",
"if",
"key",
"in",
"scheduler_kwargs",
":",
... | Method to simulate scheduled values during num_events events.
Args:
num_events (int): number of events during the simulation.
**scheduler_kwargs : parameter scheduler configuration kwargs.
Returns:
list of pairs: [event_index, value]
Examples:
.. c... | [
"Method",
"to",
"simulate",
"scheduled",
"values",
"during",
"num_events",
"events",
"."
] | a96bd07cb58822cfb39fd81765135712f1db41ca | https://github.com/pytorch/ignite/blob/a96bd07cb58822cfb39fd81765135712f1db41ca/ignite/contrib/handlers/param_scheduler.py#L75-L108 | train |
pytorch/ignite | ignite/contrib/handlers/param_scheduler.py | CosineAnnealingScheduler.get_param | def get_param(self):
"""Method to get current optimizer's parameter value
"""
cycle_progress = self.event_index / self.cycle_size
return self.start_value + ((self.end_value - self.start_value) / 2) * (1 - math.cos(math.pi * cycle_progress)) | python | def get_param(self):
"""Method to get current optimizer's parameter value
"""
cycle_progress = self.event_index / self.cycle_size
return self.start_value + ((self.end_value - self.start_value) / 2) * (1 - math.cos(math.pi * cycle_progress)) | [
"def",
"get_param",
"(",
"self",
")",
":",
"cycle_progress",
"=",
"self",
".",
"event_index",
"/",
"self",
".",
"cycle_size",
"return",
"self",
".",
"start_value",
"+",
"(",
"(",
"self",
".",
"end_value",
"-",
"self",
".",
"start_value",
")",
"/",
"2",
... | Method to get current optimizer's parameter value | [
"Method",
"to",
"get",
"current",
"optimizer",
"s",
"parameter",
"value"
] | a96bd07cb58822cfb39fd81765135712f1db41ca | https://github.com/pytorch/ignite/blob/a96bd07cb58822cfb39fd81765135712f1db41ca/ignite/contrib/handlers/param_scheduler.py#L274-L278 | train |
pytorch/ignite | ignite/contrib/handlers/param_scheduler.py | ConcatScheduler.simulate_values | def simulate_values(cls, num_events, schedulers, durations, param_names=None, **kwargs):
"""Method to simulate scheduled values during num_events events.
Args:
num_events (int): number of events during the simulation.
schedulers (list of ParamScheduler): list of parameter schedu... | python | def simulate_values(cls, num_events, schedulers, durations, param_names=None, **kwargs):
"""Method to simulate scheduled values during num_events events.
Args:
num_events (int): number of events during the simulation.
schedulers (list of ParamScheduler): list of parameter schedu... | [
"def",
"simulate_values",
"(",
"cls",
",",
"num_events",
",",
"schedulers",
",",
"durations",
",",
"param_names",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"param_names",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"param_names",
",",... | Method to simulate scheduled values during num_events events.
Args:
num_events (int): number of events during the simulation.
schedulers (list of ParamScheduler): list of parameter schedulers.
durations (list of int): list of number of events that lasts a parameter scheduler... | [
"Method",
"to",
"simulate",
"scheduled",
"values",
"during",
"num_events",
"events",
"."
] | a96bd07cb58822cfb39fd81765135712f1db41ca | https://github.com/pytorch/ignite/blob/a96bd07cb58822cfb39fd81765135712f1db41ca/ignite/contrib/handlers/param_scheduler.py#L379-L408 | train |
pytorch/ignite | ignite/contrib/handlers/param_scheduler.py | LRScheduler.get_param | def get_param(self):
"""Method to get current optimizer's parameter value
"""
lr_list = self.lr_scheduler.get_lr()
if len(lr_list) > 1:
raise ValueError("Optimizer passed to lr_scheduler should have a single param group, "
"but currently there are... | python | def get_param(self):
"""Method to get current optimizer's parameter value
"""
lr_list = self.lr_scheduler.get_lr()
if len(lr_list) > 1:
raise ValueError("Optimizer passed to lr_scheduler should have a single param group, "
"but currently there are... | [
"def",
"get_param",
"(",
"self",
")",
":",
"lr_list",
"=",
"self",
".",
"lr_scheduler",
".",
"get_lr",
"(",
")",
"if",
"len",
"(",
"lr_list",
")",
">",
"1",
":",
"raise",
"ValueError",
"(",
"\"Optimizer passed to lr_scheduler should have a single param group, \"",... | Method to get current optimizer's parameter value | [
"Method",
"to",
"get",
"current",
"optimizer",
"s",
"parameter",
"value"
] | a96bd07cb58822cfb39fd81765135712f1db41ca | https://github.com/pytorch/ignite/blob/a96bd07cb58822cfb39fd81765135712f1db41ca/ignite/contrib/handlers/param_scheduler.py#L450-L457 | train |
pytorch/ignite | ignite/contrib/handlers/param_scheduler.py | LRScheduler.simulate_values | def simulate_values(cls, num_events, lr_scheduler, **kwargs):
"""Method to simulate scheduled values during num_events events.
Args:
num_events (int): number of events during the simulation.
lr_scheduler (subclass of `torch.optim.lr_scheduler._LRScheduler`): lr_scheduler object ... | python | def simulate_values(cls, num_events, lr_scheduler, **kwargs):
"""Method to simulate scheduled values during num_events events.
Args:
num_events (int): number of events during the simulation.
lr_scheduler (subclass of `torch.optim.lr_scheduler._LRScheduler`): lr_scheduler object ... | [
"def",
"simulate_values",
"(",
"cls",
",",
"num_events",
",",
"lr_scheduler",
",",
"*",
"*",
"kwargs",
")",
":",
"# This scheduler uses `torch.optim.lr_scheduler._LRScheduler` which",
"# should be replicated in order to simulate LR values and",
"# not perturb original scheduler.",
... | Method to simulate scheduled values during num_events events.
Args:
num_events (int): number of events during the simulation.
lr_scheduler (subclass of `torch.optim.lr_scheduler._LRScheduler`): lr_scheduler object to wrap.
Returns:
list of pairs: [event_index, value... | [
"Method",
"to",
"simulate",
"scheduled",
"values",
"during",
"num_events",
"events",
"."
] | a96bd07cb58822cfb39fd81765135712f1db41ca | https://github.com/pytorch/ignite/blob/a96bd07cb58822cfb39fd81765135712f1db41ca/ignite/contrib/handlers/param_scheduler.py#L460-L481 | train |
pytorch/ignite | examples/gan/dcgan.py | check_manual_seed | def check_manual_seed(seed):
""" If manual seed is not specified, choose a random one and communicate it to the user.
"""
seed = seed or random.randint(1, 10000)
random.seed(seed)
torch.manual_seed(seed)
print('Using manual seed: {seed}'.format(seed=seed)) | python | def check_manual_seed(seed):
""" If manual seed is not specified, choose a random one and communicate it to the user.
"""
seed = seed or random.randint(1, 10000)
random.seed(seed)
torch.manual_seed(seed)
print('Using manual seed: {seed}'.format(seed=seed)) | [
"def",
"check_manual_seed",
"(",
"seed",
")",
":",
"seed",
"=",
"seed",
"or",
"random",
".",
"randint",
"(",
"1",
",",
"10000",
")",
"random",
".",
"seed",
"(",
"seed",
")",
"torch",
".",
"manual_seed",
"(",
"seed",
")",
"print",
"(",
"'Using manual se... | If manual seed is not specified, choose a random one and communicate it to the user. | [
"If",
"manual",
"seed",
"is",
"not",
"specified",
"choose",
"a",
"random",
"one",
"and",
"communicate",
"it",
"to",
"the",
"user",
"."
] | a96bd07cb58822cfb39fd81765135712f1db41ca | https://github.com/pytorch/ignite/blob/a96bd07cb58822cfb39fd81765135712f1db41ca/examples/gan/dcgan.py#L146-L155 | train |
pytorch/ignite | ignite/contrib/handlers/base_logger.py | BaseLogger.attach | def attach(self, engine, log_handler, event_name):
"""Attach the logger to the engine and execute `log_handler` function at `event_name` events.
Args:
engine (Engine): engine object.
log_handler (callable): a logging handler to execute
event_name: event to attach the... | python | def attach(self, engine, log_handler, event_name):
"""Attach the logger to the engine and execute `log_handler` function at `event_name` events.
Args:
engine (Engine): engine object.
log_handler (callable): a logging handler to execute
event_name: event to attach the... | [
"def",
"attach",
"(",
"self",
",",
"engine",
",",
"log_handler",
",",
"event_name",
")",
":",
"if",
"event_name",
"not",
"in",
"State",
".",
"event_to_attr",
":",
"raise",
"RuntimeError",
"(",
"\"Unknown event name '{}'\"",
".",
"format",
"(",
"event_name",
")... | Attach the logger to the engine and execute `log_handler` function at `event_name` events.
Args:
engine (Engine): engine object.
log_handler (callable): a logging handler to execute
event_name: event to attach the logging handler to. Valid events are from :class:`~ignite.eng... | [
"Attach",
"the",
"logger",
"to",
"the",
"engine",
"and",
"execute",
"log_handler",
"function",
"at",
"event_name",
"events",
"."
] | a96bd07cb58822cfb39fd81765135712f1db41ca | https://github.com/pytorch/ignite/blob/a96bd07cb58822cfb39fd81765135712f1db41ca/ignite/contrib/handlers/base_logger.py#L16-L29 | train |
pytorch/ignite | ignite/contrib/handlers/base_logger.py | BaseOutputHandler._setup_output_metrics | def _setup_output_metrics(self, engine):
"""Helper method to setup metrics to log
"""
metrics = {}
if self.metric_names is not None:
for name in self.metric_names:
if name not in engine.state.metrics:
warnings.warn("Provided metric name '{}... | python | def _setup_output_metrics(self, engine):
"""Helper method to setup metrics to log
"""
metrics = {}
if self.metric_names is not None:
for name in self.metric_names:
if name not in engine.state.metrics:
warnings.warn("Provided metric name '{}... | [
"def",
"_setup_output_metrics",
"(",
"self",
",",
"engine",
")",
":",
"metrics",
"=",
"{",
"}",
"if",
"self",
".",
"metric_names",
"is",
"not",
"None",
":",
"for",
"name",
"in",
"self",
".",
"metric_names",
":",
"if",
"name",
"not",
"in",
"engine",
"."... | Helper method to setup metrics to log | [
"Helper",
"method",
"to",
"setup",
"metrics",
"to",
"log"
] | a96bd07cb58822cfb39fd81765135712f1db41ca | https://github.com/pytorch/ignite/blob/a96bd07cb58822cfb39fd81765135712f1db41ca/ignite/contrib/handlers/base_logger.py#L89-L108 | train |
pytorch/ignite | ignite/handlers/timing.py | Timer.attach | def attach(self, engine, start=Events.STARTED, pause=Events.COMPLETED, resume=None, step=None):
""" Register callbacks to control the timer.
Args:
engine (Engine):
Engine that this timer will be attached to.
start (Events):
Event which should star... | python | def attach(self, engine, start=Events.STARTED, pause=Events.COMPLETED, resume=None, step=None):
""" Register callbacks to control the timer.
Args:
engine (Engine):
Engine that this timer will be attached to.
start (Events):
Event which should star... | [
"def",
"attach",
"(",
"self",
",",
"engine",
",",
"start",
"=",
"Events",
".",
"STARTED",
",",
"pause",
"=",
"Events",
".",
"COMPLETED",
",",
"resume",
"=",
"None",
",",
"step",
"=",
"None",
")",
":",
"engine",
".",
"add_event_handler",
"(",
"start",
... | Register callbacks to control the timer.
Args:
engine (Engine):
Engine that this timer will be attached to.
start (Events):
Event which should start (reset) the timer.
pause (Events):
Event which should pause the timer.
... | [
"Register",
"callbacks",
"to",
"control",
"the",
"timer",
"."
] | a96bd07cb58822cfb39fd81765135712f1db41ca | https://github.com/pytorch/ignite/blob/a96bd07cb58822cfb39fd81765135712f1db41ca/ignite/handlers/timing.py#L87-L116 | train |
pytorch/ignite | ignite/contrib/handlers/visdom_logger.py | _BaseVisDrawer.add_scalar | def add_scalar(self, logger, k, v, event_name, global_step):
"""
Helper method to log a scalar with VisdomLogger.
Args:
logger (VisdomLogger): visdom logger
k (str): scalar name which is used to set window title and y-axis label
v (int or float): scalar value... | python | def add_scalar(self, logger, k, v, event_name, global_step):
"""
Helper method to log a scalar with VisdomLogger.
Args:
logger (VisdomLogger): visdom logger
k (str): scalar name which is used to set window title and y-axis label
v (int or float): scalar value... | [
"def",
"add_scalar",
"(",
"self",
",",
"logger",
",",
"k",
",",
"v",
",",
"event_name",
",",
"global_step",
")",
":",
"if",
"k",
"not",
"in",
"self",
".",
"windows",
":",
"self",
".",
"windows",
"[",
"k",
"]",
"=",
"{",
"'win'",
":",
"None",
",",... | Helper method to log a scalar with VisdomLogger.
Args:
logger (VisdomLogger): visdom logger
k (str): scalar name which is used to set window title and y-axis label
v (int or float): scalar value, y-axis value
event_name: Event name which is used to setup x-axis l... | [
"Helper",
"method",
"to",
"log",
"a",
"scalar",
"with",
"VisdomLogger",
"."
] | a96bd07cb58822cfb39fd81765135712f1db41ca | https://github.com/pytorch/ignite/blob/a96bd07cb58822cfb39fd81765135712f1db41ca/ignite/contrib/handlers/visdom_logger.py#L21-L60 | train |
pytorch/ignite | ignite/_utils.py | _to_hours_mins_secs | def _to_hours_mins_secs(time_taken):
"""Convert seconds to hours, mins, and seconds."""
mins, secs = divmod(time_taken, 60)
hours, mins = divmod(mins, 60)
return hours, mins, secs | python | def _to_hours_mins_secs(time_taken):
"""Convert seconds to hours, mins, and seconds."""
mins, secs = divmod(time_taken, 60)
hours, mins = divmod(mins, 60)
return hours, mins, secs | [
"def",
"_to_hours_mins_secs",
"(",
"time_taken",
")",
":",
"mins",
",",
"secs",
"=",
"divmod",
"(",
"time_taken",
",",
"60",
")",
"hours",
",",
"mins",
"=",
"divmod",
"(",
"mins",
",",
"60",
")",
"return",
"hours",
",",
"mins",
",",
"secs"
] | Convert seconds to hours, mins, and seconds. | [
"Convert",
"seconds",
"to",
"hours",
"mins",
"and",
"seconds",
"."
] | a96bd07cb58822cfb39fd81765135712f1db41ca | https://github.com/pytorch/ignite/blob/a96bd07cb58822cfb39fd81765135712f1db41ca/ignite/_utils.py#L6-L10 | train |
coursera-dl/coursera-dl | coursera/commandline.py | parse_args | def parse_args(args=None):
"""
Parse the arguments/options passed to the program on the command line.
"""
parse_kwargs = {
"description": 'Download Coursera.org lecture material and resources.'
}
conf_file_path = os.path.join(os.getcwd(), LOCAL_CONF_FILE_NAME)
if os.path.isfile(co... | python | def parse_args(args=None):
"""
Parse the arguments/options passed to the program on the command line.
"""
parse_kwargs = {
"description": 'Download Coursera.org lecture material and resources.'
}
conf_file_path = os.path.join(os.getcwd(), LOCAL_CONF_FILE_NAME)
if os.path.isfile(co... | [
"def",
"parse_args",
"(",
"args",
"=",
"None",
")",
":",
"parse_kwargs",
"=",
"{",
"\"description\"",
":",
"'Download Coursera.org lecture material and resources.'",
"}",
"conf_file_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"getcwd",
"(",
")",
... | Parse the arguments/options passed to the program on the command line. | [
"Parse",
"the",
"arguments",
"/",
"options",
"passed",
"to",
"the",
"program",
"on",
"the",
"command",
"line",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/commandline.py#L33-L504 | train |
coursera-dl/coursera-dl | coursera/utils.py | random_string | def random_string(length):
"""
Return a pseudo-random string of specified length.
"""
valid_chars = string_ascii_letters + string_digits
return ''.join(random.choice(valid_chars) for i in range(length)) | python | def random_string(length):
"""
Return a pseudo-random string of specified length.
"""
valid_chars = string_ascii_letters + string_digits
return ''.join(random.choice(valid_chars) for i in range(length)) | [
"def",
"random_string",
"(",
"length",
")",
":",
"valid_chars",
"=",
"string_ascii_letters",
"+",
"string_digits",
"return",
"''",
".",
"join",
"(",
"random",
".",
"choice",
"(",
"valid_chars",
")",
"for",
"i",
"in",
"range",
"(",
"length",
")",
")"
] | Return a pseudo-random string of specified length. | [
"Return",
"a",
"pseudo",
"-",
"random",
"string",
"of",
"specified",
"length",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/utils.py#L81-L87 | train |
coursera-dl/coursera-dl | coursera/utils.py | clean_filename | def clean_filename(s, minimal_change=False):
"""
Sanitize a string to be used as a filename.
If minimal_change is set to true, then we only strip the bare minimum of
characters that are problematic for filesystems (namely, ':', '/' and
'\x00', '\n').
"""
# First, deal with URL encoded stri... | python | def clean_filename(s, minimal_change=False):
"""
Sanitize a string to be used as a filename.
If minimal_change is set to true, then we only strip the bare minimum of
characters that are problematic for filesystems (namely, ':', '/' and
'\x00', '\n').
"""
# First, deal with URL encoded stri... | [
"def",
"clean_filename",
"(",
"s",
",",
"minimal_change",
"=",
"False",
")",
":",
"# First, deal with URL encoded strings",
"h",
"=",
"html_parser",
".",
"HTMLParser",
"(",
")",
"s",
"=",
"h",
".",
"unescape",
"(",
"s",
")",
"s",
"=",
"unquote_plus",
"(",
... | Sanitize a string to be used as a filename.
If minimal_change is set to true, then we only strip the bare minimum of
characters that are problematic for filesystems (namely, ':', '/' and
'\x00', '\n'). | [
"Sanitize",
"a",
"string",
"to",
"be",
"used",
"as",
"a",
"filename",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/utils.py#L107-L148 | train |
coursera-dl/coursera-dl | coursera/utils.py | normalize_path | def normalize_path(path):
"""
Normalizes path on Windows OS. This means prepending
<backslash><backslash>?<backslash> to the path to get access to
Win32 device namespace instead of Win32 file namespace.
See https://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx#maxpath
@param path:... | python | def normalize_path(path):
"""
Normalizes path on Windows OS. This means prepending
<backslash><backslash>?<backslash> to the path to get access to
Win32 device namespace instead of Win32 file namespace.
See https://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx#maxpath
@param path:... | [
"def",
"normalize_path",
"(",
"path",
")",
":",
"if",
"sys",
".",
"platform",
"!=",
"'win32'",
":",
"return",
"path",
"if",
"path",
".",
"startswith",
"(",
"WINDOWS_UNC_PREFIX",
")",
":",
"return",
"path",
"return",
"WINDOWS_UNC_PREFIX",
"+",
"os",
".",
"p... | Normalizes path on Windows OS. This means prepending
<backslash><backslash>?<backslash> to the path to get access to
Win32 device namespace instead of Win32 file namespace.
See https://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx#maxpath
@param path: Path to normalize.
@type path: st... | [
"Normalizes",
"path",
"on",
"Windows",
"OS",
".",
"This",
"means",
"prepending",
"<backslash",
">",
"<backslash",
">",
"?<backslash",
">",
"to",
"the",
"path",
"to",
"get",
"access",
"to",
"Win32",
"device",
"namespace",
"instead",
"of",
"Win32",
"file",
"na... | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/utils.py#L151-L170 | train |
coursera-dl/coursera-dl | coursera/utils.py | get_anchor_format | def get_anchor_format(a):
"""
Extract the resource file-type format from the anchor.
"""
# (. or format=) then (file_extension) then (? or $)
# e.g. "...format=txt" or "...download.mp4?..."
fmt = re.search(r"(?:\.|format=)(\w+)(?:\?.*)?$", a)
return fmt.group(1) if fmt else None | python | def get_anchor_format(a):
"""
Extract the resource file-type format from the anchor.
"""
# (. or format=) then (file_extension) then (? or $)
# e.g. "...format=txt" or "...download.mp4?..."
fmt = re.search(r"(?:\.|format=)(\w+)(?:\?.*)?$", a)
return fmt.group(1) if fmt else None | [
"def",
"get_anchor_format",
"(",
"a",
")",
":",
"# (. or format=) then (file_extension) then (? or $)",
"# e.g. \"...format=txt\" or \"...download.mp4?...\"",
"fmt",
"=",
"re",
".",
"search",
"(",
"r\"(?:\\.|format=)(\\w+)(?:\\?.*)?$\"",
",",
"a",
")",
"return",
"fmt",
".",
... | Extract the resource file-type format from the anchor. | [
"Extract",
"the",
"resource",
"file",
"-",
"type",
"format",
"from",
"the",
"anchor",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/utils.py#L173-L181 | train |
coursera-dl/coursera-dl | coursera/utils.py | clean_url | def clean_url(url):
"""
Remove params, query and fragment parts from URL so that `os.path.basename`
and `os.path.splitext` can work correctly.
@param url: URL to clean.
@type url: str
@return: Cleaned URL.
@rtype: str
"""
parsed = urlparse(url.strip())
reconstructed = ParseResu... | python | def clean_url(url):
"""
Remove params, query and fragment parts from URL so that `os.path.basename`
and `os.path.splitext` can work correctly.
@param url: URL to clean.
@type url: str
@return: Cleaned URL.
@rtype: str
"""
parsed = urlparse(url.strip())
reconstructed = ParseResu... | [
"def",
"clean_url",
"(",
"url",
")",
":",
"parsed",
"=",
"urlparse",
"(",
"url",
".",
"strip",
"(",
")",
")",
"reconstructed",
"=",
"ParseResult",
"(",
"parsed",
".",
"scheme",
",",
"parsed",
".",
"netloc",
",",
"parsed",
".",
"path",
",",
"params",
... | Remove params, query and fragment parts from URL so that `os.path.basename`
and `os.path.splitext` can work correctly.
@param url: URL to clean.
@type url: str
@return: Cleaned URL.
@rtype: str | [
"Remove",
"params",
"query",
"and",
"fragment",
"parts",
"from",
"URL",
"so",
"that",
"os",
".",
"path",
".",
"basename",
"and",
"os",
".",
"path",
".",
"splitext",
"can",
"work",
"correctly",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/utils.py#L198-L213 | train |
coursera-dl/coursera-dl | coursera/utils.py | fix_url | def fix_url(url):
"""
Strip whitespace characters from the beginning and the end of the url
and add a default scheme.
"""
if url is None:
return None
url = url.strip()
if url and not urlparse(url).scheme:
url = "http://" + url
return url | python | def fix_url(url):
"""
Strip whitespace characters from the beginning and the end of the url
and add a default scheme.
"""
if url is None:
return None
url = url.strip()
if url and not urlparse(url).scheme:
url = "http://" + url
return url | [
"def",
"fix_url",
"(",
"url",
")",
":",
"if",
"url",
"is",
"None",
":",
"return",
"None",
"url",
"=",
"url",
".",
"strip",
"(",
")",
"if",
"url",
"and",
"not",
"urlparse",
"(",
"url",
")",
".",
"scheme",
":",
"url",
"=",
"\"http://\"",
"+",
"url"... | Strip whitespace characters from the beginning and the end of the url
and add a default scheme. | [
"Strip",
"whitespace",
"characters",
"from",
"the",
"beginning",
"and",
"the",
"end",
"of",
"the",
"url",
"and",
"add",
"a",
"default",
"scheme",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/utils.py#L216-L229 | train |
coursera-dl/coursera-dl | coursera/utils.py | is_course_complete | def is_course_complete(last_update):
"""
Determine is the course is likely to have been terminated or not.
We return True if the timestamp given by last_update is 30 days or older
than today's date. Otherwise, we return True.
The intended use case for this is to detect if a given courses has not
... | python | def is_course_complete(last_update):
"""
Determine is the course is likely to have been terminated or not.
We return True if the timestamp given by last_update is 30 days or older
than today's date. Otherwise, we return True.
The intended use case for this is to detect if a given courses has not
... | [
"def",
"is_course_complete",
"(",
"last_update",
")",
":",
"rv",
"=",
"False",
"if",
"last_update",
">=",
"0",
":",
"delta",
"=",
"time",
".",
"time",
"(",
")",
"-",
"last_update",
"max_delta",
"=",
"total_seconds",
"(",
"datetime",
".",
"timedelta",
"(",
... | Determine is the course is likely to have been terminated or not.
We return True if the timestamp given by last_update is 30 days or older
than today's date. Otherwise, we return True.
The intended use case for this is to detect if a given courses has not
seen any update in the last 30 days or more. ... | [
"Determine",
"is",
"the",
"course",
"is",
"likely",
"to",
"have",
"been",
"terminated",
"or",
"not",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/utils.py#L232-L249 | train |
coursera-dl/coursera-dl | coursera/utils.py | make_coursera_absolute_url | def make_coursera_absolute_url(url):
"""
If given url is relative adds coursera netloc,
otherwise returns it without any changes.
"""
if not bool(urlparse(url).netloc):
return urljoin(COURSERA_URL, url)
return url | python | def make_coursera_absolute_url(url):
"""
If given url is relative adds coursera netloc,
otherwise returns it without any changes.
"""
if not bool(urlparse(url).netloc):
return urljoin(COURSERA_URL, url)
return url | [
"def",
"make_coursera_absolute_url",
"(",
"url",
")",
":",
"if",
"not",
"bool",
"(",
"urlparse",
"(",
"url",
")",
".",
"netloc",
")",
":",
"return",
"urljoin",
"(",
"COURSERA_URL",
",",
"url",
")",
"return",
"url"
] | If given url is relative adds coursera netloc,
otherwise returns it without any changes. | [
"If",
"given",
"url",
"is",
"relative",
"adds",
"coursera",
"netloc",
"otherwise",
"returns",
"it",
"without",
"any",
"changes",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/utils.py#L262-L271 | train |
coursera-dl/coursera-dl | coursera/utils.py | extend_supplement_links | def extend_supplement_links(destination, source):
"""
Extends (merges) destination dictionary with supplement_links
from source dictionary. Values are expected to be lists, or any
data structure that has `extend` method.
@param destination: Destination dictionary that will be extended.
@type de... | python | def extend_supplement_links(destination, source):
"""
Extends (merges) destination dictionary with supplement_links
from source dictionary. Values are expected to be lists, or any
data structure that has `extend` method.
@param destination: Destination dictionary that will be extended.
@type de... | [
"def",
"extend_supplement_links",
"(",
"destination",
",",
"source",
")",
":",
"for",
"key",
",",
"value",
"in",
"iteritems",
"(",
"source",
")",
":",
"if",
"key",
"not",
"in",
"destination",
":",
"destination",
"[",
"key",
"]",
"=",
"value",
"else",
":"... | Extends (merges) destination dictionary with supplement_links
from source dictionary. Values are expected to be lists, or any
data structure that has `extend` method.
@param destination: Destination dictionary that will be extended.
@type destination: @see CourseraOnDemand._extract_links_from_text
... | [
"Extends",
"(",
"merges",
")",
"destination",
"dictionary",
"with",
"supplement_links",
"from",
"source",
"dictionary",
".",
"Values",
"are",
"expected",
"to",
"be",
"lists",
"or",
"any",
"data",
"structure",
"that",
"has",
"extend",
"method",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/utils.py#L274-L291 | train |
coursera-dl/coursera-dl | coursera/utils.py | print_ssl_error_message | def print_ssl_error_message(exception):
"""
Print SSLError message with URL to instructions on how to fix it.
"""
message = """
#####################################################################
# ATTENTION! PLEASE READ THIS!
#
# The following error has just occurred:
# %s %s
#
# Please read instruct... | python | def print_ssl_error_message(exception):
"""
Print SSLError message with URL to instructions on how to fix it.
"""
message = """
#####################################################################
# ATTENTION! PLEASE READ THIS!
#
# The following error has just occurred:
# %s %s
#
# Please read instruct... | [
"def",
"print_ssl_error_message",
"(",
"exception",
")",
":",
"message",
"=",
"\"\"\"\n#####################################################################\n# ATTENTION! PLEASE READ THIS!\n#\n# The following error has just occurred:\n# %s %s\n#\n# Please read instructions on how to fix this error h... | Print SSLError message with URL to instructions on how to fix it. | [
"Print",
"SSLError",
"message",
"with",
"URL",
"to",
"instructions",
"on",
"how",
"to",
"fix",
"it",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/utils.py#L294-L309 | train |
coursera-dl/coursera-dl | coursera/coursera_dl.py | list_courses | def list_courses(args):
"""
List enrolled courses.
@param args: Command-line arguments.
@type args: namedtuple
"""
session = get_session()
login(session, args.username, args.password)
extractor = CourseraExtractor(session)
courses = extractor.list_courses()
logging.info('Found %... | python | def list_courses(args):
"""
List enrolled courses.
@param args: Command-line arguments.
@type args: namedtuple
"""
session = get_session()
login(session, args.username, args.password)
extractor = CourseraExtractor(session)
courses = extractor.list_courses()
logging.info('Found %... | [
"def",
"list_courses",
"(",
"args",
")",
":",
"session",
"=",
"get_session",
"(",
")",
"login",
"(",
"session",
",",
"args",
".",
"username",
",",
"args",
".",
"password",
")",
"extractor",
"=",
"CourseraExtractor",
"(",
"session",
")",
"courses",
"=",
"... | List enrolled courses.
@param args: Command-line arguments.
@type args: namedtuple | [
"List",
"enrolled",
"courses",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/coursera_dl.py#L100-L113 | train |
coursera-dl/coursera-dl | coursera/coursera_dl.py | download_on_demand_class | def download_on_demand_class(session, args, class_name):
"""
Download all requested resources from the on-demand class given
in class_name.
@return: Tuple of (bool, bool), where the first bool indicates whether
errors occurred while parsing syllabus, the second bool indicates
whether th... | python | def download_on_demand_class(session, args, class_name):
"""
Download all requested resources from the on-demand class given
in class_name.
@return: Tuple of (bool, bool), where the first bool indicates whether
errors occurred while parsing syllabus, the second bool indicates
whether th... | [
"def",
"download_on_demand_class",
"(",
"session",
",",
"args",
",",
"class_name",
")",
":",
"error_occurred",
"=",
"False",
"extractor",
"=",
"CourseraExtractor",
"(",
"session",
")",
"cached_syllabus_filename",
"=",
"'%s-syllabus-parsed.json'",
"%",
"class_name",
"i... | Download all requested resources from the on-demand class given
in class_name.
@return: Tuple of (bool, bool), where the first bool indicates whether
errors occurred while parsing syllabus, the second bool indicates
whether the course appears to be completed.
@rtype: (bool, bool) | [
"Download",
"all",
"requested",
"resources",
"from",
"the",
"on",
"-",
"demand",
"class",
"given",
"in",
"class_name",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/coursera_dl.py#L116-L181 | train |
coursera-dl/coursera-dl | coursera/coursera_dl.py | download_class | def download_class(session, args, class_name):
"""
Try to download on-demand class.
@return: Tuple of (bool, bool), where the first bool indicates whether
errors occurred while parsing syllabus, the second bool indicates
whether the course appears to be completed.
@rtype: (bool, bool)
... | python | def download_class(session, args, class_name):
"""
Try to download on-demand class.
@return: Tuple of (bool, bool), where the first bool indicates whether
errors occurred while parsing syllabus, the second bool indicates
whether the course appears to be completed.
@rtype: (bool, bool)
... | [
"def",
"download_class",
"(",
"session",
",",
"args",
",",
"class_name",
")",
":",
"logging",
".",
"debug",
"(",
"'Downloading new style (on demand) class %s'",
",",
"class_name",
")",
"return",
"download_on_demand_class",
"(",
"session",
",",
"args",
",",
"class_na... | Try to download on-demand class.
@return: Tuple of (bool, bool), where the first bool indicates whether
errors occurred while parsing syllabus, the second bool indicates
whether the course appears to be completed.
@rtype: (bool, bool) | [
"Try",
"to",
"download",
"on",
"-",
"demand",
"class",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/coursera_dl.py#L204-L214 | train |
coursera-dl/coursera-dl | coursera/coursera_dl.py | main | def main():
"""
Main entry point for execution as a program (instead of as a module).
"""
args = parse_args()
logging.info('coursera_dl version %s', __version__)
completed_classes = []
classes_with_errors = []
mkdir_p(PATH_CACHE, 0o700)
if args.clear_cache:
shutil.rmtree(PA... | python | def main():
"""
Main entry point for execution as a program (instead of as a module).
"""
args = parse_args()
logging.info('coursera_dl version %s', __version__)
completed_classes = []
classes_with_errors = []
mkdir_p(PATH_CACHE, 0o700)
if args.clear_cache:
shutil.rmtree(PA... | [
"def",
"main",
"(",
")",
":",
"args",
"=",
"parse_args",
"(",
")",
"logging",
".",
"info",
"(",
"'coursera_dl version %s'",
",",
"__version__",
")",
"completed_classes",
"=",
"[",
"]",
"classes_with_errors",
"=",
"[",
"]",
"mkdir_p",
"(",
"PATH_CACHE",
",",
... | Main entry point for execution as a program (instead of as a module). | [
"Main",
"entry",
"point",
"for",
"execution",
"as",
"a",
"program",
"(",
"instead",
"of",
"as",
"a",
"module",
")",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/coursera_dl.py#L217-L283 | train |
coursera-dl/coursera-dl | coursera/cookies.py | prepare_auth_headers | def prepare_auth_headers(session, include_cauth=False):
"""
This function prepares headers with CSRF/CAUTH tokens that can
be used in POST requests such as login/get_quiz.
@param session: Requests session.
@type session: requests.Session
@param include_cauth: Flag that indicates whether CAUTH ... | python | def prepare_auth_headers(session, include_cauth=False):
"""
This function prepares headers with CSRF/CAUTH tokens that can
be used in POST requests such as login/get_quiz.
@param session: Requests session.
@type session: requests.Session
@param include_cauth: Flag that indicates whether CAUTH ... | [
"def",
"prepare_auth_headers",
"(",
"session",
",",
"include_cauth",
"=",
"False",
")",
":",
"# csrftoken is simply a 20 char random string.",
"csrftoken",
"=",
"random_string",
"(",
"20",
")",
"# Now make a call to the authenticator url.",
"csrf2cookie",
"=",
"'csrf2_token_%... | This function prepares headers with CSRF/CAUTH tokens that can
be used in POST requests such as login/get_quiz.
@param session: Requests session.
@type session: requests.Session
@param include_cauth: Flag that indicates whether CAUTH cookies should be
included as well.
@type include_cauth:... | [
"This",
"function",
"prepares",
"headers",
"with",
"CSRF",
"/",
"CAUTH",
"tokens",
"that",
"can",
"be",
"used",
"in",
"POST",
"requests",
"such",
"as",
"login",
"/",
"get_quiz",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/cookies.py#L72-L108 | train |
coursera-dl/coursera-dl | coursera/cookies.py | login | def login(session, username, password, class_name=None):
"""
Login on coursera.org with the given credentials.
This adds the following cookies to the session:
sessionid, maestro_login, maestro_login_flag
"""
logging.debug('Initiating login.')
try:
session.cookies.clear('.course... | python | def login(session, username, password, class_name=None):
"""
Login on coursera.org with the given credentials.
This adds the following cookies to the session:
sessionid, maestro_login, maestro_login_flag
"""
logging.debug('Initiating login.')
try:
session.cookies.clear('.course... | [
"def",
"login",
"(",
"session",
",",
"username",
",",
"password",
",",
"class_name",
"=",
"None",
")",
":",
"logging",
".",
"debug",
"(",
"'Initiating login.'",
")",
"try",
":",
"session",
".",
"cookies",
".",
"clear",
"(",
"'.coursera.org'",
")",
"logging... | Login on coursera.org with the given credentials.
This adds the following cookies to the session:
sessionid, maestro_login, maestro_login_flag | [
"Login",
"on",
"coursera",
".",
"org",
"with",
"the",
"given",
"credentials",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/cookies.py#L111-L157 | train |
coursera-dl/coursera-dl | coursera/cookies.py | down_the_wabbit_hole | def down_the_wabbit_hole(session, class_name):
"""
Authenticate on class.coursera.org
"""
auth_redirector_url = AUTH_REDIRECT_URL.format(class_name=class_name)
r = session.get(auth_redirector_url)
logging.debug('Following %s to authenticate on class.coursera.org.',
auth_redir... | python | def down_the_wabbit_hole(session, class_name):
"""
Authenticate on class.coursera.org
"""
auth_redirector_url = AUTH_REDIRECT_URL.format(class_name=class_name)
r = session.get(auth_redirector_url)
logging.debug('Following %s to authenticate on class.coursera.org.',
auth_redir... | [
"def",
"down_the_wabbit_hole",
"(",
"session",
",",
"class_name",
")",
":",
"auth_redirector_url",
"=",
"AUTH_REDIRECT_URL",
".",
"format",
"(",
"class_name",
"=",
"class_name",
")",
"r",
"=",
"session",
".",
"get",
"(",
"auth_redirector_url",
")",
"logging",
".... | Authenticate on class.coursera.org | [
"Authenticate",
"on",
"class",
".",
"coursera",
".",
"org"
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/cookies.py#L160-L177 | train |
coursera-dl/coursera-dl | coursera/cookies.py | get_authentication_cookies | def get_authentication_cookies(session, class_name, username, password):
"""
Get the necessary cookies to authenticate on class.coursera.org.
To access the class pages we need two cookies on class.coursera.org:
csrf_token, session
"""
# First, check if we already have the .coursera.org coo... | python | def get_authentication_cookies(session, class_name, username, password):
"""
Get the necessary cookies to authenticate on class.coursera.org.
To access the class pages we need two cookies on class.coursera.org:
csrf_token, session
"""
# First, check if we already have the .coursera.org coo... | [
"def",
"get_authentication_cookies",
"(",
"session",
",",
"class_name",
",",
"username",
",",
"password",
")",
":",
"# First, check if we already have the .coursera.org cookies.",
"if",
"session",
".",
"cookies",
".",
"get",
"(",
"'CAUTH'",
",",
"domain",
"=",
"\".cou... | Get the necessary cookies to authenticate on class.coursera.org.
To access the class pages we need two cookies on class.coursera.org:
csrf_token, session | [
"Get",
"the",
"necessary",
"cookies",
"to",
"authenticate",
"on",
"class",
".",
"coursera",
".",
"org",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/cookies.py#L180-L206 | train |
coursera-dl/coursera-dl | coursera/cookies.py | do_we_have_enough_cookies | def do_we_have_enough_cookies(cj, class_name):
"""
Check whether we have all the required cookies
to authenticate on class.coursera.org.
"""
domain = 'class.coursera.org'
path = "/" + class_name
return cj.get('csrf_token', domain=domain, path=path) is not None | python | def do_we_have_enough_cookies(cj, class_name):
"""
Check whether we have all the required cookies
to authenticate on class.coursera.org.
"""
domain = 'class.coursera.org'
path = "/" + class_name
return cj.get('csrf_token', domain=domain, path=path) is not None | [
"def",
"do_we_have_enough_cookies",
"(",
"cj",
",",
"class_name",
")",
":",
"domain",
"=",
"'class.coursera.org'",
"path",
"=",
"\"/\"",
"+",
"class_name",
"return",
"cj",
".",
"get",
"(",
"'csrf_token'",
",",
"domain",
"=",
"domain",
",",
"path",
"=",
"path... | Check whether we have all the required cookies
to authenticate on class.coursera.org. | [
"Check",
"whether",
"we",
"have",
"all",
"the",
"required",
"cookies",
"to",
"authenticate",
"on",
"class",
".",
"coursera",
".",
"org",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/cookies.py#L209-L217 | train |
coursera-dl/coursera-dl | coursera/cookies.py | validate_cookies | def validate_cookies(session, class_name):
"""
Checks whether we have all the required cookies
to authenticate on class.coursera.org. Also check for and remove
stale session.
"""
if not do_we_have_enough_cookies(session.cookies, class_name):
return False
url = CLASS_URL.format(class... | python | def validate_cookies(session, class_name):
"""
Checks whether we have all the required cookies
to authenticate on class.coursera.org. Also check for and remove
stale session.
"""
if not do_we_have_enough_cookies(session.cookies, class_name):
return False
url = CLASS_URL.format(class... | [
"def",
"validate_cookies",
"(",
"session",
",",
"class_name",
")",
":",
"if",
"not",
"do_we_have_enough_cookies",
"(",
"session",
".",
"cookies",
",",
"class_name",
")",
":",
"return",
"False",
"url",
"=",
"CLASS_URL",
".",
"format",
"(",
"class_name",
"=",
... | Checks whether we have all the required cookies
to authenticate on class.coursera.org. Also check for and remove
stale session. | [
"Checks",
"whether",
"we",
"have",
"all",
"the",
"required",
"cookies",
"to",
"authenticate",
"on",
"class",
".",
"coursera",
".",
"org",
".",
"Also",
"check",
"for",
"and",
"remove",
"stale",
"session",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/cookies.py#L220-L240 | train |
coursera-dl/coursera-dl | coursera/cookies.py | make_cookie_values | def make_cookie_values(cj, class_name):
"""
Makes a string of cookie keys and values.
Can be used to set a Cookie header.
"""
path = "/" + class_name
cookies = [c.name + '=' + c.value
for c in cj
if c.domain == "class.coursera.org"
and c.path == path... | python | def make_cookie_values(cj, class_name):
"""
Makes a string of cookie keys and values.
Can be used to set a Cookie header.
"""
path = "/" + class_name
cookies = [c.name + '=' + c.value
for c in cj
if c.domain == "class.coursera.org"
and c.path == path... | [
"def",
"make_cookie_values",
"(",
"cj",
",",
"class_name",
")",
":",
"path",
"=",
"\"/\"",
"+",
"class_name",
"cookies",
"=",
"[",
"c",
".",
"name",
"+",
"'='",
"+",
"c",
".",
"value",
"for",
"c",
"in",
"cj",
"if",
"c",
".",
"domain",
"==",
"\"clas... | Makes a string of cookie keys and values.
Can be used to set a Cookie header. | [
"Makes",
"a",
"string",
"of",
"cookie",
"keys",
"and",
"values",
".",
"Can",
"be",
"used",
"to",
"set",
"a",
"Cookie",
"header",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/cookies.py#L243-L255 | train |
coursera-dl/coursera-dl | coursera/cookies.py | find_cookies_for_class | def find_cookies_for_class(cookies_file, class_name):
"""
Return a RequestsCookieJar containing the cookies for
.coursera.org and class.coursera.org found in the given cookies_file.
"""
path = "/" + class_name
def cookies_filter(c):
return c.domain == ".coursera.org" \
or (... | python | def find_cookies_for_class(cookies_file, class_name):
"""
Return a RequestsCookieJar containing the cookies for
.coursera.org and class.coursera.org found in the given cookies_file.
"""
path = "/" + class_name
def cookies_filter(c):
return c.domain == ".coursera.org" \
or (... | [
"def",
"find_cookies_for_class",
"(",
"cookies_file",
",",
"class_name",
")",
":",
"path",
"=",
"\"/\"",
"+",
"class_name",
"def",
"cookies_filter",
"(",
"c",
")",
":",
"return",
"c",
".",
"domain",
"==",
"\".coursera.org\"",
"or",
"(",
"c",
".",
"domain",
... | Return a RequestsCookieJar containing the cookies for
.coursera.org and class.coursera.org found in the given cookies_file. | [
"Return",
"a",
"RequestsCookieJar",
"containing",
"the",
"cookies",
"for",
".",
"coursera",
".",
"org",
"and",
"class",
".",
"coursera",
".",
"org",
"found",
"in",
"the",
"given",
"cookies_file",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/cookies.py#L258-L276 | train |
coursera-dl/coursera-dl | coursera/cookies.py | load_cookies_file | def load_cookies_file(cookies_file):
"""
Load cookies file.
We pre-pend the file with the special Netscape header because the cookie
loader is very particular about this string.
"""
logging.debug('Loading cookie file %s into memory.', cookies_file)
cookies = StringIO()
cookies.write('... | python | def load_cookies_file(cookies_file):
"""
Load cookies file.
We pre-pend the file with the special Netscape header because the cookie
loader is very particular about this string.
"""
logging.debug('Loading cookie file %s into memory.', cookies_file)
cookies = StringIO()
cookies.write('... | [
"def",
"load_cookies_file",
"(",
"cookies_file",
")",
":",
"logging",
".",
"debug",
"(",
"'Loading cookie file %s into memory.'",
",",
"cookies_file",
")",
"cookies",
"=",
"StringIO",
"(",
")",
"cookies",
".",
"write",
"(",
"'# Netscape HTTP Cookie File'",
")",
"coo... | Load cookies file.
We pre-pend the file with the special Netscape header because the cookie
loader is very particular about this string. | [
"Load",
"cookies",
"file",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/cookies.py#L279-L294 | train |
coursera-dl/coursera-dl | coursera/cookies.py | get_cookies_from_cache | def get_cookies_from_cache(username):
"""
Returns a RequestsCookieJar containing the cached cookies for the given
user.
"""
logging.debug('Trying to get cookies from the cache.')
path = get_cookies_cache_path(username)
cj = requests.cookies.RequestsCookieJar()
try:
cached_cj = ... | python | def get_cookies_from_cache(username):
"""
Returns a RequestsCookieJar containing the cached cookies for the given
user.
"""
logging.debug('Trying to get cookies from the cache.')
path = get_cookies_cache_path(username)
cj = requests.cookies.RequestsCookieJar()
try:
cached_cj = ... | [
"def",
"get_cookies_from_cache",
"(",
"username",
")",
":",
"logging",
".",
"debug",
"(",
"'Trying to get cookies from the cache.'",
")",
"path",
"=",
"get_cookies_cache_path",
"(",
"username",
")",
"cj",
"=",
"requests",
".",
"cookies",
".",
"RequestsCookieJar",
"(... | Returns a RequestsCookieJar containing the cached cookies for the given
user. | [
"Returns",
"a",
"RequestsCookieJar",
"containing",
"the",
"cached",
"cookies",
"for",
"the",
"given",
"user",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/cookies.py#L313-L332 | train |
coursera-dl/coursera-dl | coursera/cookies.py | write_cookies_to_cache | def write_cookies_to_cache(cj, username):
"""
Save RequestsCookieJar to disk in Mozilla's cookies.txt file format.
This prevents us from repeated authentications on the
accounts.coursera.org and class.coursera.org/class_name sites.
"""
mkdir_p(PATH_COOKIES, 0o700)
path = get_cookies_cache_p... | python | def write_cookies_to_cache(cj, username):
"""
Save RequestsCookieJar to disk in Mozilla's cookies.txt file format.
This prevents us from repeated authentications on the
accounts.coursera.org and class.coursera.org/class_name sites.
"""
mkdir_p(PATH_COOKIES, 0o700)
path = get_cookies_cache_p... | [
"def",
"write_cookies_to_cache",
"(",
"cj",
",",
"username",
")",
":",
"mkdir_p",
"(",
"PATH_COOKIES",
",",
"0o700",
")",
"path",
"=",
"get_cookies_cache_path",
"(",
"username",
")",
"cached_cj",
"=",
"cookielib",
".",
"MozillaCookieJar",
"(",
")",
"for",
"coo... | Save RequestsCookieJar to disk in Mozilla's cookies.txt file format.
This prevents us from repeated authentications on the
accounts.coursera.org and class.coursera.org/class_name sites. | [
"Save",
"RequestsCookieJar",
"to",
"disk",
"in",
"Mozilla",
"s",
"cookies",
".",
"txt",
"file",
"format",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/cookies.py#L335-L347 | train |
coursera-dl/coursera-dl | coursera/cookies.py | get_cookies_for_class | def get_cookies_for_class(session, class_name,
cookies_file=None,
username=None,
password=None):
"""
Get the cookies for the given class.
We do not validate the cookies if they are loaded from a cookies file
because this is i... | python | def get_cookies_for_class(session, class_name,
cookies_file=None,
username=None,
password=None):
"""
Get the cookies for the given class.
We do not validate the cookies if they are loaded from a cookies file
because this is i... | [
"def",
"get_cookies_for_class",
"(",
"session",
",",
"class_name",
",",
"cookies_file",
"=",
"None",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"if",
"cookies_file",
":",
"cookies",
"=",
"find_cookies_for_class",
"(",
"cookies_file",
... | Get the cookies for the given class.
We do not validate the cookies if they are loaded from a cookies file
because this is intended for debugging purposes or if the coursera
authentication process has changed. | [
"Get",
"the",
"cookies",
"for",
"the",
"given",
"class",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/cookies.py#L350-L372 | train |
coursera-dl/coursera-dl | coursera/network.py | get_reply | def get_reply(session, url, post=False, data=None, headers=None, quiet=False):
"""
Download an HTML page using the requests session. Low-level function
that allows for flexible request configuration.
@param session: Requests session.
@type session: requests.Session
@param url: URL pattern with... | python | def get_reply(session, url, post=False, data=None, headers=None, quiet=False):
"""
Download an HTML page using the requests session. Low-level function
that allows for flexible request configuration.
@param session: Requests session.
@type session: requests.Session
@param url: URL pattern with... | [
"def",
"get_reply",
"(",
"session",
",",
"url",
",",
"post",
"=",
"False",
",",
"data",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"quiet",
"=",
"False",
")",
":",
"request_headers",
"=",
"{",
"}",
"if",
"headers",
"is",
"None",
"else",
"headers"... | Download an HTML page using the requests session. Low-level function
that allows for flexible request configuration.
@param session: Requests session.
@type session: requests.Session
@param url: URL pattern with optional keywords to format.
@type url: str
@param post: Flag that indicates whet... | [
"Download",
"an",
"HTML",
"page",
"using",
"the",
"requests",
"session",
".",
"Low",
"-",
"level",
"function",
"that",
"allows",
"for",
"flexible",
"request",
"configuration",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/network.py#L12-L58 | train |
coursera-dl/coursera-dl | coursera/network.py | get_page | def get_page(session,
url,
json=False,
post=False,
data=None,
headers=None,
quiet=False,
**kwargs):
"""
Download an HTML page using the requests session.
@param session: Requests session.
@type session: requests.... | python | def get_page(session,
url,
json=False,
post=False,
data=None,
headers=None,
quiet=False,
**kwargs):
"""
Download an HTML page using the requests session.
@param session: Requests session.
@type session: requests.... | [
"def",
"get_page",
"(",
"session",
",",
"url",
",",
"json",
"=",
"False",
",",
"post",
"=",
"False",
",",
"data",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"quiet",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"url",
"=",
"url",
".",
"... | Download an HTML page using the requests session.
@param session: Requests session.
@type session: requests.Session
@param url: URL pattern with optional keywords to format.
@type url: str
@param post: Flag that indicates whether POST request should be sent.
@type post: bool
@param data:... | [
"Download",
"an",
"HTML",
"page",
"using",
"the",
"requests",
"session",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/network.py#L61-L93 | train |
coursera-dl/coursera-dl | coursera/network.py | get_page_and_url | def get_page_and_url(session, url):
"""
Download an HTML page using the requests session and return
the final URL after following redirects.
"""
reply = get_reply(session, url)
return reply.text, reply.url | python | def get_page_and_url(session, url):
"""
Download an HTML page using the requests session and return
the final URL after following redirects.
"""
reply = get_reply(session, url)
return reply.text, reply.url | [
"def",
"get_page_and_url",
"(",
"session",
",",
"url",
")",
":",
"reply",
"=",
"get_reply",
"(",
"session",
",",
"url",
")",
"return",
"reply",
".",
"text",
",",
"reply",
".",
"url"
] | Download an HTML page using the requests session and return
the final URL after following redirects. | [
"Download",
"an",
"HTML",
"page",
"using",
"the",
"requests",
"session",
"and",
"return",
"the",
"final",
"URL",
"after",
"following",
"redirects",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/network.py#L96-L102 | train |
coursera-dl/coursera-dl | coursera/filtering.py | skip_format_url | def skip_format_url(format_, url):
"""
Checks whether a give format/url should be skipped and not downloaded.
@param format_: Filename format (extension).
@type format_: str (e.g. html, txt, zip, pdf)
@param url: URL.
@type url: str
@return: True if format/url should be skipped, False oth... | python | def skip_format_url(format_, url):
"""
Checks whether a give format/url should be skipped and not downloaded.
@param format_: Filename format (extension).
@type format_: str (e.g. html, txt, zip, pdf)
@param url: URL.
@type url: str
@return: True if format/url should be skipped, False oth... | [
"def",
"skip_format_url",
"(",
"format_",
",",
"url",
")",
":",
"# Do not download empty formats",
"if",
"format_",
"==",
"''",
":",
"return",
"True",
"# Do not download email addresses",
"if",
"(",
"'mailto:'",
"in",
"url",
")",
"and",
"(",
"'@'",
"in",
"url",
... | Checks whether a give format/url should be skipped and not downloaded.
@param format_: Filename format (extension).
@type format_: str (e.g. html, txt, zip, pdf)
@param url: URL.
@type url: str
@return: True if format/url should be skipped, False otherwise.
@rtype bool | [
"Checks",
"whether",
"a",
"give",
"format",
"/",
"url",
"should",
"be",
"skipped",
"and",
"not",
"downloaded",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/filtering.py#L41-L81 | train |
coursera-dl/coursera-dl | coursera/filtering.py | find_resources_to_get | def find_resources_to_get(lecture, file_formats, resource_filter, ignored_formats=None):
"""
Select formats to download.
"""
resources_to_get = []
if ignored_formats is None:
ignored_formats = []
if len(ignored_formats):
logging.info("The following file formats will be ignored:... | python | def find_resources_to_get(lecture, file_formats, resource_filter, ignored_formats=None):
"""
Select formats to download.
"""
resources_to_get = []
if ignored_formats is None:
ignored_formats = []
if len(ignored_formats):
logging.info("The following file formats will be ignored:... | [
"def",
"find_resources_to_get",
"(",
"lecture",
",",
"file_formats",
",",
"resource_filter",
",",
"ignored_formats",
"=",
"None",
")",
":",
"resources_to_get",
"=",
"[",
"]",
"if",
"ignored_formats",
"is",
"None",
":",
"ignored_formats",
"=",
"[",
"]",
"if",
"... | Select formats to download. | [
"Select",
"formats",
"to",
"download",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/filtering.py#L84-L117 | train |
coursera-dl/coursera-dl | setup.py | generate_readme_rst | def generate_readme_rst():
"""
Generate README.rst from README.md via pandoc.
In case of errors, we show a message having the error that we got and
exit the program.
"""
pandoc_cmd = [
'pandoc',
'--from=markdown',
'--to=rst',
'--output=README.rst',
'READ... | python | def generate_readme_rst():
"""
Generate README.rst from README.md via pandoc.
In case of errors, we show a message having the error that we got and
exit the program.
"""
pandoc_cmd = [
'pandoc',
'--from=markdown',
'--to=rst',
'--output=README.rst',
'READ... | [
"def",
"generate_readme_rst",
"(",
")",
":",
"pandoc_cmd",
"=",
"[",
"'pandoc'",
",",
"'--from=markdown'",
",",
"'--to=rst'",
",",
"'--output=README.rst'",
",",
"'README.md'",
"]",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"'README.rst'",
")",
":",
"return"... | Generate README.rst from README.md via pandoc.
In case of errors, we show a message having the error that we got and
exit the program. | [
"Generate",
"README",
".",
"rst",
"from",
"README",
".",
"md",
"via",
"pandoc",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/setup.py#L21-L43 | train |
coursera-dl/coursera-dl | setup.py | read_file | def read_file(filename, alt=None):
"""
Read the contents of filename or give an alternative result instead.
"""
lines = None
try:
with open(filename, encoding='utf-8') as f:
lines = f.read()
except IOError:
lines = [] if alt is None else alt
return lines | python | def read_file(filename, alt=None):
"""
Read the contents of filename or give an alternative result instead.
"""
lines = None
try:
with open(filename, encoding='utf-8') as f:
lines = f.read()
except IOError:
lines = [] if alt is None else alt
return lines | [
"def",
"read_file",
"(",
"filename",
",",
"alt",
"=",
"None",
")",
":",
"lines",
"=",
"None",
"try",
":",
"with",
"open",
"(",
"filename",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"f",
":",
"lines",
"=",
"f",
".",
"read",
"(",
")",
"except",
"... | Read the contents of filename or give an alternative result instead. | [
"Read",
"the",
"contents",
"of",
"filename",
"or",
"give",
"an",
"alternative",
"result",
"instead",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/setup.py#L46-L57 | train |
coursera-dl/coursera-dl | fabfile.py | release_check | def release_check():
"""Check if there is a Git tag already in place"""
tags = local("git tag", capture=True)
tags = set(tags.splitlines())
if env.version in tags:
raise Exception("Already released v. %r" % env.version) | python | def release_check():
"""Check if there is a Git tag already in place"""
tags = local("git tag", capture=True)
tags = set(tags.splitlines())
if env.version in tags:
raise Exception("Already released v. %r" % env.version) | [
"def",
"release_check",
"(",
")",
":",
"tags",
"=",
"local",
"(",
"\"git tag\"",
",",
"capture",
"=",
"True",
")",
"tags",
"=",
"set",
"(",
"tags",
".",
"splitlines",
"(",
")",
")",
"if",
"env",
".",
"version",
"in",
"tags",
":",
"raise",
"Exception"... | Check if there is a Git tag already in place | [
"Check",
"if",
"there",
"is",
"a",
"Git",
"tag",
"already",
"in",
"place"
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/fabfile.py#L75-L80 | train |
coursera-dl/coursera-dl | fabfile.py | release | def release():
"""Release a new version"""
release_check()
build()
print("Releasing %s version %s." % (env.projname, env.version))
local("git tag %s" % env.version)
local('gpg --detach-sign --armor dist/coursera-*.tar.gz*')
local('twine upload dist/coursera-*.tar.gz*')
local("git push")
... | python | def release():
"""Release a new version"""
release_check()
build()
print("Releasing %s version %s." % (env.projname, env.version))
local("git tag %s" % env.version)
local('gpg --detach-sign --armor dist/coursera-*.tar.gz*')
local('twine upload dist/coursera-*.tar.gz*')
local("git push")
... | [
"def",
"release",
"(",
")",
":",
"release_check",
"(",
")",
"build",
"(",
")",
"print",
"(",
"\"Releasing %s version %s.\"",
"%",
"(",
"env",
".",
"projname",
",",
"env",
".",
"version",
")",
")",
"local",
"(",
"\"git tag %s\"",
"%",
"env",
".",
"version... | Release a new version | [
"Release",
"a",
"new",
"version"
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/fabfile.py#L84-L93 | train |
coursera-dl/coursera-dl | coursera/api.py | expand_specializations | def expand_specializations(session, class_names):
"""
Checks whether any given name is not a class but a specialization.
If it's a specialization, expand the list of class names with the child
class names.
"""
result = []
for class_name in class_names:
specialization = Specializatio... | python | def expand_specializations(session, class_names):
"""
Checks whether any given name is not a class but a specialization.
If it's a specialization, expand the list of class names with the child
class names.
"""
result = []
for class_name in class_names:
specialization = Specializatio... | [
"def",
"expand_specializations",
"(",
"session",
",",
"class_names",
")",
":",
"result",
"=",
"[",
"]",
"for",
"class_name",
"in",
"class_names",
":",
"specialization",
"=",
"SpecializationV1",
".",
"create",
"(",
"session",
",",
"class_name",
")",
"if",
"spec... | Checks whether any given name is not a class but a specialization.
If it's a specialization, expand the list of class names with the child
class names. | [
"Checks",
"whether",
"any",
"given",
"name",
"is",
"not",
"a",
"class",
"but",
"a",
"specialization",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/api.py#L545-L563 | train |
coursera-dl/coursera-dl | coursera/api.py | MarkupToHTMLConverter._convert_markup_basic | def _convert_markup_basic(self, soup):
"""
Perform basic conversion of instructions markup. This includes
replacement of several textual markup tags with their HTML equivalents.
@param soup: BeautifulSoup instance.
@type soup: BeautifulSoup
"""
# Inject meta char... | python | def _convert_markup_basic(self, soup):
"""
Perform basic conversion of instructions markup. This includes
replacement of several textual markup tags with their HTML equivalents.
@param soup: BeautifulSoup instance.
@type soup: BeautifulSoup
"""
# Inject meta char... | [
"def",
"_convert_markup_basic",
"(",
"self",
",",
"soup",
")",
":",
"# Inject meta charset tag",
"meta",
"=",
"soup",
".",
"new_tag",
"(",
"'meta'",
",",
"charset",
"=",
"'UTF-8'",
")",
"soup",
".",
"insert",
"(",
"0",
",",
"meta",
")",
"# 1. Inject basic CS... | Perform basic conversion of instructions markup. This includes
replacement of several textual markup tags with their HTML equivalents.
@param soup: BeautifulSoup instance.
@type soup: BeautifulSoup | [
"Perform",
"basic",
"conversion",
"of",
"instructions",
"markup",
".",
"This",
"includes",
"replacement",
"of",
"several",
"textual",
"markup",
"tags",
"with",
"their",
"HTML",
"equivalents",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/api.py#L186-L223 | train |
coursera-dl/coursera-dl | coursera/api.py | MarkupToHTMLConverter._convert_markup_images | def _convert_markup_images(self, soup):
"""
Convert images of instructions markup. Images are downloaded,
base64-encoded and inserted into <img> tags.
@param soup: BeautifulSoup instance.
@type soup: BeautifulSoup
"""
# 6. Replace <img> assets with actual image c... | python | def _convert_markup_images(self, soup):
"""
Convert images of instructions markup. Images are downloaded,
base64-encoded and inserted into <img> tags.
@param soup: BeautifulSoup instance.
@type soup: BeautifulSoup
"""
# 6. Replace <img> assets with actual image c... | [
"def",
"_convert_markup_images",
"(",
"self",
",",
"soup",
")",
":",
"# 6. Replace <img> assets with actual image contents",
"images",
"=",
"[",
"image",
"for",
"image",
"in",
"soup",
".",
"find_all",
"(",
"'img'",
")",
"if",
"image",
".",
"attrs",
".",
"get",
... | Convert images of instructions markup. Images are downloaded,
base64-encoded and inserted into <img> tags.
@param soup: BeautifulSoup instance.
@type soup: BeautifulSoup | [
"Convert",
"images",
"of",
"instructions",
"markup",
".",
"Images",
"are",
"downloaded",
"base64",
"-",
"encoded",
"and",
"inserted",
"into",
"<img",
">",
"tags",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/api.py#L225-L249 | train |
coursera-dl/coursera-dl | coursera/api.py | MarkupToHTMLConverter._convert_markup_audios | def _convert_markup_audios(self, soup):
"""
Convert audios of instructions markup. Audios are downloaded,
base64-encoded and inserted as <audio controls> <source> tag.
@param soup: BeautifulSoup instance.
@type soup: BeautifulSoup
"""
# 7. Replace <asset> audio a... | python | def _convert_markup_audios(self, soup):
"""
Convert audios of instructions markup. Audios are downloaded,
base64-encoded and inserted as <audio controls> <source> tag.
@param soup: BeautifulSoup instance.
@type soup: BeautifulSoup
"""
# 7. Replace <asset> audio a... | [
"def",
"_convert_markup_audios",
"(",
"self",
",",
"soup",
")",
":",
"# 7. Replace <asset> audio assets with actual audio contents",
"audios",
"=",
"[",
"audio",
"for",
"audio",
"in",
"soup",
".",
"find_all",
"(",
"'asset'",
")",
"if",
"audio",
".",
"attrs",
".",
... | Convert audios of instructions markup. Audios are downloaded,
base64-encoded and inserted as <audio controls> <source> tag.
@param soup: BeautifulSoup instance.
@type soup: BeautifulSoup | [
"Convert",
"audios",
"of",
"instructions",
"markup",
".",
"Audios",
"are",
"downloaded",
"base64",
"-",
"encoded",
"and",
"inserted",
"as",
"<audio",
"controls",
">",
"<source",
">",
"tag",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/api.py#L251-L284 | train |
coursera-dl/coursera-dl | coursera/api.py | OnDemandCourseMaterialItemsV1.create | def create(session, course_name):
"""
Create an instance using a session and a course_name.
@param session: Requests session.
@type session: requests.Session
@param course_name: Course name (slug) from course json.
@type course_name: str
@return: Instance of On... | python | def create(session, course_name):
"""
Create an instance using a session and a course_name.
@param session: Requests session.
@type session: requests.Session
@param course_name: Course name (slug) from course json.
@type course_name: str
@return: Instance of On... | [
"def",
"create",
"(",
"session",
",",
"course_name",
")",
":",
"dom",
"=",
"get_page",
"(",
"session",
",",
"OPENCOURSE_ONDEMAND_COURSE_MATERIALS",
",",
"json",
"=",
"True",
",",
"class_name",
"=",
"course_name",
")",
"return",
"OnDemandCourseMaterialItemsV1",
"("... | Create an instance using a session and a course_name.
@param session: Requests session.
@type session: requests.Session
@param course_name: Course name (slug) from course json.
@type course_name: str
@return: Instance of OnDemandCourseMaterialItems
@rtype: OnDemandCour... | [
"Create",
"an",
"instance",
"using",
"a",
"session",
"and",
"a",
"course_name",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/api.py#L304-L322 | train |
coursera-dl/coursera-dl | coursera/api.py | CourseraOnDemand.list_courses | def list_courses(self):
"""
List enrolled courses.
@return: List of enrolled courses.
@rtype: [str]
"""
reply = get_page(self._session, OPENCOURSE_MEMBERSHIPS, json=True)
course_list = reply['linked']['courses.v1']
slugs = [element['slug'] for element in ... | python | def list_courses(self):
"""
List enrolled courses.
@return: List of enrolled courses.
@rtype: [str]
"""
reply = get_page(self._session, OPENCOURSE_MEMBERSHIPS, json=True)
course_list = reply['linked']['courses.v1']
slugs = [element['slug'] for element in ... | [
"def",
"list_courses",
"(",
"self",
")",
":",
"reply",
"=",
"get_page",
"(",
"self",
".",
"_session",
",",
"OPENCOURSE_MEMBERSHIPS",
",",
"json",
"=",
"True",
")",
"course_list",
"=",
"reply",
"[",
"'linked'",
"]",
"[",
"'courses.v1'",
"]",
"slugs",
"=",
... | List enrolled courses.
@return: List of enrolled courses.
@rtype: [str] | [
"List",
"enrolled",
"courses",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/api.py#L628-L638 | train |
coursera-dl/coursera-dl | coursera/api.py | CourseraOnDemand.extract_links_from_lecture | def extract_links_from_lecture(self, course_id,
video_id, subtitle_language='en',
resolution='540p'):
"""
Return the download URLs of on-demand course video.
@param video_id: Video ID.
@type video_id: str
@pa... | python | def extract_links_from_lecture(self, course_id,
video_id, subtitle_language='en',
resolution='540p'):
"""
Return the download URLs of on-demand course video.
@param video_id: Video ID.
@type video_id: str
@pa... | [
"def",
"extract_links_from_lecture",
"(",
"self",
",",
"course_id",
",",
"video_id",
",",
"subtitle_language",
"=",
"'en'",
",",
"resolution",
"=",
"'540p'",
")",
":",
"try",
":",
"links",
"=",
"self",
".",
"_extract_videos_and_subtitles_from_lecture",
"(",
"cours... | Return the download URLs of on-demand course video.
@param video_id: Video ID.
@type video_id: str
@param subtitle_language: Subtitle language.
@type subtitle_language: str
@param resolution: Preferred video resolution.
@type resolution: str
@return: @see Cour... | [
"Return",
"the",
"download",
"URLs",
"of",
"on",
"-",
"demand",
"course",
"video",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/api.py#L863-L896 | train |
coursera-dl/coursera-dl | coursera/api.py | CourseraOnDemand._get_lecture_asset_ids | def _get_lecture_asset_ids(self, course_id, video_id):
"""
Obtain a list of asset ids from a lecture.
"""
dom = get_page(self._session, OPENCOURSE_ONDEMAND_LECTURE_ASSETS_URL,
json=True, course_id=course_id, video_id=video_id)
# Note that we extract here "i... | python | def _get_lecture_asset_ids(self, course_id, video_id):
"""
Obtain a list of asset ids from a lecture.
"""
dom = get_page(self._session, OPENCOURSE_ONDEMAND_LECTURE_ASSETS_URL,
json=True, course_id=course_id, video_id=video_id)
# Note that we extract here "i... | [
"def",
"_get_lecture_asset_ids",
"(",
"self",
",",
"course_id",
",",
"video_id",
")",
":",
"dom",
"=",
"get_page",
"(",
"self",
".",
"_session",
",",
"OPENCOURSE_ONDEMAND_LECTURE_ASSETS_URL",
",",
"json",
"=",
"True",
",",
"course_id",
"=",
"course_id",
",",
"... | Obtain a list of asset ids from a lecture. | [
"Obtain",
"a",
"list",
"of",
"asset",
"ids",
"from",
"a",
"lecture",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/api.py#L898-L907 | train |
coursera-dl/coursera-dl | coursera/api.py | CourseraOnDemand._normalize_assets | def _normalize_assets(self, assets):
"""
Perform asset normalization. For some reason, assets that are sometimes
present in lectures, have "@1" at the end of their id. Such "uncut"
asset id when fed to OPENCOURSE_ASSETS_URL results in error that says:
"Routing error: 'get-all' no... | python | def _normalize_assets(self, assets):
"""
Perform asset normalization. For some reason, assets that are sometimes
present in lectures, have "@1" at the end of their id. Such "uncut"
asset id when fed to OPENCOURSE_ASSETS_URL results in error that says:
"Routing error: 'get-all' no... | [
"def",
"_normalize_assets",
"(",
"self",
",",
"assets",
")",
":",
"new_assets",
"=",
"[",
"]",
"for",
"asset",
"in",
"assets",
":",
"# For example: giAxucdaEeWJTQ5WTi8YJQ@1",
"if",
"len",
"(",
"asset",
")",
"==",
"24",
":",
"# Turn it into: giAxucdaEeWJTQ5WTi8YJQ"... | Perform asset normalization. For some reason, assets that are sometimes
present in lectures, have "@1" at the end of their id. Such "uncut"
asset id when fed to OPENCOURSE_ASSETS_URL results in error that says:
"Routing error: 'get-all' not implemented". To avoid that, the last
two chara... | [
"Perform",
"asset",
"normalization",
".",
"For",
"some",
"reason",
"assets",
"that",
"are",
"sometimes",
"present",
"in",
"lectures",
"have",
"@1",
"at",
"the",
"end",
"of",
"their",
"id",
".",
"Such",
"uncut",
"asset",
"id",
"when",
"fed",
"to",
"OPENCOUR... | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/api.py#L909-L933 | train |
coursera-dl/coursera-dl | coursera/api.py | CourseraOnDemand._extract_links_from_lecture_assets | def _extract_links_from_lecture_assets(self, asset_ids):
"""
Extract links to files of the asset ids.
@param asset_ids: List of asset ids.
@type asset_ids: [str]
@return: @see CourseraOnDemand._extract_links_from_text
"""
links = {}
def _add_asset(name,... | python | def _extract_links_from_lecture_assets(self, asset_ids):
"""
Extract links to files of the asset ids.
@param asset_ids: List of asset ids.
@type asset_ids: [str]
@return: @see CourseraOnDemand._extract_links_from_text
"""
links = {}
def _add_asset(name,... | [
"def",
"_extract_links_from_lecture_assets",
"(",
"self",
",",
"asset_ids",
")",
":",
"links",
"=",
"{",
"}",
"def",
"_add_asset",
"(",
"name",
",",
"url",
",",
"destination",
")",
":",
"filename",
",",
"extension",
"=",
"os",
".",
"path",
".",
"splitext",... | Extract links to files of the asset ids.
@param asset_ids: List of asset ids.
@type asset_ids: [str]
@return: @see CourseraOnDemand._extract_links_from_text | [
"Extract",
"links",
"to",
"files",
"of",
"the",
"asset",
"ids",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/api.py#L935-L967 | train |
coursera-dl/coursera-dl | coursera/api.py | CourseraOnDemand._get_asset_urls | def _get_asset_urls(self, asset_id):
"""
Get list of asset urls and file names. This method may internally
use AssetRetriever to extract `asset` element types.
@param asset_id: Asset ID.
@type asset_id: str
@return List of dictionaries with asset file names and urls.
... | python | def _get_asset_urls(self, asset_id):
"""
Get list of asset urls and file names. This method may internally
use AssetRetriever to extract `asset` element types.
@param asset_id: Asset ID.
@type asset_id: str
@return List of dictionaries with asset file names and urls.
... | [
"def",
"_get_asset_urls",
"(",
"self",
",",
"asset_id",
")",
":",
"dom",
"=",
"get_page",
"(",
"self",
".",
"_session",
",",
"OPENCOURSE_ASSETS_URL",
",",
"json",
"=",
"True",
",",
"id",
"=",
"asset_id",
")",
"logging",
".",
"debug",
"(",
"'Parsing JSON fo... | Get list of asset urls and file names. This method may internally
use AssetRetriever to extract `asset` element types.
@param asset_id: Asset ID.
@type asset_id: str
@return List of dictionaries with asset file names and urls.
@rtype [{
'name': '<filename.ext>'
... | [
"Get",
"list",
"of",
"asset",
"urls",
"and",
"file",
"names",
".",
"This",
"method",
"may",
"internally",
"use",
"AssetRetriever",
"to",
"extract",
"asset",
"element",
"types",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/api.py#L969-L1029 | train |
coursera-dl/coursera-dl | coursera/api.py | CourseraOnDemand.extract_links_from_peer_assignment | def extract_links_from_peer_assignment(self, element_id):
"""
Return a dictionary with links to supplement files (pdf, csv, zip,
ipynb, html and so on) extracted from peer assignment.
@param element_id: Element ID to extract files from.
@type element_id: str
@return: @s... | python | def extract_links_from_peer_assignment(self, element_id):
"""
Return a dictionary with links to supplement files (pdf, csv, zip,
ipynb, html and so on) extracted from peer assignment.
@param element_id: Element ID to extract files from.
@type element_id: str
@return: @s... | [
"def",
"extract_links_from_peer_assignment",
"(",
"self",
",",
"element_id",
")",
":",
"logging",
".",
"debug",
"(",
"'Gathering supplement URLs for element_id <%s>.'",
",",
"element_id",
")",
"try",
":",
"# Assignment text (instructions) contains asset tags which describe",
"#... | Return a dictionary with links to supplement files (pdf, csv, zip,
ipynb, html and so on) extracted from peer assignment.
@param element_id: Element ID to extract files from.
@type element_id: str
@return: @see CourseraOnDemand._extract_links_from_text | [
"Return",
"a",
"dictionary",
"with",
"links",
"to",
"supplement",
"files",
"(",
"pdf",
"csv",
"zip",
"ipynb",
"html",
"and",
"so",
"on",
")",
"extracted",
"from",
"peer",
"assignment",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/api.py#L1204-L1236 | train |
coursera-dl/coursera-dl | coursera/api.py | CourseraOnDemand.extract_links_from_supplement | def extract_links_from_supplement(self, element_id):
"""
Return a dictionary with supplement files (pdf, csv, zip, ipynb, html
and so on) extracted from supplement page.
@return: @see CourseraOnDemand._extract_links_from_text
"""
logging.debug(
'Gathering sup... | python | def extract_links_from_supplement(self, element_id):
"""
Return a dictionary with supplement files (pdf, csv, zip, ipynb, html
and so on) extracted from supplement page.
@return: @see CourseraOnDemand._extract_links_from_text
"""
logging.debug(
'Gathering sup... | [
"def",
"extract_links_from_supplement",
"(",
"self",
",",
"element_id",
")",
":",
"logging",
".",
"debug",
"(",
"'Gathering supplement URLs for element_id <%s>.'",
",",
"element_id",
")",
"try",
":",
"dom",
"=",
"get_page",
"(",
"self",
".",
"_session",
",",
"OPEN... | Return a dictionary with supplement files (pdf, csv, zip, ipynb, html
and so on) extracted from supplement page.
@return: @see CourseraOnDemand._extract_links_from_text | [
"Return",
"a",
"dictionary",
"with",
"supplement",
"files",
"(",
"pdf",
"csv",
"zip",
"ipynb",
"html",
"and",
"so",
"on",
")",
"extracted",
"from",
"supplement",
"page",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/api.py#L1238-L1282 | train |
coursera-dl/coursera-dl | coursera/api.py | CourseraOnDemand._extract_asset_tags | def _extract_asset_tags(self, text):
"""
Extract asset tags from text into a convenient form.
@param text: Text to extract asset tags from. This text contains HTML
code that is parsed by BeautifulSoup.
@type text: str
@return: Asset map.
@rtype: {
... | python | def _extract_asset_tags(self, text):
"""
Extract asset tags from text into a convenient form.
@param text: Text to extract asset tags from. This text contains HTML
code that is parsed by BeautifulSoup.
@type text: str
@return: Asset map.
@rtype: {
... | [
"def",
"_extract_asset_tags",
"(",
"self",
",",
"text",
")",
":",
"soup",
"=",
"BeautifulSoup",
"(",
"text",
")",
"asset_tags_map",
"=",
"{",
"}",
"for",
"asset",
"in",
"soup",
".",
"find_all",
"(",
"'asset'",
")",
":",
"asset_tags_map",
"[",
"asset",
"[... | Extract asset tags from text into a convenient form.
@param text: Text to extract asset tags from. This text contains HTML
code that is parsed by BeautifulSoup.
@type text: str
@return: Asset map.
@rtype: {
'<id>': {
'name': '<name>',
... | [
"Extract",
"asset",
"tags",
"from",
"text",
"into",
"a",
"convenient",
"form",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/api.py#L1284-L1308 | train |
coursera-dl/coursera-dl | coursera/api.py | CourseraOnDemand._extract_asset_urls | def _extract_asset_urls(self, asset_ids):
"""
Extract asset URLs along with asset ids.
@param asset_ids: List of ids to get URLs for.
@type assertn: [str]
@return: List of dictionaries with asset URLs and ids.
@rtype: [{
'id': '<id>',
'url': '<ur... | python | def _extract_asset_urls(self, asset_ids):
"""
Extract asset URLs along with asset ids.
@param asset_ids: List of ids to get URLs for.
@type assertn: [str]
@return: List of dictionaries with asset URLs and ids.
@rtype: [{
'id': '<id>',
'url': '<ur... | [
"def",
"_extract_asset_urls",
"(",
"self",
",",
"asset_ids",
")",
":",
"dom",
"=",
"get_page",
"(",
"self",
".",
"_session",
",",
"OPENCOURSE_ASSET_URL",
",",
"json",
"=",
"True",
",",
"ids",
"=",
"quote_plus",
"(",
"','",
".",
"join",
"(",
"asset_ids",
... | Extract asset URLs along with asset ids.
@param asset_ids: List of ids to get URLs for.
@type assertn: [str]
@return: List of dictionaries with asset URLs and ids.
@rtype: [{
'id': '<id>',
'url': '<url>'
}] | [
"Extract",
"asset",
"URLs",
"along",
"with",
"asset",
"ids",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/api.py#L1310-L1329 | train |
coursera-dl/coursera-dl | coursera/api.py | CourseraOnDemand.extract_links_from_reference | def extract_links_from_reference(self, short_id):
"""
Return a dictionary with supplement files (pdf, csv, zip, ipynb, html
and so on) extracted from supplement page.
@return: @see CourseraOnDemand._extract_links_from_text
"""
logging.debug('Gathering resource URLs for s... | python | def extract_links_from_reference(self, short_id):
"""
Return a dictionary with supplement files (pdf, csv, zip, ipynb, html
and so on) extracted from supplement page.
@return: @see CourseraOnDemand._extract_links_from_text
"""
logging.debug('Gathering resource URLs for s... | [
"def",
"extract_links_from_reference",
"(",
"self",
",",
"short_id",
")",
":",
"logging",
".",
"debug",
"(",
"'Gathering resource URLs for short_id <%s>.'",
",",
"short_id",
")",
"try",
":",
"dom",
"=",
"get_page",
"(",
"self",
".",
"_session",
",",
"OPENCOURSE_RE... | Return a dictionary with supplement files (pdf, csv, zip, ipynb, html
and so on) extracted from supplement page.
@return: @see CourseraOnDemand._extract_links_from_text | [
"Return",
"a",
"dictionary",
"with",
"supplement",
"files",
"(",
"pdf",
"csv",
"zip",
"ipynb",
"html",
"and",
"so",
"on",
")",
"extracted",
"from",
"supplement",
"page",
"."
] | 9b434bcf3c4011bf3181429fe674633ae5fb7d4d | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/api.py#L1349-L1392 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.