partition stringclasses 3 values | func_name stringlengths 1 134 | docstring stringlengths 1 46.9k | path stringlengths 4 223 | original_string stringlengths 75 104k | code stringlengths 75 104k | docstring_tokens listlengths 1 1.97k | repo stringlengths 7 55 | language stringclasses 1 value | url stringlengths 87 315 | code_tokens listlengths 19 28.4k | sha stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|
test | get_messages | Fetch messages for given user. Returns None if no such message exists.
:param user: User instance | async_messages/__init__.py | def get_messages(user):
"""
Fetch messages for given user. Returns None if no such message exists.
:param user: User instance
"""
key = _user_key(user)
result = cache.get(key)
if result:
cache.delete(key)
return result
return None | def get_messages(user):
"""
Fetch messages for given user. Returns None if no such message exists.
:param user: User instance
"""
key = _user_key(user)
result = cache.get(key)
if result:
cache.delete(key)
return result
return None | [
"Fetch",
"messages",
"for",
"given",
"user",
".",
"Returns",
"None",
"if",
"no",
"such",
"message",
"exists",
"."
] | codeinthehole/django-async-messages | python | https://github.com/codeinthehole/django-async-messages/blob/292cb2fc517521dabc67b90e7ca5b1617f59e214/async_messages/__init__.py#L33-L44 | [
"def",
"get_messages",
"(",
"user",
")",
":",
"key",
"=",
"_user_key",
"(",
"user",
")",
"result",
"=",
"cache",
".",
"get",
"(",
"key",
")",
"if",
"result",
":",
"cache",
".",
"delete",
"(",
"key",
")",
"return",
"result",
"return",
"None"
] | 292cb2fc517521dabc67b90e7ca5b1617f59e214 |
test | AsyncMiddleware.process_response | Check for messages for this user and, if it exists,
call the messages API with it | async_messages/middleware.py | def process_response(self, request, response):
"""
Check for messages for this user and, if it exists,
call the messages API with it
"""
if hasattr(request, "session") and hasattr(request, "user") and request.user.is_authenticated():
msgs = get_messages(request.user)
if msgs:
for msg, level in msgs:
messages.add_message(request, level, msg)
return response | def process_response(self, request, response):
"""
Check for messages for this user and, if it exists,
call the messages API with it
"""
if hasattr(request, "session") and hasattr(request, "user") and request.user.is_authenticated():
msgs = get_messages(request.user)
if msgs:
for msg, level in msgs:
messages.add_message(request, level, msg)
return response | [
"Check",
"for",
"messages",
"for",
"this",
"user",
"and",
"if",
"it",
"exists",
"call",
"the",
"messages",
"API",
"with",
"it"
] | codeinthehole/django-async-messages | python | https://github.com/codeinthehole/django-async-messages/blob/292cb2fc517521dabc67b90e7ca5b1617f59e214/async_messages/middleware.py#L8-L18 | [
"def",
"process_response",
"(",
"self",
",",
"request",
",",
"response",
")",
":",
"if",
"hasattr",
"(",
"request",
",",
"\"session\"",
")",
"and",
"hasattr",
"(",
"request",
",",
"\"user\"",
")",
"and",
"request",
".",
"user",
".",
"is_authenticated",
"(",
")",
":",
"msgs",
"=",
"get_messages",
"(",
"request",
".",
"user",
")",
"if",
"msgs",
":",
"for",
"msg",
",",
"level",
"in",
"msgs",
":",
"messages",
".",
"add_message",
"(",
"request",
",",
"level",
",",
"msg",
")",
"return",
"response"
] | 292cb2fc517521dabc67b90e7ca5b1617f59e214 |
test | check_config_file | Checks the config.json file for default settings and auth values.
Args:
:msg: (Message class) an instance of a message class. | messages/_config.py | def check_config_file(msg):
"""
Checks the config.json file for default settings and auth values.
Args:
:msg: (Message class) an instance of a message class.
"""
with jsonconfig.Config("messages", indent=4) as cfg:
verify_profile_name(msg, cfg)
retrieve_data_from_config(msg, cfg)
if msg._auth is None:
retrieve_pwd_from_config(msg, cfg)
if msg.save:
update_config_data(msg, cfg)
update_config_pwd(msg, cfg) | def check_config_file(msg):
"""
Checks the config.json file for default settings and auth values.
Args:
:msg: (Message class) an instance of a message class.
"""
with jsonconfig.Config("messages", indent=4) as cfg:
verify_profile_name(msg, cfg)
retrieve_data_from_config(msg, cfg)
if msg._auth is None:
retrieve_pwd_from_config(msg, cfg)
if msg.save:
update_config_data(msg, cfg)
update_config_pwd(msg, cfg) | [
"Checks",
"the",
"config",
".",
"json",
"file",
"for",
"default",
"settings",
"and",
"auth",
"values",
"."
] | trp07/messages | python | https://github.com/trp07/messages/blob/7789ebc960335a59ea5d319fceed3dd349023648/messages/_config.py#L72-L89 | [
"def",
"check_config_file",
"(",
"msg",
")",
":",
"with",
"jsonconfig",
".",
"Config",
"(",
"\"messages\"",
",",
"indent",
"=",
"4",
")",
"as",
"cfg",
":",
"verify_profile_name",
"(",
"msg",
",",
"cfg",
")",
"retrieve_data_from_config",
"(",
"msg",
",",
"cfg",
")",
"if",
"msg",
".",
"_auth",
"is",
"None",
":",
"retrieve_pwd_from_config",
"(",
"msg",
",",
"cfg",
")",
"if",
"msg",
".",
"save",
":",
"update_config_data",
"(",
"msg",
",",
"cfg",
")",
"update_config_pwd",
"(",
"msg",
",",
"cfg",
")"
] | 7789ebc960335a59ea5d319fceed3dd349023648 |
test | verify_profile_name | Verifies the profile name exists in the config.json file.
Args:
:msg: (Message class) an instance of a message class.
:cfg: (jsonconfig.Config) config instance. | messages/_config.py | def verify_profile_name(msg, cfg):
"""
Verifies the profile name exists in the config.json file.
Args:
:msg: (Message class) an instance of a message class.
:cfg: (jsonconfig.Config) config instance.
"""
if msg.profile not in cfg.data:
raise UnknownProfileError(msg.profile) | def verify_profile_name(msg, cfg):
"""
Verifies the profile name exists in the config.json file.
Args:
:msg: (Message class) an instance of a message class.
:cfg: (jsonconfig.Config) config instance.
"""
if msg.profile not in cfg.data:
raise UnknownProfileError(msg.profile) | [
"Verifies",
"the",
"profile",
"name",
"exists",
"in",
"the",
"config",
".",
"json",
"file",
"."
] | trp07/messages | python | https://github.com/trp07/messages/blob/7789ebc960335a59ea5d319fceed3dd349023648/messages/_config.py#L92-L101 | [
"def",
"verify_profile_name",
"(",
"msg",
",",
"cfg",
")",
":",
"if",
"msg",
".",
"profile",
"not",
"in",
"cfg",
".",
"data",
":",
"raise",
"UnknownProfileError",
"(",
"msg",
".",
"profile",
")"
] | 7789ebc960335a59ea5d319fceed3dd349023648 |
test | retrieve_data_from_config | Update msg attrs with values from the profile configuration if the
msg.attr=None, else leave it alone.
Args:
:msg: (Message class) an instance of a message class.
:cfg: (jsonconfig.Config) config instance. | messages/_config.py | def retrieve_data_from_config(msg, cfg):
"""
Update msg attrs with values from the profile configuration if the
msg.attr=None, else leave it alone.
Args:
:msg: (Message class) an instance of a message class.
:cfg: (jsonconfig.Config) config instance.
"""
msg_type = msg.__class__.__name__.lower()
for attr in msg:
if getattr(msg, attr) is None and attr in cfg.data[msg.profile][msg_type]:
setattr(msg, attr, cfg.data[msg.profile][msg_type][attr]) | def retrieve_data_from_config(msg, cfg):
"""
Update msg attrs with values from the profile configuration if the
msg.attr=None, else leave it alone.
Args:
:msg: (Message class) an instance of a message class.
:cfg: (jsonconfig.Config) config instance.
"""
msg_type = msg.__class__.__name__.lower()
for attr in msg:
if getattr(msg, attr) is None and attr in cfg.data[msg.profile][msg_type]:
setattr(msg, attr, cfg.data[msg.profile][msg_type][attr]) | [
"Update",
"msg",
"attrs",
"with",
"values",
"from",
"the",
"profile",
"configuration",
"if",
"the",
"msg",
".",
"attr",
"=",
"None",
"else",
"leave",
"it",
"alone",
"."
] | trp07/messages | python | https://github.com/trp07/messages/blob/7789ebc960335a59ea5d319fceed3dd349023648/messages/_config.py#L104-L116 | [
"def",
"retrieve_data_from_config",
"(",
"msg",
",",
"cfg",
")",
":",
"msg_type",
"=",
"msg",
".",
"__class__",
".",
"__name__",
".",
"lower",
"(",
")",
"for",
"attr",
"in",
"msg",
":",
"if",
"getattr",
"(",
"msg",
",",
"attr",
")",
"is",
"None",
"and",
"attr",
"in",
"cfg",
".",
"data",
"[",
"msg",
".",
"profile",
"]",
"[",
"msg_type",
"]",
":",
"setattr",
"(",
"msg",
",",
"attr",
",",
"cfg",
".",
"data",
"[",
"msg",
".",
"profile",
"]",
"[",
"msg_type",
"]",
"[",
"attr",
"]",
")"
] | 7789ebc960335a59ea5d319fceed3dd349023648 |
test | retrieve_pwd_from_config | Retrieve auth from profile configuration and set in msg.auth attr.
Args:
:msg: (Message class) an instance of a message class.
:cfg: (jsonconfig.Config) config instance. | messages/_config.py | def retrieve_pwd_from_config(msg, cfg):
"""
Retrieve auth from profile configuration and set in msg.auth attr.
Args:
:msg: (Message class) an instance of a message class.
:cfg: (jsonconfig.Config) config instance.
"""
msg_type = msg.__class__.__name__.lower()
key_fmt = msg.profile + "_" + msg_type
pwd = cfg.pwd[key_fmt].split(" :: ")
if len(pwd) == 1:
msg.auth = pwd[0]
else:
msg.auth = tuple(pwd) | def retrieve_pwd_from_config(msg, cfg):
"""
Retrieve auth from profile configuration and set in msg.auth attr.
Args:
:msg: (Message class) an instance of a message class.
:cfg: (jsonconfig.Config) config instance.
"""
msg_type = msg.__class__.__name__.lower()
key_fmt = msg.profile + "_" + msg_type
pwd = cfg.pwd[key_fmt].split(" :: ")
if len(pwd) == 1:
msg.auth = pwd[0]
else:
msg.auth = tuple(pwd) | [
"Retrieve",
"auth",
"from",
"profile",
"configuration",
"and",
"set",
"in",
"msg",
".",
"auth",
"attr",
"."
] | trp07/messages | python | https://github.com/trp07/messages/blob/7789ebc960335a59ea5d319fceed3dd349023648/messages/_config.py#L119-L133 | [
"def",
"retrieve_pwd_from_config",
"(",
"msg",
",",
"cfg",
")",
":",
"msg_type",
"=",
"msg",
".",
"__class__",
".",
"__name__",
".",
"lower",
"(",
")",
"key_fmt",
"=",
"msg",
".",
"profile",
"+",
"\"_\"",
"+",
"msg_type",
"pwd",
"=",
"cfg",
".",
"pwd",
"[",
"key_fmt",
"]",
".",
"split",
"(",
"\" :: \"",
")",
"if",
"len",
"(",
"pwd",
")",
"==",
"1",
":",
"msg",
".",
"auth",
"=",
"pwd",
"[",
"0",
"]",
"else",
":",
"msg",
".",
"auth",
"=",
"tuple",
"(",
"pwd",
")"
] | 7789ebc960335a59ea5d319fceed3dd349023648 |
test | update_config_data | Updates the profile's config entry with values set in each attr by the
user. This will overwrite existing values.
Args:
:msg: (Message class) an instance of a message class.
:cfg: (jsonconfig.Config) config instance. | messages/_config.py | def update_config_data(msg, cfg):
"""
Updates the profile's config entry with values set in each attr by the
user. This will overwrite existing values.
Args:
:msg: (Message class) an instance of a message class.
:cfg: (jsonconfig.Config) config instance.
"""
for attr in msg:
if attr in cfg.data[msg.profile] and attr is not "auth":
cfg.data[msg.profile][attr] = getattr(msg, attr) | def update_config_data(msg, cfg):
"""
Updates the profile's config entry with values set in each attr by the
user. This will overwrite existing values.
Args:
:msg: (Message class) an instance of a message class.
:cfg: (jsonconfig.Config) config instance.
"""
for attr in msg:
if attr in cfg.data[msg.profile] and attr is not "auth":
cfg.data[msg.profile][attr] = getattr(msg, attr) | [
"Updates",
"the",
"profile",
"s",
"config",
"entry",
"with",
"values",
"set",
"in",
"each",
"attr",
"by",
"the",
"user",
".",
"This",
"will",
"overwrite",
"existing",
"values",
"."
] | trp07/messages | python | https://github.com/trp07/messages/blob/7789ebc960335a59ea5d319fceed3dd349023648/messages/_config.py#L136-L147 | [
"def",
"update_config_data",
"(",
"msg",
",",
"cfg",
")",
":",
"for",
"attr",
"in",
"msg",
":",
"if",
"attr",
"in",
"cfg",
".",
"data",
"[",
"msg",
".",
"profile",
"]",
"and",
"attr",
"is",
"not",
"\"auth\"",
":",
"cfg",
".",
"data",
"[",
"msg",
".",
"profile",
"]",
"[",
"attr",
"]",
"=",
"getattr",
"(",
"msg",
",",
"attr",
")"
] | 7789ebc960335a59ea5d319fceed3dd349023648 |
test | update_config_pwd | Updates the profile's auth entry with values set by the user.
This will overwrite existing values.
Args:
:msg: (Message class) an instance of a message class.
:cfg: (jsonconfig.Config) config instance. | messages/_config.py | def update_config_pwd(msg, cfg):
"""
Updates the profile's auth entry with values set by the user.
This will overwrite existing values.
Args:
:msg: (Message class) an instance of a message class.
:cfg: (jsonconfig.Config) config instance.
"""
msg_type = msg.__class__.__name__.lower()
key_fmt = msg.profile + "_" + msg_type
if isinstance(msg._auth, (MutableSequence, tuple)):
cfg.pwd[key_fmt] = " :: ".join(msg._auth)
else:
cfg.pwd[key_fmt] = msg._auth | def update_config_pwd(msg, cfg):
"""
Updates the profile's auth entry with values set by the user.
This will overwrite existing values.
Args:
:msg: (Message class) an instance of a message class.
:cfg: (jsonconfig.Config) config instance.
"""
msg_type = msg.__class__.__name__.lower()
key_fmt = msg.profile + "_" + msg_type
if isinstance(msg._auth, (MutableSequence, tuple)):
cfg.pwd[key_fmt] = " :: ".join(msg._auth)
else:
cfg.pwd[key_fmt] = msg._auth | [
"Updates",
"the",
"profile",
"s",
"auth",
"entry",
"with",
"values",
"set",
"by",
"the",
"user",
".",
"This",
"will",
"overwrite",
"existing",
"values",
"."
] | trp07/messages | python | https://github.com/trp07/messages/blob/7789ebc960335a59ea5d319fceed3dd349023648/messages/_config.py#L150-L164 | [
"def",
"update_config_pwd",
"(",
"msg",
",",
"cfg",
")",
":",
"msg_type",
"=",
"msg",
".",
"__class__",
".",
"__name__",
".",
"lower",
"(",
")",
"key_fmt",
"=",
"msg",
".",
"profile",
"+",
"\"_\"",
"+",
"msg_type",
"if",
"isinstance",
"(",
"msg",
".",
"_auth",
",",
"(",
"MutableSequence",
",",
"tuple",
")",
")",
":",
"cfg",
".",
"pwd",
"[",
"key_fmt",
"]",
"=",
"\" :: \"",
".",
"join",
"(",
"msg",
".",
"_auth",
")",
"else",
":",
"cfg",
".",
"pwd",
"[",
"key_fmt",
"]",
"=",
"msg",
".",
"_auth"
] | 7789ebc960335a59ea5d319fceed3dd349023648 |
test | create_config_profile | Create a profile for the given message type.
Args:
:msg_type: (str) message type to create config entry. | messages/_config.py | def create_config_profile(msg_type):
"""
Create a profile for the given message type.
Args:
:msg_type: (str) message type to create config entry.
"""
msg_type = msg_type.lower()
if msg_type not in CONFIG.keys():
raise UnsupportedMessageTypeError(msg_type)
display_required_items(msg_type)
if get_user_ack():
profile_name = input("Profile Name: ")
data = get_data_from_user(msg_type)
auth = get_auth_from_user(msg_type)
configure_profile(msg_type, profile_name, data, auth) | def create_config_profile(msg_type):
"""
Create a profile for the given message type.
Args:
:msg_type: (str) message type to create config entry.
"""
msg_type = msg_type.lower()
if msg_type not in CONFIG.keys():
raise UnsupportedMessageTypeError(msg_type)
display_required_items(msg_type)
if get_user_ack():
profile_name = input("Profile Name: ")
data = get_data_from_user(msg_type)
auth = get_auth_from_user(msg_type)
configure_profile(msg_type, profile_name, data, auth) | [
"Create",
"a",
"profile",
"for",
"the",
"given",
"message",
"type",
"."
] | trp07/messages | python | https://github.com/trp07/messages/blob/7789ebc960335a59ea5d319fceed3dd349023648/messages/_config.py#L172-L190 | [
"def",
"create_config_profile",
"(",
"msg_type",
")",
":",
"msg_type",
"=",
"msg_type",
".",
"lower",
"(",
")",
"if",
"msg_type",
"not",
"in",
"CONFIG",
".",
"keys",
"(",
")",
":",
"raise",
"UnsupportedMessageTypeError",
"(",
"msg_type",
")",
"display_required_items",
"(",
"msg_type",
")",
"if",
"get_user_ack",
"(",
")",
":",
"profile_name",
"=",
"input",
"(",
"\"Profile Name: \"",
")",
"data",
"=",
"get_data_from_user",
"(",
"msg_type",
")",
"auth",
"=",
"get_auth_from_user",
"(",
"msg_type",
")",
"configure_profile",
"(",
"msg_type",
",",
"profile_name",
",",
"data",
",",
"auth",
")"
] | 7789ebc960335a59ea5d319fceed3dd349023648 |
test | display_required_items | Display the required items needed to configure a profile for the given
message type.
Args:
:msg_type: (str) message type to create config entry. | messages/_config.py | def display_required_items(msg_type):
"""
Display the required items needed to configure a profile for the given
message type.
Args:
:msg_type: (str) message type to create config entry.
"""
print("Configure a profile for: " + msg_type)
print("You will need the following information:")
for k, v in CONFIG[msg_type]["settings"].items():
print(" * " + v)
print("Authorization/credentials required:")
for k, v in CONFIG[msg_type]["auth"].items():
print(" * " + v) | def display_required_items(msg_type):
"""
Display the required items needed to configure a profile for the given
message type.
Args:
:msg_type: (str) message type to create config entry.
"""
print("Configure a profile for: " + msg_type)
print("You will need the following information:")
for k, v in CONFIG[msg_type]["settings"].items():
print(" * " + v)
print("Authorization/credentials required:")
for k, v in CONFIG[msg_type]["auth"].items():
print(" * " + v) | [
"Display",
"the",
"required",
"items",
"needed",
"to",
"configure",
"a",
"profile",
"for",
"the",
"given",
"message",
"type",
"."
] | trp07/messages | python | https://github.com/trp07/messages/blob/7789ebc960335a59ea5d319fceed3dd349023648/messages/_config.py#L193-L207 | [
"def",
"display_required_items",
"(",
"msg_type",
")",
":",
"print",
"(",
"\"Configure a profile for: \"",
"+",
"msg_type",
")",
"print",
"(",
"\"You will need the following information:\"",
")",
"for",
"k",
",",
"v",
"in",
"CONFIG",
"[",
"msg_type",
"]",
"[",
"\"settings\"",
"]",
".",
"items",
"(",
")",
":",
"print",
"(",
"\" * \"",
"+",
"v",
")",
"print",
"(",
"\"Authorization/credentials required:\"",
")",
"for",
"k",
",",
"v",
"in",
"CONFIG",
"[",
"msg_type",
"]",
"[",
"\"auth\"",
"]",
".",
"items",
"(",
")",
":",
"print",
"(",
"\" * \"",
"+",
"v",
")"
] | 7789ebc960335a59ea5d319fceed3dd349023648 |
test | get_data_from_user | Get the required 'settings' from the user and return as a dict. | messages/_config.py | def get_data_from_user(msg_type):
"""Get the required 'settings' from the user and return as a dict."""
data = {}
for k, v in CONFIG[msg_type]["settings"].items():
data[k] = input(v + ": ")
return data | def get_data_from_user(msg_type):
"""Get the required 'settings' from the user and return as a dict."""
data = {}
for k, v in CONFIG[msg_type]["settings"].items():
data[k] = input(v + ": ")
return data | [
"Get",
"the",
"required",
"settings",
"from",
"the",
"user",
"and",
"return",
"as",
"a",
"dict",
"."
] | trp07/messages | python | https://github.com/trp07/messages/blob/7789ebc960335a59ea5d319fceed3dd349023648/messages/_config.py#L220-L225 | [
"def",
"get_data_from_user",
"(",
"msg_type",
")",
":",
"data",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"CONFIG",
"[",
"msg_type",
"]",
"[",
"\"settings\"",
"]",
".",
"items",
"(",
")",
":",
"data",
"[",
"k",
"]",
"=",
"input",
"(",
"v",
"+",
"\": \"",
")",
"return",
"data"
] | 7789ebc960335a59ea5d319fceed3dd349023648 |
test | get_auth_from_user | Get the required 'auth' from the user and return as a dict. | messages/_config.py | def get_auth_from_user(msg_type):
"""Get the required 'auth' from the user and return as a dict."""
auth = []
for k, v in CONFIG[msg_type]["auth"].items():
auth.append((k, getpass(v + ": ")))
return OrderedDict(auth) | def get_auth_from_user(msg_type):
"""Get the required 'auth' from the user and return as a dict."""
auth = []
for k, v in CONFIG[msg_type]["auth"].items():
auth.append((k, getpass(v + ": ")))
return OrderedDict(auth) | [
"Get",
"the",
"required",
"auth",
"from",
"the",
"user",
"and",
"return",
"as",
"a",
"dict",
"."
] | trp07/messages | python | https://github.com/trp07/messages/blob/7789ebc960335a59ea5d319fceed3dd349023648/messages/_config.py#L228-L233 | [
"def",
"get_auth_from_user",
"(",
"msg_type",
")",
":",
"auth",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"CONFIG",
"[",
"msg_type",
"]",
"[",
"\"auth\"",
"]",
".",
"items",
"(",
")",
":",
"auth",
".",
"append",
"(",
"(",
"k",
",",
"getpass",
"(",
"v",
"+",
"\": \"",
")",
")",
")",
"return",
"OrderedDict",
"(",
"auth",
")"
] | 7789ebc960335a59ea5d319fceed3dd349023648 |
test | configure_profile | Create the profile entry.
Args:
:msg_type: (str) message type to create config entry.
:profile_name: (str) name of the profile entry
:data: (dict) dict values for the 'settings'
:auth: (dict) auth parameters | messages/_config.py | def configure_profile(msg_type, profile_name, data, auth):
"""
Create the profile entry.
Args:
:msg_type: (str) message type to create config entry.
:profile_name: (str) name of the profile entry
:data: (dict) dict values for the 'settings'
:auth: (dict) auth parameters
"""
with jsonconfig.Config("messages", indent=4) as cfg:
write_data(msg_type, profile_name, data, cfg)
write_auth(msg_type, profile_name, auth, cfg)
print("[+] Configuration entry for <" + profile_name + "> created.")
print("[+] Configuration file location: " + cfg.filename) | def configure_profile(msg_type, profile_name, data, auth):
"""
Create the profile entry.
Args:
:msg_type: (str) message type to create config entry.
:profile_name: (str) name of the profile entry
:data: (dict) dict values for the 'settings'
:auth: (dict) auth parameters
"""
with jsonconfig.Config("messages", indent=4) as cfg:
write_data(msg_type, profile_name, data, cfg)
write_auth(msg_type, profile_name, auth, cfg)
print("[+] Configuration entry for <" + profile_name + "> created.")
print("[+] Configuration file location: " + cfg.filename) | [
"Create",
"the",
"profile",
"entry",
"."
] | trp07/messages | python | https://github.com/trp07/messages/blob/7789ebc960335a59ea5d319fceed3dd349023648/messages/_config.py#L236-L251 | [
"def",
"configure_profile",
"(",
"msg_type",
",",
"profile_name",
",",
"data",
",",
"auth",
")",
":",
"with",
"jsonconfig",
".",
"Config",
"(",
"\"messages\"",
",",
"indent",
"=",
"4",
")",
"as",
"cfg",
":",
"write_data",
"(",
"msg_type",
",",
"profile_name",
",",
"data",
",",
"cfg",
")",
"write_auth",
"(",
"msg_type",
",",
"profile_name",
",",
"auth",
",",
"cfg",
")",
"print",
"(",
"\"[+] Configuration entry for <\"",
"+",
"profile_name",
"+",
"\"> created.\"",
")",
"print",
"(",
"\"[+] Configuration file location: \"",
"+",
"cfg",
".",
"filename",
")"
] | 7789ebc960335a59ea5d319fceed3dd349023648 |
test | write_data | Write the settings into the data portion of the cfg.
Args:
:msg_type: (str) message type to create config entry.
:profile_name: (str) name of the profile entry
:data: (dict) dict values for the 'settings'
:cfg: (jsonconfig.Config) config instance. | messages/_config.py | def write_data(msg_type, profile_name, data, cfg):
"""
Write the settings into the data portion of the cfg.
Args:
:msg_type: (str) message type to create config entry.
:profile_name: (str) name of the profile entry
:data: (dict) dict values for the 'settings'
:cfg: (jsonconfig.Config) config instance.
"""
if profile_name not in cfg.data:
cfg.data[profile_name] = {}
cfg.data[profile_name][msg_type] = data | def write_data(msg_type, profile_name, data, cfg):
"""
Write the settings into the data portion of the cfg.
Args:
:msg_type: (str) message type to create config entry.
:profile_name: (str) name of the profile entry
:data: (dict) dict values for the 'settings'
:cfg: (jsonconfig.Config) config instance.
"""
if profile_name not in cfg.data:
cfg.data[profile_name] = {}
cfg.data[profile_name][msg_type] = data | [
"Write",
"the",
"settings",
"into",
"the",
"data",
"portion",
"of",
"the",
"cfg",
"."
] | trp07/messages | python | https://github.com/trp07/messages/blob/7789ebc960335a59ea5d319fceed3dd349023648/messages/_config.py#L254-L266 | [
"def",
"write_data",
"(",
"msg_type",
",",
"profile_name",
",",
"data",
",",
"cfg",
")",
":",
"if",
"profile_name",
"not",
"in",
"cfg",
".",
"data",
":",
"cfg",
".",
"data",
"[",
"profile_name",
"]",
"=",
"{",
"}",
"cfg",
".",
"data",
"[",
"profile_name",
"]",
"[",
"msg_type",
"]",
"=",
"data"
] | 7789ebc960335a59ea5d319fceed3dd349023648 |
test | write_auth | Write the settings into the auth portion of the cfg.
Args:
:msg_type: (str) message type to create config entry.
:profile_name: (str) name of the profile entry
:auth: (dict) auth parameters
:cfg: (jsonconfig.Config) config instance. | messages/_config.py | def write_auth(msg_type, profile_name, auth, cfg):
"""
Write the settings into the auth portion of the cfg.
Args:
:msg_type: (str) message type to create config entry.
:profile_name: (str) name of the profile entry
:auth: (dict) auth parameters
:cfg: (jsonconfig.Config) config instance.
"""
key_fmt = profile_name + "_" + msg_type
pwd = []
for k, v in CONFIG[msg_type]["auth"].items():
pwd.append(auth[k])
if len(pwd) > 1:
cfg.pwd[key_fmt] = " :: ".join(pwd)
else:
cfg.pwd[key_fmt] = pwd[0] | def write_auth(msg_type, profile_name, auth, cfg):
"""
Write the settings into the auth portion of the cfg.
Args:
:msg_type: (str) message type to create config entry.
:profile_name: (str) name of the profile entry
:auth: (dict) auth parameters
:cfg: (jsonconfig.Config) config instance.
"""
key_fmt = profile_name + "_" + msg_type
pwd = []
for k, v in CONFIG[msg_type]["auth"].items():
pwd.append(auth[k])
if len(pwd) > 1:
cfg.pwd[key_fmt] = " :: ".join(pwd)
else:
cfg.pwd[key_fmt] = pwd[0] | [
"Write",
"the",
"settings",
"into",
"the",
"auth",
"portion",
"of",
"the",
"cfg",
"."
] | trp07/messages | python | https://github.com/trp07/messages/blob/7789ebc960335a59ea5d319fceed3dd349023648/messages/_config.py#L269-L287 | [
"def",
"write_auth",
"(",
"msg_type",
",",
"profile_name",
",",
"auth",
",",
"cfg",
")",
":",
"key_fmt",
"=",
"profile_name",
"+",
"\"_\"",
"+",
"msg_type",
"pwd",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"CONFIG",
"[",
"msg_type",
"]",
"[",
"\"auth\"",
"]",
".",
"items",
"(",
")",
":",
"pwd",
".",
"append",
"(",
"auth",
"[",
"k",
"]",
")",
"if",
"len",
"(",
"pwd",
")",
">",
"1",
":",
"cfg",
".",
"pwd",
"[",
"key_fmt",
"]",
"=",
"\" :: \"",
".",
"join",
"(",
"pwd",
")",
"else",
":",
"cfg",
".",
"pwd",
"[",
"key_fmt",
"]",
"=",
"pwd",
"[",
"0",
"]"
] | 7789ebc960335a59ea5d319fceed3dd349023648 |
test | Slack._construct_message | Build the message params. | messages/slack.py | def _construct_message(self):
"""Build the message params."""
self.message["text"] = ""
if self.from_:
self.message["text"] += "From: " + self.from_ + "\n"
if self.subject:
self.message["text"] += "Subject: " + self.subject + "\n"
self.message["text"] += self.body
self._add_attachments() | def _construct_message(self):
"""Build the message params."""
self.message["text"] = ""
if self.from_:
self.message["text"] += "From: " + self.from_ + "\n"
if self.subject:
self.message["text"] += "Subject: " + self.subject + "\n"
self.message["text"] += self.body
self._add_attachments() | [
"Build",
"the",
"message",
"params",
"."
] | trp07/messages | python | https://github.com/trp07/messages/blob/7789ebc960335a59ea5d319fceed3dd349023648/messages/slack.py#L36-L45 | [
"def",
"_construct_message",
"(",
"self",
")",
":",
"self",
".",
"message",
"[",
"\"text\"",
"]",
"=",
"\"\"",
"if",
"self",
".",
"from_",
":",
"self",
".",
"message",
"[",
"\"text\"",
"]",
"+=",
"\"From: \"",
"+",
"self",
".",
"from_",
"+",
"\"\\n\"",
"if",
"self",
".",
"subject",
":",
"self",
".",
"message",
"[",
"\"text\"",
"]",
"+=",
"\"Subject: \"",
"+",
"self",
".",
"subject",
"+",
"\"\\n\"",
"self",
".",
"message",
"[",
"\"text\"",
"]",
"+=",
"self",
".",
"body",
"self",
".",
"_add_attachments",
"(",
")"
] | 7789ebc960335a59ea5d319fceed3dd349023648 |
test | Slack._add_attachments | Add attachments. | messages/slack.py | def _add_attachments(self):
"""Add attachments."""
if self.attachments:
if not isinstance(self.attachments, list):
self.attachments = [self.attachments]
self.message["attachments"] = [
{"image_url": url, "author_name": ""} for url in self.attachments
]
if self.params:
for attachment in self.message["attachments"]:
attachment.update(self.params) | def _add_attachments(self):
"""Add attachments."""
if self.attachments:
if not isinstance(self.attachments, list):
self.attachments = [self.attachments]
self.message["attachments"] = [
{"image_url": url, "author_name": ""} for url in self.attachments
]
if self.params:
for attachment in self.message["attachments"]:
attachment.update(self.params) | [
"Add",
"attachments",
"."
] | trp07/messages | python | https://github.com/trp07/messages/blob/7789ebc960335a59ea5d319fceed3dd349023648/messages/slack.py#L47-L58 | [
"def",
"_add_attachments",
"(",
"self",
")",
":",
"if",
"self",
".",
"attachments",
":",
"if",
"not",
"isinstance",
"(",
"self",
".",
"attachments",
",",
"list",
")",
":",
"self",
".",
"attachments",
"=",
"[",
"self",
".",
"attachments",
"]",
"self",
".",
"message",
"[",
"\"attachments\"",
"]",
"=",
"[",
"{",
"\"image_url\"",
":",
"url",
",",
"\"author_name\"",
":",
"\"\"",
"}",
"for",
"url",
"in",
"self",
".",
"attachments",
"]",
"if",
"self",
".",
"params",
":",
"for",
"attachment",
"in",
"self",
".",
"message",
"[",
"\"attachments\"",
"]",
":",
"attachment",
".",
"update",
"(",
"self",
".",
"params",
")"
] | 7789ebc960335a59ea5d319fceed3dd349023648 |
test | Slack.send | Send the message via HTTP POST, default is json-encoded. | messages/slack.py | def send(self, encoding="json"):
"""Send the message via HTTP POST, default is json-encoded."""
self._construct_message()
if self.verbose:
print(
"Debugging info"
"\n--------------"
"\n{} Message created.".format(timestamp())
)
if encoding == "json":
resp = requests.post(self.url, json=self.message)
elif encoding == "url":
resp = requests.post(self.url, data=self.message)
try:
resp.raise_for_status()
if resp.history and resp.history[0].status_code >= 300:
raise MessageSendError("HTTP Redirect: Possibly Invalid authentication")
elif "invalid_auth" in resp.text:
raise MessageSendError("Invalid Auth: Possibly Bad Auth Token")
except (requests.exceptions.HTTPError, MessageSendError) as e:
raise MessageSendError(e)
if self.verbose:
print(
timestamp(),
type(self).__name__,
" info:",
self.__str__(indentation="\n * "),
"\n * HTTP status code:",
resp.status_code,
)
print("Message sent.") | def send(self, encoding="json"):
"""Send the message via HTTP POST, default is json-encoded."""
self._construct_message()
if self.verbose:
print(
"Debugging info"
"\n--------------"
"\n{} Message created.".format(timestamp())
)
if encoding == "json":
resp = requests.post(self.url, json=self.message)
elif encoding == "url":
resp = requests.post(self.url, data=self.message)
try:
resp.raise_for_status()
if resp.history and resp.history[0].status_code >= 300:
raise MessageSendError("HTTP Redirect: Possibly Invalid authentication")
elif "invalid_auth" in resp.text:
raise MessageSendError("Invalid Auth: Possibly Bad Auth Token")
except (requests.exceptions.HTTPError, MessageSendError) as e:
raise MessageSendError(e)
if self.verbose:
print(
timestamp(),
type(self).__name__,
" info:",
self.__str__(indentation="\n * "),
"\n * HTTP status code:",
resp.status_code,
)
print("Message sent.") | [
"Send",
"the",
"message",
"via",
"HTTP",
"POST",
"default",
"is",
"json",
"-",
"encoded",
"."
] | trp07/messages | python | https://github.com/trp07/messages/blob/7789ebc960335a59ea5d319fceed3dd349023648/messages/slack.py#L60-L94 | [
"def",
"send",
"(",
"self",
",",
"encoding",
"=",
"\"json\"",
")",
":",
"self",
".",
"_construct_message",
"(",
")",
"if",
"self",
".",
"verbose",
":",
"print",
"(",
"\"Debugging info\"",
"\"\\n--------------\"",
"\"\\n{} Message created.\"",
".",
"format",
"(",
"timestamp",
"(",
")",
")",
")",
"if",
"encoding",
"==",
"\"json\"",
":",
"resp",
"=",
"requests",
".",
"post",
"(",
"self",
".",
"url",
",",
"json",
"=",
"self",
".",
"message",
")",
"elif",
"encoding",
"==",
"\"url\"",
":",
"resp",
"=",
"requests",
".",
"post",
"(",
"self",
".",
"url",
",",
"data",
"=",
"self",
".",
"message",
")",
"try",
":",
"resp",
".",
"raise_for_status",
"(",
")",
"if",
"resp",
".",
"history",
"and",
"resp",
".",
"history",
"[",
"0",
"]",
".",
"status_code",
">=",
"300",
":",
"raise",
"MessageSendError",
"(",
"\"HTTP Redirect: Possibly Invalid authentication\"",
")",
"elif",
"\"invalid_auth\"",
"in",
"resp",
".",
"text",
":",
"raise",
"MessageSendError",
"(",
"\"Invalid Auth: Possibly Bad Auth Token\"",
")",
"except",
"(",
"requests",
".",
"exceptions",
".",
"HTTPError",
",",
"MessageSendError",
")",
"as",
"e",
":",
"raise",
"MessageSendError",
"(",
"e",
")",
"if",
"self",
".",
"verbose",
":",
"print",
"(",
"timestamp",
"(",
")",
",",
"type",
"(",
"self",
")",
".",
"__name__",
",",
"\" info:\"",
",",
"self",
".",
"__str__",
"(",
"indentation",
"=",
"\"\\n * \"",
")",
",",
"\"\\n * HTTP status code:\"",
",",
"resp",
".",
"status_code",
",",
")",
"print",
"(",
"\"Message sent.\"",
")"
] | 7789ebc960335a59ea5d319fceed3dd349023648 |
test | SlackPost._construct_message | Set the message token/channel, then call the bas class constructor. | messages/slack.py | def _construct_message(self):
"""Set the message token/channel, then call the bas class constructor."""
self.message = {"token": self._auth, "channel": self.channel}
super()._construct_message() | def _construct_message(self):
"""Set the message token/channel, then call the bas class constructor."""
self.message = {"token": self._auth, "channel": self.channel}
super()._construct_message() | [
"Set",
"the",
"message",
"token",
"/",
"channel",
"then",
"call",
"the",
"bas",
"class",
"constructor",
"."
] | trp07/messages | python | https://github.com/trp07/messages/blob/7789ebc960335a59ea5d319fceed3dd349023648/messages/slack.py#L283-L286 | [
"def",
"_construct_message",
"(",
"self",
")",
":",
"self",
".",
"message",
"=",
"{",
"\"token\"",
":",
"self",
".",
"_auth",
",",
"\"channel\"",
":",
"self",
".",
"channel",
"}",
"super",
"(",
")",
".",
"_construct_message",
"(",
")"
] | 7789ebc960335a59ea5d319fceed3dd349023648 |
test | send | Constructs a message class and sends the message.
Defaults to sending synchronously. Set send_async=True to send
asynchronously.
Args:
:msg_type: (str) the type of message to send, i.e. 'Email'
:send_async: (bool) default is False, set True to send asynchronously.
:kwargs: (dict) keywords arguments that are required for the
various message types. See docstrings for each type.
i.e. help(messages.Email), help(messages.Twilio), etc.
Example:
>>> kwargs = {
from_: 'me@here.com',
to: 'you@there.com',
auth: 'yourPassword',
subject: 'Email Subject',
body: 'Your message to send',
attachments: ['filepath1', 'filepath2'],
}
>>> messages.send('email', **kwargs)
Message sent... | messages/api.py | def send(msg_type, send_async=False, *args, **kwargs):
"""
Constructs a message class and sends the message.
Defaults to sending synchronously. Set send_async=True to send
asynchronously.
Args:
:msg_type: (str) the type of message to send, i.e. 'Email'
:send_async: (bool) default is False, set True to send asynchronously.
:kwargs: (dict) keywords arguments that are required for the
various message types. See docstrings for each type.
i.e. help(messages.Email), help(messages.Twilio), etc.
Example:
>>> kwargs = {
from_: 'me@here.com',
to: 'you@there.com',
auth: 'yourPassword',
subject: 'Email Subject',
body: 'Your message to send',
attachments: ['filepath1', 'filepath2'],
}
>>> messages.send('email', **kwargs)
Message sent...
"""
message = message_factory(msg_type, *args, **kwargs)
try:
if send_async:
message.send_async()
else:
message.send()
except MessageSendError as e:
err_exit("Unable to send message: ", e) | def send(msg_type, send_async=False, *args, **kwargs):
"""
Constructs a message class and sends the message.
Defaults to sending synchronously. Set send_async=True to send
asynchronously.
Args:
:msg_type: (str) the type of message to send, i.e. 'Email'
:send_async: (bool) default is False, set True to send asynchronously.
:kwargs: (dict) keywords arguments that are required for the
various message types. See docstrings for each type.
i.e. help(messages.Email), help(messages.Twilio), etc.
Example:
>>> kwargs = {
from_: 'me@here.com',
to: 'you@there.com',
auth: 'yourPassword',
subject: 'Email Subject',
body: 'Your message to send',
attachments: ['filepath1', 'filepath2'],
}
>>> messages.send('email', **kwargs)
Message sent...
"""
message = message_factory(msg_type, *args, **kwargs)
try:
if send_async:
message.send_async()
else:
message.send()
except MessageSendError as e:
err_exit("Unable to send message: ", e) | [
"Constructs",
"a",
"message",
"class",
"and",
"sends",
"the",
"message",
".",
"Defaults",
"to",
"sending",
"synchronously",
".",
"Set",
"send_async",
"=",
"True",
"to",
"send",
"asynchronously",
"."
] | trp07/messages | python | https://github.com/trp07/messages/blob/7789ebc960335a59ea5d319fceed3dd349023648/messages/api.py#L29-L62 | [
"def",
"send",
"(",
"msg_type",
",",
"send_async",
"=",
"False",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"message",
"=",
"message_factory",
"(",
"msg_type",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"if",
"send_async",
":",
"message",
".",
"send_async",
"(",
")",
"else",
":",
"message",
".",
"send",
"(",
")",
"except",
"MessageSendError",
"as",
"e",
":",
"err_exit",
"(",
"\"Unable to send message: \"",
",",
"e",
")"
] | 7789ebc960335a59ea5d319fceed3dd349023648 |
test | message_factory | Factory function to return the specified message instance.
Args:
:msg_type: (str) the type of message to send, i.e. 'Email'
:msg_types: (str, list, or set) the supported message types
:kwargs: (dict) keywords arguments that are required for the
various message types. See docstrings for each type.
i.e. help(messages.Email), help(messages.Twilio), etc. | messages/api.py | def message_factory(msg_type, msg_types=MESSAGE_TYPES, *args, **kwargs):
"""
Factory function to return the specified message instance.
Args:
:msg_type: (str) the type of message to send, i.e. 'Email'
:msg_types: (str, list, or set) the supported message types
:kwargs: (dict) keywords arguments that are required for the
various message types. See docstrings for each type.
i.e. help(messages.Email), help(messages.Twilio), etc.
"""
try:
return msg_types[msg_type.lower()](*args, **kwargs)
except (UnknownProfileError, InvalidMessageInputError) as e:
err_exit("Unable to send message: ", e)
except KeyError:
raise UnsupportedMessageTypeError(msg_type, msg_types) | def message_factory(msg_type, msg_types=MESSAGE_TYPES, *args, **kwargs):
"""
Factory function to return the specified message instance.
Args:
:msg_type: (str) the type of message to send, i.e. 'Email'
:msg_types: (str, list, or set) the supported message types
:kwargs: (dict) keywords arguments that are required for the
various message types. See docstrings for each type.
i.e. help(messages.Email), help(messages.Twilio), etc.
"""
try:
return msg_types[msg_type.lower()](*args, **kwargs)
except (UnknownProfileError, InvalidMessageInputError) as e:
err_exit("Unable to send message: ", e)
except KeyError:
raise UnsupportedMessageTypeError(msg_type, msg_types) | [
"Factory",
"function",
"to",
"return",
"the",
"specified",
"message",
"instance",
"."
] | trp07/messages | python | https://github.com/trp07/messages/blob/7789ebc960335a59ea5d319fceed3dd349023648/messages/api.py#L65-L81 | [
"def",
"message_factory",
"(",
"msg_type",
",",
"msg_types",
"=",
"MESSAGE_TYPES",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"msg_types",
"[",
"msg_type",
".",
"lower",
"(",
")",
"]",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"(",
"UnknownProfileError",
",",
"InvalidMessageInputError",
")",
"as",
"e",
":",
"err_exit",
"(",
"\"Unable to send message: \"",
",",
"e",
")",
"except",
"KeyError",
":",
"raise",
"UnsupportedMessageTypeError",
"(",
"msg_type",
",",
"msg_types",
")"
] | 7789ebc960335a59ea5d319fceed3dd349023648 |
test | credential_property | A credential property factory for each message class that will set
private attributes and return obfuscated credentials when requested. | messages/_utils.py | def credential_property(cred):
"""
A credential property factory for each message class that will set
private attributes and return obfuscated credentials when requested.
"""
def getter(instance):
return "***obfuscated***"
def setter(instance, value):
private = "_" + cred
instance.__dict__[private] = value
return property(fget=getter, fset=setter) | def credential_property(cred):
"""
A credential property factory for each message class that will set
private attributes and return obfuscated credentials when requested.
"""
def getter(instance):
return "***obfuscated***"
def setter(instance, value):
private = "_" + cred
instance.__dict__[private] = value
return property(fget=getter, fset=setter) | [
"A",
"credential",
"property",
"factory",
"for",
"each",
"message",
"class",
"that",
"will",
"set",
"private",
"attributes",
"and",
"return",
"obfuscated",
"credentials",
"when",
"requested",
"."
] | trp07/messages | python | https://github.com/trp07/messages/blob/7789ebc960335a59ea5d319fceed3dd349023648/messages/_utils.py#L19-L32 | [
"def",
"credential_property",
"(",
"cred",
")",
":",
"def",
"getter",
"(",
"instance",
")",
":",
"return",
"\"***obfuscated***\"",
"def",
"setter",
"(",
"instance",
",",
"value",
")",
":",
"private",
"=",
"\"_\"",
"+",
"cred",
"instance",
".",
"__dict__",
"[",
"private",
"]",
"=",
"value",
"return",
"property",
"(",
"fget",
"=",
"getter",
",",
"fset",
"=",
"setter",
")"
] | 7789ebc960335a59ea5d319fceed3dd349023648 |
test | validate_property | A property factory that will dispatch the to a specific validator function
that will validate the user's input to ensure critical parameters are of a
specific type. | messages/_utils.py | def validate_property(attr):
"""
A property factory that will dispatch the to a specific validator function
that will validate the user's input to ensure critical parameters are of a
specific type.
"""
def getter(instance):
return instance.__dict__[attr]
def setter(instance, value):
validate_input(instance.__class__.__name__, attr, value)
instance.__dict__[attr] = value
return property(fget=getter, fset=setter) | def validate_property(attr):
"""
A property factory that will dispatch the to a specific validator function
that will validate the user's input to ensure critical parameters are of a
specific type.
"""
def getter(instance):
return instance.__dict__[attr]
def setter(instance, value):
validate_input(instance.__class__.__name__, attr, value)
instance.__dict__[attr] = value
return property(fget=getter, fset=setter) | [
"A",
"property",
"factory",
"that",
"will",
"dispatch",
"the",
"to",
"a",
"specific",
"validator",
"function",
"that",
"will",
"validate",
"the",
"user",
"s",
"input",
"to",
"ensure",
"critical",
"parameters",
"are",
"of",
"a",
"specific",
"type",
"."
] | trp07/messages | python | https://github.com/trp07/messages/blob/7789ebc960335a59ea5d319fceed3dd349023648/messages/_utils.py#L35-L49 | [
"def",
"validate_property",
"(",
"attr",
")",
":",
"def",
"getter",
"(",
"instance",
")",
":",
"return",
"instance",
".",
"__dict__",
"[",
"attr",
"]",
"def",
"setter",
"(",
"instance",
",",
"value",
")",
":",
"validate_input",
"(",
"instance",
".",
"__class__",
".",
"__name__",
",",
"attr",
",",
"value",
")",
"instance",
".",
"__dict__",
"[",
"attr",
"]",
"=",
"value",
"return",
"property",
"(",
"fget",
"=",
"getter",
",",
"fset",
"=",
"setter",
")"
] | 7789ebc960335a59ea5d319fceed3dd349023648 |
test | validate_input | Base function to validate input, dispatched via message type. | messages/_utils.py | def validate_input(msg_type, attr, value):
"""Base function to validate input, dispatched via message type."""
try:
valid = {
"Email": validate_email,
"Twilio": validate_twilio,
"SlackWebhook": validate_slackwebhook,
"SlackPost": validate_slackpost,
"TelegramBot": validate_telegrambot,
"WhatsApp": validate_whatsapp,
}[msg_type](attr, value)
except KeyError:
return 1
else:
return 0 | def validate_input(msg_type, attr, value):
"""Base function to validate input, dispatched via message type."""
try:
valid = {
"Email": validate_email,
"Twilio": validate_twilio,
"SlackWebhook": validate_slackwebhook,
"SlackPost": validate_slackpost,
"TelegramBot": validate_telegrambot,
"WhatsApp": validate_whatsapp,
}[msg_type](attr, value)
except KeyError:
return 1
else:
return 0 | [
"Base",
"function",
"to",
"validate",
"input",
"dispatched",
"via",
"message",
"type",
"."
] | trp07/messages | python | https://github.com/trp07/messages/blob/7789ebc960335a59ea5d319fceed3dd349023648/messages/_utils.py#L52-L66 | [
"def",
"validate_input",
"(",
"msg_type",
",",
"attr",
",",
"value",
")",
":",
"try",
":",
"valid",
"=",
"{",
"\"Email\"",
":",
"validate_email",
",",
"\"Twilio\"",
":",
"validate_twilio",
",",
"\"SlackWebhook\"",
":",
"validate_slackwebhook",
",",
"\"SlackPost\"",
":",
"validate_slackpost",
",",
"\"TelegramBot\"",
":",
"validate_telegrambot",
",",
"\"WhatsApp\"",
":",
"validate_whatsapp",
",",
"}",
"[",
"msg_type",
"]",
"(",
"attr",
",",
"value",
")",
"except",
"KeyError",
":",
"return",
"1",
"else",
":",
"return",
"0"
] | 7789ebc960335a59ea5d319fceed3dd349023648 |
test | check_valid | Checker function all validate_* functions below will call.
Raises InvalidMessageInputError if input is not valid as per
given func. | messages/_utils.py | def check_valid(msg_type, attr, value, func, exec_info):
"""
Checker function all validate_* functions below will call.
Raises InvalidMessageInputError if input is not valid as per
given func.
"""
if value is not None:
if isinstance(value, MutableSequence):
for v in value:
if not func(v):
raise InvalidMessageInputError(msg_type, attr, value, exec_info)
else:
if not func(value):
raise InvalidMessageInputError(msg_type, attr, value, exec_info) | def check_valid(msg_type, attr, value, func, exec_info):
"""
Checker function all validate_* functions below will call.
Raises InvalidMessageInputError if input is not valid as per
given func.
"""
if value is not None:
if isinstance(value, MutableSequence):
for v in value:
if not func(v):
raise InvalidMessageInputError(msg_type, attr, value, exec_info)
else:
if not func(value):
raise InvalidMessageInputError(msg_type, attr, value, exec_info) | [
"Checker",
"function",
"all",
"validate_",
"*",
"functions",
"below",
"will",
"call",
".",
"Raises",
"InvalidMessageInputError",
"if",
"input",
"is",
"not",
"valid",
"as",
"per",
"given",
"func",
"."
] | trp07/messages | python | https://github.com/trp07/messages/blob/7789ebc960335a59ea5d319fceed3dd349023648/messages/_utils.py#L69-L82 | [
"def",
"check_valid",
"(",
"msg_type",
",",
"attr",
",",
"value",
",",
"func",
",",
"exec_info",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"value",
",",
"MutableSequence",
")",
":",
"for",
"v",
"in",
"value",
":",
"if",
"not",
"func",
"(",
"v",
")",
":",
"raise",
"InvalidMessageInputError",
"(",
"msg_type",
",",
"attr",
",",
"value",
",",
"exec_info",
")",
"else",
":",
"if",
"not",
"func",
"(",
"value",
")",
":",
"raise",
"InvalidMessageInputError",
"(",
"msg_type",
",",
"attr",
",",
"value",
",",
"exec_info",
")"
] | 7789ebc960335a59ea5d319fceed3dd349023648 |
test | validate_twilio | Twilio input validator function. | messages/_utils.py | def validate_twilio(attr, value):
"""Twilio input validator function."""
if attr in ("from_", "to"):
check_valid("Twilio", attr, value, validus.isphone, "phone number")
elif attr in ("attachments"):
check_valid("Twilio", attr, value, validus.isurl, "url") | def validate_twilio(attr, value):
"""Twilio input validator function."""
if attr in ("from_", "to"):
check_valid("Twilio", attr, value, validus.isphone, "phone number")
elif attr in ("attachments"):
check_valid("Twilio", attr, value, validus.isurl, "url") | [
"Twilio",
"input",
"validator",
"function",
"."
] | trp07/messages | python | https://github.com/trp07/messages/blob/7789ebc960335a59ea5d319fceed3dd349023648/messages/_utils.py#L90-L95 | [
"def",
"validate_twilio",
"(",
"attr",
",",
"value",
")",
":",
"if",
"attr",
"in",
"(",
"\"from_\"",
",",
"\"to\"",
")",
":",
"check_valid",
"(",
"\"Twilio\"",
",",
"attr",
",",
"value",
",",
"validus",
".",
"isphone",
",",
"\"phone number\"",
")",
"elif",
"attr",
"in",
"(",
"\"attachments\"",
")",
":",
"check_valid",
"(",
"\"Twilio\"",
",",
"attr",
",",
"value",
",",
"validus",
".",
"isurl",
",",
"\"url\"",
")"
] | 7789ebc960335a59ea5d319fceed3dd349023648 |
test | validate_slackpost | SlackPost input validator function. | messages/_utils.py | def validate_slackpost(attr, value):
"""SlackPost input validator function."""
if attr in ("channel", "credentials"):
if not isinstance(value, str):
raise InvalidMessageInputError("SlackPost", attr, value, "string")
elif attr in ("attachments"):
check_valid("SlackPost", attr, value, validus.isurl, "url") | def validate_slackpost(attr, value):
"""SlackPost input validator function."""
if attr in ("channel", "credentials"):
if not isinstance(value, str):
raise InvalidMessageInputError("SlackPost", attr, value, "string")
elif attr in ("attachments"):
check_valid("SlackPost", attr, value, validus.isurl, "url") | [
"SlackPost",
"input",
"validator",
"function",
"."
] | trp07/messages | python | https://github.com/trp07/messages/blob/7789ebc960335a59ea5d319fceed3dd349023648/messages/_utils.py#L103-L109 | [
"def",
"validate_slackpost",
"(",
"attr",
",",
"value",
")",
":",
"if",
"attr",
"in",
"(",
"\"channel\"",
",",
"\"credentials\"",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"raise",
"InvalidMessageInputError",
"(",
"\"SlackPost\"",
",",
"attr",
",",
"value",
",",
"\"string\"",
")",
"elif",
"attr",
"in",
"(",
"\"attachments\"",
")",
":",
"check_valid",
"(",
"\"SlackPost\"",
",",
"attr",
",",
"value",
",",
"validus",
".",
"isurl",
",",
"\"url\"",
")"
] | 7789ebc960335a59ea5d319fceed3dd349023648 |
test | validate_whatsapp | WhatsApp input validator function. | messages/_utils.py | def validate_whatsapp(attr, value):
"""WhatsApp input validator function."""
if attr in ("from_", "to"):
if value is not None and "whatsapp:" in value:
value = value.split("whatsapp:+")[-1]
check_valid(
"WhatsApp",
attr,
value,
validus.isint,
"phone number starting with the '+' symbol",
)
elif attr in ("attachments"):
check_valid("WhatsApp", attr, value, validus.isurl, "url") | def validate_whatsapp(attr, value):
"""WhatsApp input validator function."""
if attr in ("from_", "to"):
if value is not None and "whatsapp:" in value:
value = value.split("whatsapp:+")[-1]
check_valid(
"WhatsApp",
attr,
value,
validus.isint,
"phone number starting with the '+' symbol",
)
elif attr in ("attachments"):
check_valid("WhatsApp", attr, value, validus.isurl, "url") | [
"WhatsApp",
"input",
"validator",
"function",
"."
] | trp07/messages | python | https://github.com/trp07/messages/blob/7789ebc960335a59ea5d319fceed3dd349023648/messages/_utils.py#L117-L130 | [
"def",
"validate_whatsapp",
"(",
"attr",
",",
"value",
")",
":",
"if",
"attr",
"in",
"(",
"\"from_\"",
",",
"\"to\"",
")",
":",
"if",
"value",
"is",
"not",
"None",
"and",
"\"whatsapp:\"",
"in",
"value",
":",
"value",
"=",
"value",
".",
"split",
"(",
"\"whatsapp:+\"",
")",
"[",
"-",
"1",
"]",
"check_valid",
"(",
"\"WhatsApp\"",
",",
"attr",
",",
"value",
",",
"validus",
".",
"isint",
",",
"\"phone number starting with the '+' symbol\"",
",",
")",
"elif",
"attr",
"in",
"(",
"\"attachments\"",
")",
":",
"check_valid",
"(",
"\"WhatsApp\"",
",",
"attr",
",",
"value",
",",
"validus",
".",
"isurl",
",",
"\"url\"",
")"
] | 7789ebc960335a59ea5d319fceed3dd349023648 |
test | _send_coroutine | Creates a running coroutine to receive message instances and send
them in a futures executor. | messages/_eventloop.py | def _send_coroutine():
"""
Creates a running coroutine to receive message instances and send
them in a futures executor.
"""
with PoolExecutor() as executor:
while True:
msg = yield
future = executor.submit(msg.send)
future.add_done_callback(_exception_handler) | def _send_coroutine():
"""
Creates a running coroutine to receive message instances and send
them in a futures executor.
"""
with PoolExecutor() as executor:
while True:
msg = yield
future = executor.submit(msg.send)
future.add_done_callback(_exception_handler) | [
"Creates",
"a",
"running",
"coroutine",
"to",
"receive",
"message",
"instances",
"and",
"send",
"them",
"in",
"a",
"futures",
"executor",
"."
] | trp07/messages | python | https://github.com/trp07/messages/blob/7789ebc960335a59ea5d319fceed3dd349023648/messages/_eventloop.py#L11-L20 | [
"def",
"_send_coroutine",
"(",
")",
":",
"with",
"PoolExecutor",
"(",
")",
"as",
"executor",
":",
"while",
"True",
":",
"msg",
"=",
"yield",
"future",
"=",
"executor",
".",
"submit",
"(",
"msg",
".",
"send",
")",
"future",
".",
"add_done_callback",
"(",
"_exception_handler",
")"
] | 7789ebc960335a59ea5d319fceed3dd349023648 |
test | MessageLoop.add_message | Add a message to the futures executor. | messages/_eventloop.py | def add_message(self, msg):
"""Add a message to the futures executor."""
try:
self._coro.send(msg)
except AttributeError:
raise UnsupportedMessageTypeError(msg.__class__.__name__) | def add_message(self, msg):
"""Add a message to the futures executor."""
try:
self._coro.send(msg)
except AttributeError:
raise UnsupportedMessageTypeError(msg.__class__.__name__) | [
"Add",
"a",
"message",
"to",
"the",
"futures",
"executor",
"."
] | trp07/messages | python | https://github.com/trp07/messages/blob/7789ebc960335a59ea5d319fceed3dd349023648/messages/_eventloop.py#L37-L42 | [
"def",
"add_message",
"(",
"self",
",",
"msg",
")",
":",
"try",
":",
"self",
".",
"_coro",
".",
"send",
"(",
"msg",
")",
"except",
"AttributeError",
":",
"raise",
"UnsupportedMessageTypeError",
"(",
"msg",
".",
"__class__",
".",
"__name__",
")"
] | 7789ebc960335a59ea5d319fceed3dd349023648 |
test | get_body_from_file | Reads message body if specified via filepath. | messages/cli.py | def get_body_from_file(kwds):
"""Reads message body if specified via filepath."""
if kwds["file"] and os.path.isfile(kwds["file"]):
kwds["body"] = open(kwds["file"], "r").read()
kwds["file"] = None | def get_body_from_file(kwds):
"""Reads message body if specified via filepath."""
if kwds["file"] and os.path.isfile(kwds["file"]):
kwds["body"] = open(kwds["file"], "r").read()
kwds["file"] = None | [
"Reads",
"message",
"body",
"if",
"specified",
"via",
"filepath",
"."
] | trp07/messages | python | https://github.com/trp07/messages/blob/7789ebc960335a59ea5d319fceed3dd349023648/messages/cli.py#L20-L24 | [
"def",
"get_body_from_file",
"(",
"kwds",
")",
":",
"if",
"kwds",
"[",
"\"file\"",
"]",
"and",
"os",
".",
"path",
".",
"isfile",
"(",
"kwds",
"[",
"\"file\"",
"]",
")",
":",
"kwds",
"[",
"\"body\"",
"]",
"=",
"open",
"(",
"kwds",
"[",
"\"file\"",
"]",
",",
"\"r\"",
")",
".",
"read",
"(",
")",
"kwds",
"[",
"\"file\"",
"]",
"=",
"None"
] | 7789ebc960335a59ea5d319fceed3dd349023648 |
test | trim_args | Gets rid of args with value of None, as well as select keys. | messages/cli.py | def trim_args(kwds):
"""Gets rid of args with value of None, as well as select keys."""
reject_key = ("type", "types", "configure")
reject_val = (None, ())
kwargs = {
k: v for k, v in kwds.items() if k not in reject_key and v not in reject_val
}
for k, v in kwargs.items():
if k in ("to", "cc", "bcc", "attachments"):
kwargs[k] = list(kwargs[k])
return kwargs | def trim_args(kwds):
"""Gets rid of args with value of None, as well as select keys."""
reject_key = ("type", "types", "configure")
reject_val = (None, ())
kwargs = {
k: v for k, v in kwds.items() if k not in reject_key and v not in reject_val
}
for k, v in kwargs.items():
if k in ("to", "cc", "bcc", "attachments"):
kwargs[k] = list(kwargs[k])
return kwargs | [
"Gets",
"rid",
"of",
"args",
"with",
"value",
"of",
"None",
"as",
"well",
"as",
"select",
"keys",
"."
] | trp07/messages | python | https://github.com/trp07/messages/blob/7789ebc960335a59ea5d319fceed3dd349023648/messages/cli.py#L27-L37 | [
"def",
"trim_args",
"(",
"kwds",
")",
":",
"reject_key",
"=",
"(",
"\"type\"",
",",
"\"types\"",
",",
"\"configure\"",
")",
"reject_val",
"=",
"(",
"None",
",",
"(",
")",
")",
"kwargs",
"=",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"kwds",
".",
"items",
"(",
")",
"if",
"k",
"not",
"in",
"reject_key",
"and",
"v",
"not",
"in",
"reject_val",
"}",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"k",
"in",
"(",
"\"to\"",
",",
"\"cc\"",
",",
"\"bcc\"",
",",
"\"attachments\"",
")",
":",
"kwargs",
"[",
"k",
"]",
"=",
"list",
"(",
"kwargs",
"[",
"k",
"]",
")",
"return",
"kwargs"
] | 7789ebc960335a59ea5d319fceed3dd349023648 |
test | send_message | Do some final preprocessing and send the message. | messages/cli.py | def send_message(msg_type, kwds):
"""Do some final preprocessing and send the message."""
if kwds["file"]:
get_body_from_file(kwds)
kwargs = trim_args(kwds)
send(msg_type, send_async=False, **kwargs) | def send_message(msg_type, kwds):
"""Do some final preprocessing and send the message."""
if kwds["file"]:
get_body_from_file(kwds)
kwargs = trim_args(kwds)
send(msg_type, send_async=False, **kwargs) | [
"Do",
"some",
"final",
"preprocessing",
"and",
"send",
"the",
"message",
"."
] | trp07/messages | python | https://github.com/trp07/messages/blob/7789ebc960335a59ea5d319fceed3dd349023648/messages/cli.py#L40-L45 | [
"def",
"send_message",
"(",
"msg_type",
",",
"kwds",
")",
":",
"if",
"kwds",
"[",
"\"file\"",
"]",
":",
"get_body_from_file",
"(",
"kwds",
")",
"kwargs",
"=",
"trim_args",
"(",
"kwds",
")",
"send",
"(",
"msg_type",
",",
"send_async",
"=",
"False",
",",
"*",
"*",
"kwargs",
")"
] | 7789ebc960335a59ea5d319fceed3dd349023648 |
test | TelegramBot.get_chat_id | Lookup chat_id of username if chat_id is unknown via API call. | messages/telegram.py | def get_chat_id(self, username):
"""Lookup chat_id of username if chat_id is unknown via API call."""
if username is not None:
chats = requests.get(self.base_url + "/getUpdates").json()
user = username.split("@")[-1]
for chat in chats["result"]:
if chat["message"]["from"]["username"] == user:
return chat["message"]["from"]["id"] | def get_chat_id(self, username):
"""Lookup chat_id of username if chat_id is unknown via API call."""
if username is not None:
chats = requests.get(self.base_url + "/getUpdates").json()
user = username.split("@")[-1]
for chat in chats["result"]:
if chat["message"]["from"]["username"] == user:
return chat["message"]["from"]["id"] | [
"Lookup",
"chat_id",
"of",
"username",
"if",
"chat_id",
"is",
"unknown",
"via",
"API",
"call",
"."
] | trp07/messages | python | https://github.com/trp07/messages/blob/7789ebc960335a59ea5d319fceed3dd349023648/messages/telegram.py#L125-L132 | [
"def",
"get_chat_id",
"(",
"self",
",",
"username",
")",
":",
"if",
"username",
"is",
"not",
"None",
":",
"chats",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"base_url",
"+",
"\"/getUpdates\"",
")",
".",
"json",
"(",
")",
"user",
"=",
"username",
".",
"split",
"(",
"\"@\"",
")",
"[",
"-",
"1",
"]",
"for",
"chat",
"in",
"chats",
"[",
"\"result\"",
"]",
":",
"if",
"chat",
"[",
"\"message\"",
"]",
"[",
"\"from\"",
"]",
"[",
"\"username\"",
"]",
"==",
"user",
":",
"return",
"chat",
"[",
"\"message\"",
"]",
"[",
"\"from\"",
"]",
"[",
"\"id\"",
"]"
] | 7789ebc960335a59ea5d319fceed3dd349023648 |
test | TelegramBot._construct_message | Build the message params. | messages/telegram.py | def _construct_message(self):
"""Build the message params."""
self.message["chat_id"] = self.chat_id
self.message["text"] = ""
if self.from_:
self.message["text"] += "From: " + self.from_ + "\n"
if self.subject:
self.message["text"] += "Subject: " + self.subject + "\n"
self.message["text"] += self.body
self.message.update(self.params) | def _construct_message(self):
"""Build the message params."""
self.message["chat_id"] = self.chat_id
self.message["text"] = ""
if self.from_:
self.message["text"] += "From: " + self.from_ + "\n"
if self.subject:
self.message["text"] += "Subject: " + self.subject + "\n"
self.message["text"] += self.body
self.message.update(self.params) | [
"Build",
"the",
"message",
"params",
"."
] | trp07/messages | python | https://github.com/trp07/messages/blob/7789ebc960335a59ea5d319fceed3dd349023648/messages/telegram.py#L134-L144 | [
"def",
"_construct_message",
"(",
"self",
")",
":",
"self",
".",
"message",
"[",
"\"chat_id\"",
"]",
"=",
"self",
".",
"chat_id",
"self",
".",
"message",
"[",
"\"text\"",
"]",
"=",
"\"\"",
"if",
"self",
".",
"from_",
":",
"self",
".",
"message",
"[",
"\"text\"",
"]",
"+=",
"\"From: \"",
"+",
"self",
".",
"from_",
"+",
"\"\\n\"",
"if",
"self",
".",
"subject",
":",
"self",
".",
"message",
"[",
"\"text\"",
"]",
"+=",
"\"Subject: \"",
"+",
"self",
".",
"subject",
"+",
"\"\\n\"",
"self",
".",
"message",
"[",
"\"text\"",
"]",
"+=",
"self",
".",
"body",
"self",
".",
"message",
".",
"update",
"(",
"self",
".",
"params",
")"
] | 7789ebc960335a59ea5d319fceed3dd349023648 |
test | TelegramBot._send_content | send via HTTP Post. | messages/telegram.py | def _send_content(self, method="/sendMessage"):
"""send via HTTP Post."""
url = self.base_url + method
try:
resp = requests.post(url, json=self.message)
resp.raise_for_status()
except requests.exceptions.HTTPError as e:
raise MessageSendError(e)
if self.verbose:
if method == "/sendMessage":
content_type = "Message body"
elif method == "/sendDocument":
content_type = "Attachment: " + self.message["document"]
print(timestamp(), content_type, "sent.") | def _send_content(self, method="/sendMessage"):
"""send via HTTP Post."""
url = self.base_url + method
try:
resp = requests.post(url, json=self.message)
resp.raise_for_status()
except requests.exceptions.HTTPError as e:
raise MessageSendError(e)
if self.verbose:
if method == "/sendMessage":
content_type = "Message body"
elif method == "/sendDocument":
content_type = "Attachment: " + self.message["document"]
print(timestamp(), content_type, "sent.") | [
"send",
"via",
"HTTP",
"Post",
"."
] | trp07/messages | python | https://github.com/trp07/messages/blob/7789ebc960335a59ea5d319fceed3dd349023648/messages/telegram.py#L146-L161 | [
"def",
"_send_content",
"(",
"self",
",",
"method",
"=",
"\"/sendMessage\"",
")",
":",
"url",
"=",
"self",
".",
"base_url",
"+",
"method",
"try",
":",
"resp",
"=",
"requests",
".",
"post",
"(",
"url",
",",
"json",
"=",
"self",
".",
"message",
")",
"resp",
".",
"raise_for_status",
"(",
")",
"except",
"requests",
".",
"exceptions",
".",
"HTTPError",
"as",
"e",
":",
"raise",
"MessageSendError",
"(",
"e",
")",
"if",
"self",
".",
"verbose",
":",
"if",
"method",
"==",
"\"/sendMessage\"",
":",
"content_type",
"=",
"\"Message body\"",
"elif",
"method",
"==",
"\"/sendDocument\"",
":",
"content_type",
"=",
"\"Attachment: \"",
"+",
"self",
".",
"message",
"[",
"\"document\"",
"]",
"print",
"(",
"timestamp",
"(",
")",
",",
"content_type",
",",
"\"sent.\"",
")"
] | 7789ebc960335a59ea5d319fceed3dd349023648 |
test | TelegramBot.send | Start sending the message and attachments. | messages/telegram.py | def send(self):
"""Start sending the message and attachments."""
self._construct_message()
if self.verbose:
print(
"Debugging info"
"\n--------------"
"\n{} Message created.".format(timestamp())
)
self._send_content("/sendMessage")
if self.attachments:
if isinstance(self.attachments, str):
self.attachments = [self.attachments]
for a in self.attachments:
self.message["document"] = a
self._send_content(method="/sendDocument")
if self.verbose:
print(
timestamp(),
type(self).__name__ + " info:",
self.__str__(indentation="\n * "),
)
print("Message sent.") | def send(self):
"""Start sending the message and attachments."""
self._construct_message()
if self.verbose:
print(
"Debugging info"
"\n--------------"
"\n{} Message created.".format(timestamp())
)
self._send_content("/sendMessage")
if self.attachments:
if isinstance(self.attachments, str):
self.attachments = [self.attachments]
for a in self.attachments:
self.message["document"] = a
self._send_content(method="/sendDocument")
if self.verbose:
print(
timestamp(),
type(self).__name__ + " info:",
self.__str__(indentation="\n * "),
)
print("Message sent.") | [
"Start",
"sending",
"the",
"message",
"and",
"attachments",
"."
] | trp07/messages | python | https://github.com/trp07/messages/blob/7789ebc960335a59ea5d319fceed3dd349023648/messages/telegram.py#L163-L190 | [
"def",
"send",
"(",
"self",
")",
":",
"self",
".",
"_construct_message",
"(",
")",
"if",
"self",
".",
"verbose",
":",
"print",
"(",
"\"Debugging info\"",
"\"\\n--------------\"",
"\"\\n{} Message created.\"",
".",
"format",
"(",
"timestamp",
"(",
")",
")",
")",
"self",
".",
"_send_content",
"(",
"\"/sendMessage\"",
")",
"if",
"self",
".",
"attachments",
":",
"if",
"isinstance",
"(",
"self",
".",
"attachments",
",",
"str",
")",
":",
"self",
".",
"attachments",
"=",
"[",
"self",
".",
"attachments",
"]",
"for",
"a",
"in",
"self",
".",
"attachments",
":",
"self",
".",
"message",
"[",
"\"document\"",
"]",
"=",
"a",
"self",
".",
"_send_content",
"(",
"method",
"=",
"\"/sendDocument\"",
")",
"if",
"self",
".",
"verbose",
":",
"print",
"(",
"timestamp",
"(",
")",
",",
"type",
"(",
"self",
")",
".",
"__name__",
"+",
"\" info:\"",
",",
"self",
".",
"__str__",
"(",
"indentation",
"=",
"\"\\n * \"",
")",
",",
")",
"print",
"(",
"\"Message sent.\"",
")"
] | 7789ebc960335a59ea5d319fceed3dd349023648 |
test | Twilio.send | Send the SMS/MMS message.
Set self.sid to return code of message. | messages/text.py | def send(self):
"""
Send the SMS/MMS message.
Set self.sid to return code of message.
"""
url = (
"https://api.twilio.com/2010-04-01/Accounts/"
+ self._auth[0]
+ "/Messages.json"
)
data = {
"From": self.from_,
"To": self.to,
"Body": self.body,
"MediaUrl": self.attachments,
}
if self.verbose:
print(
"Debugging info"
"\n--------------"
"\n{} Message created.".format(timestamp())
)
try:
resp = requests.post(url, data=data, auth=(self._auth[0], self._auth[1]))
resp.raise_for_status()
except requests.exceptions.RequestException as e:
exc = "{}\n{}".format(e, resp.json()["message"])
raise MessageSendError(exc)
self.sid = resp.json()["sid"]
if self.verbose:
print(
timestamp(),
type(self).__name__ + " info:",
self.__str__(indentation="\n * "),
"\n * HTTP status code:",
resp.status_code,
)
print("Message sent.")
return resp | def send(self):
"""
Send the SMS/MMS message.
Set self.sid to return code of message.
"""
url = (
"https://api.twilio.com/2010-04-01/Accounts/"
+ self._auth[0]
+ "/Messages.json"
)
data = {
"From": self.from_,
"To": self.to,
"Body": self.body,
"MediaUrl": self.attachments,
}
if self.verbose:
print(
"Debugging info"
"\n--------------"
"\n{} Message created.".format(timestamp())
)
try:
resp = requests.post(url, data=data, auth=(self._auth[0], self._auth[1]))
resp.raise_for_status()
except requests.exceptions.RequestException as e:
exc = "{}\n{}".format(e, resp.json()["message"])
raise MessageSendError(exc)
self.sid = resp.json()["sid"]
if self.verbose:
print(
timestamp(),
type(self).__name__ + " info:",
self.__str__(indentation="\n * "),
"\n * HTTP status code:",
resp.status_code,
)
print("Message sent.")
return resp | [
"Send",
"the",
"SMS",
"/",
"MMS",
"message",
".",
"Set",
"self",
".",
"sid",
"to",
"return",
"code",
"of",
"message",
"."
] | trp07/messages | python | https://github.com/trp07/messages/blob/7789ebc960335a59ea5d319fceed3dd349023648/messages/text.py#L111-L155 | [
"def",
"send",
"(",
"self",
")",
":",
"url",
"=",
"(",
"\"https://api.twilio.com/2010-04-01/Accounts/\"",
"+",
"self",
".",
"_auth",
"[",
"0",
"]",
"+",
"\"/Messages.json\"",
")",
"data",
"=",
"{",
"\"From\"",
":",
"self",
".",
"from_",
",",
"\"To\"",
":",
"self",
".",
"to",
",",
"\"Body\"",
":",
"self",
".",
"body",
",",
"\"MediaUrl\"",
":",
"self",
".",
"attachments",
",",
"}",
"if",
"self",
".",
"verbose",
":",
"print",
"(",
"\"Debugging info\"",
"\"\\n--------------\"",
"\"\\n{} Message created.\"",
".",
"format",
"(",
"timestamp",
"(",
")",
")",
")",
"try",
":",
"resp",
"=",
"requests",
".",
"post",
"(",
"url",
",",
"data",
"=",
"data",
",",
"auth",
"=",
"(",
"self",
".",
"_auth",
"[",
"0",
"]",
",",
"self",
".",
"_auth",
"[",
"1",
"]",
")",
")",
"resp",
".",
"raise_for_status",
"(",
")",
"except",
"requests",
".",
"exceptions",
".",
"RequestException",
"as",
"e",
":",
"exc",
"=",
"\"{}\\n{}\"",
".",
"format",
"(",
"e",
",",
"resp",
".",
"json",
"(",
")",
"[",
"\"message\"",
"]",
")",
"raise",
"MessageSendError",
"(",
"exc",
")",
"self",
".",
"sid",
"=",
"resp",
".",
"json",
"(",
")",
"[",
"\"sid\"",
"]",
"if",
"self",
".",
"verbose",
":",
"print",
"(",
"timestamp",
"(",
")",
",",
"type",
"(",
"self",
")",
".",
"__name__",
"+",
"\" info:\"",
",",
"self",
".",
"__str__",
"(",
"indentation",
"=",
"\"\\n * \"",
")",
",",
"\"\\n * HTTP status code:\"",
",",
"resp",
".",
"status_code",
",",
")",
"print",
"(",
"\"Message sent.\"",
")",
"return",
"resp"
] | 7789ebc960335a59ea5d319fceed3dd349023648 |
test | Email.get_server | Return an SMTP servername guess from outgoing email address. | messages/email_.py | def get_server(address=None):
"""Return an SMTP servername guess from outgoing email address."""
if address:
domain = address.split("@")[1]
try:
return SMTP_SERVERS[domain]
except KeyError:
return ("smtp." + domain, 465)
return (None, None) | def get_server(address=None):
"""Return an SMTP servername guess from outgoing email address."""
if address:
domain = address.split("@")[1]
try:
return SMTP_SERVERS[domain]
except KeyError:
return ("smtp." + domain, 465)
return (None, None) | [
"Return",
"an",
"SMTP",
"servername",
"guess",
"from",
"outgoing",
"email",
"address",
"."
] | trp07/messages | python | https://github.com/trp07/messages/blob/7789ebc960335a59ea5d319fceed3dd349023648/messages/email_.py#L161-L169 | [
"def",
"get_server",
"(",
"address",
"=",
"None",
")",
":",
"if",
"address",
":",
"domain",
"=",
"address",
".",
"split",
"(",
"\"@\"",
")",
"[",
"1",
"]",
"try",
":",
"return",
"SMTP_SERVERS",
"[",
"domain",
"]",
"except",
"KeyError",
":",
"return",
"(",
"\"smtp.\"",
"+",
"domain",
",",
"465",
")",
"return",
"(",
"None",
",",
"None",
")"
] | 7789ebc960335a59ea5d319fceed3dd349023648 |
test | Email._generate_email | Put the parts of the email together. | messages/email_.py | def _generate_email(self):
"""Put the parts of the email together."""
self.message = MIMEMultipart()
self._add_header()
self._add_body()
self._add_attachments() | def _generate_email(self):
"""Put the parts of the email together."""
self.message = MIMEMultipart()
self._add_header()
self._add_body()
self._add_attachments() | [
"Put",
"the",
"parts",
"of",
"the",
"email",
"together",
"."
] | trp07/messages | python | https://github.com/trp07/messages/blob/7789ebc960335a59ea5d319fceed3dd349023648/messages/email_.py#L185-L190 | [
"def",
"_generate_email",
"(",
"self",
")",
":",
"self",
".",
"message",
"=",
"MIMEMultipart",
"(",
")",
"self",
".",
"_add_header",
"(",
")",
"self",
".",
"_add_body",
"(",
")",
"self",
".",
"_add_attachments",
"(",
")"
] | 7789ebc960335a59ea5d319fceed3dd349023648 |
test | Email._add_header | Add email header info. | messages/email_.py | def _add_header(self):
"""Add email header info."""
self.message["From"] = self.from_
self.message["Subject"] = self.subject
if self.to:
self.message["To"] = self.list_to_string(self.to)
if self.cc:
self.message["Cc"] = self.list_to_string(self.cc)
if self.bcc:
self.message["Bcc"] = self.list_to_string(self.bcc) | def _add_header(self):
"""Add email header info."""
self.message["From"] = self.from_
self.message["Subject"] = self.subject
if self.to:
self.message["To"] = self.list_to_string(self.to)
if self.cc:
self.message["Cc"] = self.list_to_string(self.cc)
if self.bcc:
self.message["Bcc"] = self.list_to_string(self.bcc) | [
"Add",
"email",
"header",
"info",
"."
] | trp07/messages | python | https://github.com/trp07/messages/blob/7789ebc960335a59ea5d319fceed3dd349023648/messages/email_.py#L192-L201 | [
"def",
"_add_header",
"(",
"self",
")",
":",
"self",
".",
"message",
"[",
"\"From\"",
"]",
"=",
"self",
".",
"from_",
"self",
".",
"message",
"[",
"\"Subject\"",
"]",
"=",
"self",
".",
"subject",
"if",
"self",
".",
"to",
":",
"self",
".",
"message",
"[",
"\"To\"",
"]",
"=",
"self",
".",
"list_to_string",
"(",
"self",
".",
"to",
")",
"if",
"self",
".",
"cc",
":",
"self",
".",
"message",
"[",
"\"Cc\"",
"]",
"=",
"self",
".",
"list_to_string",
"(",
"self",
".",
"cc",
")",
"if",
"self",
".",
"bcc",
":",
"self",
".",
"message",
"[",
"\"Bcc\"",
"]",
"=",
"self",
".",
"list_to_string",
"(",
"self",
".",
"bcc",
")"
] | 7789ebc960335a59ea5d319fceed3dd349023648 |
test | Email._add_body | Add body content of email. | messages/email_.py | def _add_body(self):
"""Add body content of email."""
if self.body:
b = MIMEText("text", "plain")
b.set_payload(self.body)
self.message.attach(b) | def _add_body(self):
"""Add body content of email."""
if self.body:
b = MIMEText("text", "plain")
b.set_payload(self.body)
self.message.attach(b) | [
"Add",
"body",
"content",
"of",
"email",
"."
] | trp07/messages | python | https://github.com/trp07/messages/blob/7789ebc960335a59ea5d319fceed3dd349023648/messages/email_.py#L203-L208 | [
"def",
"_add_body",
"(",
"self",
")",
":",
"if",
"self",
".",
"body",
":",
"b",
"=",
"MIMEText",
"(",
"\"text\"",
",",
"\"plain\"",
")",
"b",
".",
"set_payload",
"(",
"self",
".",
"body",
")",
"self",
".",
"message",
".",
"attach",
"(",
"b",
")"
] | 7789ebc960335a59ea5d319fceed3dd349023648 |
test | Email._add_attachments | Add required attachments. | messages/email_.py | def _add_attachments(self):
"""Add required attachments."""
num_attached = 0
if self.attachments:
if isinstance(self.attachments, str):
self.attachments = [self.attachments]
for item in self.attachments:
doc = MIMEApplication(open(item, "rb").read())
doc.add_header("Content-Disposition", "attachment", filename=item)
self.message.attach(doc)
num_attached += 1
return num_attached | def _add_attachments(self):
"""Add required attachments."""
num_attached = 0
if self.attachments:
if isinstance(self.attachments, str):
self.attachments = [self.attachments]
for item in self.attachments:
doc = MIMEApplication(open(item, "rb").read())
doc.add_header("Content-Disposition", "attachment", filename=item)
self.message.attach(doc)
num_attached += 1
return num_attached | [
"Add",
"required",
"attachments",
"."
] | trp07/messages | python | https://github.com/trp07/messages/blob/7789ebc960335a59ea5d319fceed3dd349023648/messages/email_.py#L210-L222 | [
"def",
"_add_attachments",
"(",
"self",
")",
":",
"num_attached",
"=",
"0",
"if",
"self",
".",
"attachments",
":",
"if",
"isinstance",
"(",
"self",
".",
"attachments",
",",
"str",
")",
":",
"self",
".",
"attachments",
"=",
"[",
"self",
".",
"attachments",
"]",
"for",
"item",
"in",
"self",
".",
"attachments",
":",
"doc",
"=",
"MIMEApplication",
"(",
"open",
"(",
"item",
",",
"\"rb\"",
")",
".",
"read",
"(",
")",
")",
"doc",
".",
"add_header",
"(",
"\"Content-Disposition\"",
",",
"\"attachment\"",
",",
"filename",
"=",
"item",
")",
"self",
".",
"message",
".",
"attach",
"(",
"doc",
")",
"num_attached",
"+=",
"1",
"return",
"num_attached"
] | 7789ebc960335a59ea5d319fceed3dd349023648 |
test | Email._get_session | Start session with email server. | messages/email_.py | def _get_session(self):
"""Start session with email server."""
if self.port in (465, "465"):
session = self._get_ssl()
elif self.port in (587, "587"):
session = self._get_tls()
try:
session.login(self.from_, self._auth)
except SMTPResponseException as e:
raise MessageSendError(e.smtp_error.decode("unicode_escape"))
return session | def _get_session(self):
"""Start session with email server."""
if self.port in (465, "465"):
session = self._get_ssl()
elif self.port in (587, "587"):
session = self._get_tls()
try:
session.login(self.from_, self._auth)
except SMTPResponseException as e:
raise MessageSendError(e.smtp_error.decode("unicode_escape"))
return session | [
"Start",
"session",
"with",
"email",
"server",
"."
] | trp07/messages | python | https://github.com/trp07/messages/blob/7789ebc960335a59ea5d319fceed3dd349023648/messages/email_.py#L224-L236 | [
"def",
"_get_session",
"(",
"self",
")",
":",
"if",
"self",
".",
"port",
"in",
"(",
"465",
",",
"\"465\"",
")",
":",
"session",
"=",
"self",
".",
"_get_ssl",
"(",
")",
"elif",
"self",
".",
"port",
"in",
"(",
"587",
",",
"\"587\"",
")",
":",
"session",
"=",
"self",
".",
"_get_tls",
"(",
")",
"try",
":",
"session",
".",
"login",
"(",
"self",
".",
"from_",
",",
"self",
".",
"_auth",
")",
"except",
"SMTPResponseException",
"as",
"e",
":",
"raise",
"MessageSendError",
"(",
"e",
".",
"smtp_error",
".",
"decode",
"(",
"\"unicode_escape\"",
")",
")",
"return",
"session"
] | 7789ebc960335a59ea5d319fceed3dd349023648 |
test | Email._get_ssl | Get an SMTP session with SSL. | messages/email_.py | def _get_ssl(self):
"""Get an SMTP session with SSL."""
return smtplib.SMTP_SSL(
self.server, self.port, context=ssl.create_default_context()
) | def _get_ssl(self):
"""Get an SMTP session with SSL."""
return smtplib.SMTP_SSL(
self.server, self.port, context=ssl.create_default_context()
) | [
"Get",
"an",
"SMTP",
"session",
"with",
"SSL",
"."
] | trp07/messages | python | https://github.com/trp07/messages/blob/7789ebc960335a59ea5d319fceed3dd349023648/messages/email_.py#L238-L242 | [
"def",
"_get_ssl",
"(",
"self",
")",
":",
"return",
"smtplib",
".",
"SMTP_SSL",
"(",
"self",
".",
"server",
",",
"self",
".",
"port",
",",
"context",
"=",
"ssl",
".",
"create_default_context",
"(",
")",
")"
] | 7789ebc960335a59ea5d319fceed3dd349023648 |
test | Email._get_tls | Get an SMTP session with TLS. | messages/email_.py | def _get_tls(self):
"""Get an SMTP session with TLS."""
session = smtplib.SMTP(self.server, self.port)
session.ehlo()
session.starttls(context=ssl.create_default_context())
session.ehlo()
return session | def _get_tls(self):
"""Get an SMTP session with TLS."""
session = smtplib.SMTP(self.server, self.port)
session.ehlo()
session.starttls(context=ssl.create_default_context())
session.ehlo()
return session | [
"Get",
"an",
"SMTP",
"session",
"with",
"TLS",
"."
] | trp07/messages | python | https://github.com/trp07/messages/blob/7789ebc960335a59ea5d319fceed3dd349023648/messages/email_.py#L244-L250 | [
"def",
"_get_tls",
"(",
"self",
")",
":",
"session",
"=",
"smtplib",
".",
"SMTP",
"(",
"self",
".",
"server",
",",
"self",
".",
"port",
")",
"session",
".",
"ehlo",
"(",
")",
"session",
".",
"starttls",
"(",
"context",
"=",
"ssl",
".",
"create_default_context",
"(",
")",
")",
"session",
".",
"ehlo",
"(",
")",
"return",
"session"
] | 7789ebc960335a59ea5d319fceed3dd349023648 |
test | Email.send | Send the message.
First, a message is constructed, then a session with the email
servers is created, finally the message is sent and the session
is stopped. | messages/email_.py | def send(self):
"""
Send the message.
First, a message is constructed, then a session with the email
servers is created, finally the message is sent and the session
is stopped.
"""
self._generate_email()
if self.verbose:
print(
"Debugging info"
"\n--------------"
"\n{} Message created.".format(timestamp())
)
recipients = []
for i in (self.to, self.cc, self.bcc):
if i:
if isinstance(i, MutableSequence):
recipients += i
else:
recipients.append(i)
session = self._get_session()
if self.verbose:
print(timestamp(), "Login successful.")
session.sendmail(self.from_, recipients, self.message.as_string())
session.quit()
if self.verbose:
print(timestamp(), "Logged out.")
if self.verbose:
print(
timestamp(),
type(self).__name__ + " info:",
self.__str__(indentation="\n * "),
)
print("Message sent.") | def send(self):
"""
Send the message.
First, a message is constructed, then a session with the email
servers is created, finally the message is sent and the session
is stopped.
"""
self._generate_email()
if self.verbose:
print(
"Debugging info"
"\n--------------"
"\n{} Message created.".format(timestamp())
)
recipients = []
for i in (self.to, self.cc, self.bcc):
if i:
if isinstance(i, MutableSequence):
recipients += i
else:
recipients.append(i)
session = self._get_session()
if self.verbose:
print(timestamp(), "Login successful.")
session.sendmail(self.from_, recipients, self.message.as_string())
session.quit()
if self.verbose:
print(timestamp(), "Logged out.")
if self.verbose:
print(
timestamp(),
type(self).__name__ + " info:",
self.__str__(indentation="\n * "),
)
print("Message sent.") | [
"Send",
"the",
"message",
".",
"First",
"a",
"message",
"is",
"constructed",
"then",
"a",
"session",
"with",
"the",
"email",
"servers",
"is",
"created",
"finally",
"the",
"message",
"is",
"sent",
"and",
"the",
"session",
"is",
"stopped",
"."
] | trp07/messages | python | https://github.com/trp07/messages/blob/7789ebc960335a59ea5d319fceed3dd349023648/messages/email_.py#L252-L293 | [
"def",
"send",
"(",
"self",
")",
":",
"self",
".",
"_generate_email",
"(",
")",
"if",
"self",
".",
"verbose",
":",
"print",
"(",
"\"Debugging info\"",
"\"\\n--------------\"",
"\"\\n{} Message created.\"",
".",
"format",
"(",
"timestamp",
"(",
")",
")",
")",
"recipients",
"=",
"[",
"]",
"for",
"i",
"in",
"(",
"self",
".",
"to",
",",
"self",
".",
"cc",
",",
"self",
".",
"bcc",
")",
":",
"if",
"i",
":",
"if",
"isinstance",
"(",
"i",
",",
"MutableSequence",
")",
":",
"recipients",
"+=",
"i",
"else",
":",
"recipients",
".",
"append",
"(",
"i",
")",
"session",
"=",
"self",
".",
"_get_session",
"(",
")",
"if",
"self",
".",
"verbose",
":",
"print",
"(",
"timestamp",
"(",
")",
",",
"\"Login successful.\"",
")",
"session",
".",
"sendmail",
"(",
"self",
".",
"from_",
",",
"recipients",
",",
"self",
".",
"message",
".",
"as_string",
"(",
")",
")",
"session",
".",
"quit",
"(",
")",
"if",
"self",
".",
"verbose",
":",
"print",
"(",
"timestamp",
"(",
")",
",",
"\"Logged out.\"",
")",
"if",
"self",
".",
"verbose",
":",
"print",
"(",
"timestamp",
"(",
")",
",",
"type",
"(",
"self",
")",
".",
"__name__",
"+",
"\" info:\"",
",",
"self",
".",
"__str__",
"(",
"indentation",
"=",
"\"\\n * \"",
")",
",",
")",
"print",
"(",
"\"Message sent.\"",
")"
] | 7789ebc960335a59ea5d319fceed3dd349023648 |
test | FileType.delete | Remove tags from a file. | mutagen/__init__.py | def delete(self, filename=None):
"""Remove tags from a file."""
if self.tags is not None:
if filename is None:
filename = self.filename
else:
warnings.warn(
"delete(filename=...) is deprecated, reload the file",
DeprecationWarning)
return self.tags.delete(filename) | def delete(self, filename=None):
"""Remove tags from a file."""
if self.tags is not None:
if filename is None:
filename = self.filename
else:
warnings.warn(
"delete(filename=...) is deprecated, reload the file",
DeprecationWarning)
return self.tags.delete(filename) | [
"Remove",
"tags",
"from",
"a",
"file",
"."
] | LordSputnik/mutagen | python | https://github.com/LordSputnik/mutagen/blob/38e62c8dc35c72b16554f5dbe7c0fde91acc3411/mutagen/__init__.py#L138-L148 | [
"def",
"delete",
"(",
"self",
",",
"filename",
"=",
"None",
")",
":",
"if",
"self",
".",
"tags",
"is",
"not",
"None",
":",
"if",
"filename",
"is",
"None",
":",
"filename",
"=",
"self",
".",
"filename",
"else",
":",
"warnings",
".",
"warn",
"(",
"\"delete(filename=...) is deprecated, reload the file\"",
",",
"DeprecationWarning",
")",
"return",
"self",
".",
"tags",
".",
"delete",
"(",
"filename",
")"
] | 38e62c8dc35c72b16554f5dbe7c0fde91acc3411 |
test | FileType.save | Save metadata tags. | mutagen/__init__.py | def save(self, filename=None, **kwargs):
"""Save metadata tags."""
if filename is None:
filename = self.filename
else:
warnings.warn(
"save(filename=...) is deprecated, reload the file",
DeprecationWarning)
if self.tags is not None:
return self.tags.save(filename, **kwargs)
else:
raise ValueError("no tags in file") | def save(self, filename=None, **kwargs):
"""Save metadata tags."""
if filename is None:
filename = self.filename
else:
warnings.warn(
"save(filename=...) is deprecated, reload the file",
DeprecationWarning)
if self.tags is not None:
return self.tags.save(filename, **kwargs)
else:
raise ValueError("no tags in file") | [
"Save",
"metadata",
"tags",
"."
] | LordSputnik/mutagen | python | https://github.com/LordSputnik/mutagen/blob/38e62c8dc35c72b16554f5dbe7c0fde91acc3411/mutagen/__init__.py#L150-L162 | [
"def",
"save",
"(",
"self",
",",
"filename",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"filename",
"is",
"None",
":",
"filename",
"=",
"self",
".",
"filename",
"else",
":",
"warnings",
".",
"warn",
"(",
"\"save(filename=...) is deprecated, reload the file\"",
",",
"DeprecationWarning",
")",
"if",
"self",
".",
"tags",
"is",
"not",
"None",
":",
"return",
"self",
".",
"tags",
".",
"save",
"(",
"filename",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"no tags in file\"",
")"
] | 38e62c8dc35c72b16554f5dbe7c0fde91acc3411 |
test | Image.unload | Releases renderer resources associated with this image. | bacon/image.py | def unload(self):
'''Releases renderer resources associated with this image.'''
if self._handle != -1:
lib.UnloadImage(self._handle)
self._handle = -1 | def unload(self):
'''Releases renderer resources associated with this image.'''
if self._handle != -1:
lib.UnloadImage(self._handle)
self._handle = -1 | [
"Releases",
"renderer",
"resources",
"associated",
"with",
"this",
"image",
"."
] | aholkner/bacon | python | https://github.com/aholkner/bacon/blob/edf3810dcb211942d392a8637945871399b0650d/bacon/image.py#L106-L110 | [
"def",
"unload",
"(",
"self",
")",
":",
"if",
"self",
".",
"_handle",
"!=",
"-",
"1",
":",
"lib",
".",
"UnloadImage",
"(",
"self",
".",
"_handle",
")",
"self",
".",
"_handle",
"=",
"-",
"1"
] | edf3810dcb211942d392a8637945871399b0650d |
test | Image.get_region | Get an image that refers to the given rectangle within this image. The image data is not actually
copied; if the image region is rendered into, it will affect this image.
:param int x1: left edge of the image region to return
:param int y1: top edge of the image region to return
:param int x2: right edge of the image region to return
:param int y2: bottom edge of the image region to return
:return: :class:`Image` | bacon/image.py | def get_region(self, x1, y1, x2, y2):
'''Get an image that refers to the given rectangle within this image. The image data is not actually
copied; if the image region is rendered into, it will affect this image.
:param int x1: left edge of the image region to return
:param int y1: top edge of the image region to return
:param int x2: right edge of the image region to return
:param int y2: bottom edge of the image region to return
:return: :class:`Image`
'''
handle = c_int()
lib.GetImageRegion(byref(handle), self._handle, x1, y1, x2, y2)
return Image(width = x2 - x1, height = y2 - y1, content_scale = self._content_scale, handle = handle) | def get_region(self, x1, y1, x2, y2):
'''Get an image that refers to the given rectangle within this image. The image data is not actually
copied; if the image region is rendered into, it will affect this image.
:param int x1: left edge of the image region to return
:param int y1: top edge of the image region to return
:param int x2: right edge of the image region to return
:param int y2: bottom edge of the image region to return
:return: :class:`Image`
'''
handle = c_int()
lib.GetImageRegion(byref(handle), self._handle, x1, y1, x2, y2)
return Image(width = x2 - x1, height = y2 - y1, content_scale = self._content_scale, handle = handle) | [
"Get",
"an",
"image",
"that",
"refers",
"to",
"the",
"given",
"rectangle",
"within",
"this",
"image",
".",
"The",
"image",
"data",
"is",
"not",
"actually",
"copied",
";",
"if",
"the",
"image",
"region",
"is",
"rendered",
"into",
"it",
"will",
"affect",
"this",
"image",
"."
] | aholkner/bacon | python | https://github.com/aholkner/bacon/blob/edf3810dcb211942d392a8637945871399b0650d/bacon/image.py#L127-L139 | [
"def",
"get_region",
"(",
"self",
",",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
")",
":",
"handle",
"=",
"c_int",
"(",
")",
"lib",
".",
"GetImageRegion",
"(",
"byref",
"(",
"handle",
")",
",",
"self",
".",
"_handle",
",",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
")",
"return",
"Image",
"(",
"width",
"=",
"x2",
"-",
"x1",
",",
"height",
"=",
"y2",
"-",
"y1",
",",
"content_scale",
"=",
"self",
".",
"_content_scale",
",",
"handle",
"=",
"handle",
")"
] | edf3810dcb211942d392a8637945871399b0650d |
test | main | main program loop | native/Vendor/FreeType/src/tools/docmaker/docbeauty.py | def main( argv ):
"""main program loop"""
global output_dir
try:
opts, args = getopt.getopt( sys.argv[1:], \
"hb", \
["help", "backup"] )
except getopt.GetoptError:
usage()
sys.exit( 2 )
if args == []:
usage()
sys.exit( 1 )
# process options
#
output_dir = None
do_backup = None
for opt in opts:
if opt[0] in ( "-h", "--help" ):
usage()
sys.exit( 0 )
if opt[0] in ( "-b", "--backup" ):
do_backup = 1
# create context and processor
source_processor = SourceProcessor()
# retrieve the list of files to process
file_list = make_file_list( args )
for filename in file_list:
source_processor.parse_file( filename )
for block in source_processor.blocks:
beautify_block( block )
new_name = filename + ".new"
ok = None
try:
file = open( new_name, "wt" )
for block in source_processor.blocks:
for line in block.lines:
file.write( line )
file.write( "\n" )
file.close()
except:
ok = 0 | def main( argv ):
"""main program loop"""
global output_dir
try:
opts, args = getopt.getopt( sys.argv[1:], \
"hb", \
["help", "backup"] )
except getopt.GetoptError:
usage()
sys.exit( 2 )
if args == []:
usage()
sys.exit( 1 )
# process options
#
output_dir = None
do_backup = None
for opt in opts:
if opt[0] in ( "-h", "--help" ):
usage()
sys.exit( 0 )
if opt[0] in ( "-b", "--backup" ):
do_backup = 1
# create context and processor
source_processor = SourceProcessor()
# retrieve the list of files to process
file_list = make_file_list( args )
for filename in file_list:
source_processor.parse_file( filename )
for block in source_processor.blocks:
beautify_block( block )
new_name = filename + ".new"
ok = None
try:
file = open( new_name, "wt" )
for block in source_processor.blocks:
for line in block.lines:
file.write( line )
file.write( "\n" )
file.close()
except:
ok = 0 | [
"main",
"program",
"loop"
] | aholkner/bacon | python | https://github.com/aholkner/bacon/blob/edf3810dcb211942d392a8637945871399b0650d/native/Vendor/FreeType/src/tools/docmaker/docbeauty.py#L52-L104 | [
"def",
"main",
"(",
"argv",
")",
":",
"global",
"output_dir",
"try",
":",
"opts",
",",
"args",
"=",
"getopt",
".",
"getopt",
"(",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
",",
"\"hb\"",
",",
"[",
"\"help\"",
",",
"\"backup\"",
"]",
")",
"except",
"getopt",
".",
"GetoptError",
":",
"usage",
"(",
")",
"sys",
".",
"exit",
"(",
"2",
")",
"if",
"args",
"==",
"[",
"]",
":",
"usage",
"(",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"# process options",
"#",
"output_dir",
"=",
"None",
"do_backup",
"=",
"None",
"for",
"opt",
"in",
"opts",
":",
"if",
"opt",
"[",
"0",
"]",
"in",
"(",
"\"-h\"",
",",
"\"--help\"",
")",
":",
"usage",
"(",
")",
"sys",
".",
"exit",
"(",
"0",
")",
"if",
"opt",
"[",
"0",
"]",
"in",
"(",
"\"-b\"",
",",
"\"--backup\"",
")",
":",
"do_backup",
"=",
"1",
"# create context and processor",
"source_processor",
"=",
"SourceProcessor",
"(",
")",
"# retrieve the list of files to process",
"file_list",
"=",
"make_file_list",
"(",
"args",
")",
"for",
"filename",
"in",
"file_list",
":",
"source_processor",
".",
"parse_file",
"(",
"filename",
")",
"for",
"block",
"in",
"source_processor",
".",
"blocks",
":",
"beautify_block",
"(",
"block",
")",
"new_name",
"=",
"filename",
"+",
"\".new\"",
"ok",
"=",
"None",
"try",
":",
"file",
"=",
"open",
"(",
"new_name",
",",
"\"wt\"",
")",
"for",
"block",
"in",
"source_processor",
".",
"blocks",
":",
"for",
"line",
"in",
"block",
".",
"lines",
":",
"file",
".",
"write",
"(",
"line",
")",
"file",
".",
"write",
"(",
"\"\\n\"",
")",
"file",
".",
"close",
"(",
")",
"except",
":",
"ok",
"=",
"0"
] | edf3810dcb211942d392a8637945871399b0650d |
test | connect | Instantiates and returns a :py:class:`route53.connection.Route53Connection`
instance, which is how you'll start your interactions with the Route 53
API.
:keyword str aws_access_key_id: Your AWS Access Key ID
:keyword str aws_secret_access_key: Your AWS Secret Access Key
:rtype: :py:class:`route53.connection.Route53Connection`
:return: A connection to Amazon's Route 53 | route53/__init__.py | def connect(aws_access_key_id=None, aws_secret_access_key=None, **kwargs):
"""
Instantiates and returns a :py:class:`route53.connection.Route53Connection`
instance, which is how you'll start your interactions with the Route 53
API.
:keyword str aws_access_key_id: Your AWS Access Key ID
:keyword str aws_secret_access_key: Your AWS Secret Access Key
:rtype: :py:class:`route53.connection.Route53Connection`
:return: A connection to Amazon's Route 53
"""
from route53.connection import Route53Connection
return Route53Connection(
aws_access_key_id,
aws_secret_access_key,
**kwargs
) | def connect(aws_access_key_id=None, aws_secret_access_key=None, **kwargs):
"""
Instantiates and returns a :py:class:`route53.connection.Route53Connection`
instance, which is how you'll start your interactions with the Route 53
API.
:keyword str aws_access_key_id: Your AWS Access Key ID
:keyword str aws_secret_access_key: Your AWS Secret Access Key
:rtype: :py:class:`route53.connection.Route53Connection`
:return: A connection to Amazon's Route 53
"""
from route53.connection import Route53Connection
return Route53Connection(
aws_access_key_id,
aws_secret_access_key,
**kwargs
) | [
"Instantiates",
"and",
"returns",
"a",
":",
"py",
":",
"class",
":",
"route53",
".",
"connection",
".",
"Route53Connection",
"instance",
"which",
"is",
"how",
"you",
"ll",
"start",
"your",
"interactions",
"with",
"the",
"Route",
"53",
"API",
"."
] | gtaylor/python-route53 | python | https://github.com/gtaylor/python-route53/blob/b9fc7e258a79551c9ed61e4a71668b7f06f9e774/route53/__init__.py#L11-L29 | [
"def",
"connect",
"(",
"aws_access_key_id",
"=",
"None",
",",
"aws_secret_access_key",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"route53",
".",
"connection",
"import",
"Route53Connection",
"return",
"Route53Connection",
"(",
"aws_access_key_id",
",",
"aws_secret_access_key",
",",
"*",
"*",
"kwargs",
")"
] | b9fc7e258a79551c9ed61e4a71668b7f06f9e774 |
test | VComment.validate | Validate keys and values.
Check to make sure every key used is a valid Vorbis key, and
that every value used is a valid Unicode or UTF-8 string. If
any invalid keys or values are found, a ValueError is raised.
In Python 3 all keys and values have to be a string. | mutagen/_vorbis.py | def validate(self):
"""Validate keys and values.
Check to make sure every key used is a valid Vorbis key, and
that every value used is a valid Unicode or UTF-8 string. If
any invalid keys or values are found, a ValueError is raised.
In Python 3 all keys and values have to be a string.
"""
# be stricter in Python 3
if PY3:
if not isinstance(self.vendor, text_type):
raise ValueError
for key, value in self:
if not isinstance(key, text_type):
raise ValueError
if not isinstance(value, text_type):
raise ValueError
if not isinstance(self.vendor, text_type):
try:
self.vendor.decode('utf-8')
except UnicodeDecodeError:
raise ValueError
for key, value in self._internal:
try:
if not is_valid_key(key):
raise ValueError
except:
raise ValueError("%r is not a valid key" % key)
if not isinstance(value, text_type):
try:
value.decode("utf-8")
except:
raise ValueError("%r is not a valid value" % value)
else:
return True | def validate(self):
"""Validate keys and values.
Check to make sure every key used is a valid Vorbis key, and
that every value used is a valid Unicode or UTF-8 string. If
any invalid keys or values are found, a ValueError is raised.
In Python 3 all keys and values have to be a string.
"""
# be stricter in Python 3
if PY3:
if not isinstance(self.vendor, text_type):
raise ValueError
for key, value in self:
if not isinstance(key, text_type):
raise ValueError
if not isinstance(value, text_type):
raise ValueError
if not isinstance(self.vendor, text_type):
try:
self.vendor.decode('utf-8')
except UnicodeDecodeError:
raise ValueError
for key, value in self._internal:
try:
if not is_valid_key(key):
raise ValueError
except:
raise ValueError("%r is not a valid key" % key)
if not isinstance(value, text_type):
try:
value.decode("utf-8")
except:
raise ValueError("%r is not a valid value" % value)
else:
return True | [
"Validate",
"keys",
"and",
"values",
"."
] | LordSputnik/mutagen | python | https://github.com/LordSputnik/mutagen/blob/38e62c8dc35c72b16554f5dbe7c0fde91acc3411/mutagen/_vorbis.py#L156-L195 | [
"def",
"validate",
"(",
"self",
")",
":",
"# be stricter in Python 3",
"if",
"PY3",
":",
"if",
"not",
"isinstance",
"(",
"self",
".",
"vendor",
",",
"text_type",
")",
":",
"raise",
"ValueError",
"for",
"key",
",",
"value",
"in",
"self",
":",
"if",
"not",
"isinstance",
"(",
"key",
",",
"text_type",
")",
":",
"raise",
"ValueError",
"if",
"not",
"isinstance",
"(",
"value",
",",
"text_type",
")",
":",
"raise",
"ValueError",
"if",
"not",
"isinstance",
"(",
"self",
".",
"vendor",
",",
"text_type",
")",
":",
"try",
":",
"self",
".",
"vendor",
".",
"decode",
"(",
"'utf-8'",
")",
"except",
"UnicodeDecodeError",
":",
"raise",
"ValueError",
"for",
"key",
",",
"value",
"in",
"self",
".",
"_internal",
":",
"try",
":",
"if",
"not",
"is_valid_key",
"(",
"key",
")",
":",
"raise",
"ValueError",
"except",
":",
"raise",
"ValueError",
"(",
"\"%r is not a valid key\"",
"%",
"key",
")",
"if",
"not",
"isinstance",
"(",
"value",
",",
"text_type",
")",
":",
"try",
":",
"value",
".",
"decode",
"(",
"\"utf-8\"",
")",
"except",
":",
"raise",
"ValueError",
"(",
"\"%r is not a valid value\"",
"%",
"value",
")",
"else",
":",
"return",
"True"
] | 38e62c8dc35c72b16554f5dbe7c0fde91acc3411 |
test | VComment.clear | Clear all keys from the comment. | mutagen/_vorbis.py | def clear(self):
"""Clear all keys from the comment."""
for i in list(self._internal):
self._internal.remove(i) | def clear(self):
"""Clear all keys from the comment."""
for i in list(self._internal):
self._internal.remove(i) | [
"Clear",
"all",
"keys",
"from",
"the",
"comment",
"."
] | LordSputnik/mutagen | python | https://github.com/LordSputnik/mutagen/blob/38e62c8dc35c72b16554f5dbe7c0fde91acc3411/mutagen/_vorbis.py#L197-L201 | [
"def",
"clear",
"(",
"self",
")",
":",
"for",
"i",
"in",
"list",
"(",
"self",
".",
"_internal",
")",
":",
"self",
".",
"_internal",
".",
"remove",
"(",
"i",
")"
] | 38e62c8dc35c72b16554f5dbe7c0fde91acc3411 |
test | VComment.write | Return a string representation of the data.
Validation is always performed, so calling this function on
invalid data may raise a ValueError.
Keyword arguments:
* framing -- if true, append a framing bit (see load) | mutagen/_vorbis.py | def write(self, framing=True):
"""Return a string representation of the data.
Validation is always performed, so calling this function on
invalid data may raise a ValueError.
Keyword arguments:
* framing -- if true, append a framing bit (see load)
"""
self.validate()
def _encode(value):
if not isinstance(value, bytes):
return value.encode('utf-8')
return value
f = BytesIO()
vendor = _encode(self.vendor)
f.write(cdata.to_uint_le(len(vendor)))
f.write(vendor)
f.write(cdata.to_uint_le(len(self)))
for tag, value in self._internal:
tag = _encode(tag)
value = _encode(value)
comment = tag + b"=" + value
f.write(cdata.to_uint_le(len(comment)))
f.write(comment)
if framing:
f.write(b"\x01")
return f.getvalue() | def write(self, framing=True):
"""Return a string representation of the data.
Validation is always performed, so calling this function on
invalid data may raise a ValueError.
Keyword arguments:
* framing -- if true, append a framing bit (see load)
"""
self.validate()
def _encode(value):
if not isinstance(value, bytes):
return value.encode('utf-8')
return value
f = BytesIO()
vendor = _encode(self.vendor)
f.write(cdata.to_uint_le(len(vendor)))
f.write(vendor)
f.write(cdata.to_uint_le(len(self)))
for tag, value in self._internal:
tag = _encode(tag)
value = _encode(value)
comment = tag + b"=" + value
f.write(cdata.to_uint_le(len(comment)))
f.write(comment)
if framing:
f.write(b"\x01")
return f.getvalue() | [
"Return",
"a",
"string",
"representation",
"of",
"the",
"data",
"."
] | LordSputnik/mutagen | python | https://github.com/LordSputnik/mutagen/blob/38e62c8dc35c72b16554f5dbe7c0fde91acc3411/mutagen/_vorbis.py#L203-L234 | [
"def",
"write",
"(",
"self",
",",
"framing",
"=",
"True",
")",
":",
"self",
".",
"validate",
"(",
")",
"def",
"_encode",
"(",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"bytes",
")",
":",
"return",
"value",
".",
"encode",
"(",
"'utf-8'",
")",
"return",
"value",
"f",
"=",
"BytesIO",
"(",
")",
"vendor",
"=",
"_encode",
"(",
"self",
".",
"vendor",
")",
"f",
".",
"write",
"(",
"cdata",
".",
"to_uint_le",
"(",
"len",
"(",
"vendor",
")",
")",
")",
"f",
".",
"write",
"(",
"vendor",
")",
"f",
".",
"write",
"(",
"cdata",
".",
"to_uint_le",
"(",
"len",
"(",
"self",
")",
")",
")",
"for",
"tag",
",",
"value",
"in",
"self",
".",
"_internal",
":",
"tag",
"=",
"_encode",
"(",
"tag",
")",
"value",
"=",
"_encode",
"(",
"value",
")",
"comment",
"=",
"tag",
"+",
"b\"=\"",
"+",
"value",
"f",
".",
"write",
"(",
"cdata",
".",
"to_uint_le",
"(",
"len",
"(",
"comment",
")",
")",
")",
"f",
".",
"write",
"(",
"comment",
")",
"if",
"framing",
":",
"f",
".",
"write",
"(",
"b\"\\x01\"",
")",
"return",
"f",
".",
"getvalue",
"(",
")"
] | 38e62c8dc35c72b16554f5dbe7c0fde91acc3411 |
test | IFFChunk.read | Read the chunks data | mutagen/aiff.py | def read(self):
"""Read the chunks data"""
self.__fileobj.seek(self.data_offset)
self.data = self.__fileobj.read(self.data_size) | def read(self):
"""Read the chunks data"""
self.__fileobj.seek(self.data_offset)
self.data = self.__fileobj.read(self.data_size) | [
"Read",
"the",
"chunks",
"data"
] | LordSputnik/mutagen | python | https://github.com/LordSputnik/mutagen/blob/38e62c8dc35c72b16554f5dbe7c0fde91acc3411/mutagen/aiff.py#L97-L100 | [
"def",
"read",
"(",
"self",
")",
":",
"self",
".",
"__fileobj",
".",
"seek",
"(",
"self",
".",
"data_offset",
")",
"self",
".",
"data",
"=",
"self",
".",
"__fileobj",
".",
"read",
"(",
"self",
".",
"data_size",
")"
] | 38e62c8dc35c72b16554f5dbe7c0fde91acc3411 |
test | IFFChunk.delete | Removes the chunk from the file | mutagen/aiff.py | def delete(self):
"""Removes the chunk from the file"""
delete_bytes(self.__fileobj, self.size, self.offset)
if self.parent_chunk is not None:
self.parent_chunk.resize(self.parent_chunk.data_size - self.size) | def delete(self):
"""Removes the chunk from the file"""
delete_bytes(self.__fileobj, self.size, self.offset)
if self.parent_chunk is not None:
self.parent_chunk.resize(self.parent_chunk.data_size - self.size) | [
"Removes",
"the",
"chunk",
"from",
"the",
"file"
] | LordSputnik/mutagen | python | https://github.com/LordSputnik/mutagen/blob/38e62c8dc35c72b16554f5dbe7c0fde91acc3411/mutagen/aiff.py#L102-L106 | [
"def",
"delete",
"(",
"self",
")",
":",
"delete_bytes",
"(",
"self",
".",
"__fileobj",
",",
"self",
".",
"size",
",",
"self",
".",
"offset",
")",
"if",
"self",
".",
"parent_chunk",
"is",
"not",
"None",
":",
"self",
".",
"parent_chunk",
".",
"resize",
"(",
"self",
".",
"parent_chunk",
".",
"data_size",
"-",
"self",
".",
"size",
")"
] | 38e62c8dc35c72b16554f5dbe7c0fde91acc3411 |
test | IFFChunk.resize | Update the size of the chunk | mutagen/aiff.py | def resize(self, data_size):
"""Update the size of the chunk"""
self.__fileobj.seek(self.offset + 4)
self.__fileobj.write(pack('>I', data_size))
if self.parent_chunk is not None:
size_diff = self.data_size - data_size
self.parent_chunk.resize(self.parent_chunk.data_size - size_diff)
self.data_size = data_size
self.size = data_size + self.HEADER_SIZE | def resize(self, data_size):
"""Update the size of the chunk"""
self.__fileobj.seek(self.offset + 4)
self.__fileobj.write(pack('>I', data_size))
if self.parent_chunk is not None:
size_diff = self.data_size - data_size
self.parent_chunk.resize(self.parent_chunk.data_size - size_diff)
self.data_size = data_size
self.size = data_size + self.HEADER_SIZE | [
"Update",
"the",
"size",
"of",
"the",
"chunk"
] | LordSputnik/mutagen | python | https://github.com/LordSputnik/mutagen/blob/38e62c8dc35c72b16554f5dbe7c0fde91acc3411/mutagen/aiff.py#L108-L116 | [
"def",
"resize",
"(",
"self",
",",
"data_size",
")",
":",
"self",
".",
"__fileobj",
".",
"seek",
"(",
"self",
".",
"offset",
"+",
"4",
")",
"self",
".",
"__fileobj",
".",
"write",
"(",
"pack",
"(",
"'>I'",
",",
"data_size",
")",
")",
"if",
"self",
".",
"parent_chunk",
"is",
"not",
"None",
":",
"size_diff",
"=",
"self",
".",
"data_size",
"-",
"data_size",
"self",
".",
"parent_chunk",
".",
"resize",
"(",
"self",
".",
"parent_chunk",
".",
"data_size",
"-",
"size_diff",
")",
"self",
".",
"data_size",
"=",
"data_size",
"self",
".",
"size",
"=",
"data_size",
"+",
"self",
".",
"HEADER_SIZE"
] | 38e62c8dc35c72b16554f5dbe7c0fde91acc3411 |
test | IFFFile.insert_chunk | Insert a new chunk at the end of the IFF file | mutagen/aiff.py | def insert_chunk(self, id_):
"""Insert a new chunk at the end of the IFF file"""
if not isinstance(id_, text_type):
id_ = id_.decode('ascii')
if not is_valid_chunk_id(id_):
raise KeyError("AIFF key must be four ASCII characters.")
self.__fileobj.seek(self.__next_offset)
self.__fileobj.write(pack('>4si', id_.ljust(4).encode('ascii'), 0))
self.__fileobj.seek(self.__next_offset)
chunk = IFFChunk(self.__fileobj, self[u'FORM'])
self[u'FORM'].resize(self[u'FORM'].data_size + chunk.size)
self.__chunks[id_] = chunk
self.__next_offset = chunk.offset + chunk.size | def insert_chunk(self, id_):
"""Insert a new chunk at the end of the IFF file"""
if not isinstance(id_, text_type):
id_ = id_.decode('ascii')
if not is_valid_chunk_id(id_):
raise KeyError("AIFF key must be four ASCII characters.")
self.__fileobj.seek(self.__next_offset)
self.__fileobj.write(pack('>4si', id_.ljust(4).encode('ascii'), 0))
self.__fileobj.seek(self.__next_offset)
chunk = IFFChunk(self.__fileobj, self[u'FORM'])
self[u'FORM'].resize(self[u'FORM'].data_size + chunk.size)
self.__chunks[id_] = chunk
self.__next_offset = chunk.offset + chunk.size | [
"Insert",
"a",
"new",
"chunk",
"at",
"the",
"end",
"of",
"the",
"IFF",
"file"
] | LordSputnik/mutagen | python | https://github.com/LordSputnik/mutagen/blob/38e62c8dc35c72b16554f5dbe7c0fde91acc3411/mutagen/aiff.py#L190-L206 | [
"def",
"insert_chunk",
"(",
"self",
",",
"id_",
")",
":",
"if",
"not",
"isinstance",
"(",
"id_",
",",
"text_type",
")",
":",
"id_",
"=",
"id_",
".",
"decode",
"(",
"'ascii'",
")",
"if",
"not",
"is_valid_chunk_id",
"(",
"id_",
")",
":",
"raise",
"KeyError",
"(",
"\"AIFF key must be four ASCII characters.\"",
")",
"self",
".",
"__fileobj",
".",
"seek",
"(",
"self",
".",
"__next_offset",
")",
"self",
".",
"__fileobj",
".",
"write",
"(",
"pack",
"(",
"'>4si'",
",",
"id_",
".",
"ljust",
"(",
"4",
")",
".",
"encode",
"(",
"'ascii'",
")",
",",
"0",
")",
")",
"self",
".",
"__fileobj",
".",
"seek",
"(",
"self",
".",
"__next_offset",
")",
"chunk",
"=",
"IFFChunk",
"(",
"self",
".",
"__fileobj",
",",
"self",
"[",
"u'FORM'",
"]",
")",
"self",
"[",
"u'FORM'",
"]",
".",
"resize",
"(",
"self",
"[",
"u'FORM'",
"]",
".",
"data_size",
"+",
"chunk",
".",
"size",
")",
"self",
".",
"__chunks",
"[",
"id_",
"]",
"=",
"chunk",
"self",
".",
"__next_offset",
"=",
"chunk",
".",
"offset",
"+",
"chunk",
".",
"size"
] | 38e62c8dc35c72b16554f5dbe7c0fde91acc3411 |
test | _IFFID3.save | Save ID3v2 data to the AIFF file | mutagen/aiff.py | def save(self, filename=None, v2_version=4, v23_sep='/'):
"""Save ID3v2 data to the AIFF file"""
framedata = self._prepare_framedata(v2_version, v23_sep)
framesize = len(framedata)
if filename is None:
filename = self.filename
# Unlike the parent ID3.save method, we won't save to a blank file
# since we would have to construct a empty AIFF file
fileobj = open(filename, 'rb+')
iff_file = IFFFile(fileobj)
try:
if u'ID3' not in iff_file:
iff_file.insert_chunk(u'ID3')
chunk = iff_file[u'ID3']
fileobj.seek(chunk.data_offset)
header = fileobj.read(10)
header = self._prepare_id3_header(header, framesize, v2_version)
header, new_size, _ = header
data = header + framedata + (b'\x00' * (new_size - framesize))
# Include ID3 header size in 'new_size' calculation
new_size += 10
# Expand the chunk if necessary, including pad byte
if new_size > chunk.size:
insert_at = chunk.offset + chunk.size
insert_size = new_size - chunk.size + new_size % 2
insert_bytes(fileobj, insert_size, insert_at)
chunk.resize(new_size)
fileobj.seek(chunk.data_offset)
fileobj.write(data)
finally:
fileobj.close() | def save(self, filename=None, v2_version=4, v23_sep='/'):
"""Save ID3v2 data to the AIFF file"""
framedata = self._prepare_framedata(v2_version, v23_sep)
framesize = len(framedata)
if filename is None:
filename = self.filename
# Unlike the parent ID3.save method, we won't save to a blank file
# since we would have to construct a empty AIFF file
fileobj = open(filename, 'rb+')
iff_file = IFFFile(fileobj)
try:
if u'ID3' not in iff_file:
iff_file.insert_chunk(u'ID3')
chunk = iff_file[u'ID3']
fileobj.seek(chunk.data_offset)
header = fileobj.read(10)
header = self._prepare_id3_header(header, framesize, v2_version)
header, new_size, _ = header
data = header + framedata + (b'\x00' * (new_size - framesize))
# Include ID3 header size in 'new_size' calculation
new_size += 10
# Expand the chunk if necessary, including pad byte
if new_size > chunk.size:
insert_at = chunk.offset + chunk.size
insert_size = new_size - chunk.size + new_size % 2
insert_bytes(fileobj, insert_size, insert_at)
chunk.resize(new_size)
fileobj.seek(chunk.data_offset)
fileobj.write(data)
finally:
fileobj.close() | [
"Save",
"ID3v2",
"data",
"to",
"the",
"AIFF",
"file"
] | LordSputnik/mutagen | python | https://github.com/LordSputnik/mutagen/blob/38e62c8dc35c72b16554f5dbe7c0fde91acc3411/mutagen/aiff.py#L261-L301 | [
"def",
"save",
"(",
"self",
",",
"filename",
"=",
"None",
",",
"v2_version",
"=",
"4",
",",
"v23_sep",
"=",
"'/'",
")",
":",
"framedata",
"=",
"self",
".",
"_prepare_framedata",
"(",
"v2_version",
",",
"v23_sep",
")",
"framesize",
"=",
"len",
"(",
"framedata",
")",
"if",
"filename",
"is",
"None",
":",
"filename",
"=",
"self",
".",
"filename",
"# Unlike the parent ID3.save method, we won't save to a blank file",
"# since we would have to construct a empty AIFF file",
"fileobj",
"=",
"open",
"(",
"filename",
",",
"'rb+'",
")",
"iff_file",
"=",
"IFFFile",
"(",
"fileobj",
")",
"try",
":",
"if",
"u'ID3'",
"not",
"in",
"iff_file",
":",
"iff_file",
".",
"insert_chunk",
"(",
"u'ID3'",
")",
"chunk",
"=",
"iff_file",
"[",
"u'ID3'",
"]",
"fileobj",
".",
"seek",
"(",
"chunk",
".",
"data_offset",
")",
"header",
"=",
"fileobj",
".",
"read",
"(",
"10",
")",
"header",
"=",
"self",
".",
"_prepare_id3_header",
"(",
"header",
",",
"framesize",
",",
"v2_version",
")",
"header",
",",
"new_size",
",",
"_",
"=",
"header",
"data",
"=",
"header",
"+",
"framedata",
"+",
"(",
"b'\\x00'",
"*",
"(",
"new_size",
"-",
"framesize",
")",
")",
"# Include ID3 header size in 'new_size' calculation",
"new_size",
"+=",
"10",
"# Expand the chunk if necessary, including pad byte",
"if",
"new_size",
">",
"chunk",
".",
"size",
":",
"insert_at",
"=",
"chunk",
".",
"offset",
"+",
"chunk",
".",
"size",
"insert_size",
"=",
"new_size",
"-",
"chunk",
".",
"size",
"+",
"new_size",
"%",
"2",
"insert_bytes",
"(",
"fileobj",
",",
"insert_size",
",",
"insert_at",
")",
"chunk",
".",
"resize",
"(",
"new_size",
")",
"fileobj",
".",
"seek",
"(",
"chunk",
".",
"data_offset",
")",
"fileobj",
".",
"write",
"(",
"data",
")",
"finally",
":",
"fileobj",
".",
"close",
"(",
")"
] | 38e62c8dc35c72b16554f5dbe7c0fde91acc3411 |
test | _IFFID3.delete | Completely removes the ID3 chunk from the AIFF file | mutagen/aiff.py | def delete(self, filename=None):
"""Completely removes the ID3 chunk from the AIFF file"""
if filename is None:
filename = self.filename
delete(filename)
self.clear() | def delete(self, filename=None):
"""Completely removes the ID3 chunk from the AIFF file"""
if filename is None:
filename = self.filename
delete(filename)
self.clear() | [
"Completely",
"removes",
"the",
"ID3",
"chunk",
"from",
"the",
"AIFF",
"file"
] | LordSputnik/mutagen | python | https://github.com/LordSputnik/mutagen/blob/38e62c8dc35c72b16554f5dbe7c0fde91acc3411/mutagen/aiff.py#L303-L309 | [
"def",
"delete",
"(",
"self",
",",
"filename",
"=",
"None",
")",
":",
"if",
"filename",
"is",
"None",
":",
"filename",
"=",
"self",
".",
"filename",
"delete",
"(",
"filename",
")",
"self",
".",
"clear",
"(",
")"
] | 38e62c8dc35c72b16554f5dbe7c0fde91acc3411 |
test | AIFF.load | Load stream and tag information from a file. | mutagen/aiff.py | def load(self, filename, **kwargs):
"""Load stream and tag information from a file."""
self.filename = filename
try:
self.tags = _IFFID3(filename, **kwargs)
except ID3Error:
self.tags = None
try:
fileobj = open(filename, "rb")
self.info = AIFFInfo(fileobj)
finally:
fileobj.close() | def load(self, filename, **kwargs):
"""Load stream and tag information from a file."""
self.filename = filename
try:
self.tags = _IFFID3(filename, **kwargs)
except ID3Error:
self.tags = None
try:
fileobj = open(filename, "rb")
self.info = AIFFInfo(fileobj)
finally:
fileobj.close() | [
"Load",
"stream",
"and",
"tag",
"information",
"from",
"a",
"file",
"."
] | LordSputnik/mutagen | python | https://github.com/LordSputnik/mutagen/blob/38e62c8dc35c72b16554f5dbe7c0fde91acc3411/mutagen/aiff.py#L345-L358 | [
"def",
"load",
"(",
"self",
",",
"filename",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"filename",
"=",
"filename",
"try",
":",
"self",
".",
"tags",
"=",
"_IFFID3",
"(",
"filename",
",",
"*",
"*",
"kwargs",
")",
"except",
"ID3Error",
":",
"self",
".",
"tags",
"=",
"None",
"try",
":",
"fileobj",
"=",
"open",
"(",
"filename",
",",
"\"rb\"",
")",
"self",
".",
"info",
"=",
"AIFFInfo",
"(",
"fileobj",
")",
"finally",
":",
"fileobj",
".",
"close",
"(",
")"
] | 38e62c8dc35c72b16554f5dbe7c0fde91acc3411 |
test | SourceProcessor.parse_file | parse a C source file, and add its blocks to the processor's list | native/Vendor/FreeType/src/tools/docmaker/sources.py | def parse_file( self, filename ):
"""parse a C source file, and add its blocks to the processor's list"""
self.reset()
self.filename = filename
fileinput.close()
self.format = None
self.lineno = 0
self.lines = []
for line in fileinput.input( filename ):
# strip trailing newlines, important on Windows machines!
if line[-1] == '\012':
line = line[0:-1]
if self.format == None:
self.process_normal_line( line )
else:
if self.format.end.match( line ):
# that's a normal block end, add it to 'lines' and
# create a new block
self.lines.append( line )
self.add_block_lines()
elif self.format.column.match( line ):
# that's a normal column line, add it to 'lines'
self.lines.append( line )
else:
# humm.. this is an unexpected block end,
# create a new block, but don't process the line
self.add_block_lines()
# we need to process the line again
self.process_normal_line( line )
# record the last lines
self.add_block_lines() | def parse_file( self, filename ):
"""parse a C source file, and add its blocks to the processor's list"""
self.reset()
self.filename = filename
fileinput.close()
self.format = None
self.lineno = 0
self.lines = []
for line in fileinput.input( filename ):
# strip trailing newlines, important on Windows machines!
if line[-1] == '\012':
line = line[0:-1]
if self.format == None:
self.process_normal_line( line )
else:
if self.format.end.match( line ):
# that's a normal block end, add it to 'lines' and
# create a new block
self.lines.append( line )
self.add_block_lines()
elif self.format.column.match( line ):
# that's a normal column line, add it to 'lines'
self.lines.append( line )
else:
# humm.. this is an unexpected block end,
# create a new block, but don't process the line
self.add_block_lines()
# we need to process the line again
self.process_normal_line( line )
# record the last lines
self.add_block_lines() | [
"parse",
"a",
"C",
"source",
"file",
"and",
"add",
"its",
"blocks",
"to",
"the",
"processor",
"s",
"list"
] | aholkner/bacon | python | https://github.com/aholkner/bacon/blob/edf3810dcb211942d392a8637945871399b0650d/native/Vendor/FreeType/src/tools/docmaker/sources.py#L284-L320 | [
"def",
"parse_file",
"(",
"self",
",",
"filename",
")",
":",
"self",
".",
"reset",
"(",
")",
"self",
".",
"filename",
"=",
"filename",
"fileinput",
".",
"close",
"(",
")",
"self",
".",
"format",
"=",
"None",
"self",
".",
"lineno",
"=",
"0",
"self",
".",
"lines",
"=",
"[",
"]",
"for",
"line",
"in",
"fileinput",
".",
"input",
"(",
"filename",
")",
":",
"# strip trailing newlines, important on Windows machines!",
"if",
"line",
"[",
"-",
"1",
"]",
"==",
"'\\012'",
":",
"line",
"=",
"line",
"[",
"0",
":",
"-",
"1",
"]",
"if",
"self",
".",
"format",
"==",
"None",
":",
"self",
".",
"process_normal_line",
"(",
"line",
")",
"else",
":",
"if",
"self",
".",
"format",
".",
"end",
".",
"match",
"(",
"line",
")",
":",
"# that's a normal block end, add it to 'lines' and",
"# create a new block",
"self",
".",
"lines",
".",
"append",
"(",
"line",
")",
"self",
".",
"add_block_lines",
"(",
")",
"elif",
"self",
".",
"format",
".",
"column",
".",
"match",
"(",
"line",
")",
":",
"# that's a normal column line, add it to 'lines'",
"self",
".",
"lines",
".",
"append",
"(",
"line",
")",
"else",
":",
"# humm.. this is an unexpected block end,",
"# create a new block, but don't process the line",
"self",
".",
"add_block_lines",
"(",
")",
"# we need to process the line again",
"self",
".",
"process_normal_line",
"(",
"line",
")",
"# record the last lines",
"self",
".",
"add_block_lines",
"(",
")"
] | edf3810dcb211942d392a8637945871399b0650d |
test | SourceProcessor.process_normal_line | process a normal line and check whether it is the start of a new block | native/Vendor/FreeType/src/tools/docmaker/sources.py | def process_normal_line( self, line ):
"""process a normal line and check whether it is the start of a new block"""
for f in re_source_block_formats:
if f.start.match( line ):
self.add_block_lines()
self.format = f
self.lineno = fileinput.filelineno()
self.lines.append( line ) | def process_normal_line( self, line ):
"""process a normal line and check whether it is the start of a new block"""
for f in re_source_block_formats:
if f.start.match( line ):
self.add_block_lines()
self.format = f
self.lineno = fileinput.filelineno()
self.lines.append( line ) | [
"process",
"a",
"normal",
"line",
"and",
"check",
"whether",
"it",
"is",
"the",
"start",
"of",
"a",
"new",
"block"
] | aholkner/bacon | python | https://github.com/aholkner/bacon/blob/edf3810dcb211942d392a8637945871399b0650d/native/Vendor/FreeType/src/tools/docmaker/sources.py#L322-L330 | [
"def",
"process_normal_line",
"(",
"self",
",",
"line",
")",
":",
"for",
"f",
"in",
"re_source_block_formats",
":",
"if",
"f",
".",
"start",
".",
"match",
"(",
"line",
")",
":",
"self",
".",
"add_block_lines",
"(",
")",
"self",
".",
"format",
"=",
"f",
"self",
".",
"lineno",
"=",
"fileinput",
".",
"filelineno",
"(",
")",
"self",
".",
"lines",
".",
"append",
"(",
"line",
")"
] | edf3810dcb211942d392a8637945871399b0650d |
test | SourceProcessor.add_block_lines | add the current accumulated lines and create a new block | native/Vendor/FreeType/src/tools/docmaker/sources.py | def add_block_lines( self ):
"""add the current accumulated lines and create a new block"""
if self.lines != []:
block = SourceBlock( self, self.filename, self.lineno, self.lines )
self.blocks.append( block )
self.format = None
self.lines = [] | def add_block_lines( self ):
"""add the current accumulated lines and create a new block"""
if self.lines != []:
block = SourceBlock( self, self.filename, self.lineno, self.lines )
self.blocks.append( block )
self.format = None
self.lines = [] | [
"add",
"the",
"current",
"accumulated",
"lines",
"and",
"create",
"a",
"new",
"block"
] | aholkner/bacon | python | https://github.com/aholkner/bacon/blob/edf3810dcb211942d392a8637945871399b0650d/native/Vendor/FreeType/src/tools/docmaker/sources.py#L332-L339 | [
"def",
"add_block_lines",
"(",
"self",
")",
":",
"if",
"self",
".",
"lines",
"!=",
"[",
"]",
":",
"block",
"=",
"SourceBlock",
"(",
"self",
",",
"self",
".",
"filename",
",",
"self",
".",
"lineno",
",",
"self",
".",
"lines",
")",
"self",
".",
"blocks",
".",
"append",
"(",
"block",
")",
"self",
".",
"format",
"=",
"None",
"self",
".",
"lines",
"=",
"[",
"]"
] | edf3810dcb211942d392a8637945871399b0650d |
test | draw_string | Draw a string with the given font.
:note: Text alignment and word-wrapping is not yet implemented. The text is rendered with the left edge and
baseline at ``(x, y)``.
:param font: the :class:`Font` to render text with
:param text: a string of text to render. | bacon/text.py | def draw_string(font, text, x, y, width=None, height=None, align=Alignment.left, vertical_align=VerticalAlignment.baseline):
'''Draw a string with the given font.
:note: Text alignment and word-wrapping is not yet implemented. The text is rendered with the left edge and
baseline at ``(x, y)``.
:param font: the :class:`Font` to render text with
:param text: a string of text to render.
'''
style = Style(font)
run = GlyphRun(style, text)
glyph_layout = GlyphLayout([run], x, y, width, height, align, vertical_align)
draw_glyph_layout(glyph_layout) | def draw_string(font, text, x, y, width=None, height=None, align=Alignment.left, vertical_align=VerticalAlignment.baseline):
'''Draw a string with the given font.
:note: Text alignment and word-wrapping is not yet implemented. The text is rendered with the left edge and
baseline at ``(x, y)``.
:param font: the :class:`Font` to render text with
:param text: a string of text to render.
'''
style = Style(font)
run = GlyphRun(style, text)
glyph_layout = GlyphLayout([run], x, y, width, height, align, vertical_align)
draw_glyph_layout(glyph_layout) | [
"Draw",
"a",
"string",
"with",
"the",
"given",
"font",
"."
] | aholkner/bacon | python | https://github.com/aholkner/bacon/blob/edf3810dcb211942d392a8637945871399b0650d/bacon/text.py#L301-L313 | [
"def",
"draw_string",
"(",
"font",
",",
"text",
",",
"x",
",",
"y",
",",
"width",
"=",
"None",
",",
"height",
"=",
"None",
",",
"align",
"=",
"Alignment",
".",
"left",
",",
"vertical_align",
"=",
"VerticalAlignment",
".",
"baseline",
")",
":",
"style",
"=",
"Style",
"(",
"font",
")",
"run",
"=",
"GlyphRun",
"(",
"style",
",",
"text",
")",
"glyph_layout",
"=",
"GlyphLayout",
"(",
"[",
"run",
"]",
",",
"x",
",",
"y",
",",
"width",
",",
"height",
",",
"align",
",",
"vertical_align",
")",
"draw_glyph_layout",
"(",
"glyph_layout",
")"
] | edf3810dcb211942d392a8637945871399b0650d |
test | draw_glyph_layout | Draw a prepared :class:`GlyphLayout` | bacon/text.py | def draw_glyph_layout(glyph_layout):
'''Draw a prepared :class:`GlyphLayout`
'''
pushed_color = False
# Draw lines
for line in glyph_layout.lines:
x = line.x
y = line.y
for run in line.runs:
style = run.style
if style.color is not None:
if not pushed_color:
bacon.push_color()
pushed_color = True
bacon.set_color(*style.color)
elif pushed_color:
bacon.pop_color()
pushed_color = False
for glyph in run.glyphs:
if glyph.image:
bacon.draw_image(glyph.image, x + glyph.offset_x, y - glyph.offset_y)
x += glyph.advance
if pushed_color:
bacon.pop_color() | def draw_glyph_layout(glyph_layout):
'''Draw a prepared :class:`GlyphLayout`
'''
pushed_color = False
# Draw lines
for line in glyph_layout.lines:
x = line.x
y = line.y
for run in line.runs:
style = run.style
if style.color is not None:
if not pushed_color:
bacon.push_color()
pushed_color = True
bacon.set_color(*style.color)
elif pushed_color:
bacon.pop_color()
pushed_color = False
for glyph in run.glyphs:
if glyph.image:
bacon.draw_image(glyph.image, x + glyph.offset_x, y - glyph.offset_y)
x += glyph.advance
if pushed_color:
bacon.pop_color() | [
"Draw",
"a",
"prepared",
":",
"class",
":",
"GlyphLayout"
] | aholkner/bacon | python | https://github.com/aholkner/bacon/blob/edf3810dcb211942d392a8637945871399b0650d/bacon/text.py#L316-L343 | [
"def",
"draw_glyph_layout",
"(",
"glyph_layout",
")",
":",
"pushed_color",
"=",
"False",
"# Draw lines",
"for",
"line",
"in",
"glyph_layout",
".",
"lines",
":",
"x",
"=",
"line",
".",
"x",
"y",
"=",
"line",
".",
"y",
"for",
"run",
"in",
"line",
".",
"runs",
":",
"style",
"=",
"run",
".",
"style",
"if",
"style",
".",
"color",
"is",
"not",
"None",
":",
"if",
"not",
"pushed_color",
":",
"bacon",
".",
"push_color",
"(",
")",
"pushed_color",
"=",
"True",
"bacon",
".",
"set_color",
"(",
"*",
"style",
".",
"color",
")",
"elif",
"pushed_color",
":",
"bacon",
".",
"pop_color",
"(",
")",
"pushed_color",
"=",
"False",
"for",
"glyph",
"in",
"run",
".",
"glyphs",
":",
"if",
"glyph",
".",
"image",
":",
"bacon",
".",
"draw_image",
"(",
"glyph",
".",
"image",
",",
"x",
"+",
"glyph",
".",
"offset_x",
",",
"y",
"-",
"glyph",
".",
"offset_y",
")",
"x",
"+=",
"glyph",
".",
"advance",
"if",
"pushed_color",
":",
"bacon",
".",
"pop_color",
"(",
")"
] | edf3810dcb211942d392a8637945871399b0650d |
test | parse_iso_8601_time_str | Parses a standard ISO 8601 time string. The Route53 API uses these here
and there.
:param str time_str: An ISO 8601 time string.
:rtype: datetime.datetime
:returns: A timezone aware (UTC) datetime.datetime instance. | route53/util.py | def parse_iso_8601_time_str(time_str):
"""
Parses a standard ISO 8601 time string. The Route53 API uses these here
and there.
:param str time_str: An ISO 8601 time string.
:rtype: datetime.datetime
:returns: A timezone aware (UTC) datetime.datetime instance.
"""
if re.search('\.\d{3}Z$', time_str):
submitted_at = datetime.datetime.strptime(time_str, \
'%Y-%m-%dT%H:%M:%S.%fZ')
else:
submitted_at = datetime.datetime.strptime(time_str, \
'%Y-%m-%dT%H:%M:%SZ')
# Parse the string, and make it explicitly UTC.
return submitted_at.replace(tzinfo=UTC_TIMEZONE) | def parse_iso_8601_time_str(time_str):
"""
Parses a standard ISO 8601 time string. The Route53 API uses these here
and there.
:param str time_str: An ISO 8601 time string.
:rtype: datetime.datetime
:returns: A timezone aware (UTC) datetime.datetime instance.
"""
if re.search('\.\d{3}Z$', time_str):
submitted_at = datetime.datetime.strptime(time_str, \
'%Y-%m-%dT%H:%M:%S.%fZ')
else:
submitted_at = datetime.datetime.strptime(time_str, \
'%Y-%m-%dT%H:%M:%SZ')
# Parse the string, and make it explicitly UTC.
return submitted_at.replace(tzinfo=UTC_TIMEZONE) | [
"Parses",
"a",
"standard",
"ISO",
"8601",
"time",
"string",
".",
"The",
"Route53",
"API",
"uses",
"these",
"here",
"and",
"there",
"."
] | gtaylor/python-route53 | python | https://github.com/gtaylor/python-route53/blob/b9fc7e258a79551c9ed61e4a71668b7f06f9e774/route53/util.py#L14-L30 | [
"def",
"parse_iso_8601_time_str",
"(",
"time_str",
")",
":",
"if",
"re",
".",
"search",
"(",
"'\\.\\d{3}Z$'",
",",
"time_str",
")",
":",
"submitted_at",
"=",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"time_str",
",",
"'%Y-%m-%dT%H:%M:%S.%fZ'",
")",
"else",
":",
"submitted_at",
"=",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"time_str",
",",
"'%Y-%m-%dT%H:%M:%SZ'",
")",
"# Parse the string, and make it explicitly UTC.",
"return",
"submitted_at",
".",
"replace",
"(",
"tzinfo",
"=",
"UTC_TIMEZONE",
")"
] | b9fc7e258a79551c9ed61e4a71668b7f06f9e774 |
test | HtmlFormatter.make_html_words | convert a series of simple words into some HTML text | native/Vendor/FreeType/src/tools/docmaker/tohtml.py | def make_html_words( self, words ):
""" convert a series of simple words into some HTML text """
line = ""
if words:
line = html_quote( words[0] )
for w in words[1:]:
line = line + " " + html_quote( w )
return line | def make_html_words( self, words ):
""" convert a series of simple words into some HTML text """
line = ""
if words:
line = html_quote( words[0] )
for w in words[1:]:
line = line + " " + html_quote( w )
return line | [
"convert",
"a",
"series",
"of",
"simple",
"words",
"into",
"some",
"HTML",
"text"
] | aholkner/bacon | python | https://github.com/aholkner/bacon/blob/edf3810dcb211942d392a8637945871399b0650d/native/Vendor/FreeType/src/tools/docmaker/tohtml.py#L245-L253 | [
"def",
"make_html_words",
"(",
"self",
",",
"words",
")",
":",
"line",
"=",
"\"\"",
"if",
"words",
":",
"line",
"=",
"html_quote",
"(",
"words",
"[",
"0",
"]",
")",
"for",
"w",
"in",
"words",
"[",
"1",
":",
"]",
":",
"line",
"=",
"line",
"+",
"\" \"",
"+",
"html_quote",
"(",
"w",
")",
"return",
"line"
] | edf3810dcb211942d392a8637945871399b0650d |
test | HtmlFormatter.make_html_word | analyze a simple word to detect cross-references and styling | native/Vendor/FreeType/src/tools/docmaker/tohtml.py | def make_html_word( self, word ):
"""analyze a simple word to detect cross-references and styling"""
# look for cross-references
m = re_crossref.match( word )
if m:
try:
name = m.group( 1 )
rest = m.group( 2 )
block = self.identifiers[name]
url = self.make_block_url( block )
return '<a href="' + url + '">' + name + '</a>' + rest
except:
# we detected a cross-reference to an unknown item
sys.stderr.write( \
"WARNING: undefined cross reference '" + name + "'.\n" )
return '?' + name + '?' + rest
# look for italics and bolds
m = re_italic.match( word )
if m:
name = m.group( 1 )
rest = m.group( 3 )
return '<i>' + name + '</i>' + rest
m = re_bold.match( word )
if m:
name = m.group( 1 )
rest = m.group( 3 )
return '<b>' + name + '</b>' + rest
return html_quote( word ) | def make_html_word( self, word ):
"""analyze a simple word to detect cross-references and styling"""
# look for cross-references
m = re_crossref.match( word )
if m:
try:
name = m.group( 1 )
rest = m.group( 2 )
block = self.identifiers[name]
url = self.make_block_url( block )
return '<a href="' + url + '">' + name + '</a>' + rest
except:
# we detected a cross-reference to an unknown item
sys.stderr.write( \
"WARNING: undefined cross reference '" + name + "'.\n" )
return '?' + name + '?' + rest
# look for italics and bolds
m = re_italic.match( word )
if m:
name = m.group( 1 )
rest = m.group( 3 )
return '<i>' + name + '</i>' + rest
m = re_bold.match( word )
if m:
name = m.group( 1 )
rest = m.group( 3 )
return '<b>' + name + '</b>' + rest
return html_quote( word ) | [
"analyze",
"a",
"simple",
"word",
"to",
"detect",
"cross",
"-",
"references",
"and",
"styling"
] | aholkner/bacon | python | https://github.com/aholkner/bacon/blob/edf3810dcb211942d392a8637945871399b0650d/native/Vendor/FreeType/src/tools/docmaker/tohtml.py#L255-L285 | [
"def",
"make_html_word",
"(",
"self",
",",
"word",
")",
":",
"# look for cross-references",
"m",
"=",
"re_crossref",
".",
"match",
"(",
"word",
")",
"if",
"m",
":",
"try",
":",
"name",
"=",
"m",
".",
"group",
"(",
"1",
")",
"rest",
"=",
"m",
".",
"group",
"(",
"2",
")",
"block",
"=",
"self",
".",
"identifiers",
"[",
"name",
"]",
"url",
"=",
"self",
".",
"make_block_url",
"(",
"block",
")",
"return",
"'<a href=\"'",
"+",
"url",
"+",
"'\">'",
"+",
"name",
"+",
"'</a>'",
"+",
"rest",
"except",
":",
"# we detected a cross-reference to an unknown item",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"WARNING: undefined cross reference '\"",
"+",
"name",
"+",
"\"'.\\n\"",
")",
"return",
"'?'",
"+",
"name",
"+",
"'?'",
"+",
"rest",
"# look for italics and bolds",
"m",
"=",
"re_italic",
".",
"match",
"(",
"word",
")",
"if",
"m",
":",
"name",
"=",
"m",
".",
"group",
"(",
"1",
")",
"rest",
"=",
"m",
".",
"group",
"(",
"3",
")",
"return",
"'<i>'",
"+",
"name",
"+",
"'</i>'",
"+",
"rest",
"m",
"=",
"re_bold",
".",
"match",
"(",
"word",
")",
"if",
"m",
":",
"name",
"=",
"m",
".",
"group",
"(",
"1",
")",
"rest",
"=",
"m",
".",
"group",
"(",
"3",
")",
"return",
"'<b>'",
"+",
"name",
"+",
"'</b>'",
"+",
"rest",
"return",
"html_quote",
"(",
"word",
")"
] | edf3810dcb211942d392a8637945871399b0650d |
test | HtmlFormatter.make_html_para | convert words of a paragraph into tagged HTML text, handle xrefs | native/Vendor/FreeType/src/tools/docmaker/tohtml.py | def make_html_para( self, words ):
""" convert words of a paragraph into tagged HTML text, handle xrefs """
line = ""
if words:
line = self.make_html_word( words[0] )
for word in words[1:]:
line = line + " " + self.make_html_word( word )
# convert `...' quotations into real left and right single quotes
line = re.sub( r"(^|\W)`(.*?)'(\W|$)", \
r'\1‘\2’\3', \
line )
# convert tilde into non-breakable space
line = string.replace( line, "~", " " )
return para_header + line + para_footer | def make_html_para( self, words ):
""" convert words of a paragraph into tagged HTML text, handle xrefs """
line = ""
if words:
line = self.make_html_word( words[0] )
for word in words[1:]:
line = line + " " + self.make_html_word( word )
# convert `...' quotations into real left and right single quotes
line = re.sub( r"(^|\W)`(.*?)'(\W|$)", \
r'\1‘\2’\3', \
line )
# convert tilde into non-breakable space
line = string.replace( line, "~", " " )
return para_header + line + para_footer | [
"convert",
"words",
"of",
"a",
"paragraph",
"into",
"tagged",
"HTML",
"text",
"handle",
"xrefs"
] | aholkner/bacon | python | https://github.com/aholkner/bacon/blob/edf3810dcb211942d392a8637945871399b0650d/native/Vendor/FreeType/src/tools/docmaker/tohtml.py#L287-L301 | [
"def",
"make_html_para",
"(",
"self",
",",
"words",
")",
":",
"line",
"=",
"\"\"",
"if",
"words",
":",
"line",
"=",
"self",
".",
"make_html_word",
"(",
"words",
"[",
"0",
"]",
")",
"for",
"word",
"in",
"words",
"[",
"1",
":",
"]",
":",
"line",
"=",
"line",
"+",
"\" \"",
"+",
"self",
".",
"make_html_word",
"(",
"word",
")",
"# convert `...' quotations into real left and right single quotes",
"line",
"=",
"re",
".",
"sub",
"(",
"r\"(^|\\W)`(.*?)'(\\W|$)\"",
",",
"r'\\1‘\\2’\\3'",
",",
"line",
")",
"# convert tilde into non-breakable space",
"line",
"=",
"string",
".",
"replace",
"(",
"line",
",",
"\"~\"",
",",
"\" \"",
")",
"return",
"para_header",
"+",
"line",
"+",
"para_footer"
] | edf3810dcb211942d392a8637945871399b0650d |
test | HtmlFormatter.make_html_code | convert a code sequence to HTML | native/Vendor/FreeType/src/tools/docmaker/tohtml.py | def make_html_code( self, lines ):
""" convert a code sequence to HTML """
line = code_header + '\n'
for l in lines:
line = line + html_quote( l ) + '\n'
return line + code_footer | def make_html_code( self, lines ):
""" convert a code sequence to HTML """
line = code_header + '\n'
for l in lines:
line = line + html_quote( l ) + '\n'
return line + code_footer | [
"convert",
"a",
"code",
"sequence",
"to",
"HTML"
] | aholkner/bacon | python | https://github.com/aholkner/bacon/blob/edf3810dcb211942d392a8637945871399b0650d/native/Vendor/FreeType/src/tools/docmaker/tohtml.py#L303-L309 | [
"def",
"make_html_code",
"(",
"self",
",",
"lines",
")",
":",
"line",
"=",
"code_header",
"+",
"'\\n'",
"for",
"l",
"in",
"lines",
":",
"line",
"=",
"line",
"+",
"html_quote",
"(",
"l",
")",
"+",
"'\\n'",
"return",
"line",
"+",
"code_footer"
] | edf3810dcb211942d392a8637945871399b0650d |
test | HtmlFormatter.make_html_items | convert a field's content into some valid HTML | native/Vendor/FreeType/src/tools/docmaker/tohtml.py | def make_html_items( self, items ):
""" convert a field's content into some valid HTML """
lines = []
for item in items:
if item.lines:
lines.append( self.make_html_code( item.lines ) )
else:
lines.append( self.make_html_para( item.words ) )
return string.join( lines, '\n' ) | def make_html_items( self, items ):
""" convert a field's content into some valid HTML """
lines = []
for item in items:
if item.lines:
lines.append( self.make_html_code( item.lines ) )
else:
lines.append( self.make_html_para( item.words ) )
return string.join( lines, '\n' ) | [
"convert",
"a",
"field",
"s",
"content",
"into",
"some",
"valid",
"HTML"
] | aholkner/bacon | python | https://github.com/aholkner/bacon/blob/edf3810dcb211942d392a8637945871399b0650d/native/Vendor/FreeType/src/tools/docmaker/tohtml.py#L311-L320 | [
"def",
"make_html_items",
"(",
"self",
",",
"items",
")",
":",
"lines",
"=",
"[",
"]",
"for",
"item",
"in",
"items",
":",
"if",
"item",
".",
"lines",
":",
"lines",
".",
"append",
"(",
"self",
".",
"make_html_code",
"(",
"item",
".",
"lines",
")",
")",
"else",
":",
"lines",
".",
"append",
"(",
"self",
".",
"make_html_para",
"(",
"item",
".",
"words",
")",
")",
"return",
"string",
".",
"join",
"(",
"lines",
",",
"'\\n'",
")"
] | edf3810dcb211942d392a8637945871399b0650d |
test | main | main program loop | native/Vendor/FreeType/src/tools/docmaker/docmaker.py | def main( argv ):
"""main program loop"""
global output_dir
try:
opts, args = getopt.getopt( sys.argv[1:], \
"ht:o:p:", \
["help", "title=", "output=", "prefix="] )
except getopt.GetoptError:
usage()
sys.exit( 2 )
if args == []:
usage()
sys.exit( 1 )
# process options
#
project_title = "Project"
project_prefix = None
output_dir = None
for opt in opts:
if opt[0] in ( "-h", "--help" ):
usage()
sys.exit( 0 )
if opt[0] in ( "-t", "--title" ):
project_title = opt[1]
if opt[0] in ( "-o", "--output" ):
utils.output_dir = opt[1]
if opt[0] in ( "-p", "--prefix" ):
project_prefix = opt[1]
check_output()
# create context and processor
source_processor = SourceProcessor()
content_processor = ContentProcessor()
# retrieve the list of files to process
file_list = make_file_list( args )
for filename in file_list:
source_processor.parse_file( filename )
content_processor.parse_sources( source_processor )
# process sections
content_processor.finish()
formatter = HtmlFormatter( content_processor, project_title, project_prefix )
formatter.toc_dump()
formatter.index_dump()
formatter.section_dump_all() | def main( argv ):
"""main program loop"""
global output_dir
try:
opts, args = getopt.getopt( sys.argv[1:], \
"ht:o:p:", \
["help", "title=", "output=", "prefix="] )
except getopt.GetoptError:
usage()
sys.exit( 2 )
if args == []:
usage()
sys.exit( 1 )
# process options
#
project_title = "Project"
project_prefix = None
output_dir = None
for opt in opts:
if opt[0] in ( "-h", "--help" ):
usage()
sys.exit( 0 )
if opt[0] in ( "-t", "--title" ):
project_title = opt[1]
if opt[0] in ( "-o", "--output" ):
utils.output_dir = opt[1]
if opt[0] in ( "-p", "--prefix" ):
project_prefix = opt[1]
check_output()
# create context and processor
source_processor = SourceProcessor()
content_processor = ContentProcessor()
# retrieve the list of files to process
file_list = make_file_list( args )
for filename in file_list:
source_processor.parse_file( filename )
content_processor.parse_sources( source_processor )
# process sections
content_processor.finish()
formatter = HtmlFormatter( content_processor, project_title, project_prefix )
formatter.toc_dump()
formatter.index_dump()
formatter.section_dump_all() | [
"main",
"program",
"loop"
] | aholkner/bacon | python | https://github.com/aholkner/bacon/blob/edf3810dcb211942d392a8637945871399b0650d/native/Vendor/FreeType/src/tools/docmaker/docmaker.py#L41-L97 | [
"def",
"main",
"(",
"argv",
")",
":",
"global",
"output_dir",
"try",
":",
"opts",
",",
"args",
"=",
"getopt",
".",
"getopt",
"(",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
",",
"\"ht:o:p:\"",
",",
"[",
"\"help\"",
",",
"\"title=\"",
",",
"\"output=\"",
",",
"\"prefix=\"",
"]",
")",
"except",
"getopt",
".",
"GetoptError",
":",
"usage",
"(",
")",
"sys",
".",
"exit",
"(",
"2",
")",
"if",
"args",
"==",
"[",
"]",
":",
"usage",
"(",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"# process options",
"#",
"project_title",
"=",
"\"Project\"",
"project_prefix",
"=",
"None",
"output_dir",
"=",
"None",
"for",
"opt",
"in",
"opts",
":",
"if",
"opt",
"[",
"0",
"]",
"in",
"(",
"\"-h\"",
",",
"\"--help\"",
")",
":",
"usage",
"(",
")",
"sys",
".",
"exit",
"(",
"0",
")",
"if",
"opt",
"[",
"0",
"]",
"in",
"(",
"\"-t\"",
",",
"\"--title\"",
")",
":",
"project_title",
"=",
"opt",
"[",
"1",
"]",
"if",
"opt",
"[",
"0",
"]",
"in",
"(",
"\"-o\"",
",",
"\"--output\"",
")",
":",
"utils",
".",
"output_dir",
"=",
"opt",
"[",
"1",
"]",
"if",
"opt",
"[",
"0",
"]",
"in",
"(",
"\"-p\"",
",",
"\"--prefix\"",
")",
":",
"project_prefix",
"=",
"opt",
"[",
"1",
"]",
"check_output",
"(",
")",
"# create context and processor",
"source_processor",
"=",
"SourceProcessor",
"(",
")",
"content_processor",
"=",
"ContentProcessor",
"(",
")",
"# retrieve the list of files to process",
"file_list",
"=",
"make_file_list",
"(",
"args",
")",
"for",
"filename",
"in",
"file_list",
":",
"source_processor",
".",
"parse_file",
"(",
"filename",
")",
"content_processor",
".",
"parse_sources",
"(",
"source_processor",
")",
"# process sections",
"content_processor",
".",
"finish",
"(",
")",
"formatter",
"=",
"HtmlFormatter",
"(",
"content_processor",
",",
"project_title",
",",
"project_prefix",
")",
"formatter",
".",
"toc_dump",
"(",
")",
"formatter",
".",
"index_dump",
"(",
")",
"formatter",
".",
"section_dump_all",
"(",
")"
] | edf3810dcb211942d392a8637945871399b0650d |
test | get_hosted_zone_by_id_parser | Parses the API responses for the
:py:meth:`route53.connection.Route53Connection.get_hosted_zone_by_id` method.
:param lxml.etree._Element root: The root node of the etree parsed
response from the API.
:param Route53Connection connection: The connection instance used to
query the API.
:rtype: HostedZone
:returns: The requested HostedZone. | route53/xml_parsers/get_hosted_zone_by_id.py | def get_hosted_zone_by_id_parser(root, connection):
"""
Parses the API responses for the
:py:meth:`route53.connection.Route53Connection.get_hosted_zone_by_id` method.
:param lxml.etree._Element root: The root node of the etree parsed
response from the API.
:param Route53Connection connection: The connection instance used to
query the API.
:rtype: HostedZone
:returns: The requested HostedZone.
"""
e_zone = root.find('./{*}HostedZone')
# This pops out a HostedZone instance.
hosted_zone = parse_hosted_zone(e_zone, connection)
# Now we'll fill in the nameservers.
e_delegation_set = root.find('./{*}DelegationSet')
# Modifies the HostedZone in place.
parse_delegation_set(hosted_zone, e_delegation_set)
return hosted_zone | def get_hosted_zone_by_id_parser(root, connection):
"""
Parses the API responses for the
:py:meth:`route53.connection.Route53Connection.get_hosted_zone_by_id` method.
:param lxml.etree._Element root: The root node of the etree parsed
response from the API.
:param Route53Connection connection: The connection instance used to
query the API.
:rtype: HostedZone
:returns: The requested HostedZone.
"""
e_zone = root.find('./{*}HostedZone')
# This pops out a HostedZone instance.
hosted_zone = parse_hosted_zone(e_zone, connection)
# Now we'll fill in the nameservers.
e_delegation_set = root.find('./{*}DelegationSet')
# Modifies the HostedZone in place.
parse_delegation_set(hosted_zone, e_delegation_set)
return hosted_zone | [
"Parses",
"the",
"API",
"responses",
"for",
"the",
":",
"py",
":",
"meth",
":",
"route53",
".",
"connection",
".",
"Route53Connection",
".",
"get_hosted_zone_by_id",
"method",
"."
] | gtaylor/python-route53 | python | https://github.com/gtaylor/python-route53/blob/b9fc7e258a79551c9ed61e4a71668b7f06f9e774/route53/xml_parsers/get_hosted_zone_by_id.py#L3-L23 | [
"def",
"get_hosted_zone_by_id_parser",
"(",
"root",
",",
"connection",
")",
":",
"e_zone",
"=",
"root",
".",
"find",
"(",
"'./{*}HostedZone'",
")",
"# This pops out a HostedZone instance.",
"hosted_zone",
"=",
"parse_hosted_zone",
"(",
"e_zone",
",",
"connection",
")",
"# Now we'll fill in the nameservers.",
"e_delegation_set",
"=",
"root",
".",
"find",
"(",
"'./{*}DelegationSet'",
")",
"# Modifies the HostedZone in place.",
"parse_delegation_set",
"(",
"hosted_zone",
",",
"e_delegation_set",
")",
"return",
"hosted_zone"
] | b9fc7e258a79551c9ed61e4a71668b7f06f9e774 |
test | MP4Tags.save | Save the metadata to the given filename. | mutagen/mp4.py | def save(self, filename):
"""Save the metadata to the given filename."""
values = []
items = sorted(self.items(), key=MP4Tags.__get_sort_stats )
for key, value in items:
info = self.__atoms.get(key[:4], (None, type(self).__render_text))
try:
values.append(info[1](self, key, value, *info[2:]))
except (TypeError, ValueError) as s:
reraise(MP4MetadataValueError, s, sys.exc_info()[2])
data = Atom.render(b"ilst", b"".join(values))
# Find the old atoms.
fileobj = open(filename, "rb+")
try:
atoms = Atoms(fileobj)
try:
path = atoms.path(b"moov", b"udta", b"meta", b"ilst")
except KeyError:
self.__save_new(fileobj, atoms, data)
else:
self.__save_existing(fileobj, atoms, path, data)
finally:
fileobj.close() | def save(self, filename):
"""Save the metadata to the given filename."""
values = []
items = sorted(self.items(), key=MP4Tags.__get_sort_stats )
for key, value in items:
info = self.__atoms.get(key[:4], (None, type(self).__render_text))
try:
values.append(info[1](self, key, value, *info[2:]))
except (TypeError, ValueError) as s:
reraise(MP4MetadataValueError, s, sys.exc_info()[2])
data = Atom.render(b"ilst", b"".join(values))
# Find the old atoms.
fileobj = open(filename, "rb+")
try:
atoms = Atoms(fileobj)
try:
path = atoms.path(b"moov", b"udta", b"meta", b"ilst")
except KeyError:
self.__save_new(fileobj, atoms, data)
else:
self.__save_existing(fileobj, atoms, path, data)
finally:
fileobj.close() | [
"Save",
"the",
"metadata",
"to",
"the",
"given",
"filename",
"."
] | LordSputnik/mutagen | python | https://github.com/LordSputnik/mutagen/blob/38e62c8dc35c72b16554f5dbe7c0fde91acc3411/mutagen/mp4.py#L362-L386 | [
"def",
"save",
"(",
"self",
",",
"filename",
")",
":",
"values",
"=",
"[",
"]",
"items",
"=",
"sorted",
"(",
"self",
".",
"items",
"(",
")",
",",
"key",
"=",
"MP4Tags",
".",
"__get_sort_stats",
")",
"for",
"key",
",",
"value",
"in",
"items",
":",
"info",
"=",
"self",
".",
"__atoms",
".",
"get",
"(",
"key",
"[",
":",
"4",
"]",
",",
"(",
"None",
",",
"type",
"(",
"self",
")",
".",
"__render_text",
")",
")",
"try",
":",
"values",
".",
"append",
"(",
"info",
"[",
"1",
"]",
"(",
"self",
",",
"key",
",",
"value",
",",
"*",
"info",
"[",
"2",
":",
"]",
")",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
"as",
"s",
":",
"reraise",
"(",
"MP4MetadataValueError",
",",
"s",
",",
"sys",
".",
"exc_info",
"(",
")",
"[",
"2",
"]",
")",
"data",
"=",
"Atom",
".",
"render",
"(",
"b\"ilst\"",
",",
"b\"\"",
".",
"join",
"(",
"values",
")",
")",
"# Find the old atoms.",
"fileobj",
"=",
"open",
"(",
"filename",
",",
"\"rb+\"",
")",
"try",
":",
"atoms",
"=",
"Atoms",
"(",
"fileobj",
")",
"try",
":",
"path",
"=",
"atoms",
".",
"path",
"(",
"b\"moov\"",
",",
"b\"udta\"",
",",
"b\"meta\"",
",",
"b\"ilst\"",
")",
"except",
"KeyError",
":",
"self",
".",
"__save_new",
"(",
"fileobj",
",",
"atoms",
",",
"data",
")",
"else",
":",
"self",
".",
"__save_existing",
"(",
"fileobj",
",",
"atoms",
",",
"path",
",",
"data",
")",
"finally",
":",
"fileobj",
".",
"close",
"(",
")"
] | 38e62c8dc35c72b16554f5dbe7c0fde91acc3411 |
test | MP4Tags.__update_parents | Update all parent atoms with the new size. | mutagen/mp4.py | def __update_parents(self, fileobj, path, delta):
"""Update all parent atoms with the new size."""
for atom in path:
fileobj.seek(atom.offset)
size = cdata.uint_be(fileobj.read(4))
if size == 1: # 64bit
# skip name (4B) and read size (8B)
size = cdata.ulonglong_be(fileobj.read(12)[4:])
fileobj.seek(atom.offset + 8)
fileobj.write(cdata.to_ulonglong_be(size + delta))
else: # 32bit
fileobj.seek(atom.offset)
fileobj.write(cdata.to_uint_be(size + delta)) | def __update_parents(self, fileobj, path, delta):
"""Update all parent atoms with the new size."""
for atom in path:
fileobj.seek(atom.offset)
size = cdata.uint_be(fileobj.read(4))
if size == 1: # 64bit
# skip name (4B) and read size (8B)
size = cdata.ulonglong_be(fileobj.read(12)[4:])
fileobj.seek(atom.offset + 8)
fileobj.write(cdata.to_ulonglong_be(size + delta))
else: # 32bit
fileobj.seek(atom.offset)
fileobj.write(cdata.to_uint_be(size + delta)) | [
"Update",
"all",
"parent",
"atoms",
"with",
"the",
"new",
"size",
"."
] | LordSputnik/mutagen | python | https://github.com/LordSputnik/mutagen/blob/38e62c8dc35c72b16554f5dbe7c0fde91acc3411/mutagen/mp4.py#L447-L459 | [
"def",
"__update_parents",
"(",
"self",
",",
"fileobj",
",",
"path",
",",
"delta",
")",
":",
"for",
"atom",
"in",
"path",
":",
"fileobj",
".",
"seek",
"(",
"atom",
".",
"offset",
")",
"size",
"=",
"cdata",
".",
"uint_be",
"(",
"fileobj",
".",
"read",
"(",
"4",
")",
")",
"if",
"size",
"==",
"1",
":",
"# 64bit",
"# skip name (4B) and read size (8B)",
"size",
"=",
"cdata",
".",
"ulonglong_be",
"(",
"fileobj",
".",
"read",
"(",
"12",
")",
"[",
"4",
":",
"]",
")",
"fileobj",
".",
"seek",
"(",
"atom",
".",
"offset",
"+",
"8",
")",
"fileobj",
".",
"write",
"(",
"cdata",
".",
"to_ulonglong_be",
"(",
"size",
"+",
"delta",
")",
")",
"else",
":",
"# 32bit",
"fileobj",
".",
"seek",
"(",
"atom",
".",
"offset",
")",
"fileobj",
".",
"write",
"(",
"cdata",
".",
"to_uint_be",
"(",
"size",
"+",
"delta",
")",
")"
] | 38e62c8dc35c72b16554f5dbe7c0fde91acc3411 |
test | run | Start running the game. The window is created and shown at this point, and then
the main event loop is entered. 'game.on_tick' and other event handlers are called
repeatedly until the game exits.
If a game is already running, this function replaces the :class:`Game` instance that
receives events. | bacon/game.py | def run(game):
'''Start running the game. The window is created and shown at this point, and then
the main event loop is entered. 'game.on_tick' and other event handlers are called
repeatedly until the game exits.
If a game is already running, this function replaces the :class:`Game` instance that
receives events.
'''
if bacon._current_game:
bacon._current_game = game
return
global _tick_callback_handle
bacon._current_game = game
# Window handler
window_resize_callback_handle = lib.WindowResizeEventHandler(window._window_resize_event_handler)
lib.SetWindowResizeEventHandler(window_resize_callback_handle)
# Key handler
key_callback_handle = lib.KeyEventHandler(keyboard._key_event_handler)
lib.SetKeyEventHandler(key_callback_handle)
# Mouse handlers
mouse_button_callback_handle = lib.MouseButtonEventHandler(mouse_input._mouse_button_event_handler)
lib.SetMouseButtonEventHandler(mouse_button_callback_handle)
mouse_scroll_callback_handle = lib.MouseScrollEventHandler(mouse_input._mouse_scroll_event_handler)
lib.SetMouseScrollEventHandler(mouse_scroll_callback_handle)
# Controller handlers
controller_connected_handle = lib.ControllerConnectedEventHandler(controller._controller_connected_event_handler)
lib.SetControllerConnectedEventHandler(controller_connected_handle)
controller_button_handle = lib.ControllerButtonEventHandler(controller._controller_button_event_handler)
lib.SetControllerButtonEventHandler(controller_button_handle)
controller_axis_handle = lib.ControllerAxisEventHandler(controller._controller_axis_event_handler)
lib.SetControllerAxisEventHandler(controller_axis_handle)
# Tick handler
_tick_callback_handle = lib.TickCallback(_first_tick_callback)
lib.SetTickCallback(_tick_callback_handle)
lib.Run()
bacon._current_game = None
_tick_callback_handle = None
lib.SetWindowResizeEventHandler(lib.WindowResizeEventHandler(0))
lib.SetKeyEventHandler(lib.KeyEventHandler(0))
lib.SetMouseButtonEventHandler(lib.MouseButtonEventHandler(0))
lib.SetMouseScrollEventHandler(lib.MouseScrollEventHandler(0))
lib.SetControllerConnectedEventHandler(lib.ControllerConnectedEventHandler(0))
lib.SetControllerButtonEventHandler(lib.ControllerButtonEventHandler(0))
lib.SetControllerAxisEventHandler(lib.ControllerAxisEventHandler(0))
lib.SetTickCallback(lib.TickCallback(0)) | def run(game):
'''Start running the game. The window is created and shown at this point, and then
the main event loop is entered. 'game.on_tick' and other event handlers are called
repeatedly until the game exits.
If a game is already running, this function replaces the :class:`Game` instance that
receives events.
'''
if bacon._current_game:
bacon._current_game = game
return
global _tick_callback_handle
bacon._current_game = game
# Window handler
window_resize_callback_handle = lib.WindowResizeEventHandler(window._window_resize_event_handler)
lib.SetWindowResizeEventHandler(window_resize_callback_handle)
# Key handler
key_callback_handle = lib.KeyEventHandler(keyboard._key_event_handler)
lib.SetKeyEventHandler(key_callback_handle)
# Mouse handlers
mouse_button_callback_handle = lib.MouseButtonEventHandler(mouse_input._mouse_button_event_handler)
lib.SetMouseButtonEventHandler(mouse_button_callback_handle)
mouse_scroll_callback_handle = lib.MouseScrollEventHandler(mouse_input._mouse_scroll_event_handler)
lib.SetMouseScrollEventHandler(mouse_scroll_callback_handle)
# Controller handlers
controller_connected_handle = lib.ControllerConnectedEventHandler(controller._controller_connected_event_handler)
lib.SetControllerConnectedEventHandler(controller_connected_handle)
controller_button_handle = lib.ControllerButtonEventHandler(controller._controller_button_event_handler)
lib.SetControllerButtonEventHandler(controller_button_handle)
controller_axis_handle = lib.ControllerAxisEventHandler(controller._controller_axis_event_handler)
lib.SetControllerAxisEventHandler(controller_axis_handle)
# Tick handler
_tick_callback_handle = lib.TickCallback(_first_tick_callback)
lib.SetTickCallback(_tick_callback_handle)
lib.Run()
bacon._current_game = None
_tick_callback_handle = None
lib.SetWindowResizeEventHandler(lib.WindowResizeEventHandler(0))
lib.SetKeyEventHandler(lib.KeyEventHandler(0))
lib.SetMouseButtonEventHandler(lib.MouseButtonEventHandler(0))
lib.SetMouseScrollEventHandler(lib.MouseScrollEventHandler(0))
lib.SetControllerConnectedEventHandler(lib.ControllerConnectedEventHandler(0))
lib.SetControllerButtonEventHandler(lib.ControllerButtonEventHandler(0))
lib.SetControllerAxisEventHandler(lib.ControllerAxisEventHandler(0))
lib.SetTickCallback(lib.TickCallback(0)) | [
"Start",
"running",
"the",
"game",
".",
"The",
"window",
"is",
"created",
"and",
"shown",
"at",
"this",
"point",
"and",
"then",
"the",
"main",
"event",
"loop",
"is",
"entered",
".",
"game",
".",
"on_tick",
"and",
"other",
"event",
"handlers",
"are",
"called",
"repeatedly",
"until",
"the",
"game",
"exits",
"."
] | aholkner/bacon | python | https://github.com/aholkner/bacon/blob/edf3810dcb211942d392a8637945871399b0650d/bacon/game.py#L166-L218 | [
"def",
"run",
"(",
"game",
")",
":",
"if",
"bacon",
".",
"_current_game",
":",
"bacon",
".",
"_current_game",
"=",
"game",
"return",
"global",
"_tick_callback_handle",
"bacon",
".",
"_current_game",
"=",
"game",
"# Window handler",
"window_resize_callback_handle",
"=",
"lib",
".",
"WindowResizeEventHandler",
"(",
"window",
".",
"_window_resize_event_handler",
")",
"lib",
".",
"SetWindowResizeEventHandler",
"(",
"window_resize_callback_handle",
")",
"# Key handler",
"key_callback_handle",
"=",
"lib",
".",
"KeyEventHandler",
"(",
"keyboard",
".",
"_key_event_handler",
")",
"lib",
".",
"SetKeyEventHandler",
"(",
"key_callback_handle",
")",
"# Mouse handlers",
"mouse_button_callback_handle",
"=",
"lib",
".",
"MouseButtonEventHandler",
"(",
"mouse_input",
".",
"_mouse_button_event_handler",
")",
"lib",
".",
"SetMouseButtonEventHandler",
"(",
"mouse_button_callback_handle",
")",
"mouse_scroll_callback_handle",
"=",
"lib",
".",
"MouseScrollEventHandler",
"(",
"mouse_input",
".",
"_mouse_scroll_event_handler",
")",
"lib",
".",
"SetMouseScrollEventHandler",
"(",
"mouse_scroll_callback_handle",
")",
"# Controller handlers",
"controller_connected_handle",
"=",
"lib",
".",
"ControllerConnectedEventHandler",
"(",
"controller",
".",
"_controller_connected_event_handler",
")",
"lib",
".",
"SetControllerConnectedEventHandler",
"(",
"controller_connected_handle",
")",
"controller_button_handle",
"=",
"lib",
".",
"ControllerButtonEventHandler",
"(",
"controller",
".",
"_controller_button_event_handler",
")",
"lib",
".",
"SetControllerButtonEventHandler",
"(",
"controller_button_handle",
")",
"controller_axis_handle",
"=",
"lib",
".",
"ControllerAxisEventHandler",
"(",
"controller",
".",
"_controller_axis_event_handler",
")",
"lib",
".",
"SetControllerAxisEventHandler",
"(",
"controller_axis_handle",
")",
"# Tick handler",
"_tick_callback_handle",
"=",
"lib",
".",
"TickCallback",
"(",
"_first_tick_callback",
")",
"lib",
".",
"SetTickCallback",
"(",
"_tick_callback_handle",
")",
"lib",
".",
"Run",
"(",
")",
"bacon",
".",
"_current_game",
"=",
"None",
"_tick_callback_handle",
"=",
"None",
"lib",
".",
"SetWindowResizeEventHandler",
"(",
"lib",
".",
"WindowResizeEventHandler",
"(",
"0",
")",
")",
"lib",
".",
"SetKeyEventHandler",
"(",
"lib",
".",
"KeyEventHandler",
"(",
"0",
")",
")",
"lib",
".",
"SetMouseButtonEventHandler",
"(",
"lib",
".",
"MouseButtonEventHandler",
"(",
"0",
")",
")",
"lib",
".",
"SetMouseScrollEventHandler",
"(",
"lib",
".",
"MouseScrollEventHandler",
"(",
"0",
")",
")",
"lib",
".",
"SetControllerConnectedEventHandler",
"(",
"lib",
".",
"ControllerConnectedEventHandler",
"(",
"0",
")",
")",
"lib",
".",
"SetControllerButtonEventHandler",
"(",
"lib",
".",
"ControllerButtonEventHandler",
"(",
"0",
")",
")",
"lib",
".",
"SetControllerAxisEventHandler",
"(",
"lib",
".",
"ControllerAxisEventHandler",
"(",
"0",
")",
")",
"lib",
".",
"SetTickCallback",
"(",
"lib",
".",
"TickCallback",
"(",
"0",
")",
")"
] | edf3810dcb211942d392a8637945871399b0650d |
test | ControllerMapping.register | Register a mapping for controllers with the given vendor and product IDs. The mapping will
replace any existing mapping for these IDs for controllers not yet connected.
:param vendor_id: the vendor ID of the controller, as reported by :attr:`Controller.vendor_id`
:param product_id: the vendor ID of the controller, as reported by :attr:`Controller.product_id`
:param mapping: a :class:`ControllerMapping` to apply | bacon/controller.py | def register(cls, vendor_id, product_id, mapping):
'''Register a mapping for controllers with the given vendor and product IDs. The mapping will
replace any existing mapping for these IDs for controllers not yet connected.
:param vendor_id: the vendor ID of the controller, as reported by :attr:`Controller.vendor_id`
:param product_id: the vendor ID of the controller, as reported by :attr:`Controller.product_id`
:param mapping: a :class:`ControllerMapping` to apply
'''
cls._registry[(vendor_id, product_id)] = mapping | def register(cls, vendor_id, product_id, mapping):
'''Register a mapping for controllers with the given vendor and product IDs. The mapping will
replace any existing mapping for these IDs for controllers not yet connected.
:param vendor_id: the vendor ID of the controller, as reported by :attr:`Controller.vendor_id`
:param product_id: the vendor ID of the controller, as reported by :attr:`Controller.product_id`
:param mapping: a :class:`ControllerMapping` to apply
'''
cls._registry[(vendor_id, product_id)] = mapping | [
"Register",
"a",
"mapping",
"for",
"controllers",
"with",
"the",
"given",
"vendor",
"and",
"product",
"IDs",
".",
"The",
"mapping",
"will",
"replace",
"any",
"existing",
"mapping",
"for",
"these",
"IDs",
"for",
"controllers",
"not",
"yet",
"connected",
"."
] | aholkner/bacon | python | https://github.com/aholkner/bacon/blob/edf3810dcb211942d392a8637945871399b0650d/bacon/controller.py#L265-L273 | [
"def",
"register",
"(",
"cls",
",",
"vendor_id",
",",
"product_id",
",",
"mapping",
")",
":",
"cls",
".",
"_registry",
"[",
"(",
"vendor_id",
",",
"product_id",
")",
"]",
"=",
"mapping"
] | edf3810dcb211942d392a8637945871399b0650d |
test | ControllerMapping.get | Find a mapping that can apply to the given controller. Returns None if unsuccessful.
:param controller: :class:`Controller` to look up
:return: :class:`ControllerMapping` | bacon/controller.py | def get(cls, controller):
'''Find a mapping that can apply to the given controller. Returns None if unsuccessful.
:param controller: :class:`Controller` to look up
:return: :class:`ControllerMapping`
'''
try:
return cls._registry[(controller.vendor_id, controller.product_id)]
except KeyError:
return None | def get(cls, controller):
'''Find a mapping that can apply to the given controller. Returns None if unsuccessful.
:param controller: :class:`Controller` to look up
:return: :class:`ControllerMapping`
'''
try:
return cls._registry[(controller.vendor_id, controller.product_id)]
except KeyError:
return None | [
"Find",
"a",
"mapping",
"that",
"can",
"apply",
"to",
"the",
"given",
"controller",
".",
"Returns",
"None",
"if",
"unsuccessful",
"."
] | aholkner/bacon | python | https://github.com/aholkner/bacon/blob/edf3810dcb211942d392a8637945871399b0650d/bacon/controller.py#L276-L285 | [
"def",
"get",
"(",
"cls",
",",
"controller",
")",
":",
"try",
":",
"return",
"cls",
".",
"_registry",
"[",
"(",
"controller",
".",
"vendor_id",
",",
"controller",
".",
"product_id",
")",
"]",
"except",
"KeyError",
":",
"return",
"None"
] | edf3810dcb211942d392a8637945871399b0650d |
test | EasyMP4Tags.RegisterFreeformKey | Register a text key.
If the key you need to register is a simple one-to-one mapping
of MP4 freeform atom (----) and name to EasyMP4Tags key, then
you can use this function::
EasyMP4Tags.RegisterFreeformKey(
"musicbrainz_artistid", b"MusicBrainz Artist Id") | mutagen/easymp4.py | def RegisterFreeformKey(cls, key, name, mean=b"com.apple.iTunes"):
"""Register a text key.
If the key you need to register is a simple one-to-one mapping
of MP4 freeform atom (----) and name to EasyMP4Tags key, then
you can use this function::
EasyMP4Tags.RegisterFreeformKey(
"musicbrainz_artistid", b"MusicBrainz Artist Id")
"""
atomid = b"----:" + mean + b":" + name
def getter(tags, key):
return [s.decode("utf-8", "replace") for s in tags[atomid]]
def setter(tags, key, value):
tags[atomid] = [utf8(v) for v in value]
def deleter(tags, key):
del(tags[atomid])
cls.RegisterKey(key, getter, setter, deleter) | def RegisterFreeformKey(cls, key, name, mean=b"com.apple.iTunes"):
"""Register a text key.
If the key you need to register is a simple one-to-one mapping
of MP4 freeform atom (----) and name to EasyMP4Tags key, then
you can use this function::
EasyMP4Tags.RegisterFreeformKey(
"musicbrainz_artistid", b"MusicBrainz Artist Id")
"""
atomid = b"----:" + mean + b":" + name
def getter(tags, key):
return [s.decode("utf-8", "replace") for s in tags[atomid]]
def setter(tags, key, value):
tags[atomid] = [utf8(v) for v in value]
def deleter(tags, key):
del(tags[atomid])
cls.RegisterKey(key, getter, setter, deleter) | [
"Register",
"a",
"text",
"key",
"."
] | LordSputnik/mutagen | python | https://github.com/LordSputnik/mutagen/blob/38e62c8dc35c72b16554f5dbe7c0fde91acc3411/mutagen/easymp4.py#L148-L169 | [
"def",
"RegisterFreeformKey",
"(",
"cls",
",",
"key",
",",
"name",
",",
"mean",
"=",
"b\"com.apple.iTunes\"",
")",
":",
"atomid",
"=",
"b\"----:\"",
"+",
"mean",
"+",
"b\":\"",
"+",
"name",
"def",
"getter",
"(",
"tags",
",",
"key",
")",
":",
"return",
"[",
"s",
".",
"decode",
"(",
"\"utf-8\"",
",",
"\"replace\"",
")",
"for",
"s",
"in",
"tags",
"[",
"atomid",
"]",
"]",
"def",
"setter",
"(",
"tags",
",",
"key",
",",
"value",
")",
":",
"tags",
"[",
"atomid",
"]",
"=",
"[",
"utf8",
"(",
"v",
")",
"for",
"v",
"in",
"value",
"]",
"def",
"deleter",
"(",
"tags",
",",
"key",
")",
":",
"del",
"(",
"tags",
"[",
"atomid",
"]",
")",
"cls",
".",
"RegisterKey",
"(",
"key",
",",
"getter",
",",
"setter",
",",
"deleter",
")"
] | 38e62c8dc35c72b16554f5dbe7c0fde91acc3411 |
test | BaseTransport._hmac_sign_string | Route53 uses AWS an HMAC-based authentication scheme, involving the
signing of a date string with the user's secret access key. More details
on the specifics can be found in their documentation_.
.. documentation:: http://docs.amazonwebservices.com/Route53/latest/DeveloperGuide/RESTAuthentication.html
This method is used to sign said time string, for use in the request
headers.
:param str string_to_sign: The time string to sign.
:rtype: str
:returns: An HMAC signed string. | route53/transport.py | def _hmac_sign_string(self, string_to_sign):
"""
Route53 uses AWS an HMAC-based authentication scheme, involving the
signing of a date string with the user's secret access key. More details
on the specifics can be found in their documentation_.
.. documentation:: http://docs.amazonwebservices.com/Route53/latest/DeveloperGuide/RESTAuthentication.html
This method is used to sign said time string, for use in the request
headers.
:param str string_to_sign: The time string to sign.
:rtype: str
:returns: An HMAC signed string.
"""
# Just use SHA256, since we're all running modern versions
# of Python (right?).
new_hmac = hmac.new(
self.connection._aws_secret_access_key.encode('utf-8'),
digestmod=hashlib.sha256
)
new_hmac.update(string_to_sign.encode('utf-8'))
# The HMAC digest str is done at this point.
digest = new_hmac.digest()
# Now we have to Base64 encode it, and we're done.
return base64.b64encode(digest).decode('utf-8') | def _hmac_sign_string(self, string_to_sign):
"""
Route53 uses AWS an HMAC-based authentication scheme, involving the
signing of a date string with the user's secret access key. More details
on the specifics can be found in their documentation_.
.. documentation:: http://docs.amazonwebservices.com/Route53/latest/DeveloperGuide/RESTAuthentication.html
This method is used to sign said time string, for use in the request
headers.
:param str string_to_sign: The time string to sign.
:rtype: str
:returns: An HMAC signed string.
"""
# Just use SHA256, since we're all running modern versions
# of Python (right?).
new_hmac = hmac.new(
self.connection._aws_secret_access_key.encode('utf-8'),
digestmod=hashlib.sha256
)
new_hmac.update(string_to_sign.encode('utf-8'))
# The HMAC digest str is done at this point.
digest = new_hmac.digest()
# Now we have to Base64 encode it, and we're done.
return base64.b64encode(digest).decode('utf-8') | [
"Route53",
"uses",
"AWS",
"an",
"HMAC",
"-",
"based",
"authentication",
"scheme",
"involving",
"the",
"signing",
"of",
"a",
"date",
"string",
"with",
"the",
"user",
"s",
"secret",
"access",
"key",
".",
"More",
"details",
"on",
"the",
"specifics",
"can",
"be",
"found",
"in",
"their",
"documentation_",
"."
] | gtaylor/python-route53 | python | https://github.com/gtaylor/python-route53/blob/b9fc7e258a79551c9ed61e4a71668b7f06f9e774/route53/transport.py#L38-L65 | [
"def",
"_hmac_sign_string",
"(",
"self",
",",
"string_to_sign",
")",
":",
"# Just use SHA256, since we're all running modern versions",
"# of Python (right?).",
"new_hmac",
"=",
"hmac",
".",
"new",
"(",
"self",
".",
"connection",
".",
"_aws_secret_access_key",
".",
"encode",
"(",
"'utf-8'",
")",
",",
"digestmod",
"=",
"hashlib",
".",
"sha256",
")",
"new_hmac",
".",
"update",
"(",
"string_to_sign",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"# The HMAC digest str is done at this point.",
"digest",
"=",
"new_hmac",
".",
"digest",
"(",
")",
"# Now we have to Base64 encode it, and we're done.",
"return",
"base64",
".",
"b64encode",
"(",
"digest",
")",
".",
"decode",
"(",
"'utf-8'",
")"
] | b9fc7e258a79551c9ed61e4a71668b7f06f9e774 |
test | BaseTransport.get_request_headers | Determine the headers to send along with the request. These are
pretty much the same for every request, with Route53. | route53/transport.py | def get_request_headers(self):
"""
Determine the headers to send along with the request. These are
pretty much the same for every request, with Route53.
"""
date_header = time.asctime(time.gmtime())
# We sign the time string above with the user's AWS secret access key
# in order to authenticate our request.
signing_key = self._hmac_sign_string(date_header)
# Amazon's super fun auth token.
auth_header = "AWS3-HTTPS AWSAccessKeyId=%s,Algorithm=HmacSHA256,Signature=%s" % (
self.connection._aws_access_key_id,
signing_key,
)
return {
'X-Amzn-Authorization': auth_header,
'x-amz-date': date_header,
'Host': 'route53.amazonaws.com',
} | def get_request_headers(self):
"""
Determine the headers to send along with the request. These are
pretty much the same for every request, with Route53.
"""
date_header = time.asctime(time.gmtime())
# We sign the time string above with the user's AWS secret access key
# in order to authenticate our request.
signing_key = self._hmac_sign_string(date_header)
# Amazon's super fun auth token.
auth_header = "AWS3-HTTPS AWSAccessKeyId=%s,Algorithm=HmacSHA256,Signature=%s" % (
self.connection._aws_access_key_id,
signing_key,
)
return {
'X-Amzn-Authorization': auth_header,
'x-amz-date': date_header,
'Host': 'route53.amazonaws.com',
} | [
"Determine",
"the",
"headers",
"to",
"send",
"along",
"with",
"the",
"request",
".",
"These",
"are",
"pretty",
"much",
"the",
"same",
"for",
"every",
"request",
"with",
"Route53",
"."
] | gtaylor/python-route53 | python | https://github.com/gtaylor/python-route53/blob/b9fc7e258a79551c9ed61e4a71668b7f06f9e774/route53/transport.py#L67-L88 | [
"def",
"get_request_headers",
"(",
"self",
")",
":",
"date_header",
"=",
"time",
".",
"asctime",
"(",
"time",
".",
"gmtime",
"(",
")",
")",
"# We sign the time string above with the user's AWS secret access key",
"# in order to authenticate our request.",
"signing_key",
"=",
"self",
".",
"_hmac_sign_string",
"(",
"date_header",
")",
"# Amazon's super fun auth token.",
"auth_header",
"=",
"\"AWS3-HTTPS AWSAccessKeyId=%s,Algorithm=HmacSHA256,Signature=%s\"",
"%",
"(",
"self",
".",
"connection",
".",
"_aws_access_key_id",
",",
"signing_key",
",",
")",
"return",
"{",
"'X-Amzn-Authorization'",
":",
"auth_header",
",",
"'x-amz-date'",
":",
"date_header",
",",
"'Host'",
":",
"'route53.amazonaws.com'",
",",
"}"
] | b9fc7e258a79551c9ed61e4a71668b7f06f9e774 |
test | BaseTransport.send_request | All outbound requests go through this method. It defers to the
transport's various HTTP method-specific methods.
:param str path: The path to tack on to the endpoint URL for
the query.
:param data: The params to send along with the request.
:type data: Either a dict or bytes, depending on the request type.
:param str method: One of 'GET', 'POST', or 'DELETE'.
:rtype: str
:returns: The body of the response. | route53/transport.py | def send_request(self, path, data, method):
"""
All outbound requests go through this method. It defers to the
transport's various HTTP method-specific methods.
:param str path: The path to tack on to the endpoint URL for
the query.
:param data: The params to send along with the request.
:type data: Either a dict or bytes, depending on the request type.
:param str method: One of 'GET', 'POST', or 'DELETE'.
:rtype: str
:returns: The body of the response.
"""
headers = self.get_request_headers()
if method == 'GET':
return self._send_get_request(path, data, headers)
elif method == 'POST':
return self._send_post_request(path, data, headers)
elif method == 'DELETE':
return self._send_delete_request(path, headers)
else:
raise Route53Error("Invalid request method: %s" % method) | def send_request(self, path, data, method):
"""
All outbound requests go through this method. It defers to the
transport's various HTTP method-specific methods.
:param str path: The path to tack on to the endpoint URL for
the query.
:param data: The params to send along with the request.
:type data: Either a dict or bytes, depending on the request type.
:param str method: One of 'GET', 'POST', or 'DELETE'.
:rtype: str
:returns: The body of the response.
"""
headers = self.get_request_headers()
if method == 'GET':
return self._send_get_request(path, data, headers)
elif method == 'POST':
return self._send_post_request(path, data, headers)
elif method == 'DELETE':
return self._send_delete_request(path, headers)
else:
raise Route53Error("Invalid request method: %s" % method) | [
"All",
"outbound",
"requests",
"go",
"through",
"this",
"method",
".",
"It",
"defers",
"to",
"the",
"transport",
"s",
"various",
"HTTP",
"method",
"-",
"specific",
"methods",
"."
] | gtaylor/python-route53 | python | https://github.com/gtaylor/python-route53/blob/b9fc7e258a79551c9ed61e4a71668b7f06f9e774/route53/transport.py#L90-L114 | [
"def",
"send_request",
"(",
"self",
",",
"path",
",",
"data",
",",
"method",
")",
":",
"headers",
"=",
"self",
".",
"get_request_headers",
"(",
")",
"if",
"method",
"==",
"'GET'",
":",
"return",
"self",
".",
"_send_get_request",
"(",
"path",
",",
"data",
",",
"headers",
")",
"elif",
"method",
"==",
"'POST'",
":",
"return",
"self",
".",
"_send_post_request",
"(",
"path",
",",
"data",
",",
"headers",
")",
"elif",
"method",
"==",
"'DELETE'",
":",
"return",
"self",
".",
"_send_delete_request",
"(",
"path",
",",
"headers",
")",
"else",
":",
"raise",
"Route53Error",
"(",
"\"Invalid request method: %s\"",
"%",
"method",
")"
] | b9fc7e258a79551c9ed61e4a71668b7f06f9e774 |
test | RequestsTransport._send_get_request | Sends the GET request to the Route53 endpoint.
:param str path: The path to tack on to the endpoint URL for
the query.
:param dict params: Key/value pairs to send.
:param dict headers: A dict of headers to send with the request.
:rtype: str
:returns: The body of the response. | route53/transport.py | def _send_get_request(self, path, params, headers):
"""
Sends the GET request to the Route53 endpoint.
:param str path: The path to tack on to the endpoint URL for
the query.
:param dict params: Key/value pairs to send.
:param dict headers: A dict of headers to send with the request.
:rtype: str
:returns: The body of the response.
"""
r = requests.get(self.endpoint + path, params=params, headers=headers)
r.raise_for_status()
return r.text | def _send_get_request(self, path, params, headers):
"""
Sends the GET request to the Route53 endpoint.
:param str path: The path to tack on to the endpoint URL for
the query.
:param dict params: Key/value pairs to send.
:param dict headers: A dict of headers to send with the request.
:rtype: str
:returns: The body of the response.
"""
r = requests.get(self.endpoint + path, params=params, headers=headers)
r.raise_for_status()
return r.text | [
"Sends",
"the",
"GET",
"request",
"to",
"the",
"Route53",
"endpoint",
"."
] | gtaylor/python-route53 | python | https://github.com/gtaylor/python-route53/blob/b9fc7e258a79551c9ed61e4a71668b7f06f9e774/route53/transport.py#L173-L187 | [
"def",
"_send_get_request",
"(",
"self",
",",
"path",
",",
"params",
",",
"headers",
")",
":",
"r",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"endpoint",
"+",
"path",
",",
"params",
"=",
"params",
",",
"headers",
"=",
"headers",
")",
"r",
".",
"raise_for_status",
"(",
")",
"return",
"r",
".",
"text"
] | b9fc7e258a79551c9ed61e4a71668b7f06f9e774 |
test | RequestsTransport._send_post_request | Sends the POST request to the Route53 endpoint.
:param str path: The path to tack on to the endpoint URL for
the query.
:param data: Either a dict, or bytes.
:type data: dict or bytes
:param dict headers: A dict of headers to send with the request.
:rtype: str
:returns: The body of the response. | route53/transport.py | def _send_post_request(self, path, data, headers):
"""
Sends the POST request to the Route53 endpoint.
:param str path: The path to tack on to the endpoint URL for
the query.
:param data: Either a dict, or bytes.
:type data: dict or bytes
:param dict headers: A dict of headers to send with the request.
:rtype: str
:returns: The body of the response.
"""
r = requests.post(self.endpoint + path, data=data, headers=headers)
return r.text | def _send_post_request(self, path, data, headers):
"""
Sends the POST request to the Route53 endpoint.
:param str path: The path to tack on to the endpoint URL for
the query.
:param data: Either a dict, or bytes.
:type data: dict or bytes
:param dict headers: A dict of headers to send with the request.
:rtype: str
:returns: The body of the response.
"""
r = requests.post(self.endpoint + path, data=data, headers=headers)
return r.text | [
"Sends",
"the",
"POST",
"request",
"to",
"the",
"Route53",
"endpoint",
"."
] | gtaylor/python-route53 | python | https://github.com/gtaylor/python-route53/blob/b9fc7e258a79551c9ed61e4a71668b7f06f9e774/route53/transport.py#L189-L203 | [
"def",
"_send_post_request",
"(",
"self",
",",
"path",
",",
"data",
",",
"headers",
")",
":",
"r",
"=",
"requests",
".",
"post",
"(",
"self",
".",
"endpoint",
"+",
"path",
",",
"data",
"=",
"data",
",",
"headers",
"=",
"headers",
")",
"return",
"r",
".",
"text"
] | b9fc7e258a79551c9ed61e4a71668b7f06f9e774 |
test | RequestsTransport._send_delete_request | Sends the DELETE request to the Route53 endpoint.
:param str path: The path to tack on to the endpoint URL for
the query.
:param dict headers: A dict of headers to send with the request.
:rtype: str
:returns: The body of the response. | route53/transport.py | def _send_delete_request(self, path, headers):
"""
Sends the DELETE request to the Route53 endpoint.
:param str path: The path to tack on to the endpoint URL for
the query.
:param dict headers: A dict of headers to send with the request.
:rtype: str
:returns: The body of the response.
"""
r = requests.delete(self.endpoint + path, headers=headers)
return r.text | def _send_delete_request(self, path, headers):
"""
Sends the DELETE request to the Route53 endpoint.
:param str path: The path to tack on to the endpoint URL for
the query.
:param dict headers: A dict of headers to send with the request.
:rtype: str
:returns: The body of the response.
"""
r = requests.delete(self.endpoint + path, headers=headers)
return r.text | [
"Sends",
"the",
"DELETE",
"request",
"to",
"the",
"Route53",
"endpoint",
"."
] | gtaylor/python-route53 | python | https://github.com/gtaylor/python-route53/blob/b9fc7e258a79551c9ed61e4a71668b7f06f9e774/route53/transport.py#L205-L217 | [
"def",
"_send_delete_request",
"(",
"self",
",",
"path",
",",
"headers",
")",
":",
"r",
"=",
"requests",
".",
"delete",
"(",
"self",
".",
"endpoint",
"+",
"path",
",",
"headers",
"=",
"headers",
")",
"return",
"r",
".",
"text"
] | b9fc7e258a79551c9ed61e4a71668b7f06f9e774 |
test | APEValue | APEv2 tag value factory.
Use this if you need to specify the value's type manually. Binary
and text data are automatically detected by APEv2.__setitem__. | mutagen/apev2.py | def APEValue(value, kind):
"""APEv2 tag value factory.
Use this if you need to specify the value's type manually. Binary
and text data are automatically detected by APEv2.__setitem__.
"""
if kind in (TEXT, EXTERNAL):
if not isinstance(value, text_type):
# stricter with py3
if PY3:
raise TypeError("str only for text/external values")
else:
value = value.encode("utf-8")
if kind == TEXT:
return APETextValue(value, kind)
elif kind == BINARY:
return APEBinaryValue(value, kind)
elif kind == EXTERNAL:
return APEExtValue(value, kind)
else:
raise ValueError("kind must be TEXT, BINARY, or EXTERNAL") | def APEValue(value, kind):
"""APEv2 tag value factory.
Use this if you need to specify the value's type manually. Binary
and text data are automatically detected by APEv2.__setitem__.
"""
if kind in (TEXT, EXTERNAL):
if not isinstance(value, text_type):
# stricter with py3
if PY3:
raise TypeError("str only for text/external values")
else:
value = value.encode("utf-8")
if kind == TEXT:
return APETextValue(value, kind)
elif kind == BINARY:
return APEBinaryValue(value, kind)
elif kind == EXTERNAL:
return APEExtValue(value, kind)
else:
raise ValueError("kind must be TEXT, BINARY, or EXTERNAL") | [
"APEv2",
"tag",
"value",
"factory",
"."
] | LordSputnik/mutagen | python | https://github.com/LordSputnik/mutagen/blob/38e62c8dc35c72b16554f5dbe7c0fde91acc3411/mutagen/apev2.py#L460-L482 | [
"def",
"APEValue",
"(",
"value",
",",
"kind",
")",
":",
"if",
"kind",
"in",
"(",
"TEXT",
",",
"EXTERNAL",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"text_type",
")",
":",
"# stricter with py3",
"if",
"PY3",
":",
"raise",
"TypeError",
"(",
"\"str only for text/external values\"",
")",
"else",
":",
"value",
"=",
"value",
".",
"encode",
"(",
"\"utf-8\"",
")",
"if",
"kind",
"==",
"TEXT",
":",
"return",
"APETextValue",
"(",
"value",
",",
"kind",
")",
"elif",
"kind",
"==",
"BINARY",
":",
"return",
"APEBinaryValue",
"(",
"value",
",",
"kind",
")",
"elif",
"kind",
"==",
"EXTERNAL",
":",
"return",
"APEExtValue",
"(",
"value",
",",
"kind",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"kind must be TEXT, BINARY, or EXTERNAL\"",
")"
] | 38e62c8dc35c72b16554f5dbe7c0fde91acc3411 |
test | APEv2.load | Load tags from a filename. | mutagen/apev2.py | def load(self, filename):
"""Load tags from a filename."""
self.filename = filename
fileobj = open(filename, "rb")
try:
data = _APEv2Data(fileobj)
finally:
fileobj.close()
if data.tag:
self.clear()
self.__casemap.clear()
self.__parse_tag(data.tag, data.items)
else:
raise APENoHeaderError("No APE tag found") | def load(self, filename):
"""Load tags from a filename."""
self.filename = filename
fileobj = open(filename, "rb")
try:
data = _APEv2Data(fileobj)
finally:
fileobj.close()
if data.tag:
self.clear()
self.__casemap.clear()
self.__parse_tag(data.tag, data.items)
else:
raise APENoHeaderError("No APE tag found") | [
"Load",
"tags",
"from",
"a",
"filename",
"."
] | LordSputnik/mutagen | python | https://github.com/LordSputnik/mutagen/blob/38e62c8dc35c72b16554f5dbe7c0fde91acc3411/mutagen/apev2.py#L251-L265 | [
"def",
"load",
"(",
"self",
",",
"filename",
")",
":",
"self",
".",
"filename",
"=",
"filename",
"fileobj",
"=",
"open",
"(",
"filename",
",",
"\"rb\"",
")",
"try",
":",
"data",
"=",
"_APEv2Data",
"(",
"fileobj",
")",
"finally",
":",
"fileobj",
".",
"close",
"(",
")",
"if",
"data",
".",
"tag",
":",
"self",
".",
"clear",
"(",
")",
"self",
".",
"__casemap",
".",
"clear",
"(",
")",
"self",
".",
"__parse_tag",
"(",
"data",
".",
"tag",
",",
"data",
".",
"items",
")",
"else",
":",
"raise",
"APENoHeaderError",
"(",
"\"No APE tag found\"",
")"
] | 38e62c8dc35c72b16554f5dbe7c0fde91acc3411 |
test | APEv2.save | Save changes to a file.
If no filename is given, the one most recently loaded is used.
Tags are always written at the end of the file, and include
a header and a footer. | mutagen/apev2.py | def save(self, filename=None):
"""Save changes to a file.
If no filename is given, the one most recently loaded is used.
Tags are always written at the end of the file, and include
a header and a footer.
"""
filename = filename or self.filename
try:
fileobj = open(filename, "r+b")
except IOError:
fileobj = open(filename, "w+b")
data = _APEv2Data(fileobj)
if data.is_at_start:
delete_bytes(fileobj, data.end - data.start, data.start)
elif data.start is not None:
fileobj.seek(data.start)
# Delete an ID3v1 tag if present, too.
fileobj.truncate()
fileobj.seek(0, 2)
# "APE tags items should be sorted ascending by size... This is
# not a MUST, but STRONGLY recommended. Actually the items should
# be sorted by importance/byte, but this is not feasible."
tags = sorted((v._internal(k) for k, v in self.items()), key=len)
num_tags = len(tags)
tags = b"".join(tags)
header = bytearray(b"APETAGEX")
# version, tag size, item count, flags
header += struct.pack("<4I", 2000, len(tags) + 32, num_tags,
HAS_HEADER | IS_HEADER)
header += b"\0" * 8
fileobj.write(header)
fileobj.write(tags)
footer = bytearray(b"APETAGEX")
footer += struct.pack("<4I", 2000, len(tags) + 32, num_tags,
HAS_HEADER)
footer += b"\0" * 8
fileobj.write(footer)
fileobj.close() | def save(self, filename=None):
"""Save changes to a file.
If no filename is given, the one most recently loaded is used.
Tags are always written at the end of the file, and include
a header and a footer.
"""
filename = filename or self.filename
try:
fileobj = open(filename, "r+b")
except IOError:
fileobj = open(filename, "w+b")
data = _APEv2Data(fileobj)
if data.is_at_start:
delete_bytes(fileobj, data.end - data.start, data.start)
elif data.start is not None:
fileobj.seek(data.start)
# Delete an ID3v1 tag if present, too.
fileobj.truncate()
fileobj.seek(0, 2)
# "APE tags items should be sorted ascending by size... This is
# not a MUST, but STRONGLY recommended. Actually the items should
# be sorted by importance/byte, but this is not feasible."
tags = sorted((v._internal(k) for k, v in self.items()), key=len)
num_tags = len(tags)
tags = b"".join(tags)
header = bytearray(b"APETAGEX")
# version, tag size, item count, flags
header += struct.pack("<4I", 2000, len(tags) + 32, num_tags,
HAS_HEADER | IS_HEADER)
header += b"\0" * 8
fileobj.write(header)
fileobj.write(tags)
footer = bytearray(b"APETAGEX")
footer += struct.pack("<4I", 2000, len(tags) + 32, num_tags,
HAS_HEADER)
footer += b"\0" * 8
fileobj.write(footer)
fileobj.close() | [
"Save",
"changes",
"to",
"a",
"file",
"."
] | LordSputnik/mutagen | python | https://github.com/LordSputnik/mutagen/blob/38e62c8dc35c72b16554f5dbe7c0fde91acc3411/mutagen/apev2.py#L386-L432 | [
"def",
"save",
"(",
"self",
",",
"filename",
"=",
"None",
")",
":",
"filename",
"=",
"filename",
"or",
"self",
".",
"filename",
"try",
":",
"fileobj",
"=",
"open",
"(",
"filename",
",",
"\"r+b\"",
")",
"except",
"IOError",
":",
"fileobj",
"=",
"open",
"(",
"filename",
",",
"\"w+b\"",
")",
"data",
"=",
"_APEv2Data",
"(",
"fileobj",
")",
"if",
"data",
".",
"is_at_start",
":",
"delete_bytes",
"(",
"fileobj",
",",
"data",
".",
"end",
"-",
"data",
".",
"start",
",",
"data",
".",
"start",
")",
"elif",
"data",
".",
"start",
"is",
"not",
"None",
":",
"fileobj",
".",
"seek",
"(",
"data",
".",
"start",
")",
"# Delete an ID3v1 tag if present, too.",
"fileobj",
".",
"truncate",
"(",
")",
"fileobj",
".",
"seek",
"(",
"0",
",",
"2",
")",
"# \"APE tags items should be sorted ascending by size... This is",
"# not a MUST, but STRONGLY recommended. Actually the items should",
"# be sorted by importance/byte, but this is not feasible.\"",
"tags",
"=",
"sorted",
"(",
"(",
"v",
".",
"_internal",
"(",
"k",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"items",
"(",
")",
")",
",",
"key",
"=",
"len",
")",
"num_tags",
"=",
"len",
"(",
"tags",
")",
"tags",
"=",
"b\"\"",
".",
"join",
"(",
"tags",
")",
"header",
"=",
"bytearray",
"(",
"b\"APETAGEX\"",
")",
"# version, tag size, item count, flags",
"header",
"+=",
"struct",
".",
"pack",
"(",
"\"<4I\"",
",",
"2000",
",",
"len",
"(",
"tags",
")",
"+",
"32",
",",
"num_tags",
",",
"HAS_HEADER",
"|",
"IS_HEADER",
")",
"header",
"+=",
"b\"\\0\"",
"*",
"8",
"fileobj",
".",
"write",
"(",
"header",
")",
"fileobj",
".",
"write",
"(",
"tags",
")",
"footer",
"=",
"bytearray",
"(",
"b\"APETAGEX\"",
")",
"footer",
"+=",
"struct",
".",
"pack",
"(",
"\"<4I\"",
",",
"2000",
",",
"len",
"(",
"tags",
")",
"+",
"32",
",",
"num_tags",
",",
"HAS_HEADER",
")",
"footer",
"+=",
"b\"\\0\"",
"*",
"8",
"fileobj",
".",
"write",
"(",
"footer",
")",
"fileobj",
".",
"close",
"(",
")"
] | 38e62c8dc35c72b16554f5dbe7c0fde91acc3411 |
test | APEv2.delete | Remove tags from a file. | mutagen/apev2.py | def delete(self, filename=None):
"""Remove tags from a file."""
filename = filename or self.filename
fileobj = open(filename, "r+b")
try:
data = _APEv2Data(fileobj)
if data.start is not None and data.size is not None:
delete_bytes(fileobj, data.end - data.start, data.start)
finally:
fileobj.close()
self.clear() | def delete(self, filename=None):
"""Remove tags from a file."""
filename = filename or self.filename
fileobj = open(filename, "r+b")
try:
data = _APEv2Data(fileobj)
if data.start is not None and data.size is not None:
delete_bytes(fileobj, data.end - data.start, data.start)
finally:
fileobj.close()
self.clear() | [
"Remove",
"tags",
"from",
"a",
"file",
"."
] | LordSputnik/mutagen | python | https://github.com/LordSputnik/mutagen/blob/38e62c8dc35c72b16554f5dbe7c0fde91acc3411/mutagen/apev2.py#L434-L445 | [
"def",
"delete",
"(",
"self",
",",
"filename",
"=",
"None",
")",
":",
"filename",
"=",
"filename",
"or",
"self",
".",
"filename",
"fileobj",
"=",
"open",
"(",
"filename",
",",
"\"r+b\"",
")",
"try",
":",
"data",
"=",
"_APEv2Data",
"(",
"fileobj",
")",
"if",
"data",
".",
"start",
"is",
"not",
"None",
"and",
"data",
".",
"size",
"is",
"not",
"None",
":",
"delete_bytes",
"(",
"fileobj",
",",
"data",
".",
"end",
"-",
"data",
".",
"start",
",",
"data",
".",
"start",
")",
"finally",
":",
"fileobj",
".",
"close",
"(",
")",
"self",
".",
"clear",
"(",
")"
] | 38e62c8dc35c72b16554f5dbe7c0fde91acc3411 |
test | Route53Connection._send_request | Uses the HTTP transport to query the Route53 API. Runs the response
through lxml's parser, before we hand it off for further picking
apart by our call-specific parsers.
:param str path: The RESTful path to tack on to the :py:attr:`endpoint`.
:param data: The params to send along with the request.
:type data: Either a dict or bytes, depending on the request type.
:param str method: One of 'GET', 'POST', or 'DELETE'.
:rtype: lxml.etree._Element
:returns: An lxml Element root. | route53/connection.py | def _send_request(self, path, data, method):
"""
Uses the HTTP transport to query the Route53 API. Runs the response
through lxml's parser, before we hand it off for further picking
apart by our call-specific parsers.
:param str path: The RESTful path to tack on to the :py:attr:`endpoint`.
:param data: The params to send along with the request.
:type data: Either a dict or bytes, depending on the request type.
:param str method: One of 'GET', 'POST', or 'DELETE'.
:rtype: lxml.etree._Element
:returns: An lxml Element root.
"""
response_body = self._transport.send_request(path, data, method)
root = etree.fromstring(response_body)
#print(prettyprint_xml(root))
return root | def _send_request(self, path, data, method):
"""
Uses the HTTP transport to query the Route53 API. Runs the response
through lxml's parser, before we hand it off for further picking
apart by our call-specific parsers.
:param str path: The RESTful path to tack on to the :py:attr:`endpoint`.
:param data: The params to send along with the request.
:type data: Either a dict or bytes, depending on the request type.
:param str method: One of 'GET', 'POST', or 'DELETE'.
:rtype: lxml.etree._Element
:returns: An lxml Element root.
"""
response_body = self._transport.send_request(path, data, method)
root = etree.fromstring(response_body)
#print(prettyprint_xml(root))
return root | [
"Uses",
"the",
"HTTP",
"transport",
"to",
"query",
"the",
"Route53",
"API",
".",
"Runs",
"the",
"response",
"through",
"lxml",
"s",
"parser",
"before",
"we",
"hand",
"it",
"off",
"for",
"further",
"picking",
"apart",
"by",
"our",
"call",
"-",
"specific",
"parsers",
"."
] | gtaylor/python-route53 | python | https://github.com/gtaylor/python-route53/blob/b9fc7e258a79551c9ed61e4a71668b7f06f9e774/route53/connection.py#L34-L51 | [
"def",
"_send_request",
"(",
"self",
",",
"path",
",",
"data",
",",
"method",
")",
":",
"response_body",
"=",
"self",
".",
"_transport",
".",
"send_request",
"(",
"path",
",",
"data",
",",
"method",
")",
"root",
"=",
"etree",
".",
"fromstring",
"(",
"response_body",
")",
"#print(prettyprint_xml(root))",
"return",
"root"
] | b9fc7e258a79551c9ed61e4a71668b7f06f9e774 |
test | Route53Connection._do_autopaginating_api_call | Given an API method, the arguments passed to it, and a function to
hand parsing off to, loop through the record sets in the API call
until all records have been yielded.
:param str method: The API method on the endpoint.
:param dict params: The kwargs from the top-level API method.
:param callable parser_func: A callable that is used for parsing the
output from the API call.
:param str next_marker_param_name: The XPath to the marker tag that
will determine whether we continue paginating.
:param str next_marker_param_name: The parameter name to manipulate
in the request data to bring up the next page on the next
request loop.
:keyword str next_type_xpath: For the
py:meth:`list_resource_record_sets_by_zone_id` method, there's
an additional paginator token. Specifying this XPath looks for it.
:keyword dict parser_kwargs: Optional dict of additional kwargs to pass
on to the parser function.
:rtype: generator
:returns: Returns a generator that may be returned by the top-level
API method. | route53/connection.py | def _do_autopaginating_api_call(self, path, params, method, parser_func,
next_marker_xpath, next_marker_param_name,
next_type_xpath=None, parser_kwargs=None):
"""
Given an API method, the arguments passed to it, and a function to
hand parsing off to, loop through the record sets in the API call
until all records have been yielded.
:param str method: The API method on the endpoint.
:param dict params: The kwargs from the top-level API method.
:param callable parser_func: A callable that is used for parsing the
output from the API call.
:param str next_marker_param_name: The XPath to the marker tag that
will determine whether we continue paginating.
:param str next_marker_param_name: The parameter name to manipulate
in the request data to bring up the next page on the next
request loop.
:keyword str next_type_xpath: For the
py:meth:`list_resource_record_sets_by_zone_id` method, there's
an additional paginator token. Specifying this XPath looks for it.
:keyword dict parser_kwargs: Optional dict of additional kwargs to pass
on to the parser function.
:rtype: generator
:returns: Returns a generator that may be returned by the top-level
API method.
"""
if not parser_kwargs:
parser_kwargs = {}
# We loop indefinitely since we have no idea how many "pages" of
# results we're going to have to go through.
while True:
# An lxml Element node.
root = self._send_request(path, params, method)
# Individually yield HostedZone instances after parsing/instantiating.
for record in parser_func(root, connection=self, **parser_kwargs):
yield record
# This will determine at what offset we start the next query.
next_marker = root.find(next_marker_xpath)
if next_marker is None:
# If the NextMarker tag is absent, we know we've hit the
# last page.
break
# if NextMarker is present, we'll adjust our API request params
# and query again for the next page.
params[next_marker_param_name] = next_marker.text
if next_type_xpath:
# This is a _list_resource_record_sets_by_zone_id call. Look
# for the given tag via XPath and adjust our type arg for
# the next request. Without specifying this, we loop
# infinitely.
next_type = root.find(next_type_xpath)
params['type'] = next_type.text | def _do_autopaginating_api_call(self, path, params, method, parser_func,
next_marker_xpath, next_marker_param_name,
next_type_xpath=None, parser_kwargs=None):
"""
Given an API method, the arguments passed to it, and a function to
hand parsing off to, loop through the record sets in the API call
until all records have been yielded.
:param str method: The API method on the endpoint.
:param dict params: The kwargs from the top-level API method.
:param callable parser_func: A callable that is used for parsing the
output from the API call.
:param str next_marker_param_name: The XPath to the marker tag that
will determine whether we continue paginating.
:param str next_marker_param_name: The parameter name to manipulate
in the request data to bring up the next page on the next
request loop.
:keyword str next_type_xpath: For the
py:meth:`list_resource_record_sets_by_zone_id` method, there's
an additional paginator token. Specifying this XPath looks for it.
:keyword dict parser_kwargs: Optional dict of additional kwargs to pass
on to the parser function.
:rtype: generator
:returns: Returns a generator that may be returned by the top-level
API method.
"""
if not parser_kwargs:
parser_kwargs = {}
# We loop indefinitely since we have no idea how many "pages" of
# results we're going to have to go through.
while True:
# An lxml Element node.
root = self._send_request(path, params, method)
# Individually yield HostedZone instances after parsing/instantiating.
for record in parser_func(root, connection=self, **parser_kwargs):
yield record
# This will determine at what offset we start the next query.
next_marker = root.find(next_marker_xpath)
if next_marker is None:
# If the NextMarker tag is absent, we know we've hit the
# last page.
break
# if NextMarker is present, we'll adjust our API request params
# and query again for the next page.
params[next_marker_param_name] = next_marker.text
if next_type_xpath:
# This is a _list_resource_record_sets_by_zone_id call. Look
# for the given tag via XPath and adjust our type arg for
# the next request. Without specifying this, we loop
# infinitely.
next_type = root.find(next_type_xpath)
params['type'] = next_type.text | [
"Given",
"an",
"API",
"method",
"the",
"arguments",
"passed",
"to",
"it",
"and",
"a",
"function",
"to",
"hand",
"parsing",
"off",
"to",
"loop",
"through",
"the",
"record",
"sets",
"in",
"the",
"API",
"call",
"until",
"all",
"records",
"have",
"been",
"yielded",
"."
] | gtaylor/python-route53 | python | https://github.com/gtaylor/python-route53/blob/b9fc7e258a79551c9ed61e4a71668b7f06f9e774/route53/connection.py#L53-L111 | [
"def",
"_do_autopaginating_api_call",
"(",
"self",
",",
"path",
",",
"params",
",",
"method",
",",
"parser_func",
",",
"next_marker_xpath",
",",
"next_marker_param_name",
",",
"next_type_xpath",
"=",
"None",
",",
"parser_kwargs",
"=",
"None",
")",
":",
"if",
"not",
"parser_kwargs",
":",
"parser_kwargs",
"=",
"{",
"}",
"# We loop indefinitely since we have no idea how many \"pages\" of",
"# results we're going to have to go through.",
"while",
"True",
":",
"# An lxml Element node.",
"root",
"=",
"self",
".",
"_send_request",
"(",
"path",
",",
"params",
",",
"method",
")",
"# Individually yield HostedZone instances after parsing/instantiating.",
"for",
"record",
"in",
"parser_func",
"(",
"root",
",",
"connection",
"=",
"self",
",",
"*",
"*",
"parser_kwargs",
")",
":",
"yield",
"record",
"# This will determine at what offset we start the next query.",
"next_marker",
"=",
"root",
".",
"find",
"(",
"next_marker_xpath",
")",
"if",
"next_marker",
"is",
"None",
":",
"# If the NextMarker tag is absent, we know we've hit the",
"# last page.",
"break",
"# if NextMarker is present, we'll adjust our API request params",
"# and query again for the next page.",
"params",
"[",
"next_marker_param_name",
"]",
"=",
"next_marker",
".",
"text",
"if",
"next_type_xpath",
":",
"# This is a _list_resource_record_sets_by_zone_id call. Look",
"# for the given tag via XPath and adjust our type arg for",
"# the next request. Without specifying this, we loop",
"# infinitely.",
"next_type",
"=",
"root",
".",
"find",
"(",
"next_type_xpath",
")",
"params",
"[",
"'type'",
"]",
"=",
"next_type",
".",
"text"
] | b9fc7e258a79551c9ed61e4a71668b7f06f9e774 |
test | Route53Connection.list_hosted_zones | List all hosted zones associated with this connection's account. Since
this method returns a generator, you can pull as many or as few
entries as you'd like, without having to query and receive every
hosted zone you may have.
:keyword int page_chunks: This API call is "paginated" behind-the-scenes
in order to break up large result sets. This number determines
the maximum number of
:py:class:`HostedZone <route53.hosted_zone.HostedZone>`
instances to retrieve per request. The default is fine for almost
everyone.
:rtype: generator
:returns: A generator of :py:class:`HostedZone <route53.hosted_zone.HostedZone>`
instances. | route53/connection.py | def list_hosted_zones(self, page_chunks=100):
"""
List all hosted zones associated with this connection's account. Since
this method returns a generator, you can pull as many or as few
entries as you'd like, without having to query and receive every
hosted zone you may have.
:keyword int page_chunks: This API call is "paginated" behind-the-scenes
in order to break up large result sets. This number determines
the maximum number of
:py:class:`HostedZone <route53.hosted_zone.HostedZone>`
instances to retrieve per request. The default is fine for almost
everyone.
:rtype: generator
:returns: A generator of :py:class:`HostedZone <route53.hosted_zone.HostedZone>`
instances.
"""
return self._do_autopaginating_api_call(
path='hostedzone',
params={'maxitems': page_chunks},
method='GET',
parser_func=xml_parsers.list_hosted_zones_parser,
next_marker_xpath="./{*}NextMarker",
next_marker_param_name="marker",
) | def list_hosted_zones(self, page_chunks=100):
"""
List all hosted zones associated with this connection's account. Since
this method returns a generator, you can pull as many or as few
entries as you'd like, without having to query and receive every
hosted zone you may have.
:keyword int page_chunks: This API call is "paginated" behind-the-scenes
in order to break up large result sets. This number determines
the maximum number of
:py:class:`HostedZone <route53.hosted_zone.HostedZone>`
instances to retrieve per request. The default is fine for almost
everyone.
:rtype: generator
:returns: A generator of :py:class:`HostedZone <route53.hosted_zone.HostedZone>`
instances.
"""
return self._do_autopaginating_api_call(
path='hostedzone',
params={'maxitems': page_chunks},
method='GET',
parser_func=xml_parsers.list_hosted_zones_parser,
next_marker_xpath="./{*}NextMarker",
next_marker_param_name="marker",
) | [
"List",
"all",
"hosted",
"zones",
"associated",
"with",
"this",
"connection",
"s",
"account",
".",
"Since",
"this",
"method",
"returns",
"a",
"generator",
"you",
"can",
"pull",
"as",
"many",
"or",
"as",
"few",
"entries",
"as",
"you",
"d",
"like",
"without",
"having",
"to",
"query",
"and",
"receive",
"every",
"hosted",
"zone",
"you",
"may",
"have",
"."
] | gtaylor/python-route53 | python | https://github.com/gtaylor/python-route53/blob/b9fc7e258a79551c9ed61e4a71668b7f06f9e774/route53/connection.py#L113-L139 | [
"def",
"list_hosted_zones",
"(",
"self",
",",
"page_chunks",
"=",
"100",
")",
":",
"return",
"self",
".",
"_do_autopaginating_api_call",
"(",
"path",
"=",
"'hostedzone'",
",",
"params",
"=",
"{",
"'maxitems'",
":",
"page_chunks",
"}",
",",
"method",
"=",
"'GET'",
",",
"parser_func",
"=",
"xml_parsers",
".",
"list_hosted_zones_parser",
",",
"next_marker_xpath",
"=",
"\"./{*}NextMarker\"",
",",
"next_marker_param_name",
"=",
"\"marker\"",
",",
")"
] | b9fc7e258a79551c9ed61e4a71668b7f06f9e774 |
test | Route53Connection.create_hosted_zone | Creates and returns a new hosted zone. Once a hosted zone is created,
its details can't be changed.
:param str name: The name of the hosted zone to create.
:keyword str caller_reference: A unique string that identifies the
request and that allows failed create_hosted_zone requests to be
retried without the risk of executing the operation twice. If no
value is given, we'll generate a Type 4 UUID for you.
:keyword str comment: An optional comment to attach to the zone.
:rtype: tuple
:returns: A tuple in the form of ``(hosted_zone, change_info)``.
The ``hosted_zone`` variable contains a
:py:class:`HostedZone <route53.hosted_zone.HostedZone>`
instance matching the newly created zone, and ``change_info``
is a dict with some details about the API request. | route53/connection.py | def create_hosted_zone(self, name, caller_reference=None, comment=None):
"""
Creates and returns a new hosted zone. Once a hosted zone is created,
its details can't be changed.
:param str name: The name of the hosted zone to create.
:keyword str caller_reference: A unique string that identifies the
request and that allows failed create_hosted_zone requests to be
retried without the risk of executing the operation twice. If no
value is given, we'll generate a Type 4 UUID for you.
:keyword str comment: An optional comment to attach to the zone.
:rtype: tuple
:returns: A tuple in the form of ``(hosted_zone, change_info)``.
The ``hosted_zone`` variable contains a
:py:class:`HostedZone <route53.hosted_zone.HostedZone>`
instance matching the newly created zone, and ``change_info``
is a dict with some details about the API request.
"""
body = xml_generators.create_hosted_zone_writer(
connection=self,
name=name,
caller_reference=caller_reference,
comment=comment
)
root = self._send_request(
path='hostedzone',
data=body,
method='POST',
)
return xml_parsers.created_hosted_zone_parser(
root=root,
connection=self
) | def create_hosted_zone(self, name, caller_reference=None, comment=None):
"""
Creates and returns a new hosted zone. Once a hosted zone is created,
its details can't be changed.
:param str name: The name of the hosted zone to create.
:keyword str caller_reference: A unique string that identifies the
request and that allows failed create_hosted_zone requests to be
retried without the risk of executing the operation twice. If no
value is given, we'll generate a Type 4 UUID for you.
:keyword str comment: An optional comment to attach to the zone.
:rtype: tuple
:returns: A tuple in the form of ``(hosted_zone, change_info)``.
The ``hosted_zone`` variable contains a
:py:class:`HostedZone <route53.hosted_zone.HostedZone>`
instance matching the newly created zone, and ``change_info``
is a dict with some details about the API request.
"""
body = xml_generators.create_hosted_zone_writer(
connection=self,
name=name,
caller_reference=caller_reference,
comment=comment
)
root = self._send_request(
path='hostedzone',
data=body,
method='POST',
)
return xml_parsers.created_hosted_zone_parser(
root=root,
connection=self
) | [
"Creates",
"and",
"returns",
"a",
"new",
"hosted",
"zone",
".",
"Once",
"a",
"hosted",
"zone",
"is",
"created",
"its",
"details",
"can",
"t",
"be",
"changed",
"."
] | gtaylor/python-route53 | python | https://github.com/gtaylor/python-route53/blob/b9fc7e258a79551c9ed61e4a71668b7f06f9e774/route53/connection.py#L141-L176 | [
"def",
"create_hosted_zone",
"(",
"self",
",",
"name",
",",
"caller_reference",
"=",
"None",
",",
"comment",
"=",
"None",
")",
":",
"body",
"=",
"xml_generators",
".",
"create_hosted_zone_writer",
"(",
"connection",
"=",
"self",
",",
"name",
"=",
"name",
",",
"caller_reference",
"=",
"caller_reference",
",",
"comment",
"=",
"comment",
")",
"root",
"=",
"self",
".",
"_send_request",
"(",
"path",
"=",
"'hostedzone'",
",",
"data",
"=",
"body",
",",
"method",
"=",
"'POST'",
",",
")",
"return",
"xml_parsers",
".",
"created_hosted_zone_parser",
"(",
"root",
"=",
"root",
",",
"connection",
"=",
"self",
")"
] | b9fc7e258a79551c9ed61e4a71668b7f06f9e774 |
test | Route53Connection.get_hosted_zone_by_id | Retrieves a hosted zone, by hosted zone ID (not name).
:param str id: The hosted zone's ID (a short hash string).
:rtype: :py:class:`HostedZone <route53.hosted_zone.HostedZone>`
:returns: An :py:class:`HostedZone <route53.hosted_zone.HostedZone>`
instance representing the requested hosted zone. | route53/connection.py | def get_hosted_zone_by_id(self, id):
"""
Retrieves a hosted zone, by hosted zone ID (not name).
:param str id: The hosted zone's ID (a short hash string).
:rtype: :py:class:`HostedZone <route53.hosted_zone.HostedZone>`
:returns: An :py:class:`HostedZone <route53.hosted_zone.HostedZone>`
instance representing the requested hosted zone.
"""
root = self._send_request(
path='hostedzone/%s' % id,
data={},
method='GET',
)
return xml_parsers.get_hosted_zone_by_id_parser(
root=root,
connection=self,
) | def get_hosted_zone_by_id(self, id):
"""
Retrieves a hosted zone, by hosted zone ID (not name).
:param str id: The hosted zone's ID (a short hash string).
:rtype: :py:class:`HostedZone <route53.hosted_zone.HostedZone>`
:returns: An :py:class:`HostedZone <route53.hosted_zone.HostedZone>`
instance representing the requested hosted zone.
"""
root = self._send_request(
path='hostedzone/%s' % id,
data={},
method='GET',
)
return xml_parsers.get_hosted_zone_by_id_parser(
root=root,
connection=self,
) | [
"Retrieves",
"a",
"hosted",
"zone",
"by",
"hosted",
"zone",
"ID",
"(",
"not",
"name",
")",
"."
] | gtaylor/python-route53 | python | https://github.com/gtaylor/python-route53/blob/b9fc7e258a79551c9ed61e4a71668b7f06f9e774/route53/connection.py#L178-L197 | [
"def",
"get_hosted_zone_by_id",
"(",
"self",
",",
"id",
")",
":",
"root",
"=",
"self",
".",
"_send_request",
"(",
"path",
"=",
"'hostedzone/%s'",
"%",
"id",
",",
"data",
"=",
"{",
"}",
",",
"method",
"=",
"'GET'",
",",
")",
"return",
"xml_parsers",
".",
"get_hosted_zone_by_id_parser",
"(",
"root",
"=",
"root",
",",
"connection",
"=",
"self",
",",
")"
] | b9fc7e258a79551c9ed61e4a71668b7f06f9e774 |
test | Route53Connection.delete_hosted_zone_by_id | Deletes a hosted zone, by hosted zone ID (not name).
.. tip:: For most cases, we recommend deleting hosted zones via a
:py:class:`HostedZone <route53.hosted_zone.HostedZone>`
instance's
:py:meth:`HostedZone.delete <route53.hosted_zone.HostedZone.delete>`
method, but this saves an HTTP request if you already know the zone's ID.
.. note:: Unlike
:py:meth:`HostedZone.delete <route53.hosted_zone.HostedZone.delete>`,
this method has no optional ``force`` kwarg.
:param str id: The hosted zone's ID (a short hash string).
:rtype: dict
:returns: A dict of change info, which contains some details about
the request. | route53/connection.py | def delete_hosted_zone_by_id(self, id):
"""
Deletes a hosted zone, by hosted zone ID (not name).
.. tip:: For most cases, we recommend deleting hosted zones via a
:py:class:`HostedZone <route53.hosted_zone.HostedZone>`
instance's
:py:meth:`HostedZone.delete <route53.hosted_zone.HostedZone.delete>`
method, but this saves an HTTP request if you already know the zone's ID.
.. note:: Unlike
:py:meth:`HostedZone.delete <route53.hosted_zone.HostedZone.delete>`,
this method has no optional ``force`` kwarg.
:param str id: The hosted zone's ID (a short hash string).
:rtype: dict
:returns: A dict of change info, which contains some details about
the request.
"""
root = self._send_request(
path='hostedzone/%s' % id,
data={},
method='DELETE',
)
return xml_parsers.delete_hosted_zone_by_id_parser(
root=root,
connection=self,
) | def delete_hosted_zone_by_id(self, id):
"""
Deletes a hosted zone, by hosted zone ID (not name).
.. tip:: For most cases, we recommend deleting hosted zones via a
:py:class:`HostedZone <route53.hosted_zone.HostedZone>`
instance's
:py:meth:`HostedZone.delete <route53.hosted_zone.HostedZone.delete>`
method, but this saves an HTTP request if you already know the zone's ID.
.. note:: Unlike
:py:meth:`HostedZone.delete <route53.hosted_zone.HostedZone.delete>`,
this method has no optional ``force`` kwarg.
:param str id: The hosted zone's ID (a short hash string).
:rtype: dict
:returns: A dict of change info, which contains some details about
the request.
"""
root = self._send_request(
path='hostedzone/%s' % id,
data={},
method='DELETE',
)
return xml_parsers.delete_hosted_zone_by_id_parser(
root=root,
connection=self,
) | [
"Deletes",
"a",
"hosted",
"zone",
"by",
"hosted",
"zone",
"ID",
"(",
"not",
"name",
")",
"."
] | gtaylor/python-route53 | python | https://github.com/gtaylor/python-route53/blob/b9fc7e258a79551c9ed61e4a71668b7f06f9e774/route53/connection.py#L199-L228 | [
"def",
"delete_hosted_zone_by_id",
"(",
"self",
",",
"id",
")",
":",
"root",
"=",
"self",
".",
"_send_request",
"(",
"path",
"=",
"'hostedzone/%s'",
"%",
"id",
",",
"data",
"=",
"{",
"}",
",",
"method",
"=",
"'DELETE'",
",",
")",
"return",
"xml_parsers",
".",
"delete_hosted_zone_by_id_parser",
"(",
"root",
"=",
"root",
",",
"connection",
"=",
"self",
",",
")"
] | b9fc7e258a79551c9ed61e4a71668b7f06f9e774 |
test | Route53Connection._list_resource_record_sets_by_zone_id | Lists a hosted zone's resource record sets by Zone ID, if you
already know it.
.. tip:: For most cases, we recommend going through a
:py:class:`HostedZone <route53.hosted_zone.HostedZone>`
instance's
:py:meth:`HostedZone.record_sets <route53.hosted_zone.HostedZone.record_sets>`
property, but this saves an HTTP request if you already know the
zone's ID.
:param str id: The ID of the zone whose record sets we're listing.
:keyword str rrset_type: The type of resource record set to begin the
record listing from.
:keyword str identifier: Weighted and latency resource record sets
only: If results were truncated for a given DNS name and type,
the value of SetIdentifier for the next resource record set
that has the current DNS name and type.
:keyword str name: Not really sure what this does.
:keyword int page_chunks: This API call is paginated behind-the-scenes
by this many ResourceRecordSet instances. The default should be
fine for just about everybody, aside from those with tons of RRS.
:rtype: generator
:returns: A generator of ResourceRecordSet instances. | route53/connection.py | def _list_resource_record_sets_by_zone_id(self, id, rrset_type=None,
identifier=None, name=None,
page_chunks=100):
"""
Lists a hosted zone's resource record sets by Zone ID, if you
already know it.
.. tip:: For most cases, we recommend going through a
:py:class:`HostedZone <route53.hosted_zone.HostedZone>`
instance's
:py:meth:`HostedZone.record_sets <route53.hosted_zone.HostedZone.record_sets>`
property, but this saves an HTTP request if you already know the
zone's ID.
:param str id: The ID of the zone whose record sets we're listing.
:keyword str rrset_type: The type of resource record set to begin the
record listing from.
:keyword str identifier: Weighted and latency resource record sets
only: If results were truncated for a given DNS name and type,
the value of SetIdentifier for the next resource record set
that has the current DNS name and type.
:keyword str name: Not really sure what this does.
:keyword int page_chunks: This API call is paginated behind-the-scenes
by this many ResourceRecordSet instances. The default should be
fine for just about everybody, aside from those with tons of RRS.
:rtype: generator
:returns: A generator of ResourceRecordSet instances.
"""
params = {
'name': name,
'type': rrset_type,
'identifier': identifier,
'maxitems': page_chunks,
}
return self._do_autopaginating_api_call(
path='hostedzone/%s/rrset' % id,
params=params,
method='GET',
parser_func=xml_parsers.list_resource_record_sets_by_zone_id_parser,
parser_kwargs={'zone_id': id},
next_marker_xpath="./{*}NextRecordName",
next_marker_param_name="name",
next_type_xpath="./{*}NextRecordType"
) | def _list_resource_record_sets_by_zone_id(self, id, rrset_type=None,
identifier=None, name=None,
page_chunks=100):
"""
Lists a hosted zone's resource record sets by Zone ID, if you
already know it.
.. tip:: For most cases, we recommend going through a
:py:class:`HostedZone <route53.hosted_zone.HostedZone>`
instance's
:py:meth:`HostedZone.record_sets <route53.hosted_zone.HostedZone.record_sets>`
property, but this saves an HTTP request if you already know the
zone's ID.
:param str id: The ID of the zone whose record sets we're listing.
:keyword str rrset_type: The type of resource record set to begin the
record listing from.
:keyword str identifier: Weighted and latency resource record sets
only: If results were truncated for a given DNS name and type,
the value of SetIdentifier for the next resource record set
that has the current DNS name and type.
:keyword str name: Not really sure what this does.
:keyword int page_chunks: This API call is paginated behind-the-scenes
by this many ResourceRecordSet instances. The default should be
fine for just about everybody, aside from those with tons of RRS.
:rtype: generator
:returns: A generator of ResourceRecordSet instances.
"""
params = {
'name': name,
'type': rrset_type,
'identifier': identifier,
'maxitems': page_chunks,
}
return self._do_autopaginating_api_call(
path='hostedzone/%s/rrset' % id,
params=params,
method='GET',
parser_func=xml_parsers.list_resource_record_sets_by_zone_id_parser,
parser_kwargs={'zone_id': id},
next_marker_xpath="./{*}NextRecordName",
next_marker_param_name="name",
next_type_xpath="./{*}NextRecordType"
) | [
"Lists",
"a",
"hosted",
"zone",
"s",
"resource",
"record",
"sets",
"by",
"Zone",
"ID",
"if",
"you",
"already",
"know",
"it",
"."
] | gtaylor/python-route53 | python | https://github.com/gtaylor/python-route53/blob/b9fc7e258a79551c9ed61e4a71668b7f06f9e774/route53/connection.py#L230-L276 | [
"def",
"_list_resource_record_sets_by_zone_id",
"(",
"self",
",",
"id",
",",
"rrset_type",
"=",
"None",
",",
"identifier",
"=",
"None",
",",
"name",
"=",
"None",
",",
"page_chunks",
"=",
"100",
")",
":",
"params",
"=",
"{",
"'name'",
":",
"name",
",",
"'type'",
":",
"rrset_type",
",",
"'identifier'",
":",
"identifier",
",",
"'maxitems'",
":",
"page_chunks",
",",
"}",
"return",
"self",
".",
"_do_autopaginating_api_call",
"(",
"path",
"=",
"'hostedzone/%s/rrset'",
"%",
"id",
",",
"params",
"=",
"params",
",",
"method",
"=",
"'GET'",
",",
"parser_func",
"=",
"xml_parsers",
".",
"list_resource_record_sets_by_zone_id_parser",
",",
"parser_kwargs",
"=",
"{",
"'zone_id'",
":",
"id",
"}",
",",
"next_marker_xpath",
"=",
"\"./{*}NextRecordName\"",
",",
"next_marker_param_name",
"=",
"\"name\"",
",",
"next_type_xpath",
"=",
"\"./{*}NextRecordType\"",
")"
] | b9fc7e258a79551c9ed61e4a71668b7f06f9e774 |
test | Route53Connection._change_resource_record_sets | Given a ChangeSet, POST it to the Route53 API.
.. note:: You probably shouldn't be using this method directly,
as there are convenience methods on the ResourceRecordSet
sub-classes.
:param change_set.ChangeSet change_set: The ChangeSet object to create
the XML doc from.
:keyword str comment: An optional comment to go along with the request.
:rtype: dict
:returns: A dict of change info, which contains some details about
the request. | route53/connection.py | def _change_resource_record_sets(self, change_set, comment=None):
"""
Given a ChangeSet, POST it to the Route53 API.
.. note:: You probably shouldn't be using this method directly,
as there are convenience methods on the ResourceRecordSet
sub-classes.
:param change_set.ChangeSet change_set: The ChangeSet object to create
the XML doc from.
:keyword str comment: An optional comment to go along with the request.
:rtype: dict
:returns: A dict of change info, which contains some details about
the request.
"""
body = xml_generators.change_resource_record_set_writer(
connection=self,
change_set=change_set,
comment=comment
)
root = self._send_request(
path='hostedzone/%s/rrset' % change_set.hosted_zone_id,
data=body,
method='POST',
)
#print(prettyprint_xml(root))
e_change_info = root.find('./{*}ChangeInfo')
if e_change_info is None:
error = root.find('./{*}Error').find('./{*}Message').text
raise Route53Error(error)
return parse_change_info(e_change_info) | def _change_resource_record_sets(self, change_set, comment=None):
"""
Given a ChangeSet, POST it to the Route53 API.
.. note:: You probably shouldn't be using this method directly,
as there are convenience methods on the ResourceRecordSet
sub-classes.
:param change_set.ChangeSet change_set: The ChangeSet object to create
the XML doc from.
:keyword str comment: An optional comment to go along with the request.
:rtype: dict
:returns: A dict of change info, which contains some details about
the request.
"""
body = xml_generators.change_resource_record_set_writer(
connection=self,
change_set=change_set,
comment=comment
)
root = self._send_request(
path='hostedzone/%s/rrset' % change_set.hosted_zone_id,
data=body,
method='POST',
)
#print(prettyprint_xml(root))
e_change_info = root.find('./{*}ChangeInfo')
if e_change_info is None:
error = root.find('./{*}Error').find('./{*}Message').text
raise Route53Error(error)
return parse_change_info(e_change_info) | [
"Given",
"a",
"ChangeSet",
"POST",
"it",
"to",
"the",
"Route53",
"API",
"."
] | gtaylor/python-route53 | python | https://github.com/gtaylor/python-route53/blob/b9fc7e258a79551c9ed61e4a71668b7f06f9e774/route53/connection.py#L278-L312 | [
"def",
"_change_resource_record_sets",
"(",
"self",
",",
"change_set",
",",
"comment",
"=",
"None",
")",
":",
"body",
"=",
"xml_generators",
".",
"change_resource_record_set_writer",
"(",
"connection",
"=",
"self",
",",
"change_set",
"=",
"change_set",
",",
"comment",
"=",
"comment",
")",
"root",
"=",
"self",
".",
"_send_request",
"(",
"path",
"=",
"'hostedzone/%s/rrset'",
"%",
"change_set",
".",
"hosted_zone_id",
",",
"data",
"=",
"body",
",",
"method",
"=",
"'POST'",
",",
")",
"#print(prettyprint_xml(root))",
"e_change_info",
"=",
"root",
".",
"find",
"(",
"'./{*}ChangeInfo'",
")",
"if",
"e_change_info",
"is",
"None",
":",
"error",
"=",
"root",
".",
"find",
"(",
"'./{*}Error'",
")",
".",
"find",
"(",
"'./{*}Message'",
")",
".",
"text",
"raise",
"Route53Error",
"(",
"error",
")",
"return",
"parse_change_info",
"(",
"e_change_info",
")"
] | b9fc7e258a79551c9ed61e4a71668b7f06f9e774 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.