id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
228,800 | Azure/azure-cli-extensions | src/interactive/azext_interactive/azclishell/gather_commands.py | add_new_lines | def add_new_lines(long_phrase, line_min=None, tolerance=TOLERANCE):
""" not everything fits on the screen, based on the size, add newlines """
if line_min is None:
line_min = math.floor(int(_get_window_columns()) / 2 - 15)
if long_phrase is None:
return long_phrase
line_min = int(line_min)
nl_loc = []
skip = False
index = 0
if len(long_phrase) > line_min:
for _ in range(int(math.floor(len(long_phrase) / line_min))):
previous = index
index += line_min
if skip:
index += 1
skip = False
while index < len(long_phrase) and \
not long_phrase[index].isspace() and \
index < tolerance + previous + line_min:
index += 1
if index < len(long_phrase):
if long_phrase[index].isspace():
index += 1
skip = True
nl_loc.append(index)
counter = 0
for loc in nl_loc:
long_phrase = long_phrase[:loc + counter] + '\n' + long_phrase[loc + counter:]
counter += 1
return long_phrase + "\n" | python | def add_new_lines(long_phrase, line_min=None, tolerance=TOLERANCE):
if line_min is None:
line_min = math.floor(int(_get_window_columns()) / 2 - 15)
if long_phrase is None:
return long_phrase
line_min = int(line_min)
nl_loc = []
skip = False
index = 0
if len(long_phrase) > line_min:
for _ in range(int(math.floor(len(long_phrase) / line_min))):
previous = index
index += line_min
if skip:
index += 1
skip = False
while index < len(long_phrase) and \
not long_phrase[index].isspace() and \
index < tolerance + previous + line_min:
index += 1
if index < len(long_phrase):
if long_phrase[index].isspace():
index += 1
skip = True
nl_loc.append(index)
counter = 0
for loc in nl_loc:
long_phrase = long_phrase[:loc + counter] + '\n' + long_phrase[loc + counter:]
counter += 1
return long_phrase + "\n" | [
"def",
"add_new_lines",
"(",
"long_phrase",
",",
"line_min",
"=",
"None",
",",
"tolerance",
"=",
"TOLERANCE",
")",
":",
"if",
"line_min",
"is",
"None",
":",
"line_min",
"=",
"math",
".",
"floor",
"(",
"int",
"(",
"_get_window_columns",
"(",
")",
")",
"/"... | not everything fits on the screen, based on the size, add newlines | [
"not",
"everything",
"fits",
"on",
"the",
"screen",
"based",
"on",
"the",
"size",
"add",
"newlines"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/interactive/azext_interactive/azclishell/gather_commands.py#L35-L68 |
228,801 | Azure/azure-cli-extensions | src/interactive/azext_interactive/azclishell/gather_commands.py | GatherCommands.add_exit | def add_exit(self):
""" adds the exits from the application """
self.completable.append("quit")
self.completable.append("exit")
self.descrip["quit"] = "Exits the program"
self.descrip["exit"] = "Exits the program"
self.command_tree.add_child(CommandBranch("quit"))
self.command_tree.add_child(CommandBranch("exit"))
self.command_param["quit"] = ""
self.command_param["exit"] = "" | python | def add_exit(self):
self.completable.append("quit")
self.completable.append("exit")
self.descrip["quit"] = "Exits the program"
self.descrip["exit"] = "Exits the program"
self.command_tree.add_child(CommandBranch("quit"))
self.command_tree.add_child(CommandBranch("exit"))
self.command_param["quit"] = ""
self.command_param["exit"] = "" | [
"def",
"add_exit",
"(",
"self",
")",
":",
"self",
".",
"completable",
".",
"append",
"(",
"\"quit\"",
")",
"self",
".",
"completable",
".",
"append",
"(",
"\"exit\"",
")",
"self",
".",
"descrip",
"[",
"\"quit\"",
"]",
"=",
"\"Exits the program\"",
"self",
... | adds the exits from the application | [
"adds",
"the",
"exits",
"from",
"the",
"application"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/interactive/azext_interactive/azclishell/gather_commands.py#L99-L111 |
228,802 | Azure/azure-cli-extensions | src/interactive/azext_interactive/azclishell/gather_commands.py | GatherCommands._gather_from_files | def _gather_from_files(self, config):
""" gathers from the files in a way that is convienent to use """
command_file = config.get_help_files()
cache_path = os.path.join(config.get_config_dir(), 'cache')
cols = _get_window_columns()
with open(os.path.join(cache_path, command_file), 'r') as help_file:
data = json.load(help_file)
self.add_exit()
commands = data.keys()
for command in commands:
branch = self.command_tree
for word in command.split():
if word not in self.completable:
self.completable.append(word)
if not branch.has_child(word):
branch.add_child(CommandBranch(word))
branch = branch.get_child(word)
description = data[command]['help']
self.descrip[command] = add_new_lines(description, line_min=int(cols) - 2 * TOLERANCE)
if 'examples' in data[command]:
examples = []
for example in data[command]['examples']:
examples.append([
add_new_lines(example[0], line_min=int(cols) - 2 * TOLERANCE),
add_new_lines(example[1], line_min=int(cols) - 2 * TOLERANCE)])
self.command_example[command] = examples
command_params = data[command].get('parameters', {})
for param in command_params:
if '==SUPPRESS==' not in command_params[param]['help']:
param_aliases = set()
for par in command_params[param]['name']:
param_aliases.add(par)
self.param_descript[command + " " + par] = \
add_new_lines(
command_params[param]['required'] +
" " + command_params[param]['help'],
line_min=int(cols) - 2 * TOLERANCE)
if par not in self.completable_param:
self.completable_param.append(par)
param_doubles = self.command_param_info.get(command, {})
for alias in param_aliases:
param_doubles[alias] = param_aliases
self.command_param_info[command] = param_doubles | python | def _gather_from_files(self, config):
command_file = config.get_help_files()
cache_path = os.path.join(config.get_config_dir(), 'cache')
cols = _get_window_columns()
with open(os.path.join(cache_path, command_file), 'r') as help_file:
data = json.load(help_file)
self.add_exit()
commands = data.keys()
for command in commands:
branch = self.command_tree
for word in command.split():
if word not in self.completable:
self.completable.append(word)
if not branch.has_child(word):
branch.add_child(CommandBranch(word))
branch = branch.get_child(word)
description = data[command]['help']
self.descrip[command] = add_new_lines(description, line_min=int(cols) - 2 * TOLERANCE)
if 'examples' in data[command]:
examples = []
for example in data[command]['examples']:
examples.append([
add_new_lines(example[0], line_min=int(cols) - 2 * TOLERANCE),
add_new_lines(example[1], line_min=int(cols) - 2 * TOLERANCE)])
self.command_example[command] = examples
command_params = data[command].get('parameters', {})
for param in command_params:
if '==SUPPRESS==' not in command_params[param]['help']:
param_aliases = set()
for par in command_params[param]['name']:
param_aliases.add(par)
self.param_descript[command + " " + par] = \
add_new_lines(
command_params[param]['required'] +
" " + command_params[param]['help'],
line_min=int(cols) - 2 * TOLERANCE)
if par not in self.completable_param:
self.completable_param.append(par)
param_doubles = self.command_param_info.get(command, {})
for alias in param_aliases:
param_doubles[alias] = param_aliases
self.command_param_info[command] = param_doubles | [
"def",
"_gather_from_files",
"(",
"self",
",",
"config",
")",
":",
"command_file",
"=",
"config",
".",
"get_help_files",
"(",
")",
"cache_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"config",
".",
"get_config_dir",
"(",
")",
",",
"'cache'",
")",
"co... | gathers from the files in a way that is convienent to use | [
"gathers",
"from",
"the",
"files",
"in",
"a",
"way",
"that",
"is",
"convienent",
"to",
"use"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/interactive/azext_interactive/azclishell/gather_commands.py#L113-L163 |
228,803 | Azure/azure-cli-extensions | src/interactive/azext_interactive/azclishell/gather_commands.py | GatherCommands.get_all_subcommands | def get_all_subcommands(self):
""" returns all the subcommands """
subcommands = []
for command in self.descrip:
for word in command.split():
for kid in self.command_tree.children:
if word != kid and word not in subcommands:
subcommands.append(word)
return subcommands | python | def get_all_subcommands(self):
subcommands = []
for command in self.descrip:
for word in command.split():
for kid in self.command_tree.children:
if word != kid and word not in subcommands:
subcommands.append(word)
return subcommands | [
"def",
"get_all_subcommands",
"(",
"self",
")",
":",
"subcommands",
"=",
"[",
"]",
"for",
"command",
"in",
"self",
".",
"descrip",
":",
"for",
"word",
"in",
"command",
".",
"split",
"(",
")",
":",
"for",
"kid",
"in",
"self",
".",
"command_tree",
".",
... | returns all the subcommands | [
"returns",
"all",
"the",
"subcommands"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/interactive/azext_interactive/azclishell/gather_commands.py#L165-L173 |
228,804 | Azure/azure-cli-extensions | src/alias/azext_alias/custom.py | create_alias | def create_alias(alias_name, alias_command):
"""
Create an alias.
Args:
alias_name: The name of the alias.
alias_command: The command that the alias points to.
"""
alias_name, alias_command = alias_name.strip(), alias_command.strip()
alias_table = get_alias_table()
if alias_name not in alias_table.sections():
alias_table.add_section(alias_name)
alias_table.set(alias_name, 'command', alias_command)
_commit_change(alias_table) | python | def create_alias(alias_name, alias_command):
alias_name, alias_command = alias_name.strip(), alias_command.strip()
alias_table = get_alias_table()
if alias_name not in alias_table.sections():
alias_table.add_section(alias_name)
alias_table.set(alias_name, 'command', alias_command)
_commit_change(alias_table) | [
"def",
"create_alias",
"(",
"alias_name",
",",
"alias_command",
")",
":",
"alias_name",
",",
"alias_command",
"=",
"alias_name",
".",
"strip",
"(",
")",
",",
"alias_command",
".",
"strip",
"(",
")",
"alias_table",
"=",
"get_alias_table",
"(",
")",
"if",
"ali... | Create an alias.
Args:
alias_name: The name of the alias.
alias_command: The command that the alias points to. | [
"Create",
"an",
"alias",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/alias/azext_alias/custom.py#L25-L39 |
228,805 | Azure/azure-cli-extensions | src/alias/azext_alias/custom.py | export_aliases | def export_aliases(export_path=None, exclusions=None):
"""
Export all registered aliases to a given path, as an INI configuration file.
Args:
export_path: The path of the alias configuration file to export to.
exclusions: Space-separated aliases excluded from export.
"""
if not export_path:
export_path = os.path.abspath(ALIAS_FILE_NAME)
alias_table = get_alias_table()
for exclusion in exclusions or []:
if exclusion not in alias_table.sections():
raise CLIError(ALIAS_NOT_FOUND_ERROR.format(exclusion))
alias_table.remove_section(exclusion)
_commit_change(alias_table, export_path=export_path, post_commit=False)
logger.warning(POST_EXPORT_ALIAS_MSG, export_path) | python | def export_aliases(export_path=None, exclusions=None):
if not export_path:
export_path = os.path.abspath(ALIAS_FILE_NAME)
alias_table = get_alias_table()
for exclusion in exclusions or []:
if exclusion not in alias_table.sections():
raise CLIError(ALIAS_NOT_FOUND_ERROR.format(exclusion))
alias_table.remove_section(exclusion)
_commit_change(alias_table, export_path=export_path, post_commit=False)
logger.warning(POST_EXPORT_ALIAS_MSG, export_path) | [
"def",
"export_aliases",
"(",
"export_path",
"=",
"None",
",",
"exclusions",
"=",
"None",
")",
":",
"if",
"not",
"export_path",
":",
"export_path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"ALIAS_FILE_NAME",
")",
"alias_table",
"=",
"get_alias_table",
"(... | Export all registered aliases to a given path, as an INI configuration file.
Args:
export_path: The path of the alias configuration file to export to.
exclusions: Space-separated aliases excluded from export. | [
"Export",
"all",
"registered",
"aliases",
"to",
"a",
"given",
"path",
"as",
"an",
"INI",
"configuration",
"file",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/alias/azext_alias/custom.py#L42-L60 |
228,806 | Azure/azure-cli-extensions | src/alias/azext_alias/custom.py | import_aliases | def import_aliases(alias_source):
"""
Import aliases from a file or an URL.
Args:
alias_source: The source of the alias. It can be a filepath or an URL.
"""
alias_table = get_alias_table()
if is_url(alias_source):
alias_source = retrieve_file_from_url(alias_source)
alias_table.read(alias_source)
os.remove(alias_source)
else:
alias_table.read(alias_source)
_commit_change(alias_table) | python | def import_aliases(alias_source):
alias_table = get_alias_table()
if is_url(alias_source):
alias_source = retrieve_file_from_url(alias_source)
alias_table.read(alias_source)
os.remove(alias_source)
else:
alias_table.read(alias_source)
_commit_change(alias_table) | [
"def",
"import_aliases",
"(",
"alias_source",
")",
":",
"alias_table",
"=",
"get_alias_table",
"(",
")",
"if",
"is_url",
"(",
"alias_source",
")",
":",
"alias_source",
"=",
"retrieve_file_from_url",
"(",
"alias_source",
")",
"alias_table",
".",
"read",
"(",
"ali... | Import aliases from a file or an URL.
Args:
alias_source: The source of the alias. It can be a filepath or an URL. | [
"Import",
"aliases",
"from",
"a",
"file",
"or",
"an",
"URL",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/alias/azext_alias/custom.py#L63-L77 |
228,807 | Azure/azure-cli-extensions | src/alias/azext_alias/custom.py | list_alias | def list_alias():
"""
List all registered aliases.
Returns:
An array of dictionary containing the alias and the command that it points to.
"""
alias_table = get_alias_table()
output = []
for alias in alias_table.sections():
if alias_table.has_option(alias, 'command'):
output.append({
'alias': alias,
# Remove unnecessary whitespaces
'command': ' '.join(alias_table.get(alias, 'command').split())
})
return output | python | def list_alias():
alias_table = get_alias_table()
output = []
for alias in alias_table.sections():
if alias_table.has_option(alias, 'command'):
output.append({
'alias': alias,
# Remove unnecessary whitespaces
'command': ' '.join(alias_table.get(alias, 'command').split())
})
return output | [
"def",
"list_alias",
"(",
")",
":",
"alias_table",
"=",
"get_alias_table",
"(",
")",
"output",
"=",
"[",
"]",
"for",
"alias",
"in",
"alias_table",
".",
"sections",
"(",
")",
":",
"if",
"alias_table",
".",
"has_option",
"(",
"alias",
",",
"'command'",
")"... | List all registered aliases.
Returns:
An array of dictionary containing the alias and the command that it points to. | [
"List",
"all",
"registered",
"aliases",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/alias/azext_alias/custom.py#L80-L97 |
228,808 | Azure/azure-cli-extensions | src/alias/azext_alias/custom.py | remove_alias | def remove_alias(alias_names):
"""
Remove an alias.
Args:
alias_name: The name of the alias to be removed.
"""
alias_table = get_alias_table()
for alias_name in alias_names:
if alias_name not in alias_table.sections():
raise CLIError(ALIAS_NOT_FOUND_ERROR.format(alias_name))
alias_table.remove_section(alias_name)
_commit_change(alias_table) | python | def remove_alias(alias_names):
alias_table = get_alias_table()
for alias_name in alias_names:
if alias_name not in alias_table.sections():
raise CLIError(ALIAS_NOT_FOUND_ERROR.format(alias_name))
alias_table.remove_section(alias_name)
_commit_change(alias_table) | [
"def",
"remove_alias",
"(",
"alias_names",
")",
":",
"alias_table",
"=",
"get_alias_table",
"(",
")",
"for",
"alias_name",
"in",
"alias_names",
":",
"if",
"alias_name",
"not",
"in",
"alias_table",
".",
"sections",
"(",
")",
":",
"raise",
"CLIError",
"(",
"AL... | Remove an alias.
Args:
alias_name: The name of the alias to be removed. | [
"Remove",
"an",
"alias",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/alias/azext_alias/custom.py#L100-L112 |
228,809 | Azure/azure-cli-extensions | src/alias/azext_alias/custom.py | _commit_change | def _commit_change(alias_table, export_path=None, post_commit=True):
"""
Record changes to the alias table.
Also write new alias config hash and collided alias, if any.
Args:
alias_table: The alias table to commit.
export_path: The path to export the aliases to. Default: GLOBAL_ALIAS_PATH.
post_commit: True if we want to perform some extra actions after writing alias to file.
"""
with open(export_path or GLOBAL_ALIAS_PATH, 'w+') as alias_config_file:
alias_table.write(alias_config_file)
if post_commit:
alias_config_file.seek(0)
alias_config_hash = hashlib.sha1(alias_config_file.read().encode('utf-8')).hexdigest()
AliasManager.write_alias_config_hash(alias_config_hash)
collided_alias = AliasManager.build_collision_table(alias_table.sections())
AliasManager.write_collided_alias(collided_alias)
build_tab_completion_table(alias_table) | python | def _commit_change(alias_table, export_path=None, post_commit=True):
with open(export_path or GLOBAL_ALIAS_PATH, 'w+') as alias_config_file:
alias_table.write(alias_config_file)
if post_commit:
alias_config_file.seek(0)
alias_config_hash = hashlib.sha1(alias_config_file.read().encode('utf-8')).hexdigest()
AliasManager.write_alias_config_hash(alias_config_hash)
collided_alias = AliasManager.build_collision_table(alias_table.sections())
AliasManager.write_collided_alias(collided_alias)
build_tab_completion_table(alias_table) | [
"def",
"_commit_change",
"(",
"alias_table",
",",
"export_path",
"=",
"None",
",",
"post_commit",
"=",
"True",
")",
":",
"with",
"open",
"(",
"export_path",
"or",
"GLOBAL_ALIAS_PATH",
",",
"'w+'",
")",
"as",
"alias_config_file",
":",
"alias_table",
".",
"write... | Record changes to the alias table.
Also write new alias config hash and collided alias, if any.
Args:
alias_table: The alias table to commit.
export_path: The path to export the aliases to. Default: GLOBAL_ALIAS_PATH.
post_commit: True if we want to perform some extra actions after writing alias to file. | [
"Record",
"changes",
"to",
"the",
"alias",
"table",
".",
"Also",
"write",
"new",
"alias",
"config",
"hash",
"and",
"collided",
"alias",
"if",
"any",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/alias/azext_alias/custom.py#L122-L140 |
228,810 | Azure/azure-cli-extensions | src/application-insights/azext_applicationinsights/_client_factory.py | applicationinsights_mgmt_plane_client | def applicationinsights_mgmt_plane_client(cli_ctx, _, subscription=None):
"""Initialize Log Analytics mgmt client for use with CLI."""
from .vendored_sdks.mgmt_applicationinsights import ApplicationInsightsManagementClient
from azure.cli.core._profile import Profile
profile = Profile(cli_ctx=cli_ctx)
# Use subscription from resource_id where possible, otherwise use login.
if subscription:
cred, _, _ = profile.get_login_credentials(subscription_id=subscription)
return ApplicationInsightsManagementClient(
cred,
subscription
)
cred, sub_id, _ = profile.get_login_credentials()
return ApplicationInsightsManagementClient(
cred,
sub_id
) | python | def applicationinsights_mgmt_plane_client(cli_ctx, _, subscription=None):
from .vendored_sdks.mgmt_applicationinsights import ApplicationInsightsManagementClient
from azure.cli.core._profile import Profile
profile = Profile(cli_ctx=cli_ctx)
# Use subscription from resource_id where possible, otherwise use login.
if subscription:
cred, _, _ = profile.get_login_credentials(subscription_id=subscription)
return ApplicationInsightsManagementClient(
cred,
subscription
)
cred, sub_id, _ = profile.get_login_credentials()
return ApplicationInsightsManagementClient(
cred,
sub_id
) | [
"def",
"applicationinsights_mgmt_plane_client",
"(",
"cli_ctx",
",",
"_",
",",
"subscription",
"=",
"None",
")",
":",
"from",
".",
"vendored_sdks",
".",
"mgmt_applicationinsights",
"import",
"ApplicationInsightsManagementClient",
"from",
"azure",
".",
"cli",
".",
"cor... | Initialize Log Analytics mgmt client for use with CLI. | [
"Initialize",
"Log",
"Analytics",
"mgmt",
"client",
"for",
"use",
"with",
"CLI",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/application-insights/azext_applicationinsights/_client_factory.py#L19-L35 |
228,811 | Azure/azure-cli-extensions | src/alias/azext_alias/hooks.py | alias_event_handler | def alias_event_handler(_, **kwargs):
"""
An event handler for alias transformation when EVENT_INVOKER_PRE_TRUNCATE_CMD_TBL event is invoked.
"""
try:
telemetry.start()
start_time = timeit.default_timer()
args = kwargs.get('args')
alias_manager = AliasManager(**kwargs)
# [:] will keep the reference of the original args
args[:] = alias_manager.transform(args)
if is_alias_command(['create', 'import'], args):
load_cmd_tbl_func = kwargs.get('load_cmd_tbl_func', lambda _: {})
cache_reserved_commands(load_cmd_tbl_func)
elapsed_time = (timeit.default_timer() - start_time) * 1000
logger.debug(DEBUG_MSG_WITH_TIMING, args, elapsed_time)
telemetry.set_execution_time(round(elapsed_time, 2))
except Exception as client_exception: # pylint: disable=broad-except
telemetry.set_exception(client_exception)
raise
finally:
telemetry.conclude() | python | def alias_event_handler(_, **kwargs):
try:
telemetry.start()
start_time = timeit.default_timer()
args = kwargs.get('args')
alias_manager = AliasManager(**kwargs)
# [:] will keep the reference of the original args
args[:] = alias_manager.transform(args)
if is_alias_command(['create', 'import'], args):
load_cmd_tbl_func = kwargs.get('load_cmd_tbl_func', lambda _: {})
cache_reserved_commands(load_cmd_tbl_func)
elapsed_time = (timeit.default_timer() - start_time) * 1000
logger.debug(DEBUG_MSG_WITH_TIMING, args, elapsed_time)
telemetry.set_execution_time(round(elapsed_time, 2))
except Exception as client_exception: # pylint: disable=broad-except
telemetry.set_exception(client_exception)
raise
finally:
telemetry.conclude() | [
"def",
"alias_event_handler",
"(",
"_",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"telemetry",
".",
"start",
"(",
")",
"start_time",
"=",
"timeit",
".",
"default_timer",
"(",
")",
"args",
"=",
"kwargs",
".",
"get",
"(",
"'args'",
")",
"alias_manag... | An event handler for alias transformation when EVENT_INVOKER_PRE_TRUNCATE_CMD_TBL event is invoked. | [
"An",
"event",
"handler",
"for",
"alias",
"transformation",
"when",
"EVENT_INVOKER_PRE_TRUNCATE_CMD_TBL",
"event",
"is",
"invoked",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/alias/azext_alias/hooks.py#L25-L51 |
228,812 | Azure/azure-cli-extensions | src/alias/azext_alias/hooks.py | enable_aliases_autocomplete | def enable_aliases_autocomplete(_, **kwargs):
"""
Enable aliases autocomplete by injecting aliases into Azure CLI tab completion list.
"""
external_completions = kwargs.get('external_completions', [])
prefix = kwargs.get('cword_prefix', [])
cur_commands = kwargs.get('comp_words', [])
alias_table = get_alias_table()
# Transform aliases if they are in current commands,
# so parser can get the correct subparser when chaining aliases
_transform_cur_commands(cur_commands, alias_table=alias_table)
for alias, alias_command in filter_aliases(alias_table):
if alias.startswith(prefix) and alias.strip() != prefix and _is_autocomplete_valid(cur_commands, alias_command):
# Only autocomplete the first word because alias is space-delimited
external_completions.append(alias)
# Append spaces if necessary (https://github.com/kislyuk/argcomplete/blob/master/argcomplete/__init__.py#L552-L559)
prequote = kwargs.get('cword_prequote', '')
continuation_chars = "=/:"
if len(external_completions) == 1 and external_completions[0][-1] not in continuation_chars and not prequote:
external_completions[0] += ' ' | python | def enable_aliases_autocomplete(_, **kwargs):
external_completions = kwargs.get('external_completions', [])
prefix = kwargs.get('cword_prefix', [])
cur_commands = kwargs.get('comp_words', [])
alias_table = get_alias_table()
# Transform aliases if they are in current commands,
# so parser can get the correct subparser when chaining aliases
_transform_cur_commands(cur_commands, alias_table=alias_table)
for alias, alias_command in filter_aliases(alias_table):
if alias.startswith(prefix) and alias.strip() != prefix and _is_autocomplete_valid(cur_commands, alias_command):
# Only autocomplete the first word because alias is space-delimited
external_completions.append(alias)
# Append spaces if necessary (https://github.com/kislyuk/argcomplete/blob/master/argcomplete/__init__.py#L552-L559)
prequote = kwargs.get('cword_prequote', '')
continuation_chars = "=/:"
if len(external_completions) == 1 and external_completions[0][-1] not in continuation_chars and not prequote:
external_completions[0] += ' ' | [
"def",
"enable_aliases_autocomplete",
"(",
"_",
",",
"*",
"*",
"kwargs",
")",
":",
"external_completions",
"=",
"kwargs",
".",
"get",
"(",
"'external_completions'",
",",
"[",
"]",
")",
"prefix",
"=",
"kwargs",
".",
"get",
"(",
"'cword_prefix'",
",",
"[",
"... | Enable aliases autocomplete by injecting aliases into Azure CLI tab completion list. | [
"Enable",
"aliases",
"autocomplete",
"by",
"injecting",
"aliases",
"into",
"Azure",
"CLI",
"tab",
"completion",
"list",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/alias/azext_alias/hooks.py#L54-L75 |
228,813 | Azure/azure-cli-extensions | src/alias/azext_alias/hooks.py | transform_cur_commands_interactive | def transform_cur_commands_interactive(_, **kwargs):
"""
Transform any aliases in current commands in interactive into their respective commands.
"""
event_payload = kwargs.get('event_payload', {})
# text_split = current commands typed in the interactive shell without any unfinished word
# text = current commands typed in the interactive shell
cur_commands = event_payload.get('text', '').split(' ')
_transform_cur_commands(cur_commands)
event_payload.update({
'text': ' '.join(cur_commands)
}) | python | def transform_cur_commands_interactive(_, **kwargs):
event_payload = kwargs.get('event_payload', {})
# text_split = current commands typed in the interactive shell without any unfinished word
# text = current commands typed in the interactive shell
cur_commands = event_payload.get('text', '').split(' ')
_transform_cur_commands(cur_commands)
event_payload.update({
'text': ' '.join(cur_commands)
}) | [
"def",
"transform_cur_commands_interactive",
"(",
"_",
",",
"*",
"*",
"kwargs",
")",
":",
"event_payload",
"=",
"kwargs",
".",
"get",
"(",
"'event_payload'",
",",
"{",
"}",
")",
"# text_split = current commands typed in the interactive shell without any unfinished word",
... | Transform any aliases in current commands in interactive into their respective commands. | [
"Transform",
"any",
"aliases",
"in",
"current",
"commands",
"in",
"interactive",
"into",
"their",
"respective",
"commands",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/alias/azext_alias/hooks.py#L78-L90 |
228,814 | Azure/azure-cli-extensions | src/alias/azext_alias/hooks.py | enable_aliases_autocomplete_interactive | def enable_aliases_autocomplete_interactive(_, **kwargs):
"""
Enable aliases autocomplete on interactive mode by injecting aliases in the command tree.
"""
subtree = kwargs.get('subtree', None)
if not subtree or not hasattr(subtree, 'children'):
return
for alias, alias_command in filter_aliases(get_alias_table()):
# Only autocomplete the first word because alias is space-delimited
if subtree.in_tree(alias_command.split()):
subtree.add_child(CommandBranch(alias)) | python | def enable_aliases_autocomplete_interactive(_, **kwargs):
subtree = kwargs.get('subtree', None)
if not subtree or not hasattr(subtree, 'children'):
return
for alias, alias_command in filter_aliases(get_alias_table()):
# Only autocomplete the first word because alias is space-delimited
if subtree.in_tree(alias_command.split()):
subtree.add_child(CommandBranch(alias)) | [
"def",
"enable_aliases_autocomplete_interactive",
"(",
"_",
",",
"*",
"*",
"kwargs",
")",
":",
"subtree",
"=",
"kwargs",
".",
"get",
"(",
"'subtree'",
",",
"None",
")",
"if",
"not",
"subtree",
"or",
"not",
"hasattr",
"(",
"subtree",
",",
"'children'",
")",... | Enable aliases autocomplete on interactive mode by injecting aliases in the command tree. | [
"Enable",
"aliases",
"autocomplete",
"on",
"interactive",
"mode",
"by",
"injecting",
"aliases",
"in",
"the",
"command",
"tree",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/alias/azext_alias/hooks.py#L93-L104 |
228,815 | Azure/azure-cli-extensions | src/alias/azext_alias/hooks.py | _is_autocomplete_valid | def _is_autocomplete_valid(cur_commands, alias_command):
"""
Determine whether autocomplete can be performed at the current state.
Args:
parser: The current CLI parser.
cur_commands: The current commands typed in the console.
alias_command: The alias command.
Returns:
True if autocomplete can be performed.
"""
parent_command = ' '.join(cur_commands[1:])
with open(GLOBAL_ALIAS_TAB_COMP_TABLE_PATH, 'r') as tab_completion_table_file:
try:
tab_completion_table = json.loads(tab_completion_table_file.read())
return alias_command in tab_completion_table and parent_command in tab_completion_table[alias_command]
except Exception: # pylint: disable=broad-except
return False | python | def _is_autocomplete_valid(cur_commands, alias_command):
parent_command = ' '.join(cur_commands[1:])
with open(GLOBAL_ALIAS_TAB_COMP_TABLE_PATH, 'r') as tab_completion_table_file:
try:
tab_completion_table = json.loads(tab_completion_table_file.read())
return alias_command in tab_completion_table and parent_command in tab_completion_table[alias_command]
except Exception: # pylint: disable=broad-except
return False | [
"def",
"_is_autocomplete_valid",
"(",
"cur_commands",
",",
"alias_command",
")",
":",
"parent_command",
"=",
"' '",
".",
"join",
"(",
"cur_commands",
"[",
"1",
":",
"]",
")",
"with",
"open",
"(",
"GLOBAL_ALIAS_TAB_COMP_TABLE_PATH",
",",
"'r'",
")",
"as",
"tab_... | Determine whether autocomplete can be performed at the current state.
Args:
parser: The current CLI parser.
cur_commands: The current commands typed in the console.
alias_command: The alias command.
Returns:
True if autocomplete can be performed. | [
"Determine",
"whether",
"autocomplete",
"can",
"be",
"performed",
"at",
"the",
"current",
"state",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/alias/azext_alias/hooks.py#L107-L125 |
228,816 | Azure/azure-cli-extensions | src/alias/azext_alias/hooks.py | _transform_cur_commands | def _transform_cur_commands(cur_commands, alias_table=None):
"""
Transform any aliases in cur_commands into their respective commands.
Args:
alias_table: The alias table.
cur_commands: current commands typed in the console.
"""
transformed = []
alias_table = alias_table if alias_table else get_alias_table()
for cmd in cur_commands:
if cmd in alias_table.sections() and alias_table.has_option(cmd, 'command'):
transformed += alias_table.get(cmd, 'command').split()
else:
transformed.append(cmd)
cur_commands[:] = transformed | python | def _transform_cur_commands(cur_commands, alias_table=None):
transformed = []
alias_table = alias_table if alias_table else get_alias_table()
for cmd in cur_commands:
if cmd in alias_table.sections() and alias_table.has_option(cmd, 'command'):
transformed += alias_table.get(cmd, 'command').split()
else:
transformed.append(cmd)
cur_commands[:] = transformed | [
"def",
"_transform_cur_commands",
"(",
"cur_commands",
",",
"alias_table",
"=",
"None",
")",
":",
"transformed",
"=",
"[",
"]",
"alias_table",
"=",
"alias_table",
"if",
"alias_table",
"else",
"get_alias_table",
"(",
")",
"for",
"cmd",
"in",
"cur_commands",
":",
... | Transform any aliases in cur_commands into their respective commands.
Args:
alias_table: The alias table.
cur_commands: current commands typed in the console. | [
"Transform",
"any",
"aliases",
"in",
"cur_commands",
"into",
"their",
"respective",
"commands",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/alias/azext_alias/hooks.py#L128-L143 |
228,817 | Azure/azure-cli-extensions | src/interactive/azext_interactive/azclishell/configuration.py | help_text | def help_text(values):
""" reformats the help text """
result = ""
for key in values:
result += key + ' '.join('' for x in range(GESTURE_LENGTH - len(key))) +\
': ' + values[key] + '\n'
return result | python | def help_text(values):
result = ""
for key in values:
result += key + ' '.join('' for x in range(GESTURE_LENGTH - len(key))) +\
': ' + values[key] + '\n'
return result | [
"def",
"help_text",
"(",
"values",
")",
":",
"result",
"=",
"\"\"",
"for",
"key",
"in",
"values",
":",
"result",
"+=",
"key",
"+",
"' '",
".",
"join",
"(",
"''",
"for",
"x",
"in",
"range",
"(",
"GESTURE_LENGTH",
"-",
"len",
"(",
"key",
")",
")",
... | reformats the help text | [
"reformats",
"the",
"help",
"text"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/interactive/azext_interactive/azclishell/configuration.py#L38-L44 |
228,818 | Azure/azure-cli-extensions | src/interactive/azext_interactive/azclishell/configuration.py | ask_user_for_telemetry | def ask_user_for_telemetry():
""" asks the user for if we can collect telemetry """
answer = " "
while answer.lower() != 'yes' and answer.lower() != 'no':
answer = prompt(u'\nDo you agree to sending telemetry (yes/no)? Default answer is yes: ')
if answer == '':
answer = 'yes'
return answer | python | def ask_user_for_telemetry():
answer = " "
while answer.lower() != 'yes' and answer.lower() != 'no':
answer = prompt(u'\nDo you agree to sending telemetry (yes/no)? Default answer is yes: ')
if answer == '':
answer = 'yes'
return answer | [
"def",
"ask_user_for_telemetry",
"(",
")",
":",
"answer",
"=",
"\" \"",
"while",
"answer",
".",
"lower",
"(",
")",
"!=",
"'yes'",
"and",
"answer",
".",
"lower",
"(",
")",
"!=",
"'no'",
":",
"answer",
"=",
"prompt",
"(",
"u'\\nDo you agree to sending telemetr... | asks the user for if we can collect telemetry | [
"asks",
"the",
"user",
"for",
"if",
"we",
"can",
"collect",
"telemetry"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/interactive/azext_interactive/azclishell/configuration.py#L140-L149 |
228,819 | Azure/azure-cli-extensions | src/interactive/azext_interactive/azclishell/configuration.py | Configuration.firsttime | def firsttime(self):
""" sets it as already done"""
self.config.set('DEFAULT', 'firsttime', 'no')
if self.cli_config.getboolean('core', 'collect_telemetry', fallback=False):
print(PRIVACY_STATEMENT)
else:
self.cli_config.set_value('core', 'collect_telemetry', ask_user_for_telemetry())
self.update() | python | def firsttime(self):
self.config.set('DEFAULT', 'firsttime', 'no')
if self.cli_config.getboolean('core', 'collect_telemetry', fallback=False):
print(PRIVACY_STATEMENT)
else:
self.cli_config.set_value('core', 'collect_telemetry', ask_user_for_telemetry())
self.update() | [
"def",
"firsttime",
"(",
"self",
")",
":",
"self",
".",
"config",
".",
"set",
"(",
"'DEFAULT'",
",",
"'firsttime'",
",",
"'no'",
")",
"if",
"self",
".",
"cli_config",
".",
"getboolean",
"(",
"'core'",
",",
"'collect_telemetry'",
",",
"fallback",
"=",
"Fa... | sets it as already done | [
"sets",
"it",
"as",
"already",
"done"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/interactive/azext_interactive/azclishell/configuration.py#L102-L110 |
228,820 | Azure/azure-cli-extensions | src/interactive/azext_interactive/azclishell/configuration.py | Configuration.set_val | def set_val(self, direct, section, val):
""" set the config values """
if val is not None:
self.config.set(direct, section, val)
self.update() | python | def set_val(self, direct, section, val):
if val is not None:
self.config.set(direct, section, val)
self.update() | [
"def",
"set_val",
"(",
"self",
",",
"direct",
",",
"section",
",",
"val",
")",
":",
"if",
"val",
"is",
"not",
"None",
":",
"self",
".",
"config",
".",
"set",
"(",
"direct",
",",
"section",
",",
"val",
")",
"self",
".",
"update",
"(",
")"
] | set the config values | [
"set",
"the",
"config",
"values"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/interactive/azext_interactive/azclishell/configuration.py#L128-L132 |
228,821 | Azure/azure-cli-extensions | src/interactive/azext_interactive/azclishell/configuration.py | Configuration.update | def update(self):
""" updates the configuration settings """
with open(os.path.join(self.config_dir, CONFIG_FILE_NAME), 'w') as config_file:
self.config.write(config_file) | python | def update(self):
with open(os.path.join(self.config_dir, CONFIG_FILE_NAME), 'w') as config_file:
self.config.write(config_file) | [
"def",
"update",
"(",
"self",
")",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"config_dir",
",",
"CONFIG_FILE_NAME",
")",
",",
"'w'",
")",
"as",
"config_file",
":",
"self",
".",
"config",
".",
"write",
"(",
"config_fi... | updates the configuration settings | [
"updates",
"the",
"configuration",
"settings"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/interactive/azext_interactive/azclishell/configuration.py#L134-L137 |
228,822 | Azure/azure-cli-extensions | src/log-analytics/azext_loganalytics/custom.py | execute_query | def execute_query(client, workspace, analytics_query, timespan=None, workspaces=None):
"""Executes a query against the provided Log Analytics workspace."""
from .vendored_sdks.loganalytics.models import QueryBody
return client.query(workspace, QueryBody(query=analytics_query, timespan=timespan, workspaces=workspaces)) | python | def execute_query(client, workspace, analytics_query, timespan=None, workspaces=None):
from .vendored_sdks.loganalytics.models import QueryBody
return client.query(workspace, QueryBody(query=analytics_query, timespan=timespan, workspaces=workspaces)) | [
"def",
"execute_query",
"(",
"client",
",",
"workspace",
",",
"analytics_query",
",",
"timespan",
"=",
"None",
",",
"workspaces",
"=",
"None",
")",
":",
"from",
".",
"vendored_sdks",
".",
"loganalytics",
".",
"models",
"import",
"QueryBody",
"return",
"client"... | Executes a query against the provided Log Analytics workspace. | [
"Executes",
"a",
"query",
"against",
"the",
"provided",
"Log",
"Analytics",
"workspace",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/log-analytics/azext_loganalytics/custom.py#L11-L14 |
228,823 | Azure/azure-cli-extensions | src/alias/azext_alias/alias.py | AliasManager.detect_alias_config_change | def detect_alias_config_change(self):
"""
Change if the alias configuration has changed since the last run.
Returns:
False if the alias configuration file has not been changed since the last run.
Otherwise, return True.
"""
# Do not load the entire command table if there is a parse error
if self.parse_error():
return False
alias_config_sha1 = hashlib.sha1(self.alias_config_str.encode('utf-8')).hexdigest()
if alias_config_sha1 != self.alias_config_hash:
# Overwrite the old hash with the new one
self.alias_config_hash = alias_config_sha1
return True
return False | python | def detect_alias_config_change(self):
# Do not load the entire command table if there is a parse error
if self.parse_error():
return False
alias_config_sha1 = hashlib.sha1(self.alias_config_str.encode('utf-8')).hexdigest()
if alias_config_sha1 != self.alias_config_hash:
# Overwrite the old hash with the new one
self.alias_config_hash = alias_config_sha1
return True
return False | [
"def",
"detect_alias_config_change",
"(",
"self",
")",
":",
"# Do not load the entire command table if there is a parse error",
"if",
"self",
".",
"parse_error",
"(",
")",
":",
"return",
"False",
"alias_config_sha1",
"=",
"hashlib",
".",
"sha1",
"(",
"self",
".",
"ali... | Change if the alias configuration has changed since the last run.
Returns:
False if the alias configuration file has not been changed since the last run.
Otherwise, return True. | [
"Change",
"if",
"the",
"alias",
"configuration",
"has",
"changed",
"since",
"the",
"last",
"run",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/alias/azext_alias/alias.py#L92-L109 |
228,824 | Azure/azure-cli-extensions | src/alias/azext_alias/alias.py | AliasManager.transform | def transform(self, args):
"""
Transform any aliases in args to their respective commands.
Args:
args: A list of space-delimited command input extracted directly from the console.
Returns:
A list of transformed commands according to the alias configuration file.
"""
if self.parse_error():
# Write an empty hash so next run will check the config file against the entire command table again
AliasManager.write_alias_config_hash(empty_hash=True)
return args
# Only load the entire command table if it detects changes in the alias config
if self.detect_alias_config_change():
self.load_full_command_table()
self.collided_alias = AliasManager.build_collision_table(self.alias_table.sections())
build_tab_completion_table(self.alias_table)
else:
self.load_collided_alias()
transformed_commands = []
alias_iter = enumerate(args, 1)
for alias_index, alias in alias_iter:
is_collided_alias = alias in self.collided_alias and alias_index in self.collided_alias[alias]
# Check if the current alias is a named argument
# index - 2 because alias_iter starts counting at index 1
is_named_arg = alias_index > 1 and args[alias_index - 2].startswith('-')
is_named_arg_flag = alias.startswith('-')
excluded_commands = is_alias_command(['remove', 'export'], transformed_commands)
if not alias or is_collided_alias or is_named_arg or is_named_arg_flag or excluded_commands:
transformed_commands.append(alias)
continue
full_alias = self.get_full_alias(alias)
if self.alias_table.has_option(full_alias, 'command'):
cmd_derived_from_alias = self.alias_table.get(full_alias, 'command')
telemetry.set_alias_hit(full_alias)
else:
transformed_commands.append(alias)
continue
pos_args_table = build_pos_args_table(full_alias, args, alias_index)
if pos_args_table:
logger.debug(POS_ARG_DEBUG_MSG, full_alias, cmd_derived_from_alias, pos_args_table)
transformed_commands += render_template(cmd_derived_from_alias, pos_args_table)
# Skip the next arg(s) because they have been already consumed as a positional argument above
for pos_arg in pos_args_table: # pylint: disable=unused-variable
next(alias_iter)
else:
logger.debug(DEBUG_MSG, full_alias, cmd_derived_from_alias)
transformed_commands += shlex.split(cmd_derived_from_alias)
return self.post_transform(transformed_commands) | python | def transform(self, args):
if self.parse_error():
# Write an empty hash so next run will check the config file against the entire command table again
AliasManager.write_alias_config_hash(empty_hash=True)
return args
# Only load the entire command table if it detects changes in the alias config
if self.detect_alias_config_change():
self.load_full_command_table()
self.collided_alias = AliasManager.build_collision_table(self.alias_table.sections())
build_tab_completion_table(self.alias_table)
else:
self.load_collided_alias()
transformed_commands = []
alias_iter = enumerate(args, 1)
for alias_index, alias in alias_iter:
is_collided_alias = alias in self.collided_alias and alias_index in self.collided_alias[alias]
# Check if the current alias is a named argument
# index - 2 because alias_iter starts counting at index 1
is_named_arg = alias_index > 1 and args[alias_index - 2].startswith('-')
is_named_arg_flag = alias.startswith('-')
excluded_commands = is_alias_command(['remove', 'export'], transformed_commands)
if not alias or is_collided_alias or is_named_arg or is_named_arg_flag or excluded_commands:
transformed_commands.append(alias)
continue
full_alias = self.get_full_alias(alias)
if self.alias_table.has_option(full_alias, 'command'):
cmd_derived_from_alias = self.alias_table.get(full_alias, 'command')
telemetry.set_alias_hit(full_alias)
else:
transformed_commands.append(alias)
continue
pos_args_table = build_pos_args_table(full_alias, args, alias_index)
if pos_args_table:
logger.debug(POS_ARG_DEBUG_MSG, full_alias, cmd_derived_from_alias, pos_args_table)
transformed_commands += render_template(cmd_derived_from_alias, pos_args_table)
# Skip the next arg(s) because they have been already consumed as a positional argument above
for pos_arg in pos_args_table: # pylint: disable=unused-variable
next(alias_iter)
else:
logger.debug(DEBUG_MSG, full_alias, cmd_derived_from_alias)
transformed_commands += shlex.split(cmd_derived_from_alias)
return self.post_transform(transformed_commands) | [
"def",
"transform",
"(",
"self",
",",
"args",
")",
":",
"if",
"self",
".",
"parse_error",
"(",
")",
":",
"# Write an empty hash so next run will check the config file against the entire command table again",
"AliasManager",
".",
"write_alias_config_hash",
"(",
"empty_hash",
... | Transform any aliases in args to their respective commands.
Args:
args: A list of space-delimited command input extracted directly from the console.
Returns:
A list of transformed commands according to the alias configuration file. | [
"Transform",
"any",
"aliases",
"in",
"args",
"to",
"their",
"respective",
"commands",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/alias/azext_alias/alias.py#L111-L168 |
228,825 | Azure/azure-cli-extensions | src/alias/azext_alias/alias.py | AliasManager.get_full_alias | def get_full_alias(self, query):
"""
Get the full alias given a search query.
Args:
query: The query this function performs searching on.
Returns:
The full alias (with the placeholders, if any).
"""
if query in self.alias_table.sections():
return query
return next((section for section in self.alias_table.sections() if section.split()[0] == query), '') | python | def get_full_alias(self, query):
if query in self.alias_table.sections():
return query
return next((section for section in self.alias_table.sections() if section.split()[0] == query), '') | [
"def",
"get_full_alias",
"(",
"self",
",",
"query",
")",
":",
"if",
"query",
"in",
"self",
".",
"alias_table",
".",
"sections",
"(",
")",
":",
"return",
"query",
"return",
"next",
"(",
"(",
"section",
"for",
"section",
"in",
"self",
".",
"alias_table",
... | Get the full alias given a search query.
Args:
query: The query this function performs searching on.
Returns:
The full alias (with the placeholders, if any). | [
"Get",
"the",
"full",
"alias",
"given",
"a",
"search",
"query",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/alias/azext_alias/alias.py#L170-L183 |
228,826 | Azure/azure-cli-extensions | src/alias/azext_alias/alias.py | AliasManager.load_full_command_table | def load_full_command_table(self):
"""
Perform a full load of the command table to get all the reserved command words.
"""
load_cmd_tbl_func = self.kwargs.get('load_cmd_tbl_func', lambda _: {})
cache_reserved_commands(load_cmd_tbl_func)
telemetry.set_full_command_table_loaded() | python | def load_full_command_table(self):
load_cmd_tbl_func = self.kwargs.get('load_cmd_tbl_func', lambda _: {})
cache_reserved_commands(load_cmd_tbl_func)
telemetry.set_full_command_table_loaded() | [
"def",
"load_full_command_table",
"(",
"self",
")",
":",
"load_cmd_tbl_func",
"=",
"self",
".",
"kwargs",
".",
"get",
"(",
"'load_cmd_tbl_func'",
",",
"lambda",
"_",
":",
"{",
"}",
")",
"cache_reserved_commands",
"(",
"load_cmd_tbl_func",
")",
"telemetry",
".",
... | Perform a full load of the command table to get all the reserved command words. | [
"Perform",
"a",
"full",
"load",
"of",
"the",
"command",
"table",
"to",
"get",
"all",
"the",
"reserved",
"command",
"words",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/alias/azext_alias/alias.py#L185-L191 |
228,827 | Azure/azure-cli-extensions | src/alias/azext_alias/alias.py | AliasManager.post_transform | def post_transform(self, args):
"""
Inject environment variables, and write hash to alias hash file after transforming alias to commands.
Args:
args: A list of args to post-transform.
"""
# Ignore 'az' if it is the first command
args = args[1:] if args and args[0] == 'az' else args
post_transform_commands = []
for i, arg in enumerate(args):
# Do not translate environment variables for command argument
if is_alias_command(['create'], args) and i > 0 and args[i - 1] in ['-c', '--command']:
post_transform_commands.append(arg)
else:
post_transform_commands.append(os.path.expandvars(arg))
AliasManager.write_alias_config_hash(self.alias_config_hash)
AliasManager.write_collided_alias(self.collided_alias)
return post_transform_commands | python | def post_transform(self, args):
# Ignore 'az' if it is the first command
args = args[1:] if args and args[0] == 'az' else args
post_transform_commands = []
for i, arg in enumerate(args):
# Do not translate environment variables for command argument
if is_alias_command(['create'], args) and i > 0 and args[i - 1] in ['-c', '--command']:
post_transform_commands.append(arg)
else:
post_transform_commands.append(os.path.expandvars(arg))
AliasManager.write_alias_config_hash(self.alias_config_hash)
AliasManager.write_collided_alias(self.collided_alias)
return post_transform_commands | [
"def",
"post_transform",
"(",
"self",
",",
"args",
")",
":",
"# Ignore 'az' if it is the first command",
"args",
"=",
"args",
"[",
"1",
":",
"]",
"if",
"args",
"and",
"args",
"[",
"0",
"]",
"==",
"'az'",
"else",
"args",
"post_transform_commands",
"=",
"[",
... | Inject environment variables, and write hash to alias hash file after transforming alias to commands.
Args:
args: A list of args to post-transform. | [
"Inject",
"environment",
"variables",
"and",
"write",
"hash",
"to",
"alias",
"hash",
"file",
"after",
"transforming",
"alias",
"to",
"commands",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/alias/azext_alias/alias.py#L193-L214 |
228,828 | Azure/azure-cli-extensions | src/alias/azext_alias/alias.py | AliasManager.build_collision_table | def build_collision_table(aliases, levels=COLLISION_CHECK_LEVEL_DEPTH):
"""
Build the collision table according to the alias configuration file against the entire command table.
self.collided_alias is structured as:
{
'collided_alias': [the command level at which collision happens]
}
For example:
{
'account': [1, 2]
}
This means that 'account' is a reserved command in level 1 and level 2 of the command tree because
(az account ...) and (az storage account ...)
lvl 1 lvl 2
Args:
levels: the amount of levels we tranverse through the command table tree.
"""
collided_alias = defaultdict(list)
for alias in aliases:
# Only care about the first word in the alias because alias
# cannot have spaces (unless they have positional arguments)
word = alias.split()[0]
for level in range(1, levels + 1):
collision_regex = r'^{}{}($|\s)'.format(r'([a-z\-]*\s)' * (level - 1), word.lower())
if list(filter(re.compile(collision_regex).match, azext_alias.cached_reserved_commands)) \
and level not in collided_alias[word]:
collided_alias[word].append(level)
telemetry.set_collided_aliases(list(collided_alias.keys()))
return collided_alias | python | def build_collision_table(aliases, levels=COLLISION_CHECK_LEVEL_DEPTH):
collided_alias = defaultdict(list)
for alias in aliases:
# Only care about the first word in the alias because alias
# cannot have spaces (unless they have positional arguments)
word = alias.split()[0]
for level in range(1, levels + 1):
collision_regex = r'^{}{}($|\s)'.format(r'([a-z\-]*\s)' * (level - 1), word.lower())
if list(filter(re.compile(collision_regex).match, azext_alias.cached_reserved_commands)) \
and level not in collided_alias[word]:
collided_alias[word].append(level)
telemetry.set_collided_aliases(list(collided_alias.keys()))
return collided_alias | [
"def",
"build_collision_table",
"(",
"aliases",
",",
"levels",
"=",
"COLLISION_CHECK_LEVEL_DEPTH",
")",
":",
"collided_alias",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"alias",
"in",
"aliases",
":",
"# Only care about the first word in the alias because alias",
"# can... | Build the collision table according to the alias configuration file against the entire command table.
self.collided_alias is structured as:
{
'collided_alias': [the command level at which collision happens]
}
For example:
{
'account': [1, 2]
}
This means that 'account' is a reserved command in level 1 and level 2 of the command tree because
(az account ...) and (az storage account ...)
lvl 1 lvl 2
Args:
levels: the amount of levels we tranverse through the command table tree. | [
"Build",
"the",
"collision",
"table",
"according",
"to",
"the",
"alias",
"configuration",
"file",
"against",
"the",
"entire",
"command",
"table",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/alias/azext_alias/alias.py#L229-L260 |
228,829 | Azure/azure-cli-extensions | src/alias/azext_alias/alias.py | AliasManager.write_alias_config_hash | def write_alias_config_hash(alias_config_hash='', empty_hash=False):
"""
Write self.alias_config_hash to the alias hash file.
Args:
empty_hash: True if we want to write an empty string into the file. Empty string in the alias hash file
means that we have to perform a full load of the command table in the next run.
"""
with open(GLOBAL_ALIAS_HASH_PATH, 'w') as alias_config_hash_file:
alias_config_hash_file.write('' if empty_hash else alias_config_hash) | python | def write_alias_config_hash(alias_config_hash='', empty_hash=False):
with open(GLOBAL_ALIAS_HASH_PATH, 'w') as alias_config_hash_file:
alias_config_hash_file.write('' if empty_hash else alias_config_hash) | [
"def",
"write_alias_config_hash",
"(",
"alias_config_hash",
"=",
"''",
",",
"empty_hash",
"=",
"False",
")",
":",
"with",
"open",
"(",
"GLOBAL_ALIAS_HASH_PATH",
",",
"'w'",
")",
"as",
"alias_config_hash_file",
":",
"alias_config_hash_file",
".",
"write",
"(",
"''"... | Write self.alias_config_hash to the alias hash file.
Args:
empty_hash: True if we want to write an empty string into the file. Empty string in the alias hash file
means that we have to perform a full load of the command table in the next run. | [
"Write",
"self",
".",
"alias_config_hash",
"to",
"the",
"alias",
"hash",
"file",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/alias/azext_alias/alias.py#L263-L272 |
228,830 | Azure/azure-cli-extensions | src/alias/azext_alias/alias.py | AliasManager.write_collided_alias | def write_collided_alias(collided_alias_dict):
"""
Write the collided aliases string into the collided alias file.
"""
# w+ creates the alias config file if it does not exist
open_mode = 'r+' if os.path.exists(GLOBAL_COLLIDED_ALIAS_PATH) else 'w+'
with open(GLOBAL_COLLIDED_ALIAS_PATH, open_mode) as collided_alias_file:
collided_alias_file.truncate()
collided_alias_file.write(json.dumps(collided_alias_dict)) | python | def write_collided_alias(collided_alias_dict):
# w+ creates the alias config file if it does not exist
open_mode = 'r+' if os.path.exists(GLOBAL_COLLIDED_ALIAS_PATH) else 'w+'
with open(GLOBAL_COLLIDED_ALIAS_PATH, open_mode) as collided_alias_file:
collided_alias_file.truncate()
collided_alias_file.write(json.dumps(collided_alias_dict)) | [
"def",
"write_collided_alias",
"(",
"collided_alias_dict",
")",
":",
"# w+ creates the alias config file if it does not exist",
"open_mode",
"=",
"'r+'",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"GLOBAL_COLLIDED_ALIAS_PATH",
")",
"else",
"'w+'",
"with",
"open",
"(",... | Write the collided aliases string into the collided alias file. | [
"Write",
"the",
"collided",
"aliases",
"string",
"into",
"the",
"collided",
"alias",
"file",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/alias/azext_alias/alias.py#L275-L283 |
228,831 | Azure/azure-cli-extensions | src/alias/azext_alias/alias.py | AliasManager.process_exception_message | def process_exception_message(exception):
"""
Process an exception message.
Args:
exception: The exception to process.
Returns:
A filtered string summarizing the exception.
"""
exception_message = str(exception)
for replace_char in ['\t', '\n', '\\n']:
exception_message = exception_message.replace(replace_char, '' if replace_char != '\t' else ' ')
return exception_message.replace('section', 'alias') | python | def process_exception_message(exception):
exception_message = str(exception)
for replace_char in ['\t', '\n', '\\n']:
exception_message = exception_message.replace(replace_char, '' if replace_char != '\t' else ' ')
return exception_message.replace('section', 'alias') | [
"def",
"process_exception_message",
"(",
"exception",
")",
":",
"exception_message",
"=",
"str",
"(",
"exception",
")",
"for",
"replace_char",
"in",
"[",
"'\\t'",
",",
"'\\n'",
",",
"'\\\\n'",
"]",
":",
"exception_message",
"=",
"exception_message",
".",
"replac... | Process an exception message.
Args:
exception: The exception to process.
Returns:
A filtered string summarizing the exception. | [
"Process",
"an",
"exception",
"message",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/alias/azext_alias/alias.py#L286-L299 |
228,832 | Azure/azure-cli-extensions | src/virtual-wan/azext_vwan/_util.py | get_network_resource_property_entry | def get_network_resource_property_entry(resource, prop):
""" Factory method for creating get functions. """
def get_func(cmd, resource_group_name, resource_name, item_name):
client = getattr(network_client_factory(cmd.cli_ctx), resource)
items = getattr(client.get(resource_group_name, resource_name), prop)
result = next((x for x in items if x.name.lower() == item_name.lower()), None)
if not result:
raise CLIError("Item '{}' does not exist on {} '{}'".format(
item_name, resource, resource_name))
else:
return result
func_name = 'get_network_resource_property_entry_{}_{}'.format(resource, prop)
setattr(sys.modules[__name__], func_name, get_func)
return func_name | python | def get_network_resource_property_entry(resource, prop):
def get_func(cmd, resource_group_name, resource_name, item_name):
client = getattr(network_client_factory(cmd.cli_ctx), resource)
items = getattr(client.get(resource_group_name, resource_name), prop)
result = next((x for x in items if x.name.lower() == item_name.lower()), None)
if not result:
raise CLIError("Item '{}' does not exist on {} '{}'".format(
item_name, resource, resource_name))
else:
return result
func_name = 'get_network_resource_property_entry_{}_{}'.format(resource, prop)
setattr(sys.modules[__name__], func_name, get_func)
return func_name | [
"def",
"get_network_resource_property_entry",
"(",
"resource",
",",
"prop",
")",
":",
"def",
"get_func",
"(",
"cmd",
",",
"resource_group_name",
",",
"resource_name",
",",
"item_name",
")",
":",
"client",
"=",
"getattr",
"(",
"network_client_factory",
"(",
"cmd",
... | Factory method for creating get functions. | [
"Factory",
"method",
"for",
"creating",
"get",
"functions",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/virtual-wan/azext_vwan/_util.py#L40-L56 |
228,833 | Azure/azure-cli-extensions | src/storage-preview/azext_storage_preview/_format.py | transform_file_directory_result | def transform_file_directory_result(cli_ctx):
"""
Transform a the result returned from file and directory listing API.
This transformer add and remove properties from File and Directory objects in the given list
in order to align the object's properties so as to offer a better view to the file and dir
list.
"""
def transformer(result):
t_file, t_dir = get_sdk(cli_ctx, CUSTOM_DATA_STORAGE, 'File', 'Directory', mod='file.models')
return_list = []
for each in result:
if isinstance(each, t_file):
delattr(each, 'content')
setattr(each, 'type', 'file')
elif isinstance(each, t_dir):
setattr(each, 'type', 'dir')
return_list.append(each)
return return_list
return transformer | python | def transform_file_directory_result(cli_ctx):
def transformer(result):
t_file, t_dir = get_sdk(cli_ctx, CUSTOM_DATA_STORAGE, 'File', 'Directory', mod='file.models')
return_list = []
for each in result:
if isinstance(each, t_file):
delattr(each, 'content')
setattr(each, 'type', 'file')
elif isinstance(each, t_dir):
setattr(each, 'type', 'dir')
return_list.append(each)
return return_list
return transformer | [
"def",
"transform_file_directory_result",
"(",
"cli_ctx",
")",
":",
"def",
"transformer",
"(",
"result",
")",
":",
"t_file",
",",
"t_dir",
"=",
"get_sdk",
"(",
"cli_ctx",
",",
"CUSTOM_DATA_STORAGE",
",",
"'File'",
",",
"'Directory'",
",",
"mod",
"=",
"'file.mo... | Transform a the result returned from file and directory listing API.
This transformer add and remove properties from File and Directory objects in the given list
in order to align the object's properties so as to offer a better view to the file and dir
list. | [
"Transform",
"a",
"the",
"result",
"returned",
"from",
"file",
"and",
"directory",
"listing",
"API",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/storage-preview/azext_storage_preview/_format.py#L129-L150 |
228,834 | Azure/azure-cli-extensions | src/subscription/azext_subscription/subscription/operations/subscription_factory_operations.py | SubscriptionFactoryOperations.create_subscription_in_enrollment_account | def create_subscription_in_enrollment_account(
self, enrollment_account_name, body, custom_headers=None, raw=False, polling=True, **operation_config):
"""Creates an Azure subscription.
:param enrollment_account_name: The name of the enrollment account to
which the subscription will be billed.
:type enrollment_account_name: str
:param body: The subscription creation parameters.
:type body:
~azure.mgmt.subscription.models.SubscriptionCreationParameters
:param dict custom_headers: headers that will be added to the request
:param bool raw: The poller return type is ClientRawResponse, the
direct response alongside the deserialized response
:param polling: True for ARMPolling, False for no polling, or a
polling object for personal polling strategy
:return: An instance of LROPoller that returns
SubscriptionCreationResult or
ClientRawResponse<SubscriptionCreationResult> if raw==True
:rtype:
~msrestazure.azure_operation.AzureOperationPoller[~azure.mgmt.subscription.models.SubscriptionCreationResult]
or
~msrestazure.azure_operation.AzureOperationPoller[~msrest.pipeline.ClientRawResponse[~azure.mgmt.subscription.models.SubscriptionCreationResult]]
:raises:
:class:`ErrorResponseException<azure.mgmt.subscription.models.ErrorResponseException>`
"""
raw_result = self._create_subscription_in_enrollment_account_initial(
enrollment_account_name=enrollment_account_name,
body=body,
custom_headers=custom_headers,
raw=True,
**operation_config
)
def get_long_running_output(response):
header_dict = {
'Location': 'str',
'Retry-After': 'str',
}
deserialized = self._deserialize('SubscriptionCreationResult', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
lro_delay = operation_config.get(
'long_running_operation_timeout',
self.config.long_running_operation_timeout)
if polling is True: polling_method = ARMPolling(lro_delay, **operation_config)
elif polling is False: polling_method = NoPolling()
else: polling_method = polling
return LROPoller(self._client, raw_result, get_long_running_output, polling_method) | python | def create_subscription_in_enrollment_account(
self, enrollment_account_name, body, custom_headers=None, raw=False, polling=True, **operation_config):
raw_result = self._create_subscription_in_enrollment_account_initial(
enrollment_account_name=enrollment_account_name,
body=body,
custom_headers=custom_headers,
raw=True,
**operation_config
)
def get_long_running_output(response):
header_dict = {
'Location': 'str',
'Retry-After': 'str',
}
deserialized = self._deserialize('SubscriptionCreationResult', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
lro_delay = operation_config.get(
'long_running_operation_timeout',
self.config.long_running_operation_timeout)
if polling is True: polling_method = ARMPolling(lro_delay, **operation_config)
elif polling is False: polling_method = NoPolling()
else: polling_method = polling
return LROPoller(self._client, raw_result, get_long_running_output, polling_method) | [
"def",
"create_subscription_in_enrollment_account",
"(",
"self",
",",
"enrollment_account_name",
",",
"body",
",",
"custom_headers",
"=",
"None",
",",
"raw",
"=",
"False",
",",
"polling",
"=",
"True",
",",
"*",
"*",
"operation_config",
")",
":",
"raw_result",
"=... | Creates an Azure subscription.
:param enrollment_account_name: The name of the enrollment account to
which the subscription will be billed.
:type enrollment_account_name: str
:param body: The subscription creation parameters.
:type body:
~azure.mgmt.subscription.models.SubscriptionCreationParameters
:param dict custom_headers: headers that will be added to the request
:param bool raw: The poller return type is ClientRawResponse, the
direct response alongside the deserialized response
:param polling: True for ARMPolling, False for no polling, or a
polling object for personal polling strategy
:return: An instance of LROPoller that returns
SubscriptionCreationResult or
ClientRawResponse<SubscriptionCreationResult> if raw==True
:rtype:
~msrestazure.azure_operation.AzureOperationPoller[~azure.mgmt.subscription.models.SubscriptionCreationResult]
or
~msrestazure.azure_operation.AzureOperationPoller[~msrest.pipeline.ClientRawResponse[~azure.mgmt.subscription.models.SubscriptionCreationResult]]
:raises:
:class:`ErrorResponseException<azure.mgmt.subscription.models.ErrorResponseException>` | [
"Creates",
"an",
"Azure",
"subscription",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/subscription/azext_subscription/subscription/operations/subscription_factory_operations.py#L93-L146 |
228,835 | Azure/azure-cli-extensions | src/mesh/azext_mesh/commands.py | transform_gateway | def transform_gateway(result):
"""Transform a gateway list to table output. """
return OrderedDict([('Name', result.get('name')),
('ResourceGroup', result.get('resourceGroup')),
('Location', result.get('location')),
('ProvisioningState', result.get('provisioningState')),
('Status', result.get('status')),
('PublicIP', result.get('ipAddress'))]) | python | def transform_gateway(result):
return OrderedDict([('Name', result.get('name')),
('ResourceGroup', result.get('resourceGroup')),
('Location', result.get('location')),
('ProvisioningState', result.get('provisioningState')),
('Status', result.get('status')),
('PublicIP', result.get('ipAddress'))]) | [
"def",
"transform_gateway",
"(",
"result",
")",
":",
"return",
"OrderedDict",
"(",
"[",
"(",
"'Name'",
",",
"result",
".",
"get",
"(",
"'name'",
")",
")",
",",
"(",
"'ResourceGroup'",
",",
"result",
".",
"get",
"(",
"'resourceGroup'",
")",
")",
",",
"(... | Transform a gateway list to table output. | [
"Transform",
"a",
"gateway",
"list",
"to",
"table",
"output",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/mesh/azext_mesh/commands.py#L153-L160 |
228,836 | Azure/azure-cli-extensions | src/storage-preview/azext_storage_preview/util.py | collect_blobs | def collect_blobs(blob_service, container, pattern=None):
"""
List the blobs in the given blob container, filter the blob by comparing their path to the given pattern.
"""
if not blob_service:
raise ValueError('missing parameter blob_service')
if not container:
raise ValueError('missing parameter container')
if not _pattern_has_wildcards(pattern):
return [pattern] if blob_service.exists(container, pattern) else []
results = []
for blob in blob_service.list_blobs(container):
try:
blob_name = blob.name.encode(
'utf-8') if isinstance(blob.name, unicode) else blob.name
except NameError:
blob_name = blob.name
if not pattern or _match_path(blob_name, pattern):
results.append(blob_name)
return results | python | def collect_blobs(blob_service, container, pattern=None):
if not blob_service:
raise ValueError('missing parameter blob_service')
if not container:
raise ValueError('missing parameter container')
if not _pattern_has_wildcards(pattern):
return [pattern] if blob_service.exists(container, pattern) else []
results = []
for blob in blob_service.list_blobs(container):
try:
blob_name = blob.name.encode(
'utf-8') if isinstance(blob.name, unicode) else blob.name
except NameError:
blob_name = blob.name
if not pattern or _match_path(blob_name, pattern):
results.append(blob_name)
return results | [
"def",
"collect_blobs",
"(",
"blob_service",
",",
"container",
",",
"pattern",
"=",
"None",
")",
":",
"if",
"not",
"blob_service",
":",
"raise",
"ValueError",
"(",
"'missing parameter blob_service'",
")",
"if",
"not",
"container",
":",
"raise",
"ValueError",
"("... | List the blobs in the given blob container, filter the blob by comparing their path to the given pattern. | [
"List",
"the",
"blobs",
"in",
"the",
"given",
"blob",
"container",
"filter",
"the",
"blob",
"by",
"comparing",
"their",
"path",
"to",
"the",
"given",
"pattern",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/storage-preview/azext_storage_preview/util.py#L10-L34 |
228,837 | Azure/azure-cli-extensions | src/storage-preview/azext_storage_preview/util.py | glob_files_locally | def glob_files_locally(folder_path, pattern):
"""glob files in local folder based on the given pattern"""
pattern = os.path.join(
folder_path, pattern.lstrip('/')) if pattern else None
len_folder_path = len(folder_path) + 1
for root, _, files in os.walk(folder_path):
for f in files:
full_path = os.path.join(root, f)
if not pattern or _match_path(full_path, pattern):
yield (full_path, full_path[len_folder_path:]) | python | def glob_files_locally(folder_path, pattern):
pattern = os.path.join(
folder_path, pattern.lstrip('/')) if pattern else None
len_folder_path = len(folder_path) + 1
for root, _, files in os.walk(folder_path):
for f in files:
full_path = os.path.join(root, f)
if not pattern or _match_path(full_path, pattern):
yield (full_path, full_path[len_folder_path:]) | [
"def",
"glob_files_locally",
"(",
"folder_path",
",",
"pattern",
")",
":",
"pattern",
"=",
"os",
".",
"path",
".",
"join",
"(",
"folder_path",
",",
"pattern",
".",
"lstrip",
"(",
"'/'",
")",
")",
"if",
"pattern",
"else",
"None",
"len_folder_path",
"=",
"... | glob files in local folder based on the given pattern | [
"glob",
"files",
"in",
"local",
"folder",
"based",
"on",
"the",
"given",
"pattern"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/storage-preview/azext_storage_preview/util.py#L72-L83 |
228,838 | Azure/azure-cli-extensions | src/storage-preview/azext_storage_preview/util.py | glob_files_remotely | def glob_files_remotely(cmd, client, share_name, pattern):
"""glob the files in remote file share based on the given pattern"""
from collections import deque
t_dir, t_file = cmd.get_models('file.models#Directory', 'file.models#File')
queue = deque([""])
while queue:
current_dir = queue.pop()
for f in client.list_directories_and_files(share_name, current_dir):
if isinstance(f, t_file):
if not pattern or _match_path(os.path.join(current_dir, f.name), pattern):
yield current_dir, f.name
elif isinstance(f, t_dir):
queue.appendleft(os.path.join(current_dir, f.name)) | python | def glob_files_remotely(cmd, client, share_name, pattern):
from collections import deque
t_dir, t_file = cmd.get_models('file.models#Directory', 'file.models#File')
queue = deque([""])
while queue:
current_dir = queue.pop()
for f in client.list_directories_and_files(share_name, current_dir):
if isinstance(f, t_file):
if not pattern or _match_path(os.path.join(current_dir, f.name), pattern):
yield current_dir, f.name
elif isinstance(f, t_dir):
queue.appendleft(os.path.join(current_dir, f.name)) | [
"def",
"glob_files_remotely",
"(",
"cmd",
",",
"client",
",",
"share_name",
",",
"pattern",
")",
":",
"from",
"collections",
"import",
"deque",
"t_dir",
",",
"t_file",
"=",
"cmd",
".",
"get_models",
"(",
"'file.models#Directory'",
",",
"'file.models#File'",
")",... | glob the files in remote file share based on the given pattern | [
"glob",
"the",
"files",
"in",
"remote",
"file",
"share",
"based",
"on",
"the",
"given",
"pattern"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/storage-preview/azext_storage_preview/util.py#L86-L99 |
228,839 | Azure/azure-cli-extensions | src/storage-preview/azext_storage_preview/__init__.py | StorageCommandGroup._register_data_plane_account_arguments | def _register_data_plane_account_arguments(self, command_name):
""" Add parameters required to create a storage client """
from azure.cli.core.commands.parameters import get_resource_name_completion_list
from ._validators import validate_client_parameters
command = self.command_loader.command_table.get(command_name, None)
if not command:
return
group_name = 'Storage Account'
command.add_argument('account_name', '--account-name', required=False, default=None,
arg_group=group_name,
completer=get_resource_name_completion_list('Microsoft.Storage/storageAccounts'),
help='Storage account name. Related environment variable: AZURE_STORAGE_ACCOUNT. Must be '
'used in conjunction with either storage account key or a SAS token. If neither are '
'present, the command will try to query the storage account key using the '
'authenticated Azure account. If a large number of storage commands are executed the '
'API quota may be hit')
command.add_argument('account_key', '--account-key', required=False, default=None,
arg_group=group_name,
help='Storage account key. Must be used in conjunction with storage account name. '
'Environment variable: AZURE_STORAGE_KEY')
command.add_argument('connection_string', '--connection-string', required=False, default=None,
validator=validate_client_parameters, arg_group=group_name,
help='Storage account connection string. Environment variable: '
'AZURE_STORAGE_CONNECTION_STRING')
command.add_argument('sas_token', '--sas-token', required=False, default=None,
arg_group=group_name,
help='A Shared Access Signature (SAS). Must be used in conjunction with storage account '
'name. Environment variable: AZURE_STORAGE_SAS_TOKEN') | python | def _register_data_plane_account_arguments(self, command_name):
from azure.cli.core.commands.parameters import get_resource_name_completion_list
from ._validators import validate_client_parameters
command = self.command_loader.command_table.get(command_name, None)
if not command:
return
group_name = 'Storage Account'
command.add_argument('account_name', '--account-name', required=False, default=None,
arg_group=group_name,
completer=get_resource_name_completion_list('Microsoft.Storage/storageAccounts'),
help='Storage account name. Related environment variable: AZURE_STORAGE_ACCOUNT. Must be '
'used in conjunction with either storage account key or a SAS token. If neither are '
'present, the command will try to query the storage account key using the '
'authenticated Azure account. If a large number of storage commands are executed the '
'API quota may be hit')
command.add_argument('account_key', '--account-key', required=False, default=None,
arg_group=group_name,
help='Storage account key. Must be used in conjunction with storage account name. '
'Environment variable: AZURE_STORAGE_KEY')
command.add_argument('connection_string', '--connection-string', required=False, default=None,
validator=validate_client_parameters, arg_group=group_name,
help='Storage account connection string. Environment variable: '
'AZURE_STORAGE_CONNECTION_STRING')
command.add_argument('sas_token', '--sas-token', required=False, default=None,
arg_group=group_name,
help='A Shared Access Signature (SAS). Must be used in conjunction with storage account '
'name. Environment variable: AZURE_STORAGE_SAS_TOKEN') | [
"def",
"_register_data_plane_account_arguments",
"(",
"self",
",",
"command_name",
")",
":",
"from",
"azure",
".",
"cli",
".",
"core",
".",
"commands",
".",
"parameters",
"import",
"get_resource_name_completion_list",
"from",
".",
"_validators",
"import",
"validate_cl... | Add parameters required to create a storage client | [
"Add",
"parameters",
"required",
"to",
"create",
"a",
"storage",
"client"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/storage-preview/azext_storage_preview/__init__.py#L194-L223 |
228,840 | Azure/azure-cli-extensions | src/aks-preview/azext_aks_preview/_completers.py | get_k8s_upgrades_completion_list | def get_k8s_upgrades_completion_list(cmd, prefix, namespace, **kwargs): # pylint: disable=unused-argument
"""Return Kubernetes versions available for upgrading an existing cluster."""
resource_group = getattr(namespace, 'resource_group_name', None)
name = getattr(namespace, 'name', None)
return get_k8s_upgrades(cmd.cli_ctx, resource_group, name) if resource_group and name else None | python | def get_k8s_upgrades_completion_list(cmd, prefix, namespace, **kwargs): # pylint: disable=unused-argument
resource_group = getattr(namespace, 'resource_group_name', None)
name = getattr(namespace, 'name', None)
return get_k8s_upgrades(cmd.cli_ctx, resource_group, name) if resource_group and name else None | [
"def",
"get_k8s_upgrades_completion_list",
"(",
"cmd",
",",
"prefix",
",",
"namespace",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=unused-argument",
"resource_group",
"=",
"getattr",
"(",
"namespace",
",",
"'resource_group_name'",
",",
"None",
")",
"name"... | Return Kubernetes versions available for upgrading an existing cluster. | [
"Return",
"Kubernetes",
"versions",
"available",
"for",
"upgrading",
"an",
"existing",
"cluster",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/aks-preview/azext_aks_preview/_completers.py#L14-L18 |
228,841 | Azure/azure-cli-extensions | src/aks-preview/azext_aks_preview/_completers.py | get_k8s_versions_completion_list | def get_k8s_versions_completion_list(cmd, prefix, namespace, **kwargs): # pylint: disable=unused-argument
"""Return Kubernetes versions available for provisioning a new cluster."""
location = _get_location(cmd.cli_ctx, namespace)
return get_k8s_versions(cmd.cli_ctx, location) if location else None | python | def get_k8s_versions_completion_list(cmd, prefix, namespace, **kwargs): # pylint: disable=unused-argument
location = _get_location(cmd.cli_ctx, namespace)
return get_k8s_versions(cmd.cli_ctx, location) if location else None | [
"def",
"get_k8s_versions_completion_list",
"(",
"cmd",
",",
"prefix",
",",
"namespace",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=unused-argument",
"location",
"=",
"_get_location",
"(",
"cmd",
".",
"cli_ctx",
",",
"namespace",
")",
"return",
"get_k8s_... | Return Kubernetes versions available for provisioning a new cluster. | [
"Return",
"Kubernetes",
"versions",
"available",
"for",
"provisioning",
"a",
"new",
"cluster",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/aks-preview/azext_aks_preview/_completers.py#L29-L32 |
228,842 | Azure/azure-cli-extensions | src/aks-preview/azext_aks_preview/_completers.py | get_k8s_versions | def get_k8s_versions(cli_ctx, location):
"""Return a list of Kubernetes versions available for a new cluster."""
from ._client_factory import cf_container_services
from jmespath import search # pylint: disable=import-error
results = cf_container_services(cli_ctx).list_orchestrators(location, resource_type='managedClusters').as_dict()
# Flatten all the "orchestrator_version" fields into one array
return search('orchestrators[*].orchestrator_version', results) | python | def get_k8s_versions(cli_ctx, location):
from ._client_factory import cf_container_services
from jmespath import search # pylint: disable=import-error
results = cf_container_services(cli_ctx).list_orchestrators(location, resource_type='managedClusters').as_dict()
# Flatten all the "orchestrator_version" fields into one array
return search('orchestrators[*].orchestrator_version', results) | [
"def",
"get_k8s_versions",
"(",
"cli_ctx",
",",
"location",
")",
":",
"from",
".",
"_client_factory",
"import",
"cf_container_services",
"from",
"jmespath",
"import",
"search",
"# pylint: disable=import-error",
"results",
"=",
"cf_container_services",
"(",
"cli_ctx",
")... | Return a list of Kubernetes versions available for a new cluster. | [
"Return",
"a",
"list",
"of",
"Kubernetes",
"versions",
"available",
"for",
"a",
"new",
"cluster",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/aks-preview/azext_aks_preview/_completers.py#L35-L42 |
228,843 | Azure/azure-cli-extensions | src/aks-preview/azext_aks_preview/_completers.py | get_vm_size_completion_list | def get_vm_size_completion_list(cmd, prefix, namespace, **kwargs): # pylint: disable=unused-argument
"""Return the intersection of the VM sizes allowed by the ACS SDK with those returned by the Compute Service."""
location = _get_location(cmd.cli_ctx, namespace)
result = get_vm_sizes(cmd.cli_ctx, location)
return set(r.name for r in result) & set(c.value for c in ContainerServiceVMSizeTypes) | python | def get_vm_size_completion_list(cmd, prefix, namespace, **kwargs): # pylint: disable=unused-argument
location = _get_location(cmd.cli_ctx, namespace)
result = get_vm_sizes(cmd.cli_ctx, location)
return set(r.name for r in result) & set(c.value for c in ContainerServiceVMSizeTypes) | [
"def",
"get_vm_size_completion_list",
"(",
"cmd",
",",
"prefix",
",",
"namespace",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=unused-argument",
"location",
"=",
"_get_location",
"(",
"cmd",
".",
"cli_ctx",
",",
"namespace",
")",
"result",
"=",
"get_vm... | Return the intersection of the VM sizes allowed by the ACS SDK with those returned by the Compute Service. | [
"Return",
"the",
"intersection",
"of",
"the",
"VM",
"sizes",
"allowed",
"by",
"the",
"ACS",
"SDK",
"with",
"those",
"returned",
"by",
"the",
"Compute",
"Service",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/aks-preview/azext_aks_preview/_completers.py#L46-L51 |
228,844 | Azure/azure-cli-extensions | src/alias/azext_alias/argument.py | normalize_placeholders | def normalize_placeholders(arg, inject_quotes=False):
"""
Normalize placeholders' names so that the template can be ingested into Jinja template engine.
- Jinja does not accept numbers as placeholder names, so add a "_"
before the numbers to make them valid placeholder names.
- Surround placeholders expressions with "" so we can preserve spaces inside the positional arguments.
Args:
arg: The string to process.
inject_qoutes: True if we want to surround placeholders with a pair of quotes.
Returns:
A processed string where placeholders are surrounded by "" and
numbered placeholders are prepended with "_".
"""
number_placeholders = re.findall(r'{{\s*\d+\s*}}', arg)
for number_placeholder in number_placeholders:
number = re.search(r'\d+', number_placeholder).group()
arg = arg.replace(number_placeholder, '{{_' + number + '}}')
return arg.replace('{{', '"{{').replace('}}', '}}"') if inject_quotes else arg | python | def normalize_placeholders(arg, inject_quotes=False):
number_placeholders = re.findall(r'{{\s*\d+\s*}}', arg)
for number_placeholder in number_placeholders:
number = re.search(r'\d+', number_placeholder).group()
arg = arg.replace(number_placeholder, '{{_' + number + '}}')
return arg.replace('{{', '"{{').replace('}}', '}}"') if inject_quotes else arg | [
"def",
"normalize_placeholders",
"(",
"arg",
",",
"inject_quotes",
"=",
"False",
")",
":",
"number_placeholders",
"=",
"re",
".",
"findall",
"(",
"r'{{\\s*\\d+\\s*}}'",
",",
"arg",
")",
"for",
"number_placeholder",
"in",
"number_placeholders",
":",
"number",
"=",
... | Normalize placeholders' names so that the template can be ingested into Jinja template engine.
- Jinja does not accept numbers as placeholder names, so add a "_"
before the numbers to make them valid placeholder names.
- Surround placeholders expressions with "" so we can preserve spaces inside the positional arguments.
Args:
arg: The string to process.
inject_qoutes: True if we want to surround placeholders with a pair of quotes.
Returns:
A processed string where placeholders are surrounded by "" and
numbered placeholders are prepended with "_". | [
"Normalize",
"placeholders",
"names",
"so",
"that",
"the",
"template",
"can",
"be",
"ingested",
"into",
"Jinja",
"template",
"engine",
".",
"-",
"Jinja",
"does",
"not",
"accept",
"numbers",
"as",
"placeholder",
"names",
"so",
"add",
"a",
"_",
"before",
"the"... | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/alias/azext_alias/argument.py#L66-L86 |
228,845 | Azure/azure-cli-extensions | src/alias/azext_alias/argument.py | build_pos_args_table | def build_pos_args_table(full_alias, args, start_index):
"""
Build a dictionary where the key is placeholder name and the value is the position argument value.
Args:
full_alias: The full alias (including any placeholders).
args: The arguments that the user inputs in the terminal.
start_index: The index at which we start ingesting position arguments.
Returns:
A dictionary with the key beign the name of the placeholder and its value
being the respective positional argument.
"""
pos_args_placeholder = get_placeholders(full_alias, check_duplicates=True)
pos_args = args[start_index: start_index + len(pos_args_placeholder)]
if len(pos_args_placeholder) != len(pos_args):
error_msg = INSUFFICIENT_POS_ARG_ERROR.format(full_alias,
len(pos_args_placeholder),
'' if len(pos_args_placeholder) == 1 else 's',
len(pos_args))
raise CLIError(error_msg)
# Escape '"' because we are using "" to surround placeholder expressions
for i, pos_arg in enumerate(pos_args):
pos_args[i] = pos_arg.replace('"', '\\"')
return dict(zip(pos_args_placeholder, pos_args)) | python | def build_pos_args_table(full_alias, args, start_index):
pos_args_placeholder = get_placeholders(full_alias, check_duplicates=True)
pos_args = args[start_index: start_index + len(pos_args_placeholder)]
if len(pos_args_placeholder) != len(pos_args):
error_msg = INSUFFICIENT_POS_ARG_ERROR.format(full_alias,
len(pos_args_placeholder),
'' if len(pos_args_placeholder) == 1 else 's',
len(pos_args))
raise CLIError(error_msg)
# Escape '"' because we are using "" to surround placeholder expressions
for i, pos_arg in enumerate(pos_args):
pos_args[i] = pos_arg.replace('"', '\\"')
return dict(zip(pos_args_placeholder, pos_args)) | [
"def",
"build_pos_args_table",
"(",
"full_alias",
",",
"args",
",",
"start_index",
")",
":",
"pos_args_placeholder",
"=",
"get_placeholders",
"(",
"full_alias",
",",
"check_duplicates",
"=",
"True",
")",
"pos_args",
"=",
"args",
"[",
"start_index",
":",
"start_ind... | Build a dictionary where the key is placeholder name and the value is the position argument value.
Args:
full_alias: The full alias (including any placeholders).
args: The arguments that the user inputs in the terminal.
start_index: The index at which we start ingesting position arguments.
Returns:
A dictionary with the key beign the name of the placeholder and its value
being the respective positional argument. | [
"Build",
"a",
"dictionary",
"where",
"the",
"key",
"is",
"placeholder",
"name",
"and",
"the",
"value",
"is",
"the",
"position",
"argument",
"value",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/alias/azext_alias/argument.py#L89-L116 |
228,846 | Azure/azure-cli-extensions | src/alias/azext_alias/argument.py | render_template | def render_template(cmd_derived_from_alias, pos_args_table):
"""
Render cmd_derived_from_alias as a Jinja template with pos_args_table as the arguments.
Args:
cmd_derived_from_alias: The string to be injected with positional arguemnts.
pos_args_table: The dictionary used to rendered.
Returns:
A processed string with positional arguments injected.
"""
try:
cmd_derived_from_alias = normalize_placeholders(cmd_derived_from_alias, inject_quotes=True)
template = jinja.Template(cmd_derived_from_alias)
# Shlex.split allows us to split a string by spaces while preserving quoted substrings
# (positional arguments in this case)
rendered = shlex.split(template.render(pos_args_table))
# Manually check if there is any runtime error (such as index out of range)
# since Jinja template engine only checks for compile time error.
# Only check for runtime errors if there is an empty string in rendered.
if '' in rendered:
check_runtime_errors(cmd_derived_from_alias, pos_args_table)
return rendered
except Exception as exception:
# Exception raised from runtime error
if isinstance(exception, CLIError):
raise
# The template has some sort of compile time errors
split_exception_message = str(exception).split()
# Check if the error message provides the index of the erroneous character
error_index = split_exception_message[-1]
if error_index.isdigit():
split_exception_message.insert(-1, 'index')
error_msg = RENDER_TEMPLATE_ERROR.format(' '.join(split_exception_message), cmd_derived_from_alias)
# Calculate where to put an arrow (^) char so that it is exactly below the erroneous character
# e.g. ... "{{a.split('|)}}"
# ^
error_msg += '\n{}^'.format(' ' * (len(error_msg) - len(cmd_derived_from_alias) + int(error_index) - 1))
else:
exception_str = str(exception).replace('"{{', '}}').replace('}}"', '}}')
error_msg = RENDER_TEMPLATE_ERROR.format(cmd_derived_from_alias, exception_str)
raise CLIError(error_msg) | python | def render_template(cmd_derived_from_alias, pos_args_table):
try:
cmd_derived_from_alias = normalize_placeholders(cmd_derived_from_alias, inject_quotes=True)
template = jinja.Template(cmd_derived_from_alias)
# Shlex.split allows us to split a string by spaces while preserving quoted substrings
# (positional arguments in this case)
rendered = shlex.split(template.render(pos_args_table))
# Manually check if there is any runtime error (such as index out of range)
# since Jinja template engine only checks for compile time error.
# Only check for runtime errors if there is an empty string in rendered.
if '' in rendered:
check_runtime_errors(cmd_derived_from_alias, pos_args_table)
return rendered
except Exception as exception:
# Exception raised from runtime error
if isinstance(exception, CLIError):
raise
# The template has some sort of compile time errors
split_exception_message = str(exception).split()
# Check if the error message provides the index of the erroneous character
error_index = split_exception_message[-1]
if error_index.isdigit():
split_exception_message.insert(-1, 'index')
error_msg = RENDER_TEMPLATE_ERROR.format(' '.join(split_exception_message), cmd_derived_from_alias)
# Calculate where to put an arrow (^) char so that it is exactly below the erroneous character
# e.g. ... "{{a.split('|)}}"
# ^
error_msg += '\n{}^'.format(' ' * (len(error_msg) - len(cmd_derived_from_alias) + int(error_index) - 1))
else:
exception_str = str(exception).replace('"{{', '}}').replace('}}"', '}}')
error_msg = RENDER_TEMPLATE_ERROR.format(cmd_derived_from_alias, exception_str)
raise CLIError(error_msg) | [
"def",
"render_template",
"(",
"cmd_derived_from_alias",
",",
"pos_args_table",
")",
":",
"try",
":",
"cmd_derived_from_alias",
"=",
"normalize_placeholders",
"(",
"cmd_derived_from_alias",
",",
"inject_quotes",
"=",
"True",
")",
"template",
"=",
"jinja",
".",
"Templa... | Render cmd_derived_from_alias as a Jinja template with pos_args_table as the arguments.
Args:
cmd_derived_from_alias: The string to be injected with positional arguemnts.
pos_args_table: The dictionary used to rendered.
Returns:
A processed string with positional arguments injected. | [
"Render",
"cmd_derived_from_alias",
"as",
"a",
"Jinja",
"template",
"with",
"pos_args_table",
"as",
"the",
"arguments",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/alias/azext_alias/argument.py#L119-L167 |
228,847 | venmo/business-rules | business_rules/utils.py | float_to_decimal | def float_to_decimal(f):
"""
Convert a floating point number to a Decimal with
no loss of information. Intended for Python 2.6 where
casting float to Decimal does not work.
"""
n, d = f.as_integer_ratio()
numerator, denominator = Decimal(n), Decimal(d)
ctx = Context(prec=60)
result = ctx.divide(numerator, denominator)
while ctx.flags[Inexact]:
ctx.flags[Inexact] = False
ctx.prec *= 2
result = ctx.divide(numerator, denominator)
return result | python | def float_to_decimal(f):
n, d = f.as_integer_ratio()
numerator, denominator = Decimal(n), Decimal(d)
ctx = Context(prec=60)
result = ctx.divide(numerator, denominator)
while ctx.flags[Inexact]:
ctx.flags[Inexact] = False
ctx.prec *= 2
result = ctx.divide(numerator, denominator)
return result | [
"def",
"float_to_decimal",
"(",
"f",
")",
":",
"n",
",",
"d",
"=",
"f",
".",
"as_integer_ratio",
"(",
")",
"numerator",
",",
"denominator",
"=",
"Decimal",
"(",
"n",
")",
",",
"Decimal",
"(",
"d",
")",
"ctx",
"=",
"Context",
"(",
"prec",
"=",
"60",... | Convert a floating point number to a Decimal with
no loss of information. Intended for Python 2.6 where
casting float to Decimal does not work. | [
"Convert",
"a",
"floating",
"point",
"number",
"to",
"a",
"Decimal",
"with",
"no",
"loss",
"of",
"information",
".",
"Intended",
"for",
"Python",
"2",
".",
"6",
"where",
"casting",
"float",
"to",
"Decimal",
"does",
"not",
"work",
"."
] | 6c79036c030e2c6b8de5524a95231fd30048defa | https://github.com/venmo/business-rules/blob/6c79036c030e2c6b8de5524a95231fd30048defa/business_rules/utils.py#L27-L41 |
228,848 | venmo/business-rules | business_rules/variables.py | rule_variable | def rule_variable(field_type, label=None, options=None):
""" Decorator to make a function into a rule variable
"""
options = options or []
def wrapper(func):
if not (type(field_type) == type and issubclass(field_type, BaseType)):
raise AssertionError("{0} is not instance of BaseType in"\
" rule_variable field_type".format(field_type))
func.field_type = field_type
func.is_rule_variable = True
func.label = label \
or fn_name_to_pretty_label(func.__name__)
func.options = options
return func
return wrapper | python | def rule_variable(field_type, label=None, options=None):
options = options or []
def wrapper(func):
if not (type(field_type) == type and issubclass(field_type, BaseType)):
raise AssertionError("{0} is not instance of BaseType in"\
" rule_variable field_type".format(field_type))
func.field_type = field_type
func.is_rule_variable = True
func.label = label \
or fn_name_to_pretty_label(func.__name__)
func.options = options
return func
return wrapper | [
"def",
"rule_variable",
"(",
"field_type",
",",
"label",
"=",
"None",
",",
"options",
"=",
"None",
")",
":",
"options",
"=",
"options",
"or",
"[",
"]",
"def",
"wrapper",
"(",
"func",
")",
":",
"if",
"not",
"(",
"type",
"(",
"field_type",
")",
"==",
... | Decorator to make a function into a rule variable | [
"Decorator",
"to",
"make",
"a",
"function",
"into",
"a",
"rule",
"variable"
] | 6c79036c030e2c6b8de5524a95231fd30048defa | https://github.com/venmo/business-rules/blob/6c79036c030e2c6b8de5524a95231fd30048defa/business_rules/variables.py#L25-L39 |
228,849 | venmo/business-rules | business_rules/operators.py | type_operator | def type_operator(input_type, label=None,
assert_type_for_arguments=True):
""" Decorator to make a function into a type operator.
- assert_type_for_arguments - if True this patches the operator function
so that arguments passed to it will have _assert_valid_value_and_cast
called on them to make type errors explicit.
"""
def wrapper(func):
func.is_operator = True
func.label = label \
or fn_name_to_pretty_label(func.__name__)
func.input_type = input_type
@wraps(func)
def inner(self, *args, **kwargs):
if assert_type_for_arguments:
args = [self._assert_valid_value_and_cast(arg) for arg in args]
kwargs = dict((k, self._assert_valid_value_and_cast(v))
for k, v in kwargs.items())
return func(self, *args, **kwargs)
return inner
return wrapper | python | def type_operator(input_type, label=None,
assert_type_for_arguments=True):
def wrapper(func):
func.is_operator = True
func.label = label \
or fn_name_to_pretty_label(func.__name__)
func.input_type = input_type
@wraps(func)
def inner(self, *args, **kwargs):
if assert_type_for_arguments:
args = [self._assert_valid_value_and_cast(arg) for arg in args]
kwargs = dict((k, self._assert_valid_value_and_cast(v))
for k, v in kwargs.items())
return func(self, *args, **kwargs)
return inner
return wrapper | [
"def",
"type_operator",
"(",
"input_type",
",",
"label",
"=",
"None",
",",
"assert_type_for_arguments",
"=",
"True",
")",
":",
"def",
"wrapper",
"(",
"func",
")",
":",
"func",
".",
"is_operator",
"=",
"True",
"func",
".",
"label",
"=",
"label",
"or",
"fn... | Decorator to make a function into a type operator.
- assert_type_for_arguments - if True this patches the operator function
so that arguments passed to it will have _assert_valid_value_and_cast
called on them to make type errors explicit. | [
"Decorator",
"to",
"make",
"a",
"function",
"into",
"a",
"type",
"operator",
"."
] | 6c79036c030e2c6b8de5524a95231fd30048defa | https://github.com/venmo/business-rules/blob/6c79036c030e2c6b8de5524a95231fd30048defa/business_rules/operators.py#L33-L55 |
228,850 | venmo/business-rules | business_rules/actions.py | rule_action | def rule_action(label=None, params=None):
""" Decorator to make a function into a rule action
"""
def wrapper(func):
params_ = params
if isinstance(params, dict):
params_ = [dict(label=fn_name_to_pretty_label(name),
name=name,
fieldType=field_type) \
for name, field_type in params.items()]
_validate_action_parameters(func, params_)
func.is_rule_action = True
func.label = label \
or fn_name_to_pretty_label(func.__name__)
func.params = params_
return func
return wrapper | python | def rule_action(label=None, params=None):
def wrapper(func):
params_ = params
if isinstance(params, dict):
params_ = [dict(label=fn_name_to_pretty_label(name),
name=name,
fieldType=field_type) \
for name, field_type in params.items()]
_validate_action_parameters(func, params_)
func.is_rule_action = True
func.label = label \
or fn_name_to_pretty_label(func.__name__)
func.params = params_
return func
return wrapper | [
"def",
"rule_action",
"(",
"label",
"=",
"None",
",",
"params",
"=",
"None",
")",
":",
"def",
"wrapper",
"(",
"func",
")",
":",
"params_",
"=",
"params",
"if",
"isinstance",
"(",
"params",
",",
"dict",
")",
":",
"params_",
"=",
"[",
"dict",
"(",
"l... | Decorator to make a function into a rule action | [
"Decorator",
"to",
"make",
"a",
"function",
"into",
"a",
"rule",
"action"
] | 6c79036c030e2c6b8de5524a95231fd30048defa | https://github.com/venmo/business-rules/blob/6c79036c030e2c6b8de5524a95231fd30048defa/business_rules/actions.py#L39-L55 |
228,851 | venmo/business-rules | business_rules/engine.py | check_condition | def check_condition(condition, defined_variables):
""" Checks a single rule condition - the condition will be made up of
variables, values, and the comparison operator. The defined_variables
object must have a variable defined for any variables in this condition.
"""
name, op, value = condition['name'], condition['operator'], condition['value']
operator_type = _get_variable_value(defined_variables, name)
return _do_operator_comparison(operator_type, op, value) | python | def check_condition(condition, defined_variables):
name, op, value = condition['name'], condition['operator'], condition['value']
operator_type = _get_variable_value(defined_variables, name)
return _do_operator_comparison(operator_type, op, value) | [
"def",
"check_condition",
"(",
"condition",
",",
"defined_variables",
")",
":",
"name",
",",
"op",
",",
"value",
"=",
"condition",
"[",
"'name'",
"]",
",",
"condition",
"[",
"'operator'",
"]",
",",
"condition",
"[",
"'value'",
"]",
"operator_type",
"=",
"_... | Checks a single rule condition - the condition will be made up of
variables, values, and the comparison operator. The defined_variables
object must have a variable defined for any variables in this condition. | [
"Checks",
"a",
"single",
"rule",
"condition",
"-",
"the",
"condition",
"will",
"be",
"made",
"up",
"of",
"variables",
"values",
"and",
"the",
"comparison",
"operator",
".",
"The",
"defined_variables",
"object",
"must",
"have",
"a",
"variable",
"defined",
"for"... | 6c79036c030e2c6b8de5524a95231fd30048defa | https://github.com/venmo/business-rules/blob/6c79036c030e2c6b8de5524a95231fd30048defa/business_rules/engine.py#L48-L55 |
228,852 | venmo/business-rules | business_rules/engine.py | _do_operator_comparison | def _do_operator_comparison(operator_type, operator_name, comparison_value):
""" Finds the method on the given operator_type and compares it to the
given comparison_value.
operator_type should be an instance of operators.BaseType
comparison_value is whatever python type to compare to
returns a bool
"""
def fallback(*args, **kwargs):
raise AssertionError("Operator {0} does not exist for type {1}".format(
operator_name, operator_type.__class__.__name__))
method = getattr(operator_type, operator_name, fallback)
if getattr(method, 'input_type', '') == FIELD_NO_INPUT:
return method()
return method(comparison_value) | python | def _do_operator_comparison(operator_type, operator_name, comparison_value):
def fallback(*args, **kwargs):
raise AssertionError("Operator {0} does not exist for type {1}".format(
operator_name, operator_type.__class__.__name__))
method = getattr(operator_type, operator_name, fallback)
if getattr(method, 'input_type', '') == FIELD_NO_INPUT:
return method()
return method(comparison_value) | [
"def",
"_do_operator_comparison",
"(",
"operator_type",
",",
"operator_name",
",",
"comparison_value",
")",
":",
"def",
"fallback",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"raise",
"AssertionError",
"(",
"\"Operator {0} does not exist for type {1}\"",
"... | Finds the method on the given operator_type and compares it to the
given comparison_value.
operator_type should be an instance of operators.BaseType
comparison_value is whatever python type to compare to
returns a bool | [
"Finds",
"the",
"method",
"on",
"the",
"given",
"operator_type",
"and",
"compares",
"it",
"to",
"the",
"given",
"comparison_value",
"."
] | 6c79036c030e2c6b8de5524a95231fd30048defa | https://github.com/venmo/business-rules/blob/6c79036c030e2c6b8de5524a95231fd30048defa/business_rules/engine.py#L71-L85 |
228,853 | mbi/django-simple-captcha | captcha/fields.py | CaptchaAnswerInput.build_attrs | def build_attrs(self, *args, **kwargs):
"""Disable automatic corrections and completions."""
attrs = super(CaptchaAnswerInput, self).build_attrs(*args, **kwargs)
attrs['autocapitalize'] = 'off'
attrs['autocomplete'] = 'off'
attrs['autocorrect'] = 'off'
attrs['spellcheck'] = 'false'
return attrs | python | def build_attrs(self, *args, **kwargs):
attrs = super(CaptchaAnswerInput, self).build_attrs(*args, **kwargs)
attrs['autocapitalize'] = 'off'
attrs['autocomplete'] = 'off'
attrs['autocorrect'] = 'off'
attrs['spellcheck'] = 'false'
return attrs | [
"def",
"build_attrs",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"attrs",
"=",
"super",
"(",
"CaptchaAnswerInput",
",",
"self",
")",
".",
"build_attrs",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"attrs",
"[",
"'autocapita... | Disable automatic corrections and completions. | [
"Disable",
"automatic",
"corrections",
"and",
"completions",
"."
] | e96cd8f63e41e658d103d12d6486b34195aee555 | https://github.com/mbi/django-simple-captcha/blob/e96cd8f63e41e658d103d12d6486b34195aee555/captcha/fields.py#L25-L32 |
228,854 | mbi/django-simple-captcha | captcha/fields.py | BaseCaptchaTextInput.fetch_captcha_store | def fetch_captcha_store(self, name, value, attrs=None, generator=None):
"""
Fetches a new CaptchaStore
This has to be called inside render
"""
try:
reverse('captcha-image', args=('dummy',))
except NoReverseMatch:
raise ImproperlyConfigured('Make sure you\'ve included captcha.urls as explained in the INSTALLATION section on http://readthedocs.org/docs/django-simple-captcha/en/latest/usage.html#installation')
if settings.CAPTCHA_GET_FROM_POOL:
key = CaptchaStore.pick()
else:
key = CaptchaStore.generate_key(generator)
# these can be used by format_output and render
self._value = [key, u('')]
self._key = key
self.id_ = self.build_attrs(attrs).get('id', None) | python | def fetch_captcha_store(self, name, value, attrs=None, generator=None):
try:
reverse('captcha-image', args=('dummy',))
except NoReverseMatch:
raise ImproperlyConfigured('Make sure you\'ve included captcha.urls as explained in the INSTALLATION section on http://readthedocs.org/docs/django-simple-captcha/en/latest/usage.html#installation')
if settings.CAPTCHA_GET_FROM_POOL:
key = CaptchaStore.pick()
else:
key = CaptchaStore.generate_key(generator)
# these can be used by format_output and render
self._value = [key, u('')]
self._key = key
self.id_ = self.build_attrs(attrs).get('id', None) | [
"def",
"fetch_captcha_store",
"(",
"self",
",",
"name",
",",
"value",
",",
"attrs",
"=",
"None",
",",
"generator",
"=",
"None",
")",
":",
"try",
":",
"reverse",
"(",
"'captcha-image'",
",",
"args",
"=",
"(",
"'dummy'",
",",
")",
")",
"except",
"NoRever... | Fetches a new CaptchaStore
This has to be called inside render | [
"Fetches",
"a",
"new",
"CaptchaStore",
"This",
"has",
"to",
"be",
"called",
"inside",
"render"
] | e96cd8f63e41e658d103d12d6486b34195aee555 | https://github.com/mbi/django-simple-captcha/blob/e96cd8f63e41e658d103d12d6486b34195aee555/captcha/fields.py#L51-L69 |
228,855 | mbi/django-simple-captcha | captcha/fields.py | CaptchaTextInput.get_context | def get_context(self, name, value, attrs):
"""Add captcha specific variables to context."""
context = super(CaptchaTextInput, self).get_context(name, value, attrs)
context['image'] = self.image_url()
context['audio'] = self.audio_url()
return context | python | def get_context(self, name, value, attrs):
context = super(CaptchaTextInput, self).get_context(name, value, attrs)
context['image'] = self.image_url()
context['audio'] = self.audio_url()
return context | [
"def",
"get_context",
"(",
"self",
",",
"name",
",",
"value",
",",
"attrs",
")",
":",
"context",
"=",
"super",
"(",
"CaptchaTextInput",
",",
"self",
")",
".",
"get_context",
"(",
"name",
",",
"value",
",",
"attrs",
")",
"context",
"[",
"'image'",
"]",
... | Add captcha specific variables to context. | [
"Add",
"captcha",
"specific",
"variables",
"to",
"context",
"."
] | e96cd8f63e41e658d103d12d6486b34195aee555 | https://github.com/mbi/django-simple-captcha/blob/e96cd8f63e41e658d103d12d6486b34195aee555/captcha/fields.py#L127-L132 |
228,856 | mbi/django-simple-captcha | captcha/fields.py | CaptchaTextInput._direct_render | def _direct_render(self, name, attrs):
"""Render the widget the old way - using field_template or output_format."""
context = {
'image': self.image_url(),
'name': name,
'key': self._key,
'id': u'%s_%s' % (self.id_prefix, attrs.get('id')) if self.id_prefix else attrs.get('id'),
'audio': self.audio_url(),
}
self.image_and_audio = render_to_string(settings.CAPTCHA_IMAGE_TEMPLATE, context)
self.hidden_field = render_to_string(settings.CAPTCHA_HIDDEN_FIELD_TEMPLATE, context)
self.text_field = render_to_string(settings.CAPTCHA_TEXT_FIELD_TEMPLATE, context)
return self.format_output(None) | python | def _direct_render(self, name, attrs):
context = {
'image': self.image_url(),
'name': name,
'key': self._key,
'id': u'%s_%s' % (self.id_prefix, attrs.get('id')) if self.id_prefix else attrs.get('id'),
'audio': self.audio_url(),
}
self.image_and_audio = render_to_string(settings.CAPTCHA_IMAGE_TEMPLATE, context)
self.hidden_field = render_to_string(settings.CAPTCHA_HIDDEN_FIELD_TEMPLATE, context)
self.text_field = render_to_string(settings.CAPTCHA_TEXT_FIELD_TEMPLATE, context)
return self.format_output(None) | [
"def",
"_direct_render",
"(",
"self",
",",
"name",
",",
"attrs",
")",
":",
"context",
"=",
"{",
"'image'",
":",
"self",
".",
"image_url",
"(",
")",
",",
"'name'",
":",
"name",
",",
"'key'",
":",
"self",
".",
"_key",
",",
"'id'",
":",
"u'%s_%s'",
"%... | Render the widget the old way - using field_template or output_format. | [
"Render",
"the",
"widget",
"the",
"old",
"way",
"-",
"using",
"field_template",
"or",
"output_format",
"."
] | e96cd8f63e41e658d103d12d6486b34195aee555 | https://github.com/mbi/django-simple-captcha/blob/e96cd8f63e41e658d103d12d6486b34195aee555/captcha/fields.py#L152-L164 |
228,857 | mbi/django-simple-captcha | captcha/views.py | captcha_refresh | def captcha_refresh(request):
""" Return json with new captcha for ajax refresh request """
if not request.is_ajax():
raise Http404
new_key = CaptchaStore.pick()
to_json_response = {
'key': new_key,
'image_url': captcha_image_url(new_key),
'audio_url': captcha_audio_url(new_key) if settings.CAPTCHA_FLITE_PATH else None
}
return HttpResponse(json.dumps(to_json_response), content_type='application/json') | python | def captcha_refresh(request):
if not request.is_ajax():
raise Http404
new_key = CaptchaStore.pick()
to_json_response = {
'key': new_key,
'image_url': captcha_image_url(new_key),
'audio_url': captcha_audio_url(new_key) if settings.CAPTCHA_FLITE_PATH else None
}
return HttpResponse(json.dumps(to_json_response), content_type='application/json') | [
"def",
"captcha_refresh",
"(",
"request",
")",
":",
"if",
"not",
"request",
".",
"is_ajax",
"(",
")",
":",
"raise",
"Http404",
"new_key",
"=",
"CaptchaStore",
".",
"pick",
"(",
")",
"to_json_response",
"=",
"{",
"'key'",
":",
"new_key",
",",
"'image_url'",... | Return json with new captcha for ajax refresh request | [
"Return",
"json",
"with",
"new",
"captcha",
"for",
"ajax",
"refresh",
"request"
] | e96cd8f63e41e658d103d12d6486b34195aee555 | https://github.com/mbi/django-simple-captcha/blob/e96cd8f63e41e658d103d12d6486b34195aee555/captcha/views.py#L153-L164 |
228,858 | singingwolfboy/flask-dance | flask_dance/contrib/zoho.py | ZohoWebClient._add_zoho_token | def _add_zoho_token(
self, uri, http_method="GET", body=None, headers=None, token_placement=None
):
"""Add a zoho token to the request uri, body or authorization header. follows bearer pattern"""
headers = self.prepare_zoho_headers(self.access_token, headers)
return uri, headers, body | python | def _add_zoho_token(
self, uri, http_method="GET", body=None, headers=None, token_placement=None
):
headers = self.prepare_zoho_headers(self.access_token, headers)
return uri, headers, body | [
"def",
"_add_zoho_token",
"(",
"self",
",",
"uri",
",",
"http_method",
"=",
"\"GET\"",
",",
"body",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"token_placement",
"=",
"None",
")",
":",
"headers",
"=",
"self",
".",
"prepare_zoho_headers",
"(",
"self",
... | Add a zoho token to the request uri, body or authorization header. follows bearer pattern | [
"Add",
"a",
"zoho",
"token",
"to",
"the",
"request",
"uri",
"body",
"or",
"authorization",
"header",
".",
"follows",
"bearer",
"pattern"
] | 87d45328bbdaff833559a6d3da71461fe4579592 | https://github.com/singingwolfboy/flask-dance/blob/87d45328bbdaff833559a6d3da71461fe4579592/flask_dance/contrib/zoho.py#L120-L125 |
228,859 | singingwolfboy/flask-dance | flask_dance/contrib/zoho.py | ZohoWebClient.prepare_zoho_headers | def prepare_zoho_headers(token, headers=None):
"""Add a `Zoho Token`_ to the request URI.
Recommended method of passing bearer tokens.
Authorization: Zoho-oauthtoken h480djs93hd8
.. _`Zoho-oauthtoken Token`: custom zoho token
"""
headers = headers or {}
headers["Authorization"] = "{token_header} {token}".format(
token_header=ZOHO_TOKEN_HEADER, token=token
)
return headers | python | def prepare_zoho_headers(token, headers=None):
headers = headers or {}
headers["Authorization"] = "{token_header} {token}".format(
token_header=ZOHO_TOKEN_HEADER, token=token
)
return headers | [
"def",
"prepare_zoho_headers",
"(",
"token",
",",
"headers",
"=",
"None",
")",
":",
"headers",
"=",
"headers",
"or",
"{",
"}",
"headers",
"[",
"\"Authorization\"",
"]",
"=",
"\"{token_header} {token}\"",
".",
"format",
"(",
"token_header",
"=",
"ZOHO_TOKEN_HEADE... | Add a `Zoho Token`_ to the request URI.
Recommended method of passing bearer tokens.
Authorization: Zoho-oauthtoken h480djs93hd8
.. _`Zoho-oauthtoken Token`: custom zoho token | [
"Add",
"a",
"Zoho",
"Token",
"_",
"to",
"the",
"request",
"URI",
".",
"Recommended",
"method",
"of",
"passing",
"bearer",
"tokens",
"."
] | 87d45328bbdaff833559a6d3da71461fe4579592 | https://github.com/singingwolfboy/flask-dance/blob/87d45328bbdaff833559a6d3da71461fe4579592/flask_dance/contrib/zoho.py#L128-L140 |
228,860 | singingwolfboy/flask-dance | flask_dance/utils.py | timestamp_from_datetime | def timestamp_from_datetime(dt):
"""
Given a datetime, in UTC, return a float that represents the timestamp for
that datetime.
http://stackoverflow.com/questions/8777753/converting-datetime-date-to-utc-timestamp-in-python#8778548
"""
dt = dt.replace(tzinfo=utc)
if hasattr(dt, "timestamp") and callable(dt.timestamp):
return dt.replace(tzinfo=utc).timestamp()
return (dt - datetime(1970, 1, 1, tzinfo=utc)).total_seconds() | python | def timestamp_from_datetime(dt):
dt = dt.replace(tzinfo=utc)
if hasattr(dt, "timestamp") and callable(dt.timestamp):
return dt.replace(tzinfo=utc).timestamp()
return (dt - datetime(1970, 1, 1, tzinfo=utc)).total_seconds() | [
"def",
"timestamp_from_datetime",
"(",
"dt",
")",
":",
"dt",
"=",
"dt",
".",
"replace",
"(",
"tzinfo",
"=",
"utc",
")",
"if",
"hasattr",
"(",
"dt",
",",
"\"timestamp\"",
")",
"and",
"callable",
"(",
"dt",
".",
"timestamp",
")",
":",
"return",
"dt",
"... | Given a datetime, in UTC, return a float that represents the timestamp for
that datetime.
http://stackoverflow.com/questions/8777753/converting-datetime-date-to-utc-timestamp-in-python#8778548 | [
"Given",
"a",
"datetime",
"in",
"UTC",
"return",
"a",
"float",
"that",
"represents",
"the",
"timestamp",
"for",
"that",
"datetime",
"."
] | 87d45328bbdaff833559a6d3da71461fe4579592 | https://github.com/singingwolfboy/flask-dance/blob/87d45328bbdaff833559a6d3da71461fe4579592/flask_dance/utils.py#L82-L92 |
228,861 | jmoiron/humanize | humanize/time.py | abs_timedelta | def abs_timedelta(delta):
"""Returns an "absolute" value for a timedelta, always representing a
time distance."""
if delta.days < 0:
now = _now()
return now - (now + delta)
return delta | python | def abs_timedelta(delta):
if delta.days < 0:
now = _now()
return now - (now + delta)
return delta | [
"def",
"abs_timedelta",
"(",
"delta",
")",
":",
"if",
"delta",
".",
"days",
"<",
"0",
":",
"now",
"=",
"_now",
"(",
")",
"return",
"now",
"-",
"(",
"now",
"+",
"delta",
")",
"return",
"delta"
] | Returns an "absolute" value for a timedelta, always representing a
time distance. | [
"Returns",
"an",
"absolute",
"value",
"for",
"a",
"timedelta",
"always",
"representing",
"a",
"time",
"distance",
"."
] | 32c469bc378de22e8eabd5f9565bd7cffe7c7ae0 | https://github.com/jmoiron/humanize/blob/32c469bc378de22e8eabd5f9565bd7cffe7c7ae0/humanize/time.py#L16-L22 |
228,862 | jmoiron/humanize | humanize/time.py | naturaltime | def naturaltime(value, future=False, months=True):
"""Given a datetime or a number of seconds, return a natural representation
of that time in a resolution that makes sense. This is more or less
compatible with Django's ``naturaltime`` filter. ``future`` is ignored for
datetimes, where the tense is always figured out based on the current time.
If an integer is passed, the return value will be past tense by default,
unless ``future`` is set to True."""
now = _now()
date, delta = date_and_delta(value)
if date is None:
return value
# determine tense by value only if datetime/timedelta were passed
if isinstance(value, (datetime, timedelta)):
future = date > now
ago = _('%s from now') if future else _('%s ago')
delta = naturaldelta(delta, months)
if delta == _("a moment"):
return _("now")
return ago % delta | python | def naturaltime(value, future=False, months=True):
now = _now()
date, delta = date_and_delta(value)
if date is None:
return value
# determine tense by value only if datetime/timedelta were passed
if isinstance(value, (datetime, timedelta)):
future = date > now
ago = _('%s from now') if future else _('%s ago')
delta = naturaldelta(delta, months)
if delta == _("a moment"):
return _("now")
return ago % delta | [
"def",
"naturaltime",
"(",
"value",
",",
"future",
"=",
"False",
",",
"months",
"=",
"True",
")",
":",
"now",
"=",
"_now",
"(",
")",
"date",
",",
"delta",
"=",
"date_and_delta",
"(",
"value",
")",
"if",
"date",
"is",
"None",
":",
"return",
"value",
... | Given a datetime or a number of seconds, return a natural representation
of that time in a resolution that makes sense. This is more or less
compatible with Django's ``naturaltime`` filter. ``future`` is ignored for
datetimes, where the tense is always figured out based on the current time.
If an integer is passed, the return value will be past tense by default,
unless ``future`` is set to True. | [
"Given",
"a",
"datetime",
"or",
"a",
"number",
"of",
"seconds",
"return",
"a",
"natural",
"representation",
"of",
"that",
"time",
"in",
"a",
"resolution",
"that",
"makes",
"sense",
".",
"This",
"is",
"more",
"or",
"less",
"compatible",
"with",
"Django",
"s... | 32c469bc378de22e8eabd5f9565bd7cffe7c7ae0 | https://github.com/jmoiron/humanize/blob/32c469bc378de22e8eabd5f9565bd7cffe7c7ae0/humanize/time.py#L108-L129 |
228,863 | jmoiron/humanize | humanize/time.py | naturalday | def naturalday(value, format='%b %d'):
"""For date values that are tomorrow, today or yesterday compared to
present day returns representing string. Otherwise, returns a string
formatted according to ``format``."""
try:
value = date(value.year, value.month, value.day)
except AttributeError:
# Passed value wasn't date-ish
return value
except (OverflowError, ValueError):
# Date arguments out of range
return value
delta = value - date.today()
if delta.days == 0:
return _('today')
elif delta.days == 1:
return _('tomorrow')
elif delta.days == -1:
return _('yesterday')
return value.strftime(format) | python | def naturalday(value, format='%b %d'):
try:
value = date(value.year, value.month, value.day)
except AttributeError:
# Passed value wasn't date-ish
return value
except (OverflowError, ValueError):
# Date arguments out of range
return value
delta = value - date.today()
if delta.days == 0:
return _('today')
elif delta.days == 1:
return _('tomorrow')
elif delta.days == -1:
return _('yesterday')
return value.strftime(format) | [
"def",
"naturalday",
"(",
"value",
",",
"format",
"=",
"'%b %d'",
")",
":",
"try",
":",
"value",
"=",
"date",
"(",
"value",
".",
"year",
",",
"value",
".",
"month",
",",
"value",
".",
"day",
")",
"except",
"AttributeError",
":",
"# Passed value wasn't da... | For date values that are tomorrow, today or yesterday compared to
present day returns representing string. Otherwise, returns a string
formatted according to ``format``. | [
"For",
"date",
"values",
"that",
"are",
"tomorrow",
"today",
"or",
"yesterday",
"compared",
"to",
"present",
"day",
"returns",
"representing",
"string",
".",
"Otherwise",
"returns",
"a",
"string",
"formatted",
"according",
"to",
"format",
"."
] | 32c469bc378de22e8eabd5f9565bd7cffe7c7ae0 | https://github.com/jmoiron/humanize/blob/32c469bc378de22e8eabd5f9565bd7cffe7c7ae0/humanize/time.py#L131-L150 |
228,864 | jmoiron/humanize | humanize/time.py | naturaldate | def naturaldate(value):
"""Like naturalday, but will append a year for dates that are a year
ago or more."""
try:
value = date(value.year, value.month, value.day)
except AttributeError:
# Passed value wasn't date-ish
return value
except (OverflowError, ValueError):
# Date arguments out of range
return value
delta = abs_timedelta(value - date.today())
if delta.days >= 365:
return naturalday(value, '%b %d %Y')
return naturalday(value) | python | def naturaldate(value):
try:
value = date(value.year, value.month, value.day)
except AttributeError:
# Passed value wasn't date-ish
return value
except (OverflowError, ValueError):
# Date arguments out of range
return value
delta = abs_timedelta(value - date.today())
if delta.days >= 365:
return naturalday(value, '%b %d %Y')
return naturalday(value) | [
"def",
"naturaldate",
"(",
"value",
")",
":",
"try",
":",
"value",
"=",
"date",
"(",
"value",
".",
"year",
",",
"value",
".",
"month",
",",
"value",
".",
"day",
")",
"except",
"AttributeError",
":",
"# Passed value wasn't date-ish",
"return",
"value",
"exc... | Like naturalday, but will append a year for dates that are a year
ago or more. | [
"Like",
"naturalday",
"but",
"will",
"append",
"a",
"year",
"for",
"dates",
"that",
"are",
"a",
"year",
"ago",
"or",
"more",
"."
] | 32c469bc378de22e8eabd5f9565bd7cffe7c7ae0 | https://github.com/jmoiron/humanize/blob/32c469bc378de22e8eabd5f9565bd7cffe7c7ae0/humanize/time.py#L152-L166 |
228,865 | jmoiron/humanize | humanize/i18n.py | activate | def activate(locale, path=None):
"""Set 'locale' as current locale. Search for locale in directory 'path'
@param locale: language name, eg 'en_GB'"""
if path is None:
path = _DEFAULT_LOCALE_PATH
if locale not in _TRANSLATIONS:
translation = gettext_module.translation('humanize', path, [locale])
_TRANSLATIONS[locale] = translation
_CURRENT.locale = locale
return _TRANSLATIONS[locale] | python | def activate(locale, path=None):
"""Set 'locale' as current locale. Search for locale in directory 'path'
@param locale: language name, eg 'en_GB'"""
if path is None:
path = _DEFAULT_LOCALE_PATH
if locale not in _TRANSLATIONS:
translation = gettext_module.translation('humanize', path, [locale])
_TRANSLATIONS[locale] = translation
_CURRENT.locale = locale
return _TRANSLATIONS[locale] | [
"def",
"activate",
"(",
"locale",
",",
"path",
"=",
"None",
")",
":",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"_DEFAULT_LOCALE_PATH",
"if",
"locale",
"not",
"in",
"_TRANSLATIONS",
":",
"translation",
"=",
"gettext_module",
".",
"translation",
"(",
"'... | Set 'locale' as current locale. Search for locale in directory 'path'
@param locale: language name, eg 'en_GB | [
"Set",
"locale",
"as",
"current",
"locale",
".",
"Search",
"for",
"locale",
"in",
"directory",
"path"
] | 32c469bc378de22e8eabd5f9565bd7cffe7c7ae0 | https://github.com/jmoiron/humanize/blob/32c469bc378de22e8eabd5f9565bd7cffe7c7ae0/humanize/i18n.py#L21-L30 |
228,866 | jmoiron/humanize | humanize/i18n.py | pgettext | def pgettext(msgctxt, message):
"""'Particular gettext' function.
It works with 'msgctxt' .po modifiers and allow duplicate keys with
different translations.
Python 2 don't have support for this GNU gettext function, so we
reimplement it. It works by joining msgctx and msgid by '4' byte."""
key = msgctxt + '\x04' + message
translation = get_translation().gettext(key)
return message if translation == key else translation | python | def pgettext(msgctxt, message):
"""'Particular gettext' function.
It works with 'msgctxt' .po modifiers and allow duplicate keys with
different translations.
Python 2 don't have support for this GNU gettext function, so we
reimplement it. It works by joining msgctx and msgid by '4' byte."""
key = msgctxt + '\x04' + message
translation = get_translation().gettext(key)
return message if translation == key else translation | [
"def",
"pgettext",
"(",
"msgctxt",
",",
"message",
")",
":",
"key",
"=",
"msgctxt",
"+",
"'\\x04'",
"+",
"message",
"translation",
"=",
"get_translation",
"(",
")",
".",
"gettext",
"(",
"key",
")",
"return",
"message",
"if",
"translation",
"==",
"key",
"... | Particular gettext' function.
It works with 'msgctxt' .po modifiers and allow duplicate keys with
different translations.
Python 2 don't have support for this GNU gettext function, so we
reimplement it. It works by joining msgctx and msgid by '4' byte. | [
"Particular",
"gettext",
"function",
".",
"It",
"works",
"with",
"msgctxt",
".",
"po",
"modifiers",
"and",
"allow",
"duplicate",
"keys",
"with",
"different",
"translations",
".",
"Python",
"2",
"don",
"t",
"have",
"support",
"for",
"this",
"GNU",
"gettext",
... | 32c469bc378de22e8eabd5f9565bd7cffe7c7ae0 | https://github.com/jmoiron/humanize/blob/32c469bc378de22e8eabd5f9565bd7cffe7c7ae0/humanize/i18n.py#L41-L49 |
228,867 | jmoiron/humanize | humanize/number.py | intcomma | def intcomma(value):
"""Converts an integer to a string containing commas every three digits.
For example, 3000 becomes '3,000' and 45000 becomes '45,000'. To maintain
some compatability with Django's intcomma, this function also accepts
floats."""
try:
if isinstance(value, compat.string_types):
float(value.replace(',', ''))
else:
float(value)
except (TypeError, ValueError):
return value
orig = str(value)
new = re.sub("^(-?\d+)(\d{3})", '\g<1>,\g<2>', orig)
if orig == new:
return new
else:
return intcomma(new) | python | def intcomma(value):
try:
if isinstance(value, compat.string_types):
float(value.replace(',', ''))
else:
float(value)
except (TypeError, ValueError):
return value
orig = str(value)
new = re.sub("^(-?\d+)(\d{3})", '\g<1>,\g<2>', orig)
if orig == new:
return new
else:
return intcomma(new) | [
"def",
"intcomma",
"(",
"value",
")",
":",
"try",
":",
"if",
"isinstance",
"(",
"value",
",",
"compat",
".",
"string_types",
")",
":",
"float",
"(",
"value",
".",
"replace",
"(",
"','",
",",
"''",
")",
")",
"else",
":",
"float",
"(",
"value",
")",
... | Converts an integer to a string containing commas every three digits.
For example, 3000 becomes '3,000' and 45000 becomes '45,000'. To maintain
some compatability with Django's intcomma, this function also accepts
floats. | [
"Converts",
"an",
"integer",
"to",
"a",
"string",
"containing",
"commas",
"every",
"three",
"digits",
".",
"For",
"example",
"3000",
"becomes",
"3",
"000",
"and",
"45000",
"becomes",
"45",
"000",
".",
"To",
"maintain",
"some",
"compatability",
"with",
"Djang... | 32c469bc378de22e8eabd5f9565bd7cffe7c7ae0 | https://github.com/jmoiron/humanize/blob/32c469bc378de22e8eabd5f9565bd7cffe7c7ae0/humanize/number.py#L35-L52 |
228,868 | jmoiron/humanize | humanize/number.py | apnumber | def apnumber(value):
"""For numbers 1-9, returns the number spelled out. Otherwise, returns the
number. This follows Associated Press style. This always returns a string
unless the value was not int-able, unlike the Django filter."""
try:
value = int(value)
except (TypeError, ValueError):
return value
if not 0 < value < 10:
return str(value)
return (_('one'), _('two'), _('three'), _('four'), _('five'), _('six'),
_('seven'), _('eight'), _('nine'))[value - 1] | python | def apnumber(value):
try:
value = int(value)
except (TypeError, ValueError):
return value
if not 0 < value < 10:
return str(value)
return (_('one'), _('two'), _('three'), _('four'), _('five'), _('six'),
_('seven'), _('eight'), _('nine'))[value - 1] | [
"def",
"apnumber",
"(",
"value",
")",
":",
"try",
":",
"value",
"=",
"int",
"(",
"value",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"return",
"value",
"if",
"not",
"0",
"<",
"value",
"<",
"10",
":",
"return",
"str",
"(",
"value"... | For numbers 1-9, returns the number spelled out. Otherwise, returns the
number. This follows Associated Press style. This always returns a string
unless the value was not int-able, unlike the Django filter. | [
"For",
"numbers",
"1",
"-",
"9",
"returns",
"the",
"number",
"spelled",
"out",
".",
"Otherwise",
"returns",
"the",
"number",
".",
"This",
"follows",
"Associated",
"Press",
"style",
".",
"This",
"always",
"returns",
"a",
"string",
"unless",
"the",
"value",
... | 32c469bc378de22e8eabd5f9565bd7cffe7c7ae0 | https://github.com/jmoiron/humanize/blob/32c469bc378de22e8eabd5f9565bd7cffe7c7ae0/humanize/number.py#L81-L92 |
228,869 | xiaoxu193/PyTeaser | pyteaser.py | keywords | def keywords(text):
"""get the top 10 keywords and their frequency scores
ignores blacklisted words in stopWords,
counts the number of occurrences of each word
"""
text = split_words(text)
numWords = len(text) # of words before removing blacklist words
freq = Counter(x for x in text if x not in stopWords)
minSize = min(10, len(freq)) # get first 10
keywords = {x: y for x, y in freq.most_common(minSize)} # recreate a dict
for k in keywords:
articleScore = keywords[k]*1.0 / numWords
keywords[k] = articleScore * 1.5 + 1
return keywords | python | def keywords(text):
text = split_words(text)
numWords = len(text) # of words before removing blacklist words
freq = Counter(x for x in text if x not in stopWords)
minSize = min(10, len(freq)) # get first 10
keywords = {x: y for x, y in freq.most_common(minSize)} # recreate a dict
for k in keywords:
articleScore = keywords[k]*1.0 / numWords
keywords[k] = articleScore * 1.5 + 1
return keywords | [
"def",
"keywords",
"(",
"text",
")",
":",
"text",
"=",
"split_words",
"(",
"text",
")",
"numWords",
"=",
"len",
"(",
"text",
")",
"# of words before removing blacklist words",
"freq",
"=",
"Counter",
"(",
"x",
"for",
"x",
"in",
"text",
"if",
"x",
"not",
... | get the top 10 keywords and their frequency scores
ignores blacklisted words in stopWords,
counts the number of occurrences of each word | [
"get",
"the",
"top",
"10",
"keywords",
"and",
"their",
"frequency",
"scores",
"ignores",
"blacklisted",
"words",
"in",
"stopWords",
"counts",
"the",
"number",
"of",
"occurrences",
"of",
"each",
"word"
] | bcbcae3586cb658d9954f440d15419a4683b48b6 | https://github.com/xiaoxu193/PyTeaser/blob/bcbcae3586cb658d9954f440d15419a4683b48b6/pyteaser.py#L177-L193 |
228,870 | xiaoxu193/PyTeaser | pyteaser.py | sentence_position | def sentence_position(i, size):
"""different sentence positions indicate different
probability of being an important sentence"""
normalized = i*1.0 / size
if 0 < normalized <= 0.1:
return 0.17
elif 0.1 < normalized <= 0.2:
return 0.23
elif 0.2 < normalized <= 0.3:
return 0.14
elif 0.3 < normalized <= 0.4:
return 0.08
elif 0.4 < normalized <= 0.5:
return 0.05
elif 0.5 < normalized <= 0.6:
return 0.04
elif 0.6 < normalized <= 0.7:
return 0.06
elif 0.7 < normalized <= 0.8:
return 0.04
elif 0.8 < normalized <= 0.9:
return 0.04
elif 0.9 < normalized <= 1.0:
return 0.15
else:
return 0 | python | def sentence_position(i, size):
normalized = i*1.0 / size
if 0 < normalized <= 0.1:
return 0.17
elif 0.1 < normalized <= 0.2:
return 0.23
elif 0.2 < normalized <= 0.3:
return 0.14
elif 0.3 < normalized <= 0.4:
return 0.08
elif 0.4 < normalized <= 0.5:
return 0.05
elif 0.5 < normalized <= 0.6:
return 0.04
elif 0.6 < normalized <= 0.7:
return 0.06
elif 0.7 < normalized <= 0.8:
return 0.04
elif 0.8 < normalized <= 0.9:
return 0.04
elif 0.9 < normalized <= 1.0:
return 0.15
else:
return 0 | [
"def",
"sentence_position",
"(",
"i",
",",
"size",
")",
":",
"normalized",
"=",
"i",
"*",
"1.0",
"/",
"size",
"if",
"0",
"<",
"normalized",
"<=",
"0.1",
":",
"return",
"0.17",
"elif",
"0.1",
"<",
"normalized",
"<=",
"0.2",
":",
"return",
"0.23",
"eli... | different sentence positions indicate different
probability of being an important sentence | [
"different",
"sentence",
"positions",
"indicate",
"different",
"probability",
"of",
"being",
"an",
"important",
"sentence"
] | bcbcae3586cb658d9954f440d15419a4683b48b6 | https://github.com/xiaoxu193/PyTeaser/blob/bcbcae3586cb658d9954f440d15419a4683b48b6/pyteaser.py#L232-L258 |
228,871 | xiaoxu193/PyTeaser | goose/extractors.py | ContentExtractor.split_title | def split_title(self, title, splitter):
"""\
Split the title to best part possible
"""
large_text_length = 0
large_text_index = 0
title_pieces = splitter.split(title)
# find the largest title piece
for i in range(len(title_pieces)):
current = title_pieces[i]
if len(current) > large_text_length:
large_text_length = len(current)
large_text_index = i
# replace content
title = title_pieces[large_text_index]
return TITLE_REPLACEMENTS.replaceAll(title).strip() | python | def split_title(self, title, splitter):
large_text_length = 0
large_text_index = 0
title_pieces = splitter.split(title)
# find the largest title piece
for i in range(len(title_pieces)):
current = title_pieces[i]
if len(current) > large_text_length:
large_text_length = len(current)
large_text_index = i
# replace content
title = title_pieces[large_text_index]
return TITLE_REPLACEMENTS.replaceAll(title).strip() | [
"def",
"split_title",
"(",
"self",
",",
"title",
",",
"splitter",
")",
":",
"large_text_length",
"=",
"0",
"large_text_index",
"=",
"0",
"title_pieces",
"=",
"splitter",
".",
"split",
"(",
"title",
")",
"# find the largest title piece",
"for",
"i",
"in",
"rang... | \
Split the title to best part possible | [
"\\",
"Split",
"the",
"title",
"to",
"best",
"part",
"possible"
] | bcbcae3586cb658d9954f440d15419a4683b48b6 | https://github.com/xiaoxu193/PyTeaser/blob/bcbcae3586cb658d9954f440d15419a4683b48b6/goose/extractors.py#L105-L122 |
228,872 | xiaoxu193/PyTeaser | goose/extractors.py | ContentExtractor.is_boostable | def is_boostable(self, node):
"""\
alot of times the first paragraph might be the caption under an image
so we'll want to make sure if we're going to boost a parent node that
it should be connected to other paragraphs,
at least for the first n paragraphs so we'll want to make sure that
the next sibling is a paragraph and has at
least some substatial weight to it
"""
para = "p"
steps_away = 0
minimum_stopword_count = 5
max_stepsaway_from_node = 3
nodes = self.walk_siblings(node)
for current_node in nodes:
# p
current_node_tag = self.parser.getTag(current_node)
if current_node_tag == para:
if steps_away >= max_stepsaway_from_node:
return False
paraText = self.parser.getText(current_node)
word_stats = self.stopwords_class(language=self.language).get_stopword_count(paraText)
if word_stats.get_stopword_count() > minimum_stopword_count:
return True
steps_away += 1
return False | python | def is_boostable(self, node):
para = "p"
steps_away = 0
minimum_stopword_count = 5
max_stepsaway_from_node = 3
nodes = self.walk_siblings(node)
for current_node in nodes:
# p
current_node_tag = self.parser.getTag(current_node)
if current_node_tag == para:
if steps_away >= max_stepsaway_from_node:
return False
paraText = self.parser.getText(current_node)
word_stats = self.stopwords_class(language=self.language).get_stopword_count(paraText)
if word_stats.get_stopword_count() > minimum_stopword_count:
return True
steps_away += 1
return False | [
"def",
"is_boostable",
"(",
"self",
",",
"node",
")",
":",
"para",
"=",
"\"p\"",
"steps_away",
"=",
"0",
"minimum_stopword_count",
"=",
"5",
"max_stepsaway_from_node",
"=",
"3",
"nodes",
"=",
"self",
".",
"walk_siblings",
"(",
"node",
")",
"for",
"current_no... | \
alot of times the first paragraph might be the caption under an image
so we'll want to make sure if we're going to boost a parent node that
it should be connected to other paragraphs,
at least for the first n paragraphs so we'll want to make sure that
the next sibling is a paragraph and has at
least some substatial weight to it | [
"\\",
"alot",
"of",
"times",
"the",
"first",
"paragraph",
"might",
"be",
"the",
"caption",
"under",
"an",
"image",
"so",
"we",
"ll",
"want",
"to",
"make",
"sure",
"if",
"we",
"re",
"going",
"to",
"boost",
"a",
"parent",
"node",
"that",
"it",
"should",
... | bcbcae3586cb658d9954f440d15419a4683b48b6 | https://github.com/xiaoxu193/PyTeaser/blob/bcbcae3586cb658d9954f440d15419a4683b48b6/goose/extractors.py#L309-L335 |
228,873 | xiaoxu193/PyTeaser | goose/extractors.py | ContentExtractor.get_siblings_content | def get_siblings_content(self, current_sibling, baselinescore_siblings_para):
"""\
adds any siblings that may have a decent score to this node
"""
if current_sibling.tag == 'p' and len(self.parser.getText(current_sibling)) > 0:
e0 = current_sibling
if e0.tail:
e0 = deepcopy(e0)
e0.tail = ''
return [e0]
else:
potential_paragraphs = self.parser.getElementsByTag(current_sibling, tag='p')
if potential_paragraphs is None:
return None
else:
ps = []
for first_paragraph in potential_paragraphs:
text = self.parser.getText(first_paragraph)
if len(text) > 0:
word_stats = self.stopwords_class(language=self.language).get_stopword_count(text)
paragraph_score = word_stats.get_stopword_count()
sibling_baseline_score = float(.30)
high_link_density = self.is_highlink_density(first_paragraph)
score = float(baselinescore_siblings_para * sibling_baseline_score)
if score < paragraph_score and not high_link_density:
p = self.parser.createElement(tag='p', text=text, tail=None)
ps.append(p)
return ps | python | def get_siblings_content(self, current_sibling, baselinescore_siblings_para):
if current_sibling.tag == 'p' and len(self.parser.getText(current_sibling)) > 0:
e0 = current_sibling
if e0.tail:
e0 = deepcopy(e0)
e0.tail = ''
return [e0]
else:
potential_paragraphs = self.parser.getElementsByTag(current_sibling, tag='p')
if potential_paragraphs is None:
return None
else:
ps = []
for first_paragraph in potential_paragraphs:
text = self.parser.getText(first_paragraph)
if len(text) > 0:
word_stats = self.stopwords_class(language=self.language).get_stopword_count(text)
paragraph_score = word_stats.get_stopword_count()
sibling_baseline_score = float(.30)
high_link_density = self.is_highlink_density(first_paragraph)
score = float(baselinescore_siblings_para * sibling_baseline_score)
if score < paragraph_score and not high_link_density:
p = self.parser.createElement(tag='p', text=text, tail=None)
ps.append(p)
return ps | [
"def",
"get_siblings_content",
"(",
"self",
",",
"current_sibling",
",",
"baselinescore_siblings_para",
")",
":",
"if",
"current_sibling",
".",
"tag",
"==",
"'p'",
"and",
"len",
"(",
"self",
".",
"parser",
".",
"getText",
"(",
"current_sibling",
")",
")",
">",... | \
adds any siblings that may have a decent score to this node | [
"\\",
"adds",
"any",
"siblings",
"that",
"may",
"have",
"a",
"decent",
"score",
"to",
"this",
"node"
] | bcbcae3586cb658d9954f440d15419a4683b48b6 | https://github.com/xiaoxu193/PyTeaser/blob/bcbcae3586cb658d9954f440d15419a4683b48b6/goose/extractors.py#L355-L382 |
228,874 | neovim/pynvim | pynvim/msgpack_rpc/event_loop/asyncio.py | AsyncioEventLoop.connection_made | def connection_made(self, transport):
"""Used to signal `asyncio.Protocol` of a successful connection."""
self._transport = transport
self._raw_transport = transport
if isinstance(transport, asyncio.SubprocessTransport):
self._transport = transport.get_pipe_transport(0) | python | def connection_made(self, transport):
self._transport = transport
self._raw_transport = transport
if isinstance(transport, asyncio.SubprocessTransport):
self._transport = transport.get_pipe_transport(0) | [
"def",
"connection_made",
"(",
"self",
",",
"transport",
")",
":",
"self",
".",
"_transport",
"=",
"transport",
"self",
".",
"_raw_transport",
"=",
"transport",
"if",
"isinstance",
"(",
"transport",
",",
"asyncio",
".",
"SubprocessTransport",
")",
":",
"self",... | Used to signal `asyncio.Protocol` of a successful connection. | [
"Used",
"to",
"signal",
"asyncio",
".",
"Protocol",
"of",
"a",
"successful",
"connection",
"."
] | 5e577188e6d7133f597ad0ce60dc6a4b1314064a | https://github.com/neovim/pynvim/blob/5e577188e6d7133f597ad0ce60dc6a4b1314064a/pynvim/msgpack_rpc/event_loop/asyncio.py#L46-L51 |
228,875 | neovim/pynvim | pynvim/msgpack_rpc/event_loop/asyncio.py | AsyncioEventLoop.data_received | def data_received(self, data):
"""Used to signal `asyncio.Protocol` of incoming data."""
if self._on_data:
self._on_data(data)
return
self._queued_data.append(data) | python | def data_received(self, data):
if self._on_data:
self._on_data(data)
return
self._queued_data.append(data) | [
"def",
"data_received",
"(",
"self",
",",
"data",
")",
":",
"if",
"self",
".",
"_on_data",
":",
"self",
".",
"_on_data",
"(",
"data",
")",
"return",
"self",
".",
"_queued_data",
".",
"append",
"(",
"data",
")"
] | Used to signal `asyncio.Protocol` of incoming data. | [
"Used",
"to",
"signal",
"asyncio",
".",
"Protocol",
"of",
"incoming",
"data",
"."
] | 5e577188e6d7133f597ad0ce60dc6a4b1314064a | https://github.com/neovim/pynvim/blob/5e577188e6d7133f597ad0ce60dc6a4b1314064a/pynvim/msgpack_rpc/event_loop/asyncio.py#L57-L62 |
228,876 | neovim/pynvim | pynvim/msgpack_rpc/event_loop/asyncio.py | AsyncioEventLoop.pipe_data_received | def pipe_data_received(self, fd, data):
"""Used to signal `asyncio.SubprocessProtocol` of incoming data."""
if fd == 2: # stderr fd number
self._on_stderr(data)
elif self._on_data:
self._on_data(data)
else:
self._queued_data.append(data) | python | def pipe_data_received(self, fd, data):
if fd == 2: # stderr fd number
self._on_stderr(data)
elif self._on_data:
self._on_data(data)
else:
self._queued_data.append(data) | [
"def",
"pipe_data_received",
"(",
"self",
",",
"fd",
",",
"data",
")",
":",
"if",
"fd",
"==",
"2",
":",
"# stderr fd number",
"self",
".",
"_on_stderr",
"(",
"data",
")",
"elif",
"self",
".",
"_on_data",
":",
"self",
".",
"_on_data",
"(",
"data",
")",
... | Used to signal `asyncio.SubprocessProtocol` of incoming data. | [
"Used",
"to",
"signal",
"asyncio",
".",
"SubprocessProtocol",
"of",
"incoming",
"data",
"."
] | 5e577188e6d7133f597ad0ce60dc6a4b1314064a | https://github.com/neovim/pynvim/blob/5e577188e6d7133f597ad0ce60dc6a4b1314064a/pynvim/msgpack_rpc/event_loop/asyncio.py#L68-L75 |
228,877 | neovim/pynvim | pynvim/util.py | format_exc_skip | def format_exc_skip(skip, limit=None):
"""Like traceback.format_exc but allow skipping the first frames."""
etype, val, tb = sys.exc_info()
for i in range(skip):
tb = tb.tb_next
return (''.join(format_exception(etype, val, tb, limit))).rstrip() | python | def format_exc_skip(skip, limit=None):
etype, val, tb = sys.exc_info()
for i in range(skip):
tb = tb.tb_next
return (''.join(format_exception(etype, val, tb, limit))).rstrip() | [
"def",
"format_exc_skip",
"(",
"skip",
",",
"limit",
"=",
"None",
")",
":",
"etype",
",",
"val",
",",
"tb",
"=",
"sys",
".",
"exc_info",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"skip",
")",
":",
"tb",
"=",
"tb",
".",
"tb_next",
"return",
"(",
... | Like traceback.format_exc but allow skipping the first frames. | [
"Like",
"traceback",
".",
"format_exc",
"but",
"allow",
"skipping",
"the",
"first",
"frames",
"."
] | 5e577188e6d7133f597ad0ce60dc6a4b1314064a | https://github.com/neovim/pynvim/blob/5e577188e6d7133f597ad0ce60dc6a4b1314064a/pynvim/util.py#L7-L12 |
228,878 | neovim/pynvim | pynvim/msgpack_rpc/async_session.py | AsyncSession.request | def request(self, method, args, response_cb):
"""Send a msgpack-rpc request to Nvim.
A msgpack-rpc with method `method` and argument `args` is sent to
Nvim. The `response_cb` function is called with when the response
is available.
"""
request_id = self._next_request_id
self._next_request_id = request_id + 1
self._msgpack_stream.send([0, request_id, method, args])
self._pending_requests[request_id] = response_cb | python | def request(self, method, args, response_cb):
request_id = self._next_request_id
self._next_request_id = request_id + 1
self._msgpack_stream.send([0, request_id, method, args])
self._pending_requests[request_id] = response_cb | [
"def",
"request",
"(",
"self",
",",
"method",
",",
"args",
",",
"response_cb",
")",
":",
"request_id",
"=",
"self",
".",
"_next_request_id",
"self",
".",
"_next_request_id",
"=",
"request_id",
"+",
"1",
"self",
".",
"_msgpack_stream",
".",
"send",
"(",
"["... | Send a msgpack-rpc request to Nvim.
A msgpack-rpc with method `method` and argument `args` is sent to
Nvim. The `response_cb` function is called with when the response
is available. | [
"Send",
"a",
"msgpack",
"-",
"rpc",
"request",
"to",
"Nvim",
"."
] | 5e577188e6d7133f597ad0ce60dc6a4b1314064a | https://github.com/neovim/pynvim/blob/5e577188e6d7133f597ad0ce60dc6a4b1314064a/pynvim/msgpack_rpc/async_session.py#L36-L46 |
228,879 | neovim/pynvim | pynvim/msgpack_rpc/async_session.py | Response.send | def send(self, value, error=False):
"""Send the response.
If `error` is True, it will be sent as an error.
"""
if error:
resp = [1, self._request_id, value, None]
else:
resp = [1, self._request_id, None, value]
debug('sending response to request %d: %s', self._request_id, resp)
self._msgpack_stream.send(resp) | python | def send(self, value, error=False):
if error:
resp = [1, self._request_id, value, None]
else:
resp = [1, self._request_id, None, value]
debug('sending response to request %d: %s', self._request_id, resp)
self._msgpack_stream.send(resp) | [
"def",
"send",
"(",
"self",
",",
"value",
",",
"error",
"=",
"False",
")",
":",
"if",
"error",
":",
"resp",
"=",
"[",
"1",
",",
"self",
".",
"_request_id",
",",
"value",
",",
"None",
"]",
"else",
":",
"resp",
"=",
"[",
"1",
",",
"self",
".",
... | Send the response.
If `error` is True, it will be sent as an error. | [
"Send",
"the",
"response",
"."
] | 5e577188e6d7133f597ad0ce60dc6a4b1314064a | https://github.com/neovim/pynvim/blob/5e577188e6d7133f597ad0ce60dc6a4b1314064a/pynvim/msgpack_rpc/async_session.py#L129-L139 |
228,880 | neovim/pynvim | pynvim/__init__.py | start_host | def start_host(session=None):
"""Promote the current process into python plugin host for Nvim.
Start msgpack-rpc event loop for `session`, listening for Nvim requests
and notifications. It registers Nvim commands for loading/unloading
python plugins.
The sys.stdout and sys.stderr streams are redirected to Nvim through
`session`. That means print statements probably won't work as expected
while this function doesn't return.
This function is normally called at program startup and could have been
defined as a separate executable. It is exposed as a library function for
testing purposes only.
"""
plugins = []
for arg in sys.argv:
_, ext = os.path.splitext(arg)
if ext == '.py':
plugins.append(arg)
elif os.path.isdir(arg):
init = os.path.join(arg, '__init__.py')
if os.path.isfile(init):
plugins.append(arg)
# This is a special case to support the old workaround of
# adding an empty .py file to make a package directory
# visible, and it should be removed soon.
for path in list(plugins):
dup = path + ".py"
if os.path.isdir(path) and dup in plugins:
plugins.remove(dup)
# Special case: the legacy scripthost receives a single relative filename
# while the rplugin host will receive absolute paths.
if plugins == ["script_host.py"]:
name = "script"
else:
name = "rplugin"
setup_logging(name)
if not session:
session = stdio_session()
nvim = Nvim.from_session(session)
if nvim.version.api_level < 1:
sys.stderr.write("This version of pynvim "
"requires nvim 0.1.6 or later")
sys.exit(1)
host = Host(nvim)
host.start(plugins) | python | def start_host(session=None):
plugins = []
for arg in sys.argv:
_, ext = os.path.splitext(arg)
if ext == '.py':
plugins.append(arg)
elif os.path.isdir(arg):
init = os.path.join(arg, '__init__.py')
if os.path.isfile(init):
plugins.append(arg)
# This is a special case to support the old workaround of
# adding an empty .py file to make a package directory
# visible, and it should be removed soon.
for path in list(plugins):
dup = path + ".py"
if os.path.isdir(path) and dup in plugins:
plugins.remove(dup)
# Special case: the legacy scripthost receives a single relative filename
# while the rplugin host will receive absolute paths.
if plugins == ["script_host.py"]:
name = "script"
else:
name = "rplugin"
setup_logging(name)
if not session:
session = stdio_session()
nvim = Nvim.from_session(session)
if nvim.version.api_level < 1:
sys.stderr.write("This version of pynvim "
"requires nvim 0.1.6 or later")
sys.exit(1)
host = Host(nvim)
host.start(plugins) | [
"def",
"start_host",
"(",
"session",
"=",
"None",
")",
":",
"plugins",
"=",
"[",
"]",
"for",
"arg",
"in",
"sys",
".",
"argv",
":",
"_",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"arg",
")",
"if",
"ext",
"==",
"'.py'",
":",
"plug... | Promote the current process into python plugin host for Nvim.
Start msgpack-rpc event loop for `session`, listening for Nvim requests
and notifications. It registers Nvim commands for loading/unloading
python plugins.
The sys.stdout and sys.stderr streams are redirected to Nvim through
`session`. That means print statements probably won't work as expected
while this function doesn't return.
This function is normally called at program startup and could have been
defined as a separate executable. It is exposed as a library function for
testing purposes only. | [
"Promote",
"the",
"current",
"process",
"into",
"python",
"plugin",
"host",
"for",
"Nvim",
"."
] | 5e577188e6d7133f597ad0ce60dc6a4b1314064a | https://github.com/neovim/pynvim/blob/5e577188e6d7133f597ad0ce60dc6a4b1314064a/pynvim/__init__.py#L25-L77 |
228,881 | neovim/pynvim | pynvim/__init__.py | attach | def attach(session_type, address=None, port=None,
path=None, argv=None, decode=None):
"""Provide a nicer interface to create python api sessions.
Previous machinery to create python api sessions is still there. This only
creates a facade function to make things easier for the most usual cases.
Thus, instead of:
from pynvim import socket_session, Nvim
session = tcp_session(address=<address>, port=<port>)
nvim = Nvim.from_session(session)
You can now do:
from pynvim import attach
nvim = attach('tcp', address=<address>, port=<port>)
And also:
nvim = attach('socket', path=<path>)
nvim = attach('child', argv=<argv>)
nvim = attach('stdio')
When the session is not needed anymore, it is recommended to explicitly
close it:
nvim.close()
It is also possible to use the session as a context mangager:
with attach('socket', path=thepath) as nvim:
print(nvim.funcs.getpid())
print(nvim.current.line)
This will automatically close the session when you're done with it, or
when an error occured.
"""
session = (tcp_session(address, port) if session_type == 'tcp' else
socket_session(path) if session_type == 'socket' else
stdio_session() if session_type == 'stdio' else
child_session(argv) if session_type == 'child' else
None)
if not session:
raise Exception('Unknown session type "%s"' % session_type)
if decode is None:
decode = IS_PYTHON3
return Nvim.from_session(session).with_decode(decode) | python | def attach(session_type, address=None, port=None,
path=None, argv=None, decode=None):
session = (tcp_session(address, port) if session_type == 'tcp' else
socket_session(path) if session_type == 'socket' else
stdio_session() if session_type == 'stdio' else
child_session(argv) if session_type == 'child' else
None)
if not session:
raise Exception('Unknown session type "%s"' % session_type)
if decode is None:
decode = IS_PYTHON3
return Nvim.from_session(session).with_decode(decode) | [
"def",
"attach",
"(",
"session_type",
",",
"address",
"=",
"None",
",",
"port",
"=",
"None",
",",
"path",
"=",
"None",
",",
"argv",
"=",
"None",
",",
"decode",
"=",
"None",
")",
":",
"session",
"=",
"(",
"tcp_session",
"(",
"address",
",",
"port",
... | Provide a nicer interface to create python api sessions.
Previous machinery to create python api sessions is still there. This only
creates a facade function to make things easier for the most usual cases.
Thus, instead of:
from pynvim import socket_session, Nvim
session = tcp_session(address=<address>, port=<port>)
nvim = Nvim.from_session(session)
You can now do:
from pynvim import attach
nvim = attach('tcp', address=<address>, port=<port>)
And also:
nvim = attach('socket', path=<path>)
nvim = attach('child', argv=<argv>)
nvim = attach('stdio')
When the session is not needed anymore, it is recommended to explicitly
close it:
nvim.close()
It is also possible to use the session as a context mangager:
with attach('socket', path=thepath) as nvim:
print(nvim.funcs.getpid())
print(nvim.current.line)
This will automatically close the session when you're done with it, or
when an error occured. | [
"Provide",
"a",
"nicer",
"interface",
"to",
"create",
"python",
"api",
"sessions",
"."
] | 5e577188e6d7133f597ad0ce60dc6a4b1314064a | https://github.com/neovim/pynvim/blob/5e577188e6d7133f597ad0ce60dc6a4b1314064a/pynvim/__init__.py#L80-L122 |
228,882 | neovim/pynvim | pynvim/__init__.py | setup_logging | def setup_logging(name):
"""Setup logging according to environment variables."""
logger = logging.getLogger(__name__)
if 'NVIM_PYTHON_LOG_FILE' in os.environ:
prefix = os.environ['NVIM_PYTHON_LOG_FILE'].strip()
major_version = sys.version_info[0]
logfile = '{}_py{}_{}'.format(prefix, major_version, name)
handler = logging.FileHandler(logfile, 'w', 'utf-8')
handler.formatter = logging.Formatter(
'%(asctime)s [%(levelname)s @ '
'%(filename)s:%(funcName)s:%(lineno)s] %(process)s - %(message)s')
logging.root.addHandler(handler)
level = logging.INFO
if 'NVIM_PYTHON_LOG_LEVEL' in os.environ:
lvl = getattr(logging,
os.environ['NVIM_PYTHON_LOG_LEVEL'].strip(),
level)
if isinstance(lvl, int):
level = lvl
logger.setLevel(level) | python | def setup_logging(name):
logger = logging.getLogger(__name__)
if 'NVIM_PYTHON_LOG_FILE' in os.environ:
prefix = os.environ['NVIM_PYTHON_LOG_FILE'].strip()
major_version = sys.version_info[0]
logfile = '{}_py{}_{}'.format(prefix, major_version, name)
handler = logging.FileHandler(logfile, 'w', 'utf-8')
handler.formatter = logging.Formatter(
'%(asctime)s [%(levelname)s @ '
'%(filename)s:%(funcName)s:%(lineno)s] %(process)s - %(message)s')
logging.root.addHandler(handler)
level = logging.INFO
if 'NVIM_PYTHON_LOG_LEVEL' in os.environ:
lvl = getattr(logging,
os.environ['NVIM_PYTHON_LOG_LEVEL'].strip(),
level)
if isinstance(lvl, int):
level = lvl
logger.setLevel(level) | [
"def",
"setup_logging",
"(",
"name",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"if",
"'NVIM_PYTHON_LOG_FILE'",
"in",
"os",
".",
"environ",
":",
"prefix",
"=",
"os",
".",
"environ",
"[",
"'NVIM_PYTHON_LOG_FILE'",
"]",
".",
... | Setup logging according to environment variables. | [
"Setup",
"logging",
"according",
"to",
"environment",
"variables",
"."
] | 5e577188e6d7133f597ad0ce60dc6a4b1314064a | https://github.com/neovim/pynvim/blob/5e577188e6d7133f597ad0ce60dc6a4b1314064a/pynvim/__init__.py#L125-L144 |
228,883 | neovim/pynvim | scripts/logging_statement_modifier.py | main | def main(argv=sys.argv[1:]):
"""Parses the command line comments."""
usage = 'usage: %prog [options] FILE\n\n' + __doc__
parser = OptionParser(usage)
# options
parser.add_option("-f", "--force",
action='store_true', default=False,
help="make changes even if they cannot undone before saving the new file")
parser.add_option("-m", "--min_level",
default='NONE',
help="minimum level of logging statements to modify [default: no minimum]")
parser.add_option("-M", "--max_level",
default='NONE',
help="maximum level of logging statements to modify [default: no maximum]")
parser.add_option("-o", "--output-file",
default=None,
help="where to output the result [default: overwrite the input file]")
parser.add_option("-r", "--restore",
action='store_true', default=False,
help="restore logging statements previously commented out and replaced with pass statements")
parser.add_option("-v", "--verbose",
action='store_true', default=False,
help="print informational messages about changes made")
(options, args) = parser.parse_args(argv)
if len(args) != 1:
parser.error("expected 1 argument but got %d arguments: %s" % (len(args), ' '.join(args)))
input_fn = args[0]
if not options.output_file:
options.output_file = input_fn
# validate min/max level
LEVEL_CHOICES = LEVELS + ['NONE']
min_level_value = 0 if options.min_level == 'NONE' else get_level_value(options.min_level)
if options.min_level is None:
parser.error("min level must be an integer or one of these values: %s" % ', '.join(LEVEL_CHOICES))
max_level_value = sys.maxint if options.max_level == 'NONE' else get_level_value(options.max_level)
if options.max_level is None:
parser.error("max level must be an integer or one of these values: %s" % ', '.join(LEVEL_CHOICES))
if options.verbose:
logging.getLogger().setLevel(logging.INFO)
try:
return modify_logging(input_fn, options.output_file,
min_level_value, max_level_value,
options.restore, options.force)
except IOError as e:
logging.error(str(e))
return -1 | python | def main(argv=sys.argv[1:]):
usage = 'usage: %prog [options] FILE\n\n' + __doc__
parser = OptionParser(usage)
# options
parser.add_option("-f", "--force",
action='store_true', default=False,
help="make changes even if they cannot undone before saving the new file")
parser.add_option("-m", "--min_level",
default='NONE',
help="minimum level of logging statements to modify [default: no minimum]")
parser.add_option("-M", "--max_level",
default='NONE',
help="maximum level of logging statements to modify [default: no maximum]")
parser.add_option("-o", "--output-file",
default=None,
help="where to output the result [default: overwrite the input file]")
parser.add_option("-r", "--restore",
action='store_true', default=False,
help="restore logging statements previously commented out and replaced with pass statements")
parser.add_option("-v", "--verbose",
action='store_true', default=False,
help="print informational messages about changes made")
(options, args) = parser.parse_args(argv)
if len(args) != 1:
parser.error("expected 1 argument but got %d arguments: %s" % (len(args), ' '.join(args)))
input_fn = args[0]
if not options.output_file:
options.output_file = input_fn
# validate min/max level
LEVEL_CHOICES = LEVELS + ['NONE']
min_level_value = 0 if options.min_level == 'NONE' else get_level_value(options.min_level)
if options.min_level is None:
parser.error("min level must be an integer or one of these values: %s" % ', '.join(LEVEL_CHOICES))
max_level_value = sys.maxint if options.max_level == 'NONE' else get_level_value(options.max_level)
if options.max_level is None:
parser.error("max level must be an integer or one of these values: %s" % ', '.join(LEVEL_CHOICES))
if options.verbose:
logging.getLogger().setLevel(logging.INFO)
try:
return modify_logging(input_fn, options.output_file,
min_level_value, max_level_value,
options.restore, options.force)
except IOError as e:
logging.error(str(e))
return -1 | [
"def",
"main",
"(",
"argv",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
")",
":",
"usage",
"=",
"'usage: %prog [options] FILE\\n\\n'",
"+",
"__doc__",
"parser",
"=",
"OptionParser",
"(",
"usage",
")",
"# options",
"parser",
".",
"add_option",
"(",
"\"-f\"... | Parses the command line comments. | [
"Parses",
"the",
"command",
"line",
"comments",
"."
] | 5e577188e6d7133f597ad0ce60dc6a4b1314064a | https://github.com/neovim/pynvim/blob/5e577188e6d7133f597ad0ce60dc6a4b1314064a/scripts/logging_statement_modifier.py#L71-L121 |
228,884 | neovim/pynvim | scripts/logging_statement_modifier.py | comment_lines | def comment_lines(lines):
"""Comment out the given list of lines and return them. The hash mark will
be inserted before the first non-whitespace character on each line."""
ret = []
for line in lines:
ws_prefix, rest, ignore = RE_LINE_SPLITTER_COMMENT.match(line).groups()
ret.append(ws_prefix + '#' + rest)
return ''.join(ret) | python | def comment_lines(lines):
ret = []
for line in lines:
ws_prefix, rest, ignore = RE_LINE_SPLITTER_COMMENT.match(line).groups()
ret.append(ws_prefix + '#' + rest)
return ''.join(ret) | [
"def",
"comment_lines",
"(",
"lines",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"line",
"in",
"lines",
":",
"ws_prefix",
",",
"rest",
",",
"ignore",
"=",
"RE_LINE_SPLITTER_COMMENT",
".",
"match",
"(",
"line",
")",
".",
"groups",
"(",
")",
"ret",
".",
"a... | Comment out the given list of lines and return them. The hash mark will
be inserted before the first non-whitespace character on each line. | [
"Comment",
"out",
"the",
"given",
"list",
"of",
"lines",
"and",
"return",
"them",
".",
"The",
"hash",
"mark",
"will",
"be",
"inserted",
"before",
"the",
"first",
"non",
"-",
"whitespace",
"character",
"on",
"each",
"line",
"."
] | 5e577188e6d7133f597ad0ce60dc6a4b1314064a | https://github.com/neovim/pynvim/blob/5e577188e6d7133f597ad0ce60dc6a4b1314064a/scripts/logging_statement_modifier.py#L125-L132 |
228,885 | neovim/pynvim | scripts/logging_statement_modifier.py | uncomment_lines | def uncomment_lines(lines):
"""Uncomment the given list of lines and return them. The first hash mark
following any amount of whitespace will be removed on each line."""
ret = []
for line in lines:
ws_prefix, rest, ignore = RE_LINE_SPLITTER_UNCOMMENT.match(line).groups()
ret.append(ws_prefix + rest)
return ''.join(ret) | python | def uncomment_lines(lines):
ret = []
for line in lines:
ws_prefix, rest, ignore = RE_LINE_SPLITTER_UNCOMMENT.match(line).groups()
ret.append(ws_prefix + rest)
return ''.join(ret) | [
"def",
"uncomment_lines",
"(",
"lines",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"line",
"in",
"lines",
":",
"ws_prefix",
",",
"rest",
",",
"ignore",
"=",
"RE_LINE_SPLITTER_UNCOMMENT",
".",
"match",
"(",
"line",
")",
".",
"groups",
"(",
")",
"ret",
".",
... | Uncomment the given list of lines and return them. The first hash mark
following any amount of whitespace will be removed on each line. | [
"Uncomment",
"the",
"given",
"list",
"of",
"lines",
"and",
"return",
"them",
".",
"The",
"first",
"hash",
"mark",
"following",
"any",
"amount",
"of",
"whitespace",
"will",
"be",
"removed",
"on",
"each",
"line",
"."
] | 5e577188e6d7133f597ad0ce60dc6a4b1314064a | https://github.com/neovim/pynvim/blob/5e577188e6d7133f597ad0ce60dc6a4b1314064a/scripts/logging_statement_modifier.py#L136-L143 |
228,886 | neovim/pynvim | scripts/logging_statement_modifier.py | get_level_value | def get_level_value(level):
"""Returns the logging value associated with a particular level name. The
argument must be present in LEVELS_DICT or be an integer constant.
Otherwise None will be returned."""
try:
# integral constants also work: they are the level value
return int(level)
except ValueError:
try:
return LEVELS_DICT[level.upper()]
except KeyError:
logging.warning("level '%s' cannot be translated to a level value (not present in LEVELS_DICT)" % level)
return None | python | def get_level_value(level):
try:
# integral constants also work: they are the level value
return int(level)
except ValueError:
try:
return LEVELS_DICT[level.upper()]
except KeyError:
logging.warning("level '%s' cannot be translated to a level value (not present in LEVELS_DICT)" % level)
return None | [
"def",
"get_level_value",
"(",
"level",
")",
":",
"try",
":",
"# integral constants also work: they are the level value",
"return",
"int",
"(",
"level",
")",
"except",
"ValueError",
":",
"try",
":",
"return",
"LEVELS_DICT",
"[",
"level",
".",
"upper",
"(",
")",
... | Returns the logging value associated with a particular level name. The
argument must be present in LEVELS_DICT or be an integer constant.
Otherwise None will be returned. | [
"Returns",
"the",
"logging",
"value",
"associated",
"with",
"a",
"particular",
"level",
"name",
".",
"The",
"argument",
"must",
"be",
"present",
"in",
"LEVELS_DICT",
"or",
"be",
"an",
"integer",
"constant",
".",
"Otherwise",
"None",
"will",
"be",
"returned",
... | 5e577188e6d7133f597ad0ce60dc6a4b1314064a | https://github.com/neovim/pynvim/blob/5e577188e6d7133f597ad0ce60dc6a4b1314064a/scripts/logging_statement_modifier.py#L158-L170 |
228,887 | neovim/pynvim | scripts/logging_statement_modifier.py | get_logging_level | def get_logging_level(logging_stmt, commented_out=False):
"""Determines the level of logging in a given logging statement. The string
representing this level is returned. False is returned if the method is
not a logging statement and thus has no level. None is returned if a level
should have been found but wasn't."""
regexp = RE_LOGGING_START_IN_COMMENT if commented_out else RE_LOGGING_START
ret = regexp.match(logging_stmt)
_, method_name, _, first_arg = ret.groups()
if method_name not in LOGGING_METHODS_OF_INTEREST:
logging.debug('skipping uninteresting logging call: %s' % method_name)
return False
if method_name != 'log':
return method_name
# if the method name did not specify the level, we must have a first_arg to extract the level from
if not first_arg:
logging.warning("logging.log statement found but we couldn't extract the first argument")
return None
# extract the level of logging from the first argument to the log() call
level = first_arg_to_level_name(first_arg)
if level is None:
logging.warning("arg does not contain any known level '%s'\n" % first_arg)
return None
return level | python | def get_logging_level(logging_stmt, commented_out=False):
regexp = RE_LOGGING_START_IN_COMMENT if commented_out else RE_LOGGING_START
ret = regexp.match(logging_stmt)
_, method_name, _, first_arg = ret.groups()
if method_name not in LOGGING_METHODS_OF_INTEREST:
logging.debug('skipping uninteresting logging call: %s' % method_name)
return False
if method_name != 'log':
return method_name
# if the method name did not specify the level, we must have a first_arg to extract the level from
if not first_arg:
logging.warning("logging.log statement found but we couldn't extract the first argument")
return None
# extract the level of logging from the first argument to the log() call
level = first_arg_to_level_name(first_arg)
if level is None:
logging.warning("arg does not contain any known level '%s'\n" % first_arg)
return None
return level | [
"def",
"get_logging_level",
"(",
"logging_stmt",
",",
"commented_out",
"=",
"False",
")",
":",
"regexp",
"=",
"RE_LOGGING_START_IN_COMMENT",
"if",
"commented_out",
"else",
"RE_LOGGING_START",
"ret",
"=",
"regexp",
".",
"match",
"(",
"logging_stmt",
")",
"_",
",",
... | Determines the level of logging in a given logging statement. The string
representing this level is returned. False is returned if the method is
not a logging statement and thus has no level. None is returned if a level
should have been found but wasn't. | [
"Determines",
"the",
"level",
"of",
"logging",
"in",
"a",
"given",
"logging",
"statement",
".",
"The",
"string",
"representing",
"this",
"level",
"is",
"returned",
".",
"False",
"is",
"returned",
"if",
"the",
"method",
"is",
"not",
"a",
"logging",
"statement... | 5e577188e6d7133f597ad0ce60dc6a4b1314064a | https://github.com/neovim/pynvim/blob/5e577188e6d7133f597ad0ce60dc6a4b1314064a/scripts/logging_statement_modifier.py#L172-L197 |
228,888 | neovim/pynvim | scripts/logging_statement_modifier.py | level_is_between | def level_is_between(level, min_level_value, max_level_value):
"""Returns True if level is between the specified min or max, inclusive."""
level_value = get_level_value(level)
if level_value is None:
# unknown level value
return False
return level_value >= min_level_value and level_value <= max_level_value | python | def level_is_between(level, min_level_value, max_level_value):
level_value = get_level_value(level)
if level_value is None:
# unknown level value
return False
return level_value >= min_level_value and level_value <= max_level_value | [
"def",
"level_is_between",
"(",
"level",
",",
"min_level_value",
",",
"max_level_value",
")",
":",
"level_value",
"=",
"get_level_value",
"(",
"level",
")",
"if",
"level_value",
"is",
"None",
":",
"# unknown level value",
"return",
"False",
"return",
"level_value",
... | Returns True if level is between the specified min or max, inclusive. | [
"Returns",
"True",
"if",
"level",
"is",
"between",
"the",
"specified",
"min",
"or",
"max",
"inclusive",
"."
] | 5e577188e6d7133f597ad0ce60dc6a4b1314064a | https://github.com/neovim/pynvim/blob/5e577188e6d7133f597ad0ce60dc6a4b1314064a/scripts/logging_statement_modifier.py#L199-L205 |
228,889 | neovim/pynvim | scripts/logging_statement_modifier.py | split_call | def split_call(lines, open_paren_line=0):
"""Returns a 2-tuple where the first element is the list of lines from the
first open paren in lines to the matching closed paren. The second element
is all remaining lines in a list."""
num_open = 0
num_closed = 0
for i, line in enumerate(lines):
c = line.count('(')
num_open += c
if not c and i==open_paren_line:
raise Exception('Exception open parenthesis in line %d but there is not one there: %s' % (i, str(lines)))
num_closed += line.count(')')
if num_open == num_closed:
return (lines[:i+1], lines[i+1:])
print(''.join(lines))
raise Exception('parenthesis are mismatched (%d open, %d closed found)' % (num_open, num_closed)) | python | def split_call(lines, open_paren_line=0):
num_open = 0
num_closed = 0
for i, line in enumerate(lines):
c = line.count('(')
num_open += c
if not c and i==open_paren_line:
raise Exception('Exception open parenthesis in line %d but there is not one there: %s' % (i, str(lines)))
num_closed += line.count(')')
if num_open == num_closed:
return (lines[:i+1], lines[i+1:])
print(''.join(lines))
raise Exception('parenthesis are mismatched (%d open, %d closed found)' % (num_open, num_closed)) | [
"def",
"split_call",
"(",
"lines",
",",
"open_paren_line",
"=",
"0",
")",
":",
"num_open",
"=",
"0",
"num_closed",
"=",
"0",
"for",
"i",
",",
"line",
"in",
"enumerate",
"(",
"lines",
")",
":",
"c",
"=",
"line",
".",
"count",
"(",
"'('",
")",
"num_o... | Returns a 2-tuple where the first element is the list of lines from the
first open paren in lines to the matching closed paren. The second element
is all remaining lines in a list. | [
"Returns",
"a",
"2",
"-",
"tuple",
"where",
"the",
"first",
"element",
"is",
"the",
"list",
"of",
"lines",
"from",
"the",
"first",
"open",
"paren",
"in",
"lines",
"to",
"the",
"matching",
"closed",
"paren",
".",
"The",
"second",
"element",
"is",
"all",
... | 5e577188e6d7133f597ad0ce60dc6a4b1314064a | https://github.com/neovim/pynvim/blob/5e577188e6d7133f597ad0ce60dc6a4b1314064a/scripts/logging_statement_modifier.py#L207-L224 |
228,890 | neovim/pynvim | scripts/logging_statement_modifier.py | modify_logging | def modify_logging(input_fn, output_fn, min_level_value, max_level_value, restore, force):
"""Modifies logging statements in the specified file."""
# read in all the lines
logging.info('reading in %s' % input_fn)
fh = open(input_fn, 'r')
lines = fh.readlines()
fh.close()
original_contents = ''.join(lines)
if restore:
forwards = restore_logging
backwards = disable_logging
else:
forwards = disable_logging
backwards = restore_logging
# apply the requested action
new_contents = forwards(lines, min_level_value, max_level_value)
# quietly check to see if we can undo what we just did (if not, the text
# contains something we cannot translate [bug or limitation with this code])
logging.disable(logging.CRITICAL)
new_contents_undone = backwards(new_contents.splitlines(True), min_level_value, max_level_value)
logging.disable(logging.DEBUG)
if original_contents != new_contents_undone:
base_str = 'We are unable to revert this action as expected'
if force:
logging.warning(base_str + " but -f was specified so we'll do it anyway.")
else:
logging.error(base_str + ', so we will not do it in the first place. Pass -f to override this and make the change anyway.')
return -1
logging.info('writing the new contents to %s' % output_fn)
fh = open(output_fn, 'w')
fh.write(new_contents)
fh.close()
logging.info('done!')
return 0 | python | def modify_logging(input_fn, output_fn, min_level_value, max_level_value, restore, force):
# read in all the lines
logging.info('reading in %s' % input_fn)
fh = open(input_fn, 'r')
lines = fh.readlines()
fh.close()
original_contents = ''.join(lines)
if restore:
forwards = restore_logging
backwards = disable_logging
else:
forwards = disable_logging
backwards = restore_logging
# apply the requested action
new_contents = forwards(lines, min_level_value, max_level_value)
# quietly check to see if we can undo what we just did (if not, the text
# contains something we cannot translate [bug or limitation with this code])
logging.disable(logging.CRITICAL)
new_contents_undone = backwards(new_contents.splitlines(True), min_level_value, max_level_value)
logging.disable(logging.DEBUG)
if original_contents != new_contents_undone:
base_str = 'We are unable to revert this action as expected'
if force:
logging.warning(base_str + " but -f was specified so we'll do it anyway.")
else:
logging.error(base_str + ', so we will not do it in the first place. Pass -f to override this and make the change anyway.')
return -1
logging.info('writing the new contents to %s' % output_fn)
fh = open(output_fn, 'w')
fh.write(new_contents)
fh.close()
logging.info('done!')
return 0 | [
"def",
"modify_logging",
"(",
"input_fn",
",",
"output_fn",
",",
"min_level_value",
",",
"max_level_value",
",",
"restore",
",",
"force",
")",
":",
"# read in all the lines",
"logging",
".",
"info",
"(",
"'reading in %s'",
"%",
"input_fn",
")",
"fh",
"=",
"open"... | Modifies logging statements in the specified file. | [
"Modifies",
"logging",
"statements",
"in",
"the",
"specified",
"file",
"."
] | 5e577188e6d7133f597ad0ce60dc6a4b1314064a | https://github.com/neovim/pynvim/blob/5e577188e6d7133f597ad0ce60dc6a4b1314064a/scripts/logging_statement_modifier.py#L226-L263 |
228,891 | neovim/pynvim | scripts/logging_statement_modifier.py | check_level | def check_level(logging_stmt, logging_stmt_is_commented_out, min_level_value, max_level_value):
"""Extracts the level of the logging statement and returns True if the
level falls betwen min and max_level_value. If the level cannot be
extracted, then a warning is logged."""
level = get_logging_level(logging_stmt, logging_stmt_is_commented_out)
if level is None:
logging.warning('skipping logging statement because the level could not be extracted: %s' % logging_stmt.strip())
return False
elif level is False:
return False
elif level_is_between(level, min_level_value, max_level_value):
return True
else:
logging.debug('keep this one as is (not in the specified level range): %s' % logging_stmt.strip())
return False | python | def check_level(logging_stmt, logging_stmt_is_commented_out, min_level_value, max_level_value):
level = get_logging_level(logging_stmt, logging_stmt_is_commented_out)
if level is None:
logging.warning('skipping logging statement because the level could not be extracted: %s' % logging_stmt.strip())
return False
elif level is False:
return False
elif level_is_between(level, min_level_value, max_level_value):
return True
else:
logging.debug('keep this one as is (not in the specified level range): %s' % logging_stmt.strip())
return False | [
"def",
"check_level",
"(",
"logging_stmt",
",",
"logging_stmt_is_commented_out",
",",
"min_level_value",
",",
"max_level_value",
")",
":",
"level",
"=",
"get_logging_level",
"(",
"logging_stmt",
",",
"logging_stmt_is_commented_out",
")",
"if",
"level",
"is",
"None",
"... | Extracts the level of the logging statement and returns True if the
level falls betwen min and max_level_value. If the level cannot be
extracted, then a warning is logged. | [
"Extracts",
"the",
"level",
"of",
"the",
"logging",
"statement",
"and",
"returns",
"True",
"if",
"the",
"level",
"falls",
"betwen",
"min",
"and",
"max_level_value",
".",
"If",
"the",
"level",
"cannot",
"be",
"extracted",
"then",
"a",
"warning",
"is",
"logged... | 5e577188e6d7133f597ad0ce60dc6a4b1314064a | https://github.com/neovim/pynvim/blob/5e577188e6d7133f597ad0ce60dc6a4b1314064a/scripts/logging_statement_modifier.py#L265-L279 |
228,892 | neovim/pynvim | scripts/logging_statement_modifier.py | disable_logging | def disable_logging(lines, min_level_value, max_level_value):
"""Disables logging statements in these lines whose logging level falls
between the specified minimum and maximum levels."""
output = ''
while lines:
line = lines[0]
ret = RE_LOGGING_START.match(line)
if not ret:
# no logging statement here, so just leave the line as-is and keep going
output += line
lines = lines[1:]
else:
# a logging call has started: find all the lines it includes and those it does not
logging_lines, remaining_lines = split_call(lines)
lines = remaining_lines
logging_stmt = ''.join(logging_lines)
# replace the logging statement if its level falls b/w min and max
if not check_level(logging_stmt, False, min_level_value, max_level_value):
output += logging_stmt
else:
# comment out this logging statement and replace it with pass
prefix_ws = ret.group(1)
pass_stmt = prefix_ws + PASS_LINE_CONTENTS
commented_out_logging_lines = comment_lines(logging_lines)
new_lines = pass_stmt + commented_out_logging_lines
logging.info('replacing:\n%s\nwith this:\n%s' % (logging_stmt.rstrip(), new_lines.rstrip()))
output += new_lines
return output | python | def disable_logging(lines, min_level_value, max_level_value):
output = ''
while lines:
line = lines[0]
ret = RE_LOGGING_START.match(line)
if not ret:
# no logging statement here, so just leave the line as-is and keep going
output += line
lines = lines[1:]
else:
# a logging call has started: find all the lines it includes and those it does not
logging_lines, remaining_lines = split_call(lines)
lines = remaining_lines
logging_stmt = ''.join(logging_lines)
# replace the logging statement if its level falls b/w min and max
if not check_level(logging_stmt, False, min_level_value, max_level_value):
output += logging_stmt
else:
# comment out this logging statement and replace it with pass
prefix_ws = ret.group(1)
pass_stmt = prefix_ws + PASS_LINE_CONTENTS
commented_out_logging_lines = comment_lines(logging_lines)
new_lines = pass_stmt + commented_out_logging_lines
logging.info('replacing:\n%s\nwith this:\n%s' % (logging_stmt.rstrip(), new_lines.rstrip()))
output += new_lines
return output | [
"def",
"disable_logging",
"(",
"lines",
",",
"min_level_value",
",",
"max_level_value",
")",
":",
"output",
"=",
"''",
"while",
"lines",
":",
"line",
"=",
"lines",
"[",
"0",
"]",
"ret",
"=",
"RE_LOGGING_START",
".",
"match",
"(",
"line",
")",
"if",
"not"... | Disables logging statements in these lines whose logging level falls
between the specified minimum and maximum levels. | [
"Disables",
"logging",
"statements",
"in",
"these",
"lines",
"whose",
"logging",
"level",
"falls",
"between",
"the",
"specified",
"minimum",
"and",
"maximum",
"levels",
"."
] | 5e577188e6d7133f597ad0ce60dc6a4b1314064a | https://github.com/neovim/pynvim/blob/5e577188e6d7133f597ad0ce60dc6a4b1314064a/scripts/logging_statement_modifier.py#L281-L309 |
228,893 | neovim/pynvim | pynvim/compat.py | check_async | def check_async(async_, kwargs, default):
"""Return a value of 'async' in kwargs or default when async_ is None.
This helper function exists for backward compatibility (See #274).
It shows a warning message when 'async' in kwargs is used to note users.
"""
if async_ is not None:
return async_
elif 'async' in kwargs:
warnings.warn(
'"async" attribute is deprecated. Use "async_" instead.',
DeprecationWarning,
)
return kwargs.pop('async')
else:
return default | python | def check_async(async_, kwargs, default):
if async_ is not None:
return async_
elif 'async' in kwargs:
warnings.warn(
'"async" attribute is deprecated. Use "async_" instead.',
DeprecationWarning,
)
return kwargs.pop('async')
else:
return default | [
"def",
"check_async",
"(",
"async_",
",",
"kwargs",
",",
"default",
")",
":",
"if",
"async_",
"is",
"not",
"None",
":",
"return",
"async_",
"elif",
"'async'",
"in",
"kwargs",
":",
"warnings",
".",
"warn",
"(",
"'\"async\" attribute is deprecated. Use \"async_\" ... | Return a value of 'async' in kwargs or default when async_ is None.
This helper function exists for backward compatibility (See #274).
It shows a warning message when 'async' in kwargs is used to note users. | [
"Return",
"a",
"value",
"of",
"async",
"in",
"kwargs",
"or",
"default",
"when",
"async_",
"is",
"None",
"."
] | 5e577188e6d7133f597ad0ce60dc6a4b1314064a | https://github.com/neovim/pynvim/blob/5e577188e6d7133f597ad0ce60dc6a4b1314064a/pynvim/compat.py#L42-L57 |
228,894 | neovim/pynvim | pynvim/plugin/decorators.py | plugin | def plugin(cls):
"""Tag a class as a plugin.
This decorator is required to make the class methods discoverable by the
plugin_load method of the host.
"""
cls._nvim_plugin = True
# the _nvim_bind attribute is set to True by default, meaning that
# decorated functions have a bound Nvim instance as first argument.
# For methods in a plugin-decorated class this is not required, because
# the class initializer will already receive the nvim object.
predicate = lambda fn: hasattr(fn, '_nvim_bind')
for _, fn in inspect.getmembers(cls, predicate):
if IS_PYTHON3:
fn._nvim_bind = False
else:
fn.im_func._nvim_bind = False
return cls | python | def plugin(cls):
cls._nvim_plugin = True
# the _nvim_bind attribute is set to True by default, meaning that
# decorated functions have a bound Nvim instance as first argument.
# For methods in a plugin-decorated class this is not required, because
# the class initializer will already receive the nvim object.
predicate = lambda fn: hasattr(fn, '_nvim_bind')
for _, fn in inspect.getmembers(cls, predicate):
if IS_PYTHON3:
fn._nvim_bind = False
else:
fn.im_func._nvim_bind = False
return cls | [
"def",
"plugin",
"(",
"cls",
")",
":",
"cls",
".",
"_nvim_plugin",
"=",
"True",
"# the _nvim_bind attribute is set to True by default, meaning that",
"# decorated functions have a bound Nvim instance as first argument.",
"# For methods in a plugin-decorated class this is not required, beca... | Tag a class as a plugin.
This decorator is required to make the class methods discoverable by the
plugin_load method of the host. | [
"Tag",
"a",
"class",
"as",
"a",
"plugin",
"."
] | 5e577188e6d7133f597ad0ce60dc6a4b1314064a | https://github.com/neovim/pynvim/blob/5e577188e6d7133f597ad0ce60dc6a4b1314064a/pynvim/plugin/decorators.py#L14-L31 |
228,895 | neovim/pynvim | pynvim/plugin/decorators.py | rpc_export | def rpc_export(rpc_method_name, sync=False):
"""Export a function or plugin method as a msgpack-rpc request handler."""
def dec(f):
f._nvim_rpc_method_name = rpc_method_name
f._nvim_rpc_sync = sync
f._nvim_bind = True
f._nvim_prefix_plugin_path = False
return f
return dec | python | def rpc_export(rpc_method_name, sync=False):
def dec(f):
f._nvim_rpc_method_name = rpc_method_name
f._nvim_rpc_sync = sync
f._nvim_bind = True
f._nvim_prefix_plugin_path = False
return f
return dec | [
"def",
"rpc_export",
"(",
"rpc_method_name",
",",
"sync",
"=",
"False",
")",
":",
"def",
"dec",
"(",
"f",
")",
":",
"f",
".",
"_nvim_rpc_method_name",
"=",
"rpc_method_name",
"f",
".",
"_nvim_rpc_sync",
"=",
"sync",
"f",
".",
"_nvim_bind",
"=",
"True",
"... | Export a function or plugin method as a msgpack-rpc request handler. | [
"Export",
"a",
"function",
"or",
"plugin",
"method",
"as",
"a",
"msgpack",
"-",
"rpc",
"request",
"handler",
"."
] | 5e577188e6d7133f597ad0ce60dc6a4b1314064a | https://github.com/neovim/pynvim/blob/5e577188e6d7133f597ad0ce60dc6a4b1314064a/pynvim/plugin/decorators.py#L34-L42 |
228,896 | neovim/pynvim | pynvim/plugin/decorators.py | command | def command(name, nargs=0, complete=None, range=None, count=None, bang=False,
register=False, sync=False, allow_nested=False, eval=None):
"""Tag a function or plugin method as a Nvim command handler."""
def dec(f):
f._nvim_rpc_method_name = 'command:{}'.format(name)
f._nvim_rpc_sync = sync
f._nvim_bind = True
f._nvim_prefix_plugin_path = True
opts = {}
if range is not None:
opts['range'] = '' if range is True else str(range)
elif count is not None:
opts['count'] = count
if bang:
opts['bang'] = ''
if register:
opts['register'] = ''
if nargs:
opts['nargs'] = nargs
if complete:
opts['complete'] = complete
if eval:
opts['eval'] = eval
if not sync and allow_nested:
rpc_sync = "urgent"
else:
rpc_sync = sync
f._nvim_rpc_spec = {
'type': 'command',
'name': name,
'sync': rpc_sync,
'opts': opts
}
return f
return dec | python | def command(name, nargs=0, complete=None, range=None, count=None, bang=False,
register=False, sync=False, allow_nested=False, eval=None):
def dec(f):
f._nvim_rpc_method_name = 'command:{}'.format(name)
f._nvim_rpc_sync = sync
f._nvim_bind = True
f._nvim_prefix_plugin_path = True
opts = {}
if range is not None:
opts['range'] = '' if range is True else str(range)
elif count is not None:
opts['count'] = count
if bang:
opts['bang'] = ''
if register:
opts['register'] = ''
if nargs:
opts['nargs'] = nargs
if complete:
opts['complete'] = complete
if eval:
opts['eval'] = eval
if not sync and allow_nested:
rpc_sync = "urgent"
else:
rpc_sync = sync
f._nvim_rpc_spec = {
'type': 'command',
'name': name,
'sync': rpc_sync,
'opts': opts
}
return f
return dec | [
"def",
"command",
"(",
"name",
",",
"nargs",
"=",
"0",
",",
"complete",
"=",
"None",
",",
"range",
"=",
"None",
",",
"count",
"=",
"None",
",",
"bang",
"=",
"False",
",",
"register",
"=",
"False",
",",
"sync",
"=",
"False",
",",
"allow_nested",
"="... | Tag a function or plugin method as a Nvim command handler. | [
"Tag",
"a",
"function",
"or",
"plugin",
"method",
"as",
"a",
"Nvim",
"command",
"handler",
"."
] | 5e577188e6d7133f597ad0ce60dc6a4b1314064a | https://github.com/neovim/pynvim/blob/5e577188e6d7133f597ad0ce60dc6a4b1314064a/pynvim/plugin/decorators.py#L45-L88 |
228,897 | neovim/pynvim | pynvim/plugin/decorators.py | autocmd | def autocmd(name, pattern='*', sync=False, allow_nested=False, eval=None):
"""Tag a function or plugin method as a Nvim autocommand handler."""
def dec(f):
f._nvim_rpc_method_name = 'autocmd:{}:{}'.format(name, pattern)
f._nvim_rpc_sync = sync
f._nvim_bind = True
f._nvim_prefix_plugin_path = True
opts = {
'pattern': pattern
}
if eval:
opts['eval'] = eval
if not sync and allow_nested:
rpc_sync = "urgent"
else:
rpc_sync = sync
f._nvim_rpc_spec = {
'type': 'autocmd',
'name': name,
'sync': rpc_sync,
'opts': opts
}
return f
return dec | python | def autocmd(name, pattern='*', sync=False, allow_nested=False, eval=None):
def dec(f):
f._nvim_rpc_method_name = 'autocmd:{}:{}'.format(name, pattern)
f._nvim_rpc_sync = sync
f._nvim_bind = True
f._nvim_prefix_plugin_path = True
opts = {
'pattern': pattern
}
if eval:
opts['eval'] = eval
if not sync and allow_nested:
rpc_sync = "urgent"
else:
rpc_sync = sync
f._nvim_rpc_spec = {
'type': 'autocmd',
'name': name,
'sync': rpc_sync,
'opts': opts
}
return f
return dec | [
"def",
"autocmd",
"(",
"name",
",",
"pattern",
"=",
"'*'",
",",
"sync",
"=",
"False",
",",
"allow_nested",
"=",
"False",
",",
"eval",
"=",
"None",
")",
":",
"def",
"dec",
"(",
"f",
")",
":",
"f",
".",
"_nvim_rpc_method_name",
"=",
"'autocmd:{}:{}'",
... | Tag a function or plugin method as a Nvim autocommand handler. | [
"Tag",
"a",
"function",
"or",
"plugin",
"method",
"as",
"a",
"Nvim",
"autocommand",
"handler",
"."
] | 5e577188e6d7133f597ad0ce60dc6a4b1314064a | https://github.com/neovim/pynvim/blob/5e577188e6d7133f597ad0ce60dc6a4b1314064a/pynvim/plugin/decorators.py#L91-L118 |
228,898 | neovim/pynvim | pynvim/plugin/decorators.py | function | def function(name, range=False, sync=False, allow_nested=False, eval=None):
"""Tag a function or plugin method as a Nvim function handler."""
def dec(f):
f._nvim_rpc_method_name = 'function:{}'.format(name)
f._nvim_rpc_sync = sync
f._nvim_bind = True
f._nvim_prefix_plugin_path = True
opts = {}
if range:
opts['range'] = '' if range is True else str(range)
if eval:
opts['eval'] = eval
if not sync and allow_nested:
rpc_sync = "urgent"
else:
rpc_sync = sync
f._nvim_rpc_spec = {
'type': 'function',
'name': name,
'sync': rpc_sync,
'opts': opts
}
return f
return dec | python | def function(name, range=False, sync=False, allow_nested=False, eval=None):
def dec(f):
f._nvim_rpc_method_name = 'function:{}'.format(name)
f._nvim_rpc_sync = sync
f._nvim_bind = True
f._nvim_prefix_plugin_path = True
opts = {}
if range:
opts['range'] = '' if range is True else str(range)
if eval:
opts['eval'] = eval
if not sync and allow_nested:
rpc_sync = "urgent"
else:
rpc_sync = sync
f._nvim_rpc_spec = {
'type': 'function',
'name': name,
'sync': rpc_sync,
'opts': opts
}
return f
return dec | [
"def",
"function",
"(",
"name",
",",
"range",
"=",
"False",
",",
"sync",
"=",
"False",
",",
"allow_nested",
"=",
"False",
",",
"eval",
"=",
"None",
")",
":",
"def",
"dec",
"(",
"f",
")",
":",
"f",
".",
"_nvim_rpc_method_name",
"=",
"'function:{}'",
"... | Tag a function or plugin method as a Nvim function handler. | [
"Tag",
"a",
"function",
"or",
"plugin",
"method",
"as",
"a",
"Nvim",
"function",
"handler",
"."
] | 5e577188e6d7133f597ad0ce60dc6a4b1314064a | https://github.com/neovim/pynvim/blob/5e577188e6d7133f597ad0ce60dc6a4b1314064a/pynvim/plugin/decorators.py#L121-L149 |
228,899 | neovim/pynvim | pynvim/api/nvim.py | Nvim.from_session | def from_session(cls, session):
"""Create a new Nvim instance for a Session instance.
This method must be called to create the first Nvim instance, since it
queries Nvim metadata for type information and sets a SessionHook for
creating specialized objects from Nvim remote handles.
"""
session.error_wrapper = lambda e: NvimError(e[1])
channel_id, metadata = session.request(b'vim_get_api_info')
if IS_PYTHON3:
# decode all metadata strings for python3
metadata = walk(decode_if_bytes, metadata)
types = {
metadata['types']['Buffer']['id']: Buffer,
metadata['types']['Window']['id']: Window,
metadata['types']['Tabpage']['id']: Tabpage,
}
return cls(session, channel_id, metadata, types) | python | def from_session(cls, session):
session.error_wrapper = lambda e: NvimError(e[1])
channel_id, metadata = session.request(b'vim_get_api_info')
if IS_PYTHON3:
# decode all metadata strings for python3
metadata = walk(decode_if_bytes, metadata)
types = {
metadata['types']['Buffer']['id']: Buffer,
metadata['types']['Window']['id']: Window,
metadata['types']['Tabpage']['id']: Tabpage,
}
return cls(session, channel_id, metadata, types) | [
"def",
"from_session",
"(",
"cls",
",",
"session",
")",
":",
"session",
".",
"error_wrapper",
"=",
"lambda",
"e",
":",
"NvimError",
"(",
"e",
"[",
"1",
"]",
")",
"channel_id",
",",
"metadata",
"=",
"session",
".",
"request",
"(",
"b'vim_get_api_info'",
"... | Create a new Nvim instance for a Session instance.
This method must be called to create the first Nvim instance, since it
queries Nvim metadata for type information and sets a SessionHook for
creating specialized objects from Nvim remote handles. | [
"Create",
"a",
"new",
"Nvim",
"instance",
"for",
"a",
"Session",
"instance",
"."
] | 5e577188e6d7133f597ad0ce60dc6a4b1314064a | https://github.com/neovim/pynvim/blob/5e577188e6d7133f597ad0ce60dc6a4b1314064a/pynvim/api/nvim.py#L72-L92 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.