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 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
Microsoft/knack | knack/commands.py | CLICommandsLoader.load_command_table | def load_command_table(self, args): # pylint: disable=unused-argument
""" Load commands into the command table
:param args: List of the arguments from the command line
:type args: list
:return: The ordered command table
:rtype: collections.OrderedDict
"""
self.cli_ctx.raise_event(EVENT_CMDLOADER_LOAD_COMMAND_TABLE, cmd_tbl=self.command_table)
return OrderedDict(self.command_table) | python | def load_command_table(self, args): # pylint: disable=unused-argument
""" Load commands into the command table
:param args: List of the arguments from the command line
:type args: list
:return: The ordered command table
:rtype: collections.OrderedDict
"""
self.cli_ctx.raise_event(EVENT_CMDLOADER_LOAD_COMMAND_TABLE, cmd_tbl=self.command_table)
return OrderedDict(self.command_table) | [
"def",
"load_command_table",
"(",
"self",
",",
"args",
")",
":",
"# pylint: disable=unused-argument",
"self",
".",
"cli_ctx",
".",
"raise_event",
"(",
"EVENT_CMDLOADER_LOAD_COMMAND_TABLE",
",",
"cmd_tbl",
"=",
"self",
".",
"command_table",
")",
"return",
"OrderedDict"... | Load commands into the command table
:param args: List of the arguments from the command line
:type args: list
:return: The ordered command table
:rtype: collections.OrderedDict | [
"Load",
"commands",
"into",
"the",
"command",
"table"
] | 5f1a480a33f103e2688c46eef59fb2d9eaf2baad | https://github.com/Microsoft/knack/blob/5f1a480a33f103e2688c46eef59fb2d9eaf2baad/knack/commands.py#L189-L198 | train | 224,200 |
Microsoft/knack | knack/commands.py | CLICommandsLoader.load_arguments | def load_arguments(self, command):
""" Load the arguments for the specified command
:param command: The command to load arguments for
:type command: str
"""
from knack.arguments import ArgumentsContext
self.cli_ctx.raise_event(EVENT_CMDLOADER_LOAD_ARGUMENTS, cmd_tbl=self.command_table, command=command)
try:
self.command_table[command].load_arguments()
except KeyError:
return
# ensure global 'cmd' is ignored
with ArgumentsContext(self, '') as c:
c.ignore('cmd')
self._apply_parameter_info(command, self.command_table[command]) | python | def load_arguments(self, command):
""" Load the arguments for the specified command
:param command: The command to load arguments for
:type command: str
"""
from knack.arguments import ArgumentsContext
self.cli_ctx.raise_event(EVENT_CMDLOADER_LOAD_ARGUMENTS, cmd_tbl=self.command_table, command=command)
try:
self.command_table[command].load_arguments()
except KeyError:
return
# ensure global 'cmd' is ignored
with ArgumentsContext(self, '') as c:
c.ignore('cmd')
self._apply_parameter_info(command, self.command_table[command]) | [
"def",
"load_arguments",
"(",
"self",
",",
"command",
")",
":",
"from",
"knack",
".",
"arguments",
"import",
"ArgumentsContext",
"self",
".",
"cli_ctx",
".",
"raise_event",
"(",
"EVENT_CMDLOADER_LOAD_ARGUMENTS",
",",
"cmd_tbl",
"=",
"self",
".",
"command_table",
... | Load the arguments for the specified command
:param command: The command to load arguments for
:type command: str | [
"Load",
"the",
"arguments",
"for",
"the",
"specified",
"command"
] | 5f1a480a33f103e2688c46eef59fb2d9eaf2baad | https://github.com/Microsoft/knack/blob/5f1a480a33f103e2688c46eef59fb2d9eaf2baad/knack/commands.py#L200-L218 | train | 224,201 |
Microsoft/knack | knack/commands.py | CLICommandsLoader.create_command | def create_command(self, name, operation, **kwargs):
""" Constructs the command object that can then be added to the command table """
if not isinstance(operation, six.string_types):
raise ValueError("Operation must be a string. Got '{}'".format(operation))
name = ' '.join(name.split())
client_factory = kwargs.get('client_factory', None)
def _command_handler(command_args):
op = CLICommandsLoader._get_op_handler(operation)
client = client_factory(command_args) if client_factory else None
result = op(client, **command_args) if client else op(**command_args)
return result
def arguments_loader():
return list(extract_args_from_signature(CLICommandsLoader._get_op_handler(operation),
excluded_params=self.excluded_command_handler_args))
def description_loader():
return extract_full_summary_from_signature(CLICommandsLoader._get_op_handler(operation))
kwargs['arguments_loader'] = arguments_loader
kwargs['description_loader'] = description_loader
cmd = self.command_cls(self.cli_ctx, name, _command_handler, **kwargs)
return cmd | python | def create_command(self, name, operation, **kwargs):
""" Constructs the command object that can then be added to the command table """
if not isinstance(operation, six.string_types):
raise ValueError("Operation must be a string. Got '{}'".format(operation))
name = ' '.join(name.split())
client_factory = kwargs.get('client_factory', None)
def _command_handler(command_args):
op = CLICommandsLoader._get_op_handler(operation)
client = client_factory(command_args) if client_factory else None
result = op(client, **command_args) if client else op(**command_args)
return result
def arguments_loader():
return list(extract_args_from_signature(CLICommandsLoader._get_op_handler(operation),
excluded_params=self.excluded_command_handler_args))
def description_loader():
return extract_full_summary_from_signature(CLICommandsLoader._get_op_handler(operation))
kwargs['arguments_loader'] = arguments_loader
kwargs['description_loader'] = description_loader
cmd = self.command_cls(self.cli_ctx, name, _command_handler, **kwargs)
return cmd | [
"def",
"create_command",
"(",
"self",
",",
"name",
",",
"operation",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"operation",
",",
"six",
".",
"string_types",
")",
":",
"raise",
"ValueError",
"(",
"\"Operation must be a string. Got '{}'\... | Constructs the command object that can then be added to the command table | [
"Constructs",
"the",
"command",
"object",
"that",
"can",
"then",
"be",
"added",
"to",
"the",
"command",
"table"
] | 5f1a480a33f103e2688c46eef59fb2d9eaf2baad | https://github.com/Microsoft/knack/blob/5f1a480a33f103e2688c46eef59fb2d9eaf2baad/knack/commands.py#L229-L255 | train | 224,202 |
Microsoft/knack | knack/commands.py | CLICommandsLoader._get_op_handler | def _get_op_handler(operation):
""" Import and load the operation handler """
try:
mod_to_import, attr_path = operation.split('#')
op = import_module(mod_to_import)
for part in attr_path.split('.'):
op = getattr(op, part)
if isinstance(op, types.FunctionType):
return op
return six.get_method_function(op)
except (ValueError, AttributeError):
raise ValueError("The operation '{}' is invalid.".format(operation)) | python | def _get_op_handler(operation):
""" Import and load the operation handler """
try:
mod_to_import, attr_path = operation.split('#')
op = import_module(mod_to_import)
for part in attr_path.split('.'):
op = getattr(op, part)
if isinstance(op, types.FunctionType):
return op
return six.get_method_function(op)
except (ValueError, AttributeError):
raise ValueError("The operation '{}' is invalid.".format(operation)) | [
"def",
"_get_op_handler",
"(",
"operation",
")",
":",
"try",
":",
"mod_to_import",
",",
"attr_path",
"=",
"operation",
".",
"split",
"(",
"'#'",
")",
"op",
"=",
"import_module",
"(",
"mod_to_import",
")",
"for",
"part",
"in",
"attr_path",
".",
"split",
"("... | Import and load the operation handler | [
"Import",
"and",
"load",
"the",
"operation",
"handler"
] | 5f1a480a33f103e2688c46eef59fb2d9eaf2baad | https://github.com/Microsoft/knack/blob/5f1a480a33f103e2688c46eef59fb2d9eaf2baad/knack/commands.py#L258-L269 | train | 224,203 |
Microsoft/knack | knack/commands.py | CommandGroup.command | def command(self, name, handler_name, **kwargs):
""" Register a command into the command table
:param name: The name of the command
:type name: str
:param handler_name: The name of the handler that will be applied to the operations template
:type handler_name: str
:param kwargs: Kwargs to apply to the command.
Possible values: `client_factory`, `arguments_loader`, `description_loader`, `description`,
`formatter_class`, `table_transformer`, `deprecate_info`, `validator`, `confirmation`.
"""
import copy
command_name = '{} {}'.format(self.group_name, name) if self.group_name else name
command_kwargs = copy.deepcopy(self.group_kwargs)
command_kwargs.update(kwargs)
# don't inherit deprecation info from command group
command_kwargs['deprecate_info'] = kwargs.get('deprecate_info', None)
self.command_loader._populate_command_group_table_with_subgroups(' '.join(command_name.split()[:-1])) # pylint: disable=protected-access
self.command_loader.command_table[command_name] = self.command_loader.create_command(
command_name,
self.operations_tmpl.format(handler_name),
**command_kwargs) | python | def command(self, name, handler_name, **kwargs):
""" Register a command into the command table
:param name: The name of the command
:type name: str
:param handler_name: The name of the handler that will be applied to the operations template
:type handler_name: str
:param kwargs: Kwargs to apply to the command.
Possible values: `client_factory`, `arguments_loader`, `description_loader`, `description`,
`formatter_class`, `table_transformer`, `deprecate_info`, `validator`, `confirmation`.
"""
import copy
command_name = '{} {}'.format(self.group_name, name) if self.group_name else name
command_kwargs = copy.deepcopy(self.group_kwargs)
command_kwargs.update(kwargs)
# don't inherit deprecation info from command group
command_kwargs['deprecate_info'] = kwargs.get('deprecate_info', None)
self.command_loader._populate_command_group_table_with_subgroups(' '.join(command_name.split()[:-1])) # pylint: disable=protected-access
self.command_loader.command_table[command_name] = self.command_loader.create_command(
command_name,
self.operations_tmpl.format(handler_name),
**command_kwargs) | [
"def",
"command",
"(",
"self",
",",
"name",
",",
"handler_name",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"copy",
"command_name",
"=",
"'{} {}'",
".",
"format",
"(",
"self",
".",
"group_name",
",",
"name",
")",
"if",
"self",
".",
"group_name",
"els... | Register a command into the command table
:param name: The name of the command
:type name: str
:param handler_name: The name of the handler that will be applied to the operations template
:type handler_name: str
:param kwargs: Kwargs to apply to the command.
Possible values: `client_factory`, `arguments_loader`, `description_loader`, `description`,
`formatter_class`, `table_transformer`, `deprecate_info`, `validator`, `confirmation`. | [
"Register",
"a",
"command",
"into",
"the",
"command",
"table"
] | 5f1a480a33f103e2688c46eef59fb2d9eaf2baad | https://github.com/Microsoft/knack/blob/5f1a480a33f103e2688c46eef59fb2d9eaf2baad/knack/commands.py#L307-L330 | train | 224,204 |
Microsoft/knack | knack/invocation.py | CommandInvoker._rudimentary_get_command | def _rudimentary_get_command(self, args):
""" Rudimentary parsing to get the command """
nouns = []
command_names = self.commands_loader.command_table.keys()
for arg in args:
if arg and arg[0] != '-':
nouns.append(arg)
else:
break
def _find_args(args):
search = ' '.join(args).lower()
return next((x for x in command_names if x.startswith(search)), False)
# since the command name may be immediately followed by a positional arg, strip those off
while nouns and not _find_args(nouns):
del nouns[-1]
# ensure the command string is case-insensitive
for i in range(len(nouns)):
args[i] = args[i].lower()
return ' '.join(nouns) | python | def _rudimentary_get_command(self, args):
""" Rudimentary parsing to get the command """
nouns = []
command_names = self.commands_loader.command_table.keys()
for arg in args:
if arg and arg[0] != '-':
nouns.append(arg)
else:
break
def _find_args(args):
search = ' '.join(args).lower()
return next((x for x in command_names if x.startswith(search)), False)
# since the command name may be immediately followed by a positional arg, strip those off
while nouns and not _find_args(nouns):
del nouns[-1]
# ensure the command string is case-insensitive
for i in range(len(nouns)):
args[i] = args[i].lower()
return ' '.join(nouns) | [
"def",
"_rudimentary_get_command",
"(",
"self",
",",
"args",
")",
":",
"nouns",
"=",
"[",
"]",
"command_names",
"=",
"self",
".",
"commands_loader",
".",
"command_table",
".",
"keys",
"(",
")",
"for",
"arg",
"in",
"args",
":",
"if",
"arg",
"and",
"arg",
... | Rudimentary parsing to get the command | [
"Rudimentary",
"parsing",
"to",
"get",
"the",
"command"
] | 5f1a480a33f103e2688c46eef59fb2d9eaf2baad | https://github.com/Microsoft/knack/blob/5f1a480a33f103e2688c46eef59fb2d9eaf2baad/knack/invocation.py#L67-L89 | train | 224,205 |
Microsoft/knack | knack/invocation.py | CommandInvoker.execute | def execute(self, args):
""" Executes the command invocation
:param args: The command arguments for this invocation
:type args: list
:return: The command result
:rtype: knack.util.CommandResultItem
"""
import colorama
self.cli_ctx.raise_event(EVENT_INVOKER_PRE_CMD_TBL_CREATE, args=args)
cmd_tbl = self.commands_loader.load_command_table(args)
command = self._rudimentary_get_command(args)
self.cli_ctx.invocation.data['command_string'] = command
self.commands_loader.load_arguments(command)
self.cli_ctx.raise_event(EVENT_INVOKER_POST_CMD_TBL_CREATE, cmd_tbl=cmd_tbl)
self.parser.load_command_table(self.commands_loader)
self.cli_ctx.raise_event(EVENT_INVOKER_CMD_TBL_LOADED, parser=self.parser)
arg_check = [a for a in args if a not in ['--verbose', '--debug']]
if not arg_check:
self.cli_ctx.completion.enable_autocomplete(self.parser)
subparser = self.parser.subparsers[tuple()]
self.help.show_welcome(subparser)
return CommandResultItem(None, exit_code=0)
if args[0].lower() == 'help':
args[0] = '--help'
self.cli_ctx.completion.enable_autocomplete(self.parser)
self.cli_ctx.raise_event(EVENT_INVOKER_PRE_PARSE_ARGS, args=args)
parsed_args = self.parser.parse_args(args)
self.cli_ctx.raise_event(EVENT_INVOKER_POST_PARSE_ARGS, command=parsed_args.command, args=parsed_args)
self._validation(parsed_args)
# save the command name (leaf in the tree)
self.data['command'] = parsed_args.command
cmd = parsed_args.func
if hasattr(parsed_args, 'cmd'):
parsed_args.cmd = cmd
deprecations = getattr(parsed_args, '_argument_deprecations', [])
if cmd.deprecate_info:
deprecations.append(cmd.deprecate_info)
params = self._filter_params(parsed_args)
# search for implicit deprecation
path_comps = cmd.name.split()[:-1]
implicit_deprecate_info = None
while path_comps and not implicit_deprecate_info:
implicit_deprecate_info = resolve_deprecate_info(self.cli_ctx, ' '.join(path_comps))
del path_comps[-1]
if implicit_deprecate_info:
deprecate_kwargs = implicit_deprecate_info.__dict__.copy()
deprecate_kwargs['object_type'] = 'command'
del deprecate_kwargs['_get_tag']
del deprecate_kwargs['_get_message']
deprecations.append(ImplicitDeprecated(**deprecate_kwargs))
colorama.init()
for d in deprecations:
print(d.message, file=sys.stderr)
colorama.deinit()
cmd_result = parsed_args.func(params)
cmd_result = todict(cmd_result)
event_data = {'result': cmd_result}
self.cli_ctx.raise_event(EVENT_INVOKER_TRANSFORM_RESULT, event_data=event_data)
self.cli_ctx.raise_event(EVENT_INVOKER_FILTER_RESULT, event_data=event_data)
return CommandResultItem(event_data['result'],
exit_code=0,
table_transformer=cmd_tbl[parsed_args.command].table_transformer,
is_query_active=self.data['query_active']) | python | def execute(self, args):
""" Executes the command invocation
:param args: The command arguments for this invocation
:type args: list
:return: The command result
:rtype: knack.util.CommandResultItem
"""
import colorama
self.cli_ctx.raise_event(EVENT_INVOKER_PRE_CMD_TBL_CREATE, args=args)
cmd_tbl = self.commands_loader.load_command_table(args)
command = self._rudimentary_get_command(args)
self.cli_ctx.invocation.data['command_string'] = command
self.commands_loader.load_arguments(command)
self.cli_ctx.raise_event(EVENT_INVOKER_POST_CMD_TBL_CREATE, cmd_tbl=cmd_tbl)
self.parser.load_command_table(self.commands_loader)
self.cli_ctx.raise_event(EVENT_INVOKER_CMD_TBL_LOADED, parser=self.parser)
arg_check = [a for a in args if a not in ['--verbose', '--debug']]
if not arg_check:
self.cli_ctx.completion.enable_autocomplete(self.parser)
subparser = self.parser.subparsers[tuple()]
self.help.show_welcome(subparser)
return CommandResultItem(None, exit_code=0)
if args[0].lower() == 'help':
args[0] = '--help'
self.cli_ctx.completion.enable_autocomplete(self.parser)
self.cli_ctx.raise_event(EVENT_INVOKER_PRE_PARSE_ARGS, args=args)
parsed_args = self.parser.parse_args(args)
self.cli_ctx.raise_event(EVENT_INVOKER_POST_PARSE_ARGS, command=parsed_args.command, args=parsed_args)
self._validation(parsed_args)
# save the command name (leaf in the tree)
self.data['command'] = parsed_args.command
cmd = parsed_args.func
if hasattr(parsed_args, 'cmd'):
parsed_args.cmd = cmd
deprecations = getattr(parsed_args, '_argument_deprecations', [])
if cmd.deprecate_info:
deprecations.append(cmd.deprecate_info)
params = self._filter_params(parsed_args)
# search for implicit deprecation
path_comps = cmd.name.split()[:-1]
implicit_deprecate_info = None
while path_comps and not implicit_deprecate_info:
implicit_deprecate_info = resolve_deprecate_info(self.cli_ctx, ' '.join(path_comps))
del path_comps[-1]
if implicit_deprecate_info:
deprecate_kwargs = implicit_deprecate_info.__dict__.copy()
deprecate_kwargs['object_type'] = 'command'
del deprecate_kwargs['_get_tag']
del deprecate_kwargs['_get_message']
deprecations.append(ImplicitDeprecated(**deprecate_kwargs))
colorama.init()
for d in deprecations:
print(d.message, file=sys.stderr)
colorama.deinit()
cmd_result = parsed_args.func(params)
cmd_result = todict(cmd_result)
event_data = {'result': cmd_result}
self.cli_ctx.raise_event(EVENT_INVOKER_TRANSFORM_RESULT, event_data=event_data)
self.cli_ctx.raise_event(EVENT_INVOKER_FILTER_RESULT, event_data=event_data)
return CommandResultItem(event_data['result'],
exit_code=0,
table_transformer=cmd_tbl[parsed_args.command].table_transformer,
is_query_active=self.data['query_active']) | [
"def",
"execute",
"(",
"self",
",",
"args",
")",
":",
"import",
"colorama",
"self",
".",
"cli_ctx",
".",
"raise_event",
"(",
"EVENT_INVOKER_PRE_CMD_TBL_CREATE",
",",
"args",
"=",
"args",
")",
"cmd_tbl",
"=",
"self",
".",
"commands_loader",
".",
"load_command_t... | Executes the command invocation
:param args: The command arguments for this invocation
:type args: list
:return: The command result
:rtype: knack.util.CommandResultItem | [
"Executes",
"the",
"command",
"invocation"
] | 5f1a480a33f103e2688c46eef59fb2d9eaf2baad | https://github.com/Microsoft/knack/blob/5f1a480a33f103e2688c46eef59fb2d9eaf2baad/knack/invocation.py#L120-L198 | train | 224,206 |
Microsoft/knack | knack/completion.py | CLICompletion.get_completion_args | def get_completion_args(self, is_completion=False, comp_line=None): # pylint: disable=no-self-use
""" Get the args that will be used to tab completion if completion is active. """
is_completion = is_completion or os.environ.get(ARGCOMPLETE_ENV_NAME)
comp_line = comp_line or os.environ.get('COMP_LINE')
# The first item is the exe name so ignore that.
return comp_line.split()[1:] if is_completion and comp_line else None | python | def get_completion_args(self, is_completion=False, comp_line=None): # pylint: disable=no-self-use
""" Get the args that will be used to tab completion if completion is active. """
is_completion = is_completion or os.environ.get(ARGCOMPLETE_ENV_NAME)
comp_line = comp_line or os.environ.get('COMP_LINE')
# The first item is the exe name so ignore that.
return comp_line.split()[1:] if is_completion and comp_line else None | [
"def",
"get_completion_args",
"(",
"self",
",",
"is_completion",
"=",
"False",
",",
"comp_line",
"=",
"None",
")",
":",
"# pylint: disable=no-self-use",
"is_completion",
"=",
"is_completion",
"or",
"os",
".",
"environ",
".",
"get",
"(",
"ARGCOMPLETE_ENV_NAME",
")"... | Get the args that will be used to tab completion if completion is active. | [
"Get",
"the",
"args",
"that",
"will",
"be",
"used",
"to",
"tab",
"completion",
"if",
"completion",
"is",
"active",
"."
] | 5f1a480a33f103e2688c46eef59fb2d9eaf2baad | https://github.com/Microsoft/knack/blob/5f1a480a33f103e2688c46eef59fb2d9eaf2baad/knack/completion.py#L37-L42 | train | 224,207 |
Microsoft/knack | knack/output.py | OutputProducer.out | def out(self, obj, formatter=None, out_file=None): # pylint: disable=no-self-use
""" Produces the output using the command result.
The method does not return a result as the output is written straight to the output file.
:param obj: The command result
:type obj: knack.util.CommandResultItem
:param formatter: The formatter we should use for the command result
:type formatter: function
:param out_file: The file to write output to
:type out_file: file-like object
"""
if not isinstance(obj, CommandResultItem):
raise TypeError('Expected {} got {}'.format(CommandResultItem.__name__, type(obj)))
import platform
import colorama
if platform.system() == 'Windows':
out_file = colorama.AnsiToWin32(out_file).stream
output = formatter(obj)
try:
print(output, file=out_file, end='')
except IOError as ex:
if ex.errno == errno.EPIPE:
pass
else:
raise
except UnicodeEncodeError:
print(output.encode('ascii', 'ignore').decode('utf-8', 'ignore'),
file=out_file, end='') | python | def out(self, obj, formatter=None, out_file=None): # pylint: disable=no-self-use
""" Produces the output using the command result.
The method does not return a result as the output is written straight to the output file.
:param obj: The command result
:type obj: knack.util.CommandResultItem
:param formatter: The formatter we should use for the command result
:type formatter: function
:param out_file: The file to write output to
:type out_file: file-like object
"""
if not isinstance(obj, CommandResultItem):
raise TypeError('Expected {} got {}'.format(CommandResultItem.__name__, type(obj)))
import platform
import colorama
if platform.system() == 'Windows':
out_file = colorama.AnsiToWin32(out_file).stream
output = formatter(obj)
try:
print(output, file=out_file, end='')
except IOError as ex:
if ex.errno == errno.EPIPE:
pass
else:
raise
except UnicodeEncodeError:
print(output.encode('ascii', 'ignore').decode('utf-8', 'ignore'),
file=out_file, end='') | [
"def",
"out",
"(",
"self",
",",
"obj",
",",
"formatter",
"=",
"None",
",",
"out_file",
"=",
"None",
")",
":",
"# pylint: disable=no-self-use",
"if",
"not",
"isinstance",
"(",
"obj",
",",
"CommandResultItem",
")",
":",
"raise",
"TypeError",
"(",
"'Expected {}... | Produces the output using the command result.
The method does not return a result as the output is written straight to the output file.
:param obj: The command result
:type obj: knack.util.CommandResultItem
:param formatter: The formatter we should use for the command result
:type formatter: function
:param out_file: The file to write output to
:type out_file: file-like object | [
"Produces",
"the",
"output",
"using",
"the",
"command",
"result",
".",
"The",
"method",
"does",
"not",
"return",
"a",
"result",
"as",
"the",
"output",
"is",
"written",
"straight",
"to",
"the",
"output",
"file",
"."
] | 5f1a480a33f103e2688c46eef59fb2d9eaf2baad | https://github.com/Microsoft/knack/blob/5f1a480a33f103e2688c46eef59fb2d9eaf2baad/knack/output.py#L113-L142 | train | 224,208 |
ryanmcgrath/twython | twython/endpoints.py | EndpointsMixin.update_status_with_media | def update_status_with_media(self, **params): # pragma: no cover
"""Updates the authenticating user's current status and attaches media
for upload. In other words, it creates a Tweet with a picture attached.
Docs:
https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update_with_media
"""
warnings.warn(
'This method is deprecated. You should use Twython.upload_media instead.',
TwythonDeprecationWarning,
stacklevel=2
)
return self.post('statuses/update_with_media', params=params) | python | def update_status_with_media(self, **params): # pragma: no cover
"""Updates the authenticating user's current status and attaches media
for upload. In other words, it creates a Tweet with a picture attached.
Docs:
https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update_with_media
"""
warnings.warn(
'This method is deprecated. You should use Twython.upload_media instead.',
TwythonDeprecationWarning,
stacklevel=2
)
return self.post('statuses/update_with_media', params=params) | [
"def",
"update_status_with_media",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"# pragma: no cover",
"warnings",
".",
"warn",
"(",
"'This method is deprecated. You should use Twython.upload_media instead.'",
",",
"TwythonDeprecationWarning",
",",
"stacklevel",
"=",
"2",... | Updates the authenticating user's current status and attaches media
for upload. In other words, it creates a Tweet with a picture attached.
Docs:
https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update_with_media | [
"Updates",
"the",
"authenticating",
"user",
"s",
"current",
"status",
"and",
"attaches",
"media",
"for",
"upload",
".",
"In",
"other",
"words",
"it",
"creates",
"a",
"Tweet",
"with",
"a",
"picture",
"attached",
"."
] | 7366de80efcbbdfaf615d3f1fea72546196916fc | https://github.com/ryanmcgrath/twython/blob/7366de80efcbbdfaf615d3f1fea72546196916fc/twython/endpoints.py#L134-L147 | train | 224,209 |
ryanmcgrath/twython | twython/endpoints.py | EndpointsMixin.create_metadata | def create_metadata(self, **params):
""" Adds metadata to a media element, such as image descriptions for visually impaired.
Docs:
https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-metadata-create
"""
params = json.dumps(params)
return self.post("https://upload.twitter.com/1.1/media/metadata/create.json", params=params) | python | def create_metadata(self, **params):
""" Adds metadata to a media element, such as image descriptions for visually impaired.
Docs:
https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-metadata-create
"""
params = json.dumps(params)
return self.post("https://upload.twitter.com/1.1/media/metadata/create.json", params=params) | [
"def",
"create_metadata",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"params",
"=",
"json",
".",
"dumps",
"(",
"params",
")",
"return",
"self",
".",
"post",
"(",
"\"https://upload.twitter.com/1.1/media/metadata/create.json\"",
",",
"params",
"=",
"params",
... | Adds metadata to a media element, such as image descriptions for visually impaired.
Docs:
https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-metadata-create | [
"Adds",
"metadata",
"to",
"a",
"media",
"element",
"such",
"as",
"image",
"descriptions",
"for",
"visually",
"impaired",
"."
] | 7366de80efcbbdfaf615d3f1fea72546196916fc | https://github.com/ryanmcgrath/twython/blob/7366de80efcbbdfaf615d3f1fea72546196916fc/twython/endpoints.py#L164-L172 | train | 224,210 |
ryanmcgrath/twython | twython/api.py | Twython._get_error_message | def _get_error_message(self, response):
"""Parse and return the first error message"""
error_message = 'An error occurred processing your request.'
try:
content = response.json()
# {"errors":[{"code":34,"message":"Sorry,
# that page does not exist"}]}
error_message = content['errors'][0]['message']
except TypeError:
error_message = content['errors']
except ValueError:
# bad json data from Twitter for an error
pass
except (KeyError, IndexError):
# missing data so fallback to default message
pass
return error_message | python | def _get_error_message(self, response):
"""Parse and return the first error message"""
error_message = 'An error occurred processing your request.'
try:
content = response.json()
# {"errors":[{"code":34,"message":"Sorry,
# that page does not exist"}]}
error_message = content['errors'][0]['message']
except TypeError:
error_message = content['errors']
except ValueError:
# bad json data from Twitter for an error
pass
except (KeyError, IndexError):
# missing data so fallback to default message
pass
return error_message | [
"def",
"_get_error_message",
"(",
"self",
",",
"response",
")",
":",
"error_message",
"=",
"'An error occurred processing your request.'",
"try",
":",
"content",
"=",
"response",
".",
"json",
"(",
")",
"# {\"errors\":[{\"code\":34,\"message\":\"Sorry,",
"# that page does no... | Parse and return the first error message | [
"Parse",
"and",
"return",
"the",
"first",
"error",
"message"
] | 7366de80efcbbdfaf615d3f1fea72546196916fc | https://github.com/ryanmcgrath/twython/blob/7366de80efcbbdfaf615d3f1fea72546196916fc/twython/api.py#L218-L236 | train | 224,211 |
ryanmcgrath/twython | twython/api.py | Twython.request | def request(self, endpoint, method='GET', params=None, version='1.1', json_encoded=False):
"""Return dict of response received from Twitter's API
:param endpoint: (required) Full url or Twitter API endpoint
(e.g. search/tweets)
:type endpoint: string
:param method: (optional) Method of accessing data, either
GET, POST or DELETE. (default GET)
:type method: string
:param params: (optional) Dict of parameters (if any) accepted
the by Twitter API endpoint you are trying to
access (default None)
:type params: dict or None
:param version: (optional) Twitter API version to access
(default 1.1)
:type version: string
:param json_encoded: (optional) Flag to indicate if this method should send data encoded as json
(default False)
:type json_encoded: bool
:rtype: dict
"""
if endpoint.startswith('http://'):
raise TwythonError('api.twitter.com is restricted to SSL/TLS traffic.')
# In case they want to pass a full Twitter URL
# i.e. https://api.twitter.com/1.1/search/tweets.json
if endpoint.startswith('https://'):
url = endpoint
else:
url = '%s/%s.json' % (self.api_url % version, endpoint)
content = self._request(url, method=method, params=params,
api_call=url, json_encoded=json_encoded)
return content | python | def request(self, endpoint, method='GET', params=None, version='1.1', json_encoded=False):
"""Return dict of response received from Twitter's API
:param endpoint: (required) Full url or Twitter API endpoint
(e.g. search/tweets)
:type endpoint: string
:param method: (optional) Method of accessing data, either
GET, POST or DELETE. (default GET)
:type method: string
:param params: (optional) Dict of parameters (if any) accepted
the by Twitter API endpoint you are trying to
access (default None)
:type params: dict or None
:param version: (optional) Twitter API version to access
(default 1.1)
:type version: string
:param json_encoded: (optional) Flag to indicate if this method should send data encoded as json
(default False)
:type json_encoded: bool
:rtype: dict
"""
if endpoint.startswith('http://'):
raise TwythonError('api.twitter.com is restricted to SSL/TLS traffic.')
# In case they want to pass a full Twitter URL
# i.e. https://api.twitter.com/1.1/search/tweets.json
if endpoint.startswith('https://'):
url = endpoint
else:
url = '%s/%s.json' % (self.api_url % version, endpoint)
content = self._request(url, method=method, params=params,
api_call=url, json_encoded=json_encoded)
return content | [
"def",
"request",
"(",
"self",
",",
"endpoint",
",",
"method",
"=",
"'GET'",
",",
"params",
"=",
"None",
",",
"version",
"=",
"'1.1'",
",",
"json_encoded",
"=",
"False",
")",
":",
"if",
"endpoint",
".",
"startswith",
"(",
"'http://'",
")",
":",
"raise"... | Return dict of response received from Twitter's API
:param endpoint: (required) Full url or Twitter API endpoint
(e.g. search/tweets)
:type endpoint: string
:param method: (optional) Method of accessing data, either
GET, POST or DELETE. (default GET)
:type method: string
:param params: (optional) Dict of parameters (if any) accepted
the by Twitter API endpoint you are trying to
access (default None)
:type params: dict or None
:param version: (optional) Twitter API version to access
(default 1.1)
:type version: string
:param json_encoded: (optional) Flag to indicate if this method should send data encoded as json
(default False)
:type json_encoded: bool
:rtype: dict | [
"Return",
"dict",
"of",
"response",
"received",
"from",
"Twitter",
"s",
"API"
] | 7366de80efcbbdfaf615d3f1fea72546196916fc | https://github.com/ryanmcgrath/twython/blob/7366de80efcbbdfaf615d3f1fea72546196916fc/twython/api.py#L238-L274 | train | 224,212 |
ryanmcgrath/twython | twython/api.py | Twython.get_lastfunction_header | def get_lastfunction_header(self, header, default_return_value=None):
"""Returns a specific header from the last API call
This will return None if the header is not present
:param header: (required) The name of the header you want to get
the value of
Most useful for the following header information:
x-rate-limit-limit,
x-rate-limit-remaining,
x-rate-limit-class,
x-rate-limit-reset
"""
if self._last_call is None:
raise TwythonError('This function must be called after an API call. \
It delivers header information.')
return self._last_call['headers'].get(header, default_return_value) | python | def get_lastfunction_header(self, header, default_return_value=None):
"""Returns a specific header from the last API call
This will return None if the header is not present
:param header: (required) The name of the header you want to get
the value of
Most useful for the following header information:
x-rate-limit-limit,
x-rate-limit-remaining,
x-rate-limit-class,
x-rate-limit-reset
"""
if self._last_call is None:
raise TwythonError('This function must be called after an API call. \
It delivers header information.')
return self._last_call['headers'].get(header, default_return_value) | [
"def",
"get_lastfunction_header",
"(",
"self",
",",
"header",
",",
"default_return_value",
"=",
"None",
")",
":",
"if",
"self",
".",
"_last_call",
"is",
"None",
":",
"raise",
"TwythonError",
"(",
"'This function must be called after an API call. \\\n ... | Returns a specific header from the last API call
This will return None if the header is not present
:param header: (required) The name of the header you want to get
the value of
Most useful for the following header information:
x-rate-limit-limit,
x-rate-limit-remaining,
x-rate-limit-class,
x-rate-limit-reset | [
"Returns",
"a",
"specific",
"header",
"from",
"the",
"last",
"API",
"call",
"This",
"will",
"return",
"None",
"if",
"the",
"header",
"is",
"not",
"present"
] | 7366de80efcbbdfaf615d3f1fea72546196916fc | https://github.com/ryanmcgrath/twython/blob/7366de80efcbbdfaf615d3f1fea72546196916fc/twython/api.py#L288-L306 | train | 224,213 |
ryanmcgrath/twython | twython/api.py | Twython.get_authentication_tokens | def get_authentication_tokens(self, callback_url=None, force_login=False,
screen_name=''):
"""Returns a dict including an authorization URL, ``auth_url``, to
direct a user to
:param callback_url: (optional) Url the user is returned to after
they authorize your app (web clients only)
:param force_login: (optional) Forces the user to enter their
credentials to ensure the correct users
account is authorized.
:param screen_name: (optional) If forced_login is set OR user is
not currently logged in, Prefills the username
input box of the OAuth login screen with the
given value
:rtype: dict
"""
if self.oauth_version != 1:
raise TwythonError('This method can only be called when your \
OAuth version is 1.0.')
request_args = {}
if callback_url:
request_args['oauth_callback'] = callback_url
response = self.client.get(self.request_token_url, params=request_args)
if response.status_code == 401:
raise TwythonAuthError(response.content,
error_code=response.status_code)
elif response.status_code != 200:
raise TwythonError(response.content,
error_code=response.status_code)
request_tokens = dict(parse_qsl(response.content.decode('utf-8')))
if not request_tokens:
raise TwythonError('Unable to decode request tokens.')
oauth_callback_confirmed = request_tokens.get('oauth_callback_confirmed') \
== 'true'
auth_url_params = {
'oauth_token': request_tokens['oauth_token'],
}
if force_login:
auth_url_params.update({
'force_login': force_login,
'screen_name': screen_name
})
# Use old-style callback argument if server didn't accept new-style
if callback_url and not oauth_callback_confirmed:
auth_url_params['oauth_callback'] = self.callback_url
request_tokens['auth_url'] = self.authenticate_url + \
'?' + urlencode(auth_url_params)
return request_tokens | python | def get_authentication_tokens(self, callback_url=None, force_login=False,
screen_name=''):
"""Returns a dict including an authorization URL, ``auth_url``, to
direct a user to
:param callback_url: (optional) Url the user is returned to after
they authorize your app (web clients only)
:param force_login: (optional) Forces the user to enter their
credentials to ensure the correct users
account is authorized.
:param screen_name: (optional) If forced_login is set OR user is
not currently logged in, Prefills the username
input box of the OAuth login screen with the
given value
:rtype: dict
"""
if self.oauth_version != 1:
raise TwythonError('This method can only be called when your \
OAuth version is 1.0.')
request_args = {}
if callback_url:
request_args['oauth_callback'] = callback_url
response = self.client.get(self.request_token_url, params=request_args)
if response.status_code == 401:
raise TwythonAuthError(response.content,
error_code=response.status_code)
elif response.status_code != 200:
raise TwythonError(response.content,
error_code=response.status_code)
request_tokens = dict(parse_qsl(response.content.decode('utf-8')))
if not request_tokens:
raise TwythonError('Unable to decode request tokens.')
oauth_callback_confirmed = request_tokens.get('oauth_callback_confirmed') \
== 'true'
auth_url_params = {
'oauth_token': request_tokens['oauth_token'],
}
if force_login:
auth_url_params.update({
'force_login': force_login,
'screen_name': screen_name
})
# Use old-style callback argument if server didn't accept new-style
if callback_url and not oauth_callback_confirmed:
auth_url_params['oauth_callback'] = self.callback_url
request_tokens['auth_url'] = self.authenticate_url + \
'?' + urlencode(auth_url_params)
return request_tokens | [
"def",
"get_authentication_tokens",
"(",
"self",
",",
"callback_url",
"=",
"None",
",",
"force_login",
"=",
"False",
",",
"screen_name",
"=",
"''",
")",
":",
"if",
"self",
".",
"oauth_version",
"!=",
"1",
":",
"raise",
"TwythonError",
"(",
"'This method can on... | Returns a dict including an authorization URL, ``auth_url``, to
direct a user to
:param callback_url: (optional) Url the user is returned to after
they authorize your app (web clients only)
:param force_login: (optional) Forces the user to enter their
credentials to ensure the correct users
account is authorized.
:param screen_name: (optional) If forced_login is set OR user is
not currently logged in, Prefills the username
input box of the OAuth login screen with the
given value
:rtype: dict | [
"Returns",
"a",
"dict",
"including",
"an",
"authorization",
"URL",
"auth_url",
"to",
"direct",
"a",
"user",
"to"
] | 7366de80efcbbdfaf615d3f1fea72546196916fc | https://github.com/ryanmcgrath/twython/blob/7366de80efcbbdfaf615d3f1fea72546196916fc/twython/api.py#L308-L365 | train | 224,214 |
ryanmcgrath/twython | twython/api.py | Twython.obtain_access_token | def obtain_access_token(self):
"""Returns an OAuth 2 access token to make OAuth 2 authenticated
read-only calls.
:rtype: string
"""
if self.oauth_version != 2:
raise TwythonError('This method can only be called when your \
OAuth version is 2.0.')
data = {'grant_type': 'client_credentials'}
basic_auth = HTTPBasicAuth(self.app_key, self.app_secret)
try:
response = self.client.post(self.request_token_url,
data=data, auth=basic_auth)
content = response.content.decode('utf-8')
try:
content = content.json()
except AttributeError:
content = json.loads(content)
access_token = content['access_token']
except (KeyError, ValueError, requests.exceptions.RequestException):
raise TwythonAuthError('Unable to obtain OAuth 2 access token.')
else:
return access_token | python | def obtain_access_token(self):
"""Returns an OAuth 2 access token to make OAuth 2 authenticated
read-only calls.
:rtype: string
"""
if self.oauth_version != 2:
raise TwythonError('This method can only be called when your \
OAuth version is 2.0.')
data = {'grant_type': 'client_credentials'}
basic_auth = HTTPBasicAuth(self.app_key, self.app_secret)
try:
response = self.client.post(self.request_token_url,
data=data, auth=basic_auth)
content = response.content.decode('utf-8')
try:
content = content.json()
except AttributeError:
content = json.loads(content)
access_token = content['access_token']
except (KeyError, ValueError, requests.exceptions.RequestException):
raise TwythonAuthError('Unable to obtain OAuth 2 access token.')
else:
return access_token | [
"def",
"obtain_access_token",
"(",
"self",
")",
":",
"if",
"self",
".",
"oauth_version",
"!=",
"2",
":",
"raise",
"TwythonError",
"(",
"'This method can only be called when your \\\n OAuth version is 2.0.'",
")",
"data",
"=",
"{",
"'grant_type'... | Returns an OAuth 2 access token to make OAuth 2 authenticated
read-only calls.
:rtype: string | [
"Returns",
"an",
"OAuth",
"2",
"access",
"token",
"to",
"make",
"OAuth",
"2",
"authenticated",
"read",
"-",
"only",
"calls",
"."
] | 7366de80efcbbdfaf615d3f1fea72546196916fc | https://github.com/ryanmcgrath/twython/blob/7366de80efcbbdfaf615d3f1fea72546196916fc/twython/api.py#L405-L429 | train | 224,215 |
ryanmcgrath/twython | twython/api.py | Twython.construct_api_url | def construct_api_url(api_url, **params):
"""Construct a Twitter API url, encoded, with parameters
:param api_url: URL of the Twitter API endpoint you are attempting
to construct
:param \*\*params: Parameters that are accepted by Twitter for the
endpoint you're requesting
:rtype: string
Usage::
>>> from twython import Twython
>>> twitter = Twython()
>>> api_url = 'https://api.twitter.com/1.1/search/tweets.json'
>>> constructed_url = twitter.construct_api_url(api_url, q='python',
result_type='popular')
>>> print constructed_url
https://api.twitter.com/1.1/search/tweets.json?q=python&result_type=popular
"""
querystring = []
params, _ = _transparent_params(params or {})
params = requests.utils.to_key_val_list(params)
for (k, v) in params:
querystring.append(
'%s=%s' % (Twython.encode(k), quote_plus(Twython.encode(v)))
)
return '%s?%s' % (api_url, '&'.join(querystring)) | python | def construct_api_url(api_url, **params):
"""Construct a Twitter API url, encoded, with parameters
:param api_url: URL of the Twitter API endpoint you are attempting
to construct
:param \*\*params: Parameters that are accepted by Twitter for the
endpoint you're requesting
:rtype: string
Usage::
>>> from twython import Twython
>>> twitter = Twython()
>>> api_url = 'https://api.twitter.com/1.1/search/tweets.json'
>>> constructed_url = twitter.construct_api_url(api_url, q='python',
result_type='popular')
>>> print constructed_url
https://api.twitter.com/1.1/search/tweets.json?q=python&result_type=popular
"""
querystring = []
params, _ = _transparent_params(params or {})
params = requests.utils.to_key_val_list(params)
for (k, v) in params:
querystring.append(
'%s=%s' % (Twython.encode(k), quote_plus(Twython.encode(v)))
)
return '%s?%s' % (api_url, '&'.join(querystring)) | [
"def",
"construct_api_url",
"(",
"api_url",
",",
"*",
"*",
"params",
")",
":",
"querystring",
"=",
"[",
"]",
"params",
",",
"_",
"=",
"_transparent_params",
"(",
"params",
"or",
"{",
"}",
")",
"params",
"=",
"requests",
".",
"utils",
".",
"to_key_val_lis... | Construct a Twitter API url, encoded, with parameters
:param api_url: URL of the Twitter API endpoint you are attempting
to construct
:param \*\*params: Parameters that are accepted by Twitter for the
endpoint you're requesting
:rtype: string
Usage::
>>> from twython import Twython
>>> twitter = Twython()
>>> api_url = 'https://api.twitter.com/1.1/search/tweets.json'
>>> constructed_url = twitter.construct_api_url(api_url, q='python',
result_type='popular')
>>> print constructed_url
https://api.twitter.com/1.1/search/tweets.json?q=python&result_type=popular | [
"Construct",
"a",
"Twitter",
"API",
"url",
"encoded",
"with",
"parameters"
] | 7366de80efcbbdfaf615d3f1fea72546196916fc | https://github.com/ryanmcgrath/twython/blob/7366de80efcbbdfaf615d3f1fea72546196916fc/twython/api.py#L432-L460 | train | 224,216 |
ryanmcgrath/twython | twython/api.py | Twython.cursor | def cursor(self, function, return_pages=False, **params):
"""Returns a generator for results that match a specified query.
:param function: Instance of a Twython function
(Twython.get_home_timeline, Twython.search)
:param \*\*params: Extra parameters to send with your request
(usually parameters accepted by the Twitter API endpoint)
:rtype: generator
Usage::
>>> from twython import Twython
>>> twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN,
OAUTH_TOKEN_SECRET)
>>> results = twitter.cursor(twitter.search, q='python')
>>> for result in results:
>>> print result
"""
if not callable(function):
raise TypeError('.cursor() takes a Twython function as its first \
argument. Did you provide the result of a \
function call?')
if not hasattr(function, 'iter_mode'):
raise TwythonError('Unable to create generator for Twython \
method "%s"' % function.__name__)
while True:
content = function(**params)
if not content:
raise StopIteration
if hasattr(function, 'iter_key'):
results = content.get(function.iter_key)
else:
results = content
if return_pages:
yield results
else:
for result in results:
yield result
if function.iter_mode == 'cursor' and \
content['next_cursor_str'] == '0':
raise StopIteration
try:
if function.iter_mode == 'id':
# Set max_id in params to one less than lowest tweet id
if hasattr(function, 'iter_metadata'):
# Get supplied next max_id
metadata = content.get(function.iter_metadata)
if 'next_results' in metadata:
next_results = urlsplit(metadata['next_results'])
params = dict(parse_qsl(next_results.query))
else:
# No more results
raise StopIteration
else:
# Twitter gives tweets in reverse chronological order:
params['max_id'] = str(int(content[-1]['id_str']) - 1)
elif function.iter_mode == 'cursor':
params['cursor'] = content['next_cursor_str']
except (TypeError, ValueError): # pragma: no cover
raise TwythonError('Unable to generate next page of search \
results, `page` is not a number.')
except (KeyError, AttributeError): #pragma no cover
raise TwythonError('Unable to generate next page of search \
results, content has unexpected structure.') | python | def cursor(self, function, return_pages=False, **params):
"""Returns a generator for results that match a specified query.
:param function: Instance of a Twython function
(Twython.get_home_timeline, Twython.search)
:param \*\*params: Extra parameters to send with your request
(usually parameters accepted by the Twitter API endpoint)
:rtype: generator
Usage::
>>> from twython import Twython
>>> twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN,
OAUTH_TOKEN_SECRET)
>>> results = twitter.cursor(twitter.search, q='python')
>>> for result in results:
>>> print result
"""
if not callable(function):
raise TypeError('.cursor() takes a Twython function as its first \
argument. Did you provide the result of a \
function call?')
if not hasattr(function, 'iter_mode'):
raise TwythonError('Unable to create generator for Twython \
method "%s"' % function.__name__)
while True:
content = function(**params)
if not content:
raise StopIteration
if hasattr(function, 'iter_key'):
results = content.get(function.iter_key)
else:
results = content
if return_pages:
yield results
else:
for result in results:
yield result
if function.iter_mode == 'cursor' and \
content['next_cursor_str'] == '0':
raise StopIteration
try:
if function.iter_mode == 'id':
# Set max_id in params to one less than lowest tweet id
if hasattr(function, 'iter_metadata'):
# Get supplied next max_id
metadata = content.get(function.iter_metadata)
if 'next_results' in metadata:
next_results = urlsplit(metadata['next_results'])
params = dict(parse_qsl(next_results.query))
else:
# No more results
raise StopIteration
else:
# Twitter gives tweets in reverse chronological order:
params['max_id'] = str(int(content[-1]['id_str']) - 1)
elif function.iter_mode == 'cursor':
params['cursor'] = content['next_cursor_str']
except (TypeError, ValueError): # pragma: no cover
raise TwythonError('Unable to generate next page of search \
results, `page` is not a number.')
except (KeyError, AttributeError): #pragma no cover
raise TwythonError('Unable to generate next page of search \
results, content has unexpected structure.') | [
"def",
"cursor",
"(",
"self",
",",
"function",
",",
"return_pages",
"=",
"False",
",",
"*",
"*",
"params",
")",
":",
"if",
"not",
"callable",
"(",
"function",
")",
":",
"raise",
"TypeError",
"(",
"'.cursor() takes a Twython function as its first \\\n ... | Returns a generator for results that match a specified query.
:param function: Instance of a Twython function
(Twython.get_home_timeline, Twython.search)
:param \*\*params: Extra parameters to send with your request
(usually parameters accepted by the Twitter API endpoint)
:rtype: generator
Usage::
>>> from twython import Twython
>>> twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN,
OAUTH_TOKEN_SECRET)
>>> results = twitter.cursor(twitter.search, q='python')
>>> for result in results:
>>> print result | [
"Returns",
"a",
"generator",
"for",
"results",
"that",
"match",
"a",
"specified",
"query",
"."
] | 7366de80efcbbdfaf615d3f1fea72546196916fc | https://github.com/ryanmcgrath/twython/blob/7366de80efcbbdfaf615d3f1fea72546196916fc/twython/api.py#L471-L543 | train | 224,217 |
ryanmcgrath/twython | twython/streaming/api.py | TwythonStreamer._request | def _request(self, url, method='GET', params=None):
"""Internal stream request handling"""
self.connected = True
retry_counter = 0
method = method.lower()
func = getattr(self.client, method)
params, _ = _transparent_params(params)
def _send(retry_counter):
requests_args = {}
for k, v in self.client_args.items():
# Maybe this should be set as a class
# variable and only done once?
if k in ('timeout', 'allow_redirects', 'verify'):
requests_args[k] = v
while self.connected:
try:
if method == 'get':
requests_args['params'] = params
else:
requests_args['data'] = params
response = func(url, **requests_args)
except requests.exceptions.Timeout:
self.on_timeout()
else:
if response.status_code != 200:
self.on_error(response.status_code, response.content)
if self.retry_count and \
(self.retry_count - retry_counter) > 0:
time.sleep(self.retry_in)
retry_counter += 1
_send(retry_counter)
return response
while self.connected:
response = _send(retry_counter)
for line in response.iter_lines(self.chunk_size):
if not self.connected:
break
if line:
try:
if is_py3:
line = line.decode('utf-8')
data = json.loads(line)
except ValueError: # pragma: no cover
self.on_error(response.status_code,
'Unable to decode response, \
not valid JSON.')
else:
if self.on_success(data): # pragma: no cover
for message_type in self.handlers:
if message_type in data:
handler = getattr(self,
'on_' + message_type,
None)
if handler \
and callable(handler) \
and not handler(data.get(message_type)):
break
response.close() | python | def _request(self, url, method='GET', params=None):
"""Internal stream request handling"""
self.connected = True
retry_counter = 0
method = method.lower()
func = getattr(self.client, method)
params, _ = _transparent_params(params)
def _send(retry_counter):
requests_args = {}
for k, v in self.client_args.items():
# Maybe this should be set as a class
# variable and only done once?
if k in ('timeout', 'allow_redirects', 'verify'):
requests_args[k] = v
while self.connected:
try:
if method == 'get':
requests_args['params'] = params
else:
requests_args['data'] = params
response = func(url, **requests_args)
except requests.exceptions.Timeout:
self.on_timeout()
else:
if response.status_code != 200:
self.on_error(response.status_code, response.content)
if self.retry_count and \
(self.retry_count - retry_counter) > 0:
time.sleep(self.retry_in)
retry_counter += 1
_send(retry_counter)
return response
while self.connected:
response = _send(retry_counter)
for line in response.iter_lines(self.chunk_size):
if not self.connected:
break
if line:
try:
if is_py3:
line = line.decode('utf-8')
data = json.loads(line)
except ValueError: # pragma: no cover
self.on_error(response.status_code,
'Unable to decode response, \
not valid JSON.')
else:
if self.on_success(data): # pragma: no cover
for message_type in self.handlers:
if message_type in data:
handler = getattr(self,
'on_' + message_type,
None)
if handler \
and callable(handler) \
and not handler(data.get(message_type)):
break
response.close() | [
"def",
"_request",
"(",
"self",
",",
"url",
",",
"method",
"=",
"'GET'",
",",
"params",
"=",
"None",
")",
":",
"self",
".",
"connected",
"=",
"True",
"retry_counter",
"=",
"0",
"method",
"=",
"method",
".",
"lower",
"(",
")",
"func",
"=",
"getattr",
... | Internal stream request handling | [
"Internal",
"stream",
"request",
"handling"
] | 7366de80efcbbdfaf615d3f1fea72546196916fc | https://github.com/ryanmcgrath/twython/blob/7366de80efcbbdfaf615d3f1fea72546196916fc/twython/streaming/api.py#L99-L165 | train | 224,218 |
orsinium/textdistance | textdistance/libraries.py | LibrariesManager.optimize | def optimize(self):
"""Sort algorithm implementations by speed.
"""
# load benchmarks results
with open(LIBRARIES_FILE, 'r') as f:
libs_data = json.load(f)
# optimize
for alg, libs_names in libs_data.items():
libs = self.get_libs(alg)
if not libs:
continue
# drop slow libs
self.libs[alg] = [lib for lib in libs if [lib.module_name, lib.func_name] in libs_names]
# sort libs by speed
self.libs[alg].sort(key=lambda lib: libs_names.index([lib.module_name, lib.func_name])) | python | def optimize(self):
"""Sort algorithm implementations by speed.
"""
# load benchmarks results
with open(LIBRARIES_FILE, 'r') as f:
libs_data = json.load(f)
# optimize
for alg, libs_names in libs_data.items():
libs = self.get_libs(alg)
if not libs:
continue
# drop slow libs
self.libs[alg] = [lib for lib in libs if [lib.module_name, lib.func_name] in libs_names]
# sort libs by speed
self.libs[alg].sort(key=lambda lib: libs_names.index([lib.module_name, lib.func_name])) | [
"def",
"optimize",
"(",
"self",
")",
":",
"# load benchmarks results",
"with",
"open",
"(",
"LIBRARIES_FILE",
",",
"'r'",
")",
"as",
"f",
":",
"libs_data",
"=",
"json",
".",
"load",
"(",
"f",
")",
"# optimize",
"for",
"alg",
",",
"libs_names",
"in",
"lib... | Sort algorithm implementations by speed. | [
"Sort",
"algorithm",
"implementations",
"by",
"speed",
"."
] | 34d2e40bb0b26efc03da80b63fd58ebbd3f2cdd7 | https://github.com/orsinium/textdistance/blob/34d2e40bb0b26efc03da80b63fd58ebbd3f2cdd7/textdistance/libraries.py#L23-L37 | train | 224,219 |
orsinium/textdistance | textdistance/libraries.py | LibrariesManager.clone | def clone(self):
"""Clone library manager prototype
"""
obj = self.__class__()
obj.libs = deepcopy(self.libs)
return obj | python | def clone(self):
"""Clone library manager prototype
"""
obj = self.__class__()
obj.libs = deepcopy(self.libs)
return obj | [
"def",
"clone",
"(",
"self",
")",
":",
"obj",
"=",
"self",
".",
"__class__",
"(",
")",
"obj",
".",
"libs",
"=",
"deepcopy",
"(",
"self",
".",
"libs",
")",
"return",
"obj"
] | Clone library manager prototype | [
"Clone",
"library",
"manager",
"prototype"
] | 34d2e40bb0b26efc03da80b63fd58ebbd3f2cdd7 | https://github.com/orsinium/textdistance/blob/34d2e40bb0b26efc03da80b63fd58ebbd3f2cdd7/textdistance/libraries.py#L51-L56 | train | 224,220 |
orsinium/textdistance | textdistance/algorithms/base.py | Base.normalized_distance | def normalized_distance(self, *sequences):
"""Get distance from 0 to 1
"""
return float(self.distance(*sequences)) / self.maximum(*sequences) | python | def normalized_distance(self, *sequences):
"""Get distance from 0 to 1
"""
return float(self.distance(*sequences)) / self.maximum(*sequences) | [
"def",
"normalized_distance",
"(",
"self",
",",
"*",
"sequences",
")",
":",
"return",
"float",
"(",
"self",
".",
"distance",
"(",
"*",
"sequences",
")",
")",
"/",
"self",
".",
"maximum",
"(",
"*",
"sequences",
")"
] | Get distance from 0 to 1 | [
"Get",
"distance",
"from",
"0",
"to",
"1"
] | 34d2e40bb0b26efc03da80b63fd58ebbd3f2cdd7 | https://github.com/orsinium/textdistance/blob/34d2e40bb0b26efc03da80b63fd58ebbd3f2cdd7/textdistance/algorithms/base.py#L39-L42 | train | 224,221 |
orsinium/textdistance | textdistance/algorithms/base.py | Base.external_answer | def external_answer(self, *sequences):
"""Try to get answer from known external libraries.
"""
# if this feature disabled
if not getattr(self, 'external', False):
return
# all external libs doesn't support test_func
if hasattr(self, 'test_func') and self.test_func is not self._ident:
return
# try to get external libs for algorithm
libs = libraries.get_libs(self.__class__.__name__)
for lib in libs:
# if conditions not satisfied
if not lib.check_conditions(self, *sequences):
continue
# if library is not installed yet
if not lib.get_function():
continue
prepared_sequences = lib.prepare(*sequences)
# fail side libraries silently and try next libs
try:
return lib.func(*prepared_sequences)
except Exception:
pass | python | def external_answer(self, *sequences):
"""Try to get answer from known external libraries.
"""
# if this feature disabled
if not getattr(self, 'external', False):
return
# all external libs doesn't support test_func
if hasattr(self, 'test_func') and self.test_func is not self._ident:
return
# try to get external libs for algorithm
libs = libraries.get_libs(self.__class__.__name__)
for lib in libs:
# if conditions not satisfied
if not lib.check_conditions(self, *sequences):
continue
# if library is not installed yet
if not lib.get_function():
continue
prepared_sequences = lib.prepare(*sequences)
# fail side libraries silently and try next libs
try:
return lib.func(*prepared_sequences)
except Exception:
pass | [
"def",
"external_answer",
"(",
"self",
",",
"*",
"sequences",
")",
":",
"# if this feature disabled",
"if",
"not",
"getattr",
"(",
"self",
",",
"'external'",
",",
"False",
")",
":",
"return",
"# all external libs doesn't support test_func",
"if",
"hasattr",
"(",
"... | Try to get answer from known external libraries. | [
"Try",
"to",
"get",
"answer",
"from",
"known",
"external",
"libraries",
"."
] | 34d2e40bb0b26efc03da80b63fd58ebbd3f2cdd7 | https://github.com/orsinium/textdistance/blob/34d2e40bb0b26efc03da80b63fd58ebbd3f2cdd7/textdistance/algorithms/base.py#L51-L75 | train | 224,222 |
orsinium/textdistance | textdistance/algorithms/base.py | Base._ident | def _ident(*elements):
"""Return True if all sequences are equal.
"""
try:
# for hashable elements
return len(set(elements)) == 1
except TypeError:
# for unhashable elements
for e1, e2 in zip(elements, elements[1:]):
if e1 != e2:
return False
return True | python | def _ident(*elements):
"""Return True if all sequences are equal.
"""
try:
# for hashable elements
return len(set(elements)) == 1
except TypeError:
# for unhashable elements
for e1, e2 in zip(elements, elements[1:]):
if e1 != e2:
return False
return True | [
"def",
"_ident",
"(",
"*",
"elements",
")",
":",
"try",
":",
"# for hashable elements",
"return",
"len",
"(",
"set",
"(",
"elements",
")",
")",
"==",
"1",
"except",
"TypeError",
":",
"# for unhashable elements",
"for",
"e1",
",",
"e2",
"in",
"zip",
"(",
... | Return True if all sequences are equal. | [
"Return",
"True",
"if",
"all",
"sequences",
"are",
"equal",
"."
] | 34d2e40bb0b26efc03da80b63fd58ebbd3f2cdd7 | https://github.com/orsinium/textdistance/blob/34d2e40bb0b26efc03da80b63fd58ebbd3f2cdd7/textdistance/algorithms/base.py#L98-L109 | train | 224,223 |
orsinium/textdistance | textdistance/algorithms/base.py | Base._get_sequences | def _get_sequences(self, *sequences):
"""Prepare sequences.
qval=None: split text by words
qval=1: do not split sequences. For text this is mean comparing by letters.
qval>1: split sequences by q-grams
"""
# by words
if not self.qval:
return [s.split() for s in sequences]
# by chars
if self.qval == 1:
return sequences
# by n-grams
return [find_ngrams(s, self.qval) for s in sequences] | python | def _get_sequences(self, *sequences):
"""Prepare sequences.
qval=None: split text by words
qval=1: do not split sequences. For text this is mean comparing by letters.
qval>1: split sequences by q-grams
"""
# by words
if not self.qval:
return [s.split() for s in sequences]
# by chars
if self.qval == 1:
return sequences
# by n-grams
return [find_ngrams(s, self.qval) for s in sequences] | [
"def",
"_get_sequences",
"(",
"self",
",",
"*",
"sequences",
")",
":",
"# by words",
"if",
"not",
"self",
".",
"qval",
":",
"return",
"[",
"s",
".",
"split",
"(",
")",
"for",
"s",
"in",
"sequences",
"]",
"# by chars",
"if",
"self",
".",
"qval",
"==",... | Prepare sequences.
qval=None: split text by words
qval=1: do not split sequences. For text this is mean comparing by letters.
qval>1: split sequences by q-grams | [
"Prepare",
"sequences",
"."
] | 34d2e40bb0b26efc03da80b63fd58ebbd3f2cdd7 | https://github.com/orsinium/textdistance/blob/34d2e40bb0b26efc03da80b63fd58ebbd3f2cdd7/textdistance/algorithms/base.py#L111-L125 | train | 224,224 |
orsinium/textdistance | textdistance/algorithms/base.py | Base._get_counters | def _get_counters(self, *sequences):
"""Prepare sequences and convert it to Counters.
"""
# already Counters
if all(isinstance(s, Counter) for s in sequences):
return sequences
return [Counter(s) for s in self._get_sequences(*sequences)] | python | def _get_counters(self, *sequences):
"""Prepare sequences and convert it to Counters.
"""
# already Counters
if all(isinstance(s, Counter) for s in sequences):
return sequences
return [Counter(s) for s in self._get_sequences(*sequences)] | [
"def",
"_get_counters",
"(",
"self",
",",
"*",
"sequences",
")",
":",
"# already Counters",
"if",
"all",
"(",
"isinstance",
"(",
"s",
",",
"Counter",
")",
"for",
"s",
"in",
"sequences",
")",
":",
"return",
"sequences",
"return",
"[",
"Counter",
"(",
"s",... | Prepare sequences and convert it to Counters. | [
"Prepare",
"sequences",
"and",
"convert",
"it",
"to",
"Counters",
"."
] | 34d2e40bb0b26efc03da80b63fd58ebbd3f2cdd7 | https://github.com/orsinium/textdistance/blob/34d2e40bb0b26efc03da80b63fd58ebbd3f2cdd7/textdistance/algorithms/base.py#L127-L133 | train | 224,225 |
orsinium/textdistance | textdistance/algorithms/base.py | Base._count_counters | def _count_counters(self, counter):
"""Return all elements count from Counter
"""
if getattr(self, 'as_set', False):
return len(set(counter))
else:
return sum(counter.values()) | python | def _count_counters(self, counter):
"""Return all elements count from Counter
"""
if getattr(self, 'as_set', False):
return len(set(counter))
else:
return sum(counter.values()) | [
"def",
"_count_counters",
"(",
"self",
",",
"counter",
")",
":",
"if",
"getattr",
"(",
"self",
",",
"'as_set'",
",",
"False",
")",
":",
"return",
"len",
"(",
"set",
"(",
"counter",
")",
")",
"else",
":",
"return",
"sum",
"(",
"counter",
".",
"values"... | Return all elements count from Counter | [
"Return",
"all",
"elements",
"count",
"from",
"Counter"
] | 34d2e40bb0b26efc03da80b63fd58ebbd3f2cdd7 | https://github.com/orsinium/textdistance/blob/34d2e40bb0b26efc03da80b63fd58ebbd3f2cdd7/textdistance/algorithms/base.py#L153-L159 | train | 224,226 |
SCIP-Interfaces/PySCIPOpt | examples/finished/transp.py | make_inst2 | def make_inst2():
"""creates example data set 2"""
I,d = multidict({1:45, 2:20, 3:30 , 4:30}) # demand
J,M = multidict({1:35, 2:50, 3:40}) # capacity
c = {(1,1):8, (1,2):9, (1,3):14 , # {(customer,factory) : cost<float>}
(2,1):6, (2,2):12, (2,3):9 ,
(3,1):10, (3,2):13, (3,3):16 ,
(4,1):9, (4,2):7, (4,3):5 ,
}
return I,J,c,d,M | python | def make_inst2():
"""creates example data set 2"""
I,d = multidict({1:45, 2:20, 3:30 , 4:30}) # demand
J,M = multidict({1:35, 2:50, 3:40}) # capacity
c = {(1,1):8, (1,2):9, (1,3):14 , # {(customer,factory) : cost<float>}
(2,1):6, (2,2):12, (2,3):9 ,
(3,1):10, (3,2):13, (3,3):16 ,
(4,1):9, (4,2):7, (4,3):5 ,
}
return I,J,c,d,M | [
"def",
"make_inst2",
"(",
")",
":",
"I",
",",
"d",
"=",
"multidict",
"(",
"{",
"1",
":",
"45",
",",
"2",
":",
"20",
",",
"3",
":",
"30",
",",
"4",
":",
"30",
"}",
")",
"# demand",
"J",
",",
"M",
"=",
"multidict",
"(",
"{",
"1",
":",
"35",... | creates example data set 2 | [
"creates",
"example",
"data",
"set",
"2"
] | 9c960b40d94a48b0304d73dbe28b467b9c065abe | https://github.com/SCIP-Interfaces/PySCIPOpt/blob/9c960b40d94a48b0304d73dbe28b467b9c065abe/examples/finished/transp.py#L62-L71 | train | 224,227 |
SCIP-Interfaces/PySCIPOpt | examples/unfinished/vrp_lazy.py | VRPconshdlr.addCuts | def addCuts(self, checkonly):
"""add cuts if necessary and return whether model is feasible"""
cutsadded = False
edges = []
x = self.model.data
for (i, j) in x:
if self.model.getVal(x[i, j]) > .5:
if i != V[0] and j != V[0]:
edges.append((i, j))
G = networkx.Graph()
G.add_edges_from(edges)
Components = list(networkx.connected_components(G))
for S in Components:
S_card = len(S)
q_sum = sum(q[i] for i in S)
NS = int(math.ceil(float(q_sum) / Q))
S_edges = [(i, j) for i in S for j in S if i < j and (i, j) in edges]
if S_card >= 3 and (len(S_edges) >= S_card or NS > 1):
cutsadded = True
if checkonly:
break
else:
self.model.addCons(quicksum(x[i, j] for i in S for j in S if j > i) <= S_card - NS)
print("adding cut for", S_edges)
return cutsadded | python | def addCuts(self, checkonly):
"""add cuts if necessary and return whether model is feasible"""
cutsadded = False
edges = []
x = self.model.data
for (i, j) in x:
if self.model.getVal(x[i, j]) > .5:
if i != V[0] and j != V[0]:
edges.append((i, j))
G = networkx.Graph()
G.add_edges_from(edges)
Components = list(networkx.connected_components(G))
for S in Components:
S_card = len(S)
q_sum = sum(q[i] for i in S)
NS = int(math.ceil(float(q_sum) / Q))
S_edges = [(i, j) for i in S for j in S if i < j and (i, j) in edges]
if S_card >= 3 and (len(S_edges) >= S_card or NS > 1):
cutsadded = True
if checkonly:
break
else:
self.model.addCons(quicksum(x[i, j] for i in S for j in S if j > i) <= S_card - NS)
print("adding cut for", S_edges)
return cutsadded | [
"def",
"addCuts",
"(",
"self",
",",
"checkonly",
")",
":",
"cutsadded",
"=",
"False",
"edges",
"=",
"[",
"]",
"x",
"=",
"self",
".",
"model",
".",
"data",
"for",
"(",
"i",
",",
"j",
")",
"in",
"x",
":",
"if",
"self",
".",
"model",
".",
"getVal"... | add cuts if necessary and return whether model is feasible | [
"add",
"cuts",
"if",
"necessary",
"and",
"return",
"whether",
"model",
"is",
"feasible"
] | 9c960b40d94a48b0304d73dbe28b467b9c065abe | https://github.com/SCIP-Interfaces/PySCIPOpt/blob/9c960b40d94a48b0304d73dbe28b467b9c065abe/examples/unfinished/vrp_lazy.py#L17-L42 | train | 224,228 |
SCIP-Interfaces/PySCIPOpt | examples/finished/read_tsplib.py | distCEIL2D | def distCEIL2D(x1,y1,x2,y2):
"""returns smallest integer not less than the distance of two points"""
xdiff = x2 - x1
ydiff = y2 - y1
return int(math.ceil(math.sqrt(xdiff*xdiff + ydiff*ydiff))) | python | def distCEIL2D(x1,y1,x2,y2):
"""returns smallest integer not less than the distance of two points"""
xdiff = x2 - x1
ydiff = y2 - y1
return int(math.ceil(math.sqrt(xdiff*xdiff + ydiff*ydiff))) | [
"def",
"distCEIL2D",
"(",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
")",
":",
"xdiff",
"=",
"x2",
"-",
"x1",
"ydiff",
"=",
"y2",
"-",
"y1",
"return",
"int",
"(",
"math",
".",
"ceil",
"(",
"math",
".",
"sqrt",
"(",
"xdiff",
"*",
"xdiff",
"+",
"yd... | returns smallest integer not less than the distance of two points | [
"returns",
"smallest",
"integer",
"not",
"less",
"than",
"the",
"distance",
"of",
"two",
"points"
] | 9c960b40d94a48b0304d73dbe28b467b9c065abe | https://github.com/SCIP-Interfaces/PySCIPOpt/blob/9c960b40d94a48b0304d73dbe28b467b9c065abe/examples/finished/read_tsplib.py#L53-L57 | train | 224,229 |
SCIP-Interfaces/PySCIPOpt | examples/finished/read_tsplib.py | read_atsplib | def read_atsplib(filename):
"basic function for reading a ATSP problem on the TSPLIB format"
"NOTE: only works for explicit matrices"
if filename[-3:] == ".gz":
f = gzip.open(filename, 'r')
data = f.readlines()
else:
f = open(filename, 'r')
data = f.readlines()
for line in data:
if line.find("DIMENSION") >= 0:
n = int(line.split()[1])
break
else:
raise IOError("'DIMENSION' keyword not found in file '%s'" % filename)
for line in data:
if line.find("EDGE_WEIGHT_TYPE") >= 0:
if line.split()[1] == "EXPLICIT":
break
else:
raise IOError("'EDGE_WEIGHT_TYPE' is not 'EXPLICIT' in file '%s'" % filename)
for k,line in enumerate(data):
if line.find("EDGE_WEIGHT_SECTION") >= 0:
break
else:
raise IOError("'EDGE_WEIGHT_SECTION' not found in file '%s'" % filename)
c = {}
# flatten list of distances
dist = []
for line in data[k+1:]:
if line.find("EOF") >= 0:
break
for val in line.split():
dist.append(int(val))
k = 0
for i in range(n):
for j in range(n):
c[i+1,j+1] = dist[k]
k += 1
return n,c | python | def read_atsplib(filename):
"basic function for reading a ATSP problem on the TSPLIB format"
"NOTE: only works for explicit matrices"
if filename[-3:] == ".gz":
f = gzip.open(filename, 'r')
data = f.readlines()
else:
f = open(filename, 'r')
data = f.readlines()
for line in data:
if line.find("DIMENSION") >= 0:
n = int(line.split()[1])
break
else:
raise IOError("'DIMENSION' keyword not found in file '%s'" % filename)
for line in data:
if line.find("EDGE_WEIGHT_TYPE") >= 0:
if line.split()[1] == "EXPLICIT":
break
else:
raise IOError("'EDGE_WEIGHT_TYPE' is not 'EXPLICIT' in file '%s'" % filename)
for k,line in enumerate(data):
if line.find("EDGE_WEIGHT_SECTION") >= 0:
break
else:
raise IOError("'EDGE_WEIGHT_SECTION' not found in file '%s'" % filename)
c = {}
# flatten list of distances
dist = []
for line in data[k+1:]:
if line.find("EOF") >= 0:
break
for val in line.split():
dist.append(int(val))
k = 0
for i in range(n):
for j in range(n):
c[i+1,j+1] = dist[k]
k += 1
return n,c | [
"def",
"read_atsplib",
"(",
"filename",
")",
":",
"\"NOTE: only works for explicit matrices\"",
"if",
"filename",
"[",
"-",
"3",
":",
"]",
"==",
"\".gz\"",
":",
"f",
"=",
"gzip",
".",
"open",
"(",
"filename",
",",
"'r'",
")",
"data",
"=",
"f",
".",
"read... | basic function for reading a ATSP problem on the TSPLIB format | [
"basic",
"function",
"for",
"reading",
"a",
"ATSP",
"problem",
"on",
"the",
"TSPLIB",
"format"
] | 9c960b40d94a48b0304d73dbe28b467b9c065abe | https://github.com/SCIP-Interfaces/PySCIPOpt/blob/9c960b40d94a48b0304d73dbe28b467b9c065abe/examples/finished/read_tsplib.py#L216-L262 | train | 224,230 |
SCIP-Interfaces/PySCIPOpt | src/pyscipopt/Multidict.py | multidict | def multidict(D):
'''creates a multidictionary'''
keys = list(D.keys())
if len(keys) == 0:
return [[]]
try:
N = len(D[keys[0]])
islist = True
except:
N = 1
islist = False
dlist = [dict() for d in range(N)]
for k in keys:
if islist:
for i in range(N):
dlist[i][k] = D[k][i]
else:
dlist[0][k] = D[k]
return [keys]+dlist | python | def multidict(D):
'''creates a multidictionary'''
keys = list(D.keys())
if len(keys) == 0:
return [[]]
try:
N = len(D[keys[0]])
islist = True
except:
N = 1
islist = False
dlist = [dict() for d in range(N)]
for k in keys:
if islist:
for i in range(N):
dlist[i][k] = D[k][i]
else:
dlist[0][k] = D[k]
return [keys]+dlist | [
"def",
"multidict",
"(",
"D",
")",
":",
"keys",
"=",
"list",
"(",
"D",
".",
"keys",
"(",
")",
")",
"if",
"len",
"(",
"keys",
")",
"==",
"0",
":",
"return",
"[",
"[",
"]",
"]",
"try",
":",
"N",
"=",
"len",
"(",
"D",
"[",
"keys",
"[",
"0",
... | creates a multidictionary | [
"creates",
"a",
"multidictionary"
] | 9c960b40d94a48b0304d73dbe28b467b9c065abe | https://github.com/SCIP-Interfaces/PySCIPOpt/blob/9c960b40d94a48b0304d73dbe28b467b9c065abe/src/pyscipopt/Multidict.py#L3-L21 | train | 224,231 |
intake/intake | intake/catalog/local.py | register_plugin_module | def register_plugin_module(mod):
"""Find plugins in given module"""
for k, v in load_plugins_from_module(mod).items():
if k:
if isinstance(k, (list, tuple)):
k = k[0]
global_registry[k] = v | python | def register_plugin_module(mod):
"""Find plugins in given module"""
for k, v in load_plugins_from_module(mod).items():
if k:
if isinstance(k, (list, tuple)):
k = k[0]
global_registry[k] = v | [
"def",
"register_plugin_module",
"(",
"mod",
")",
":",
"for",
"k",
",",
"v",
"in",
"load_plugins_from_module",
"(",
"mod",
")",
".",
"items",
"(",
")",
":",
"if",
"k",
":",
"if",
"isinstance",
"(",
"k",
",",
"(",
"list",
",",
"tuple",
")",
")",
":"... | Find plugins in given module | [
"Find",
"plugins",
"in",
"given",
"module"
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/catalog/local.py#L494-L500 | train | 224,232 |
intake/intake | intake/catalog/local.py | register_plugin_dir | def register_plugin_dir(path):
"""Find plugins in given directory"""
import glob
for f in glob.glob(path + '/*.py'):
for k, v in load_plugins_from_module(f).items():
if k:
global_registry[k] = v | python | def register_plugin_dir(path):
"""Find plugins in given directory"""
import glob
for f in glob.glob(path + '/*.py'):
for k, v in load_plugins_from_module(f).items():
if k:
global_registry[k] = v | [
"def",
"register_plugin_dir",
"(",
"path",
")",
":",
"import",
"glob",
"for",
"f",
"in",
"glob",
".",
"glob",
"(",
"path",
"+",
"'/*.py'",
")",
":",
"for",
"k",
",",
"v",
"in",
"load_plugins_from_module",
"(",
"f",
")",
".",
"items",
"(",
")",
":",
... | Find plugins in given directory | [
"Find",
"plugins",
"in",
"given",
"directory"
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/catalog/local.py#L503-L509 | train | 224,233 |
intake/intake | intake/catalog/local.py | UserParameter.describe | def describe(self):
"""Information about this parameter"""
desc = {
'name': self.name,
'description': self.description,
# the Parameter might not have a type at all
'type': self.type or 'unknown',
}
for attr in ['min', 'max', 'allowed', 'default']:
v = getattr(self, attr)
if v is not None:
desc[attr] = v
return desc | python | def describe(self):
"""Information about this parameter"""
desc = {
'name': self.name,
'description': self.description,
# the Parameter might not have a type at all
'type': self.type or 'unknown',
}
for attr in ['min', 'max', 'allowed', 'default']:
v = getattr(self, attr)
if v is not None:
desc[attr] = v
return desc | [
"def",
"describe",
"(",
"self",
")",
":",
"desc",
"=",
"{",
"'name'",
":",
"self",
".",
"name",
",",
"'description'",
":",
"self",
".",
"description",
",",
"# the Parameter might not have a type at all",
"'type'",
":",
"self",
".",
"type",
"or",
"'unknown'",
... | Information about this parameter | [
"Information",
"about",
"this",
"parameter"
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/catalog/local.py#L88-L100 | train | 224,234 |
intake/intake | intake/catalog/local.py | UserParameter.validate | def validate(self, value):
"""Does value meet parameter requirements?"""
if self.type is not None:
value = coerce(self.type, value)
if self.min is not None and value < self.min:
raise ValueError('%s=%s is less than %s' % (self.name, value,
self.min))
if self.max is not None and value > self.max:
raise ValueError('%s=%s is greater than %s' % (
self.name, value, self.max))
if self.allowed is not None and value not in self.allowed:
raise ValueError('%s=%s is not one of the allowed values: %s' % (
self.name, value, ','.join(map(str, self.allowed))))
return value | python | def validate(self, value):
"""Does value meet parameter requirements?"""
if self.type is not None:
value = coerce(self.type, value)
if self.min is not None and value < self.min:
raise ValueError('%s=%s is less than %s' % (self.name, value,
self.min))
if self.max is not None and value > self.max:
raise ValueError('%s=%s is greater than %s' % (
self.name, value, self.max))
if self.allowed is not None and value not in self.allowed:
raise ValueError('%s=%s is not one of the allowed values: %s' % (
self.name, value, ','.join(map(str, self.allowed))))
return value | [
"def",
"validate",
"(",
"self",
",",
"value",
")",
":",
"if",
"self",
".",
"type",
"is",
"not",
"None",
":",
"value",
"=",
"coerce",
"(",
"self",
".",
"type",
",",
"value",
")",
"if",
"self",
".",
"min",
"is",
"not",
"None",
"and",
"value",
"<",
... | Does value meet parameter requirements? | [
"Does",
"value",
"meet",
"parameter",
"requirements?"
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/catalog/local.py#L111-L126 | train | 224,235 |
intake/intake | intake/catalog/local.py | LocalCatalogEntry.describe | def describe(self):
"""Basic information about this entry"""
if isinstance(self._plugin, list):
pl = [p.name for p in self._plugin]
elif isinstance(self._plugin, dict):
pl = {k: classname(v) for k, v in self._plugin.items()}
else:
pl = self._plugin if isinstance(self._plugin, str) else self._plugin.name
return {
'name': self._name,
'container': self._container,
'plugin': pl,
'description': self._description,
'direct_access': self._direct_access,
'user_parameters': [u.describe() for u in self._user_parameters],
'metadata': self._metadata,
'args': self._open_args
} | python | def describe(self):
"""Basic information about this entry"""
if isinstance(self._plugin, list):
pl = [p.name for p in self._plugin]
elif isinstance(self._plugin, dict):
pl = {k: classname(v) for k, v in self._plugin.items()}
else:
pl = self._plugin if isinstance(self._plugin, str) else self._plugin.name
return {
'name': self._name,
'container': self._container,
'plugin': pl,
'description': self._description,
'direct_access': self._direct_access,
'user_parameters': [u.describe() for u in self._user_parameters],
'metadata': self._metadata,
'args': self._open_args
} | [
"def",
"describe",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"_plugin",
",",
"list",
")",
":",
"pl",
"=",
"[",
"p",
".",
"name",
"for",
"p",
"in",
"self",
".",
"_plugin",
"]",
"elif",
"isinstance",
"(",
"self",
".",
"_plugin",
... | Basic information about this entry | [
"Basic",
"information",
"about",
"this",
"entry"
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/catalog/local.py#L207-L224 | train | 224,236 |
intake/intake | intake/catalog/local.py | LocalCatalogEntry.get | def get(self, **user_parameters):
"""Instantiate the DataSource for the given parameters"""
plugin, open_args = self._create_open_args(user_parameters)
data_source = plugin(**open_args)
data_source.catalog_object = self._catalog
data_source.name = self.name
data_source.description = self._description
data_source.cat = self._catalog
return data_source | python | def get(self, **user_parameters):
"""Instantiate the DataSource for the given parameters"""
plugin, open_args = self._create_open_args(user_parameters)
data_source = plugin(**open_args)
data_source.catalog_object = self._catalog
data_source.name = self.name
data_source.description = self._description
data_source.cat = self._catalog
return data_source | [
"def",
"get",
"(",
"self",
",",
"*",
"*",
"user_parameters",
")",
":",
"plugin",
",",
"open_args",
"=",
"self",
".",
"_create_open_args",
"(",
"user_parameters",
")",
"data_source",
"=",
"plugin",
"(",
"*",
"*",
"open_args",
")",
"data_source",
".",
"catal... | Instantiate the DataSource for the given parameters | [
"Instantiate",
"the",
"DataSource",
"for",
"the",
"given",
"parameters"
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/catalog/local.py#L263-L272 | train | 224,237 |
intake/intake | intake/catalog/local.py | YAMLFileCatalog._load | def _load(self, reload=False):
"""Load text of fcatalog file and pass to parse
Will do nothing if autoreload is off and reload is not explicitly
requested
"""
if self.autoreload or reload:
# First, we load from YAML, failing if syntax errors are found
options = self.storage_options or {}
if hasattr(self.path, 'path') or hasattr(self.path, 'read'):
file_open = self.path
self.path = make_path_posix(
getattr(self.path, 'path',
getattr(self.path, 'name', 'file')))
else:
file_open = open_files(self.path, mode='rb', **options)
assert len(file_open) == 1
file_open = file_open[0]
self._dir = get_dir(self.path)
with file_open as f:
text = f.read().decode()
if "!template " in text:
logger.warning("Use of '!template' deprecated - fixing")
text = text.replace('!template ', '')
self.parse(text) | python | def _load(self, reload=False):
"""Load text of fcatalog file and pass to parse
Will do nothing if autoreload is off and reload is not explicitly
requested
"""
if self.autoreload or reload:
# First, we load from YAML, failing if syntax errors are found
options = self.storage_options or {}
if hasattr(self.path, 'path') or hasattr(self.path, 'read'):
file_open = self.path
self.path = make_path_posix(
getattr(self.path, 'path',
getattr(self.path, 'name', 'file')))
else:
file_open = open_files(self.path, mode='rb', **options)
assert len(file_open) == 1
file_open = file_open[0]
self._dir = get_dir(self.path)
with file_open as f:
text = f.read().decode()
if "!template " in text:
logger.warning("Use of '!template' deprecated - fixing")
text = text.replace('!template ', '')
self.parse(text) | [
"def",
"_load",
"(",
"self",
",",
"reload",
"=",
"False",
")",
":",
"if",
"self",
".",
"autoreload",
"or",
"reload",
":",
"# First, we load from YAML, failing if syntax errors are found",
"options",
"=",
"self",
".",
"storage_options",
"or",
"{",
"}",
"if",
"has... | Load text of fcatalog file and pass to parse
Will do nothing if autoreload is off and reload is not explicitly
requested | [
"Load",
"text",
"of",
"fcatalog",
"file",
"and",
"pass",
"to",
"parse"
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/catalog/local.py#L544-L569 | train | 224,238 |
intake/intake | intake/catalog/local.py | YAMLFileCatalog.parse | def parse(self, text):
"""Create entries from catalog text
Normally the text comes from the file at self.path via the ``_load()``
method, but could be explicitly set instead. A copy of the text is
kept in attribute ``.text`` .
Parameters
----------
text : str
YAML formatted catalog spec
"""
self.text = text
data = yaml_load(self.text)
if data is None:
raise exceptions.CatalogException('No YAML data in file')
# Second, we validate the schema and semantics
context = dict(root=self._dir)
result = CatalogParser(data, context=context, getenv=self.getenv,
getshell=self.getshell)
if result.errors:
raise exceptions.ValidationError(
"Catalog '{}' has validation errors:\n\n{}"
"".format(self.path, "\n".join(result.errors)), result.errors)
cfg = result.data
self._entries = {}
for entry in cfg['data_sources']:
entry._catalog = self
self._entries[entry.name] = entry
self.metadata = cfg.get('metadata', {})
self.name = self.name or cfg.get('name') or self.name_from_path
self.description = self.description or cfg.get('description') | python | def parse(self, text):
"""Create entries from catalog text
Normally the text comes from the file at self.path via the ``_load()``
method, but could be explicitly set instead. A copy of the text is
kept in attribute ``.text`` .
Parameters
----------
text : str
YAML formatted catalog spec
"""
self.text = text
data = yaml_load(self.text)
if data is None:
raise exceptions.CatalogException('No YAML data in file')
# Second, we validate the schema and semantics
context = dict(root=self._dir)
result = CatalogParser(data, context=context, getenv=self.getenv,
getshell=self.getshell)
if result.errors:
raise exceptions.ValidationError(
"Catalog '{}' has validation errors:\n\n{}"
"".format(self.path, "\n".join(result.errors)), result.errors)
cfg = result.data
self._entries = {}
for entry in cfg['data_sources']:
entry._catalog = self
self._entries[entry.name] = entry
self.metadata = cfg.get('metadata', {})
self.name = self.name or cfg.get('name') or self.name_from_path
self.description = self.description or cfg.get('description') | [
"def",
"parse",
"(",
"self",
",",
"text",
")",
":",
"self",
".",
"text",
"=",
"text",
"data",
"=",
"yaml_load",
"(",
"self",
".",
"text",
")",
"if",
"data",
"is",
"None",
":",
"raise",
"exceptions",
".",
"CatalogException",
"(",
"'No YAML data in file'",... | Create entries from catalog text
Normally the text comes from the file at self.path via the ``_load()``
method, but could be explicitly set instead. A copy of the text is
kept in attribute ``.text`` .
Parameters
----------
text : str
YAML formatted catalog spec | [
"Create",
"entries",
"from",
"catalog",
"text"
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/catalog/local.py#L571-L607 | train | 224,239 |
intake/intake | intake/catalog/local.py | YAMLFileCatalog.name_from_path | def name_from_path(self):
"""If catalog is named 'catalog' take name from parent directory"""
name = os.path.splitext(os.path.basename(self.path))[0]
if name == 'catalog':
name = os.path.basename(os.path.dirname(self.path))
return name.replace('.', '_') | python | def name_from_path(self):
"""If catalog is named 'catalog' take name from parent directory"""
name = os.path.splitext(os.path.basename(self.path))[0]
if name == 'catalog':
name = os.path.basename(os.path.dirname(self.path))
return name.replace('.', '_') | [
"def",
"name_from_path",
"(",
"self",
")",
":",
"name",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"self",
".",
"path",
")",
")",
"[",
"0",
"]",
"if",
"name",
"==",
"'catalog'",
":",
"name",
"=",
"os",
... | If catalog is named 'catalog' take name from parent directory | [
"If",
"catalog",
"is",
"named",
"catalog",
"take",
"name",
"from",
"parent",
"directory"
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/catalog/local.py#L610-L615 | train | 224,240 |
intake/intake | intake/cli/server/server.py | ServerSourceHandler.get | def get(self):
"""
Access one source's info.
This is for direct access to an entry by name for random access, which
is useful to the client when the whole catalog has not first been
listed and pulled locally (e.g., in the case of pagination).
"""
head = self.request.headers
name = self.get_argument('name')
if self.auth.allow_connect(head):
if 'source_id' in head:
cat = self._cache.get(head['source_id'])
else:
cat = self._catalog
try:
source = cat[name]
except KeyError:
msg = 'No such entry'
raise tornado.web.HTTPError(status_code=404, log_message=msg,
reason=msg)
if self.auth.allow_access(head, source, self._catalog):
info = source.describe()
info['name'] = name
source_info = dict(source=info)
self.write(msgpack.packb(source_info, use_bin_type=True))
return
msg = 'Access forbidden'
raise tornado.web.HTTPError(status_code=403, log_message=msg,
reason=msg) | python | def get(self):
"""
Access one source's info.
This is for direct access to an entry by name for random access, which
is useful to the client when the whole catalog has not first been
listed and pulled locally (e.g., in the case of pagination).
"""
head = self.request.headers
name = self.get_argument('name')
if self.auth.allow_connect(head):
if 'source_id' in head:
cat = self._cache.get(head['source_id'])
else:
cat = self._catalog
try:
source = cat[name]
except KeyError:
msg = 'No such entry'
raise tornado.web.HTTPError(status_code=404, log_message=msg,
reason=msg)
if self.auth.allow_access(head, source, self._catalog):
info = source.describe()
info['name'] = name
source_info = dict(source=info)
self.write(msgpack.packb(source_info, use_bin_type=True))
return
msg = 'Access forbidden'
raise tornado.web.HTTPError(status_code=403, log_message=msg,
reason=msg) | [
"def",
"get",
"(",
"self",
")",
":",
"head",
"=",
"self",
".",
"request",
".",
"headers",
"name",
"=",
"self",
".",
"get_argument",
"(",
"'name'",
")",
"if",
"self",
".",
"auth",
".",
"allow_connect",
"(",
"head",
")",
":",
"if",
"'source_id'",
"in",... | Access one source's info.
This is for direct access to an entry by name for random access, which
is useful to the client when the whole catalog has not first been
listed and pulled locally (e.g., in the case of pagination). | [
"Access",
"one",
"source",
"s",
"info",
"."
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/cli/server/server.py#L186-L216 | train | 224,241 |
intake/intake | intake/gui/catalog/select.py | CatSelector.preprocess | def preprocess(cls, cat):
"""Function to run on each cat input"""
if isinstance(cat, str):
cat = intake.open_catalog(cat)
return cat | python | def preprocess(cls, cat):
"""Function to run on each cat input"""
if isinstance(cat, str):
cat = intake.open_catalog(cat)
return cat | [
"def",
"preprocess",
"(",
"cls",
",",
"cat",
")",
":",
"if",
"isinstance",
"(",
"cat",
",",
"str",
")",
":",
"cat",
"=",
"intake",
".",
"open_catalog",
"(",
"cat",
")",
"return",
"cat"
] | Function to run on each cat input | [
"Function",
"to",
"run",
"on",
"each",
"cat",
"input"
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/gui/catalog/select.py#L57-L61 | train | 224,242 |
intake/intake | intake/gui/catalog/select.py | CatSelector.expand_nested | def expand_nested(self, cats):
"""Populate widget with nested catalogs"""
down = '│'
right = '└──'
def get_children(parent):
return [e() for e in parent._entries.values() if e._container == 'catalog']
if len(cats) == 0:
return
cat = cats[0]
old = list(self.options.items())
name = next(k for k, v in old if v == cat)
index = next(i for i, (k, v) in enumerate(old) if v == cat)
if right in name:
prefix = f'{name.split(right)[0]}{down} {right}'
else:
prefix = right
children = get_children(cat)
for i, child in enumerate(children):
old.insert(index+i+1, (f'{prefix} {child.name}', child))
self.widget.options = dict(old) | python | def expand_nested(self, cats):
"""Populate widget with nested catalogs"""
down = '│'
right = '└──'
def get_children(parent):
return [e() for e in parent._entries.values() if e._container == 'catalog']
if len(cats) == 0:
return
cat = cats[0]
old = list(self.options.items())
name = next(k for k, v in old if v == cat)
index = next(i for i, (k, v) in enumerate(old) if v == cat)
if right in name:
prefix = f'{name.split(right)[0]}{down} {right}'
else:
prefix = right
children = get_children(cat)
for i, child in enumerate(children):
old.insert(index+i+1, (f'{prefix} {child.name}', child))
self.widget.options = dict(old) | [
"def",
"expand_nested",
"(",
"self",
",",
"cats",
")",
":",
"down",
"=",
"'│'",
"right",
"=",
"'└──'",
"def",
"get_children",
"(",
"parent",
")",
":",
"return",
"[",
"e",
"(",
")",
"for",
"e",
"in",
"parent",
".",
"_entries",
".",
"values",
"(",
")... | Populate widget with nested catalogs | [
"Populate",
"widget",
"with",
"nested",
"catalogs"
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/gui/catalog/select.py#L91-L114 | train | 224,243 |
intake/intake | intake/gui/catalog/select.py | CatSelector.collapse_nested | def collapse_nested(self, cats, max_nestedness=10):
"""
Collapse any items that are nested under cats.
`max_nestedness` acts as a fail-safe to prevent infinite looping.
"""
children = []
removed = set()
nestedness = max_nestedness
old = list(self.widget.options.values())
nested = [cat for cat in old if getattr(cat, 'cat') is not None]
parents = {cat.cat for cat in nested}
parents_to_remove = cats
while len(parents_to_remove) > 0 and nestedness > 0:
for cat in nested:
if cat.cat in parents_to_remove:
children.append(cat)
removed = removed.union(parents_to_remove)
nested = [cat for cat in nested if cat not in children]
parents_to_remove = {c for c in children if c in parents - removed}
nestedness -= 1
self.remove(children) | python | def collapse_nested(self, cats, max_nestedness=10):
"""
Collapse any items that are nested under cats.
`max_nestedness` acts as a fail-safe to prevent infinite looping.
"""
children = []
removed = set()
nestedness = max_nestedness
old = list(self.widget.options.values())
nested = [cat for cat in old if getattr(cat, 'cat') is not None]
parents = {cat.cat for cat in nested}
parents_to_remove = cats
while len(parents_to_remove) > 0 and nestedness > 0:
for cat in nested:
if cat.cat in parents_to_remove:
children.append(cat)
removed = removed.union(parents_to_remove)
nested = [cat for cat in nested if cat not in children]
parents_to_remove = {c for c in children if c in parents - removed}
nestedness -= 1
self.remove(children) | [
"def",
"collapse_nested",
"(",
"self",
",",
"cats",
",",
"max_nestedness",
"=",
"10",
")",
":",
"children",
"=",
"[",
"]",
"removed",
"=",
"set",
"(",
")",
"nestedness",
"=",
"max_nestedness",
"old",
"=",
"list",
"(",
"self",
".",
"widget",
".",
"optio... | Collapse any items that are nested under cats.
`max_nestedness` acts as a fail-safe to prevent infinite looping. | [
"Collapse",
"any",
"items",
"that",
"are",
"nested",
"under",
"cats",
".",
"max_nestedness",
"acts",
"as",
"a",
"fail",
"-",
"safe",
"to",
"prevent",
"infinite",
"looping",
"."
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/gui/catalog/select.py#L116-L137 | train | 224,244 |
intake/intake | intake/gui/catalog/select.py | CatSelector.remove_selected | def remove_selected(self, *args):
"""Remove the selected catalog - allow the passing of arbitrary
args so that buttons work. Also remove any nested catalogs."""
self.collapse_nested(self.selected)
self.remove(self.selected) | python | def remove_selected(self, *args):
"""Remove the selected catalog - allow the passing of arbitrary
args so that buttons work. Also remove any nested catalogs."""
self.collapse_nested(self.selected)
self.remove(self.selected) | [
"def",
"remove_selected",
"(",
"self",
",",
"*",
"args",
")",
":",
"self",
".",
"collapse_nested",
"(",
"self",
".",
"selected",
")",
"self",
".",
"remove",
"(",
"self",
".",
"selected",
")"
] | Remove the selected catalog - allow the passing of arbitrary
args so that buttons work. Also remove any nested catalogs. | [
"Remove",
"the",
"selected",
"catalog",
"-",
"allow",
"the",
"passing",
"of",
"arbitrary",
"args",
"so",
"that",
"buttons",
"work",
".",
"Also",
"remove",
"any",
"nested",
"catalogs",
"."
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/gui/catalog/select.py#L139-L143 | train | 224,245 |
intake/intake | intake/container/persist.py | PersistStore.add | def add(self, key, source):
"""Add the persisted source to the store under the given key
key : str
The unique token of the un-persisted, original source
source : DataSource instance
The thing to add to the persisted catalogue, referring to persisted
data
"""
from intake.catalog.local import LocalCatalogEntry
try:
with self.fs.open(self.path, 'rb') as f:
data = yaml.safe_load(f)
except IOError:
data = {'sources': {}}
ds = source._yaml()['sources'][source.name]
data['sources'][key] = ds
with self.fs.open(self.path, 'wb') as fo:
fo.write(yaml.dump(data, default_flow_style=False).encode())
self._entries[key] = LocalCatalogEntry(
name=ds['metadata']['original_name'],
direct_access=True,
cache=[],
parameters=[],
catalog_dir=None,
**data['sources'][key]) | python | def add(self, key, source):
"""Add the persisted source to the store under the given key
key : str
The unique token of the un-persisted, original source
source : DataSource instance
The thing to add to the persisted catalogue, referring to persisted
data
"""
from intake.catalog.local import LocalCatalogEntry
try:
with self.fs.open(self.path, 'rb') as f:
data = yaml.safe_load(f)
except IOError:
data = {'sources': {}}
ds = source._yaml()['sources'][source.name]
data['sources'][key] = ds
with self.fs.open(self.path, 'wb') as fo:
fo.write(yaml.dump(data, default_flow_style=False).encode())
self._entries[key] = LocalCatalogEntry(
name=ds['metadata']['original_name'],
direct_access=True,
cache=[],
parameters=[],
catalog_dir=None,
**data['sources'][key]) | [
"def",
"add",
"(",
"self",
",",
"key",
",",
"source",
")",
":",
"from",
"intake",
".",
"catalog",
".",
"local",
"import",
"LocalCatalogEntry",
"try",
":",
"with",
"self",
".",
"fs",
".",
"open",
"(",
"self",
".",
"path",
",",
"'rb'",
")",
"as",
"f"... | Add the persisted source to the store under the given key
key : str
The unique token of the un-persisted, original source
source : DataSource instance
The thing to add to the persisted catalogue, referring to persisted
data | [
"Add",
"the",
"persisted",
"source",
"to",
"the",
"store",
"under",
"the",
"given",
"key"
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/container/persist.py#L84-L109 | train | 224,246 |
intake/intake | intake/container/persist.py | PersistStore.get_tok | def get_tok(self, source):
"""Get string token from object
Strings are assumed to already be a token; if source or entry, see
if it is a persisted thing ("original_tok" is in its metadata), else
generate its own token.
"""
if isinstance(source, str):
return source
if isinstance(source, CatalogEntry):
return source._metadata.get('original_tok', source._tok)
if isinstance(source, DataSource):
return source.metadata.get('original_tok', source._tok)
raise IndexError | python | def get_tok(self, source):
"""Get string token from object
Strings are assumed to already be a token; if source or entry, see
if it is a persisted thing ("original_tok" is in its metadata), else
generate its own token.
"""
if isinstance(source, str):
return source
if isinstance(source, CatalogEntry):
return source._metadata.get('original_tok', source._tok)
if isinstance(source, DataSource):
return source.metadata.get('original_tok', source._tok)
raise IndexError | [
"def",
"get_tok",
"(",
"self",
",",
"source",
")",
":",
"if",
"isinstance",
"(",
"source",
",",
"str",
")",
":",
"return",
"source",
"if",
"isinstance",
"(",
"source",
",",
"CatalogEntry",
")",
":",
"return",
"source",
".",
"_metadata",
".",
"get",
"("... | Get string token from object
Strings are assumed to already be a token; if source or entry, see
if it is a persisted thing ("original_tok" is in its metadata), else
generate its own token. | [
"Get",
"string",
"token",
"from",
"object"
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/container/persist.py#L111-L126 | train | 224,247 |
intake/intake | intake/container/persist.py | PersistStore.remove | def remove(self, source, delfiles=True):
"""Remove a dataset from the persist store
source : str or DataSource or Lo
If a str, this is the unique ID of the original source, which is
the key of the persisted dataset within the store. If a source,
can be either the original or the persisted source.
delfiles : bool
Whether to remove the on-disc artifact
"""
source = self.get_tok(source)
with self.fs.open(self.path, 'rb') as f:
data = yaml.safe_load(f.read().decode())
data['sources'].pop(source, None)
with self.fs.open(self.path, 'wb') as fo:
fo.write(yaml.dump(data, default_flow_style=False).encode())
if delfiles:
path = posixpath.join(self.pdir, source)
try:
self.fs.rm(path, True)
except Exception as e:
logger.debug("Failed to delete persisted data dir %s" % path)
self._entries.pop(source, None) | python | def remove(self, source, delfiles=True):
"""Remove a dataset from the persist store
source : str or DataSource or Lo
If a str, this is the unique ID of the original source, which is
the key of the persisted dataset within the store. If a source,
can be either the original or the persisted source.
delfiles : bool
Whether to remove the on-disc artifact
"""
source = self.get_tok(source)
with self.fs.open(self.path, 'rb') as f:
data = yaml.safe_load(f.read().decode())
data['sources'].pop(source, None)
with self.fs.open(self.path, 'wb') as fo:
fo.write(yaml.dump(data, default_flow_style=False).encode())
if delfiles:
path = posixpath.join(self.pdir, source)
try:
self.fs.rm(path, True)
except Exception as e:
logger.debug("Failed to delete persisted data dir %s" % path)
self._entries.pop(source, None) | [
"def",
"remove",
"(",
"self",
",",
"source",
",",
"delfiles",
"=",
"True",
")",
":",
"source",
"=",
"self",
".",
"get_tok",
"(",
"source",
")",
"with",
"self",
".",
"fs",
".",
"open",
"(",
"self",
".",
"path",
",",
"'rb'",
")",
"as",
"f",
":",
... | Remove a dataset from the persist store
source : str or DataSource or Lo
If a str, this is the unique ID of the original source, which is
the key of the persisted dataset within the store. If a source,
can be either the original or the persisted source.
delfiles : bool
Whether to remove the on-disc artifact | [
"Remove",
"a",
"dataset",
"from",
"the",
"persist",
"store"
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/container/persist.py#L128-L150 | train | 224,248 |
intake/intake | intake/container/persist.py | PersistStore.backtrack | def backtrack(self, source):
"""Given a unique key in the store, recreate original source"""
key = self.get_tok(source)
s = self[key]()
meta = s.metadata['original_source']
cls = meta['cls']
args = meta['args']
kwargs = meta['kwargs']
cls = import_name(cls)
sout = cls(*args, **kwargs)
sout.metadata = s.metadata['original_metadata']
sout.name = s.metadata['original_name']
return sout | python | def backtrack(self, source):
"""Given a unique key in the store, recreate original source"""
key = self.get_tok(source)
s = self[key]()
meta = s.metadata['original_source']
cls = meta['cls']
args = meta['args']
kwargs = meta['kwargs']
cls = import_name(cls)
sout = cls(*args, **kwargs)
sout.metadata = s.metadata['original_metadata']
sout.name = s.metadata['original_name']
return sout | [
"def",
"backtrack",
"(",
"self",
",",
"source",
")",
":",
"key",
"=",
"self",
".",
"get_tok",
"(",
"source",
")",
"s",
"=",
"self",
"[",
"key",
"]",
"(",
")",
"meta",
"=",
"s",
".",
"metadata",
"[",
"'original_source'",
"]",
"cls",
"=",
"meta",
"... | Given a unique key in the store, recreate original source | [
"Given",
"a",
"unique",
"key",
"in",
"the",
"store",
"recreate",
"original",
"source"
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/container/persist.py#L156-L168 | train | 224,249 |
intake/intake | intake/container/persist.py | PersistStore.refresh | def refresh(self, key):
"""Recreate and re-persist the source for the given unique ID"""
s0 = self[key]
s = self.backtrack(key)
s.persist(**s0.metadata['persist_kwargs']) | python | def refresh(self, key):
"""Recreate and re-persist the source for the given unique ID"""
s0 = self[key]
s = self.backtrack(key)
s.persist(**s0.metadata['persist_kwargs']) | [
"def",
"refresh",
"(",
"self",
",",
"key",
")",
":",
"s0",
"=",
"self",
"[",
"key",
"]",
"s",
"=",
"self",
".",
"backtrack",
"(",
"key",
")",
"s",
".",
"persist",
"(",
"*",
"*",
"s0",
".",
"metadata",
"[",
"'persist_kwargs'",
"]",
")"
] | Recreate and re-persist the source for the given unique ID | [
"Recreate",
"and",
"re",
"-",
"persist",
"the",
"source",
"for",
"the",
"given",
"unique",
"ID"
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/container/persist.py#L170-L174 | train | 224,250 |
intake/intake | intake/gui/source/select.py | SourceSelector.cats | def cats(self, cats):
"""Set sources from a list of cats"""
sources = []
for cat in coerce_to_list(cats):
sources.extend([entry for entry in cat._entries.values() if entry._container != 'catalog'])
self.items = sources | python | def cats(self, cats):
"""Set sources from a list of cats"""
sources = []
for cat in coerce_to_list(cats):
sources.extend([entry for entry in cat._entries.values() if entry._container != 'catalog'])
self.items = sources | [
"def",
"cats",
"(",
"self",
",",
"cats",
")",
":",
"sources",
"=",
"[",
"]",
"for",
"cat",
"in",
"coerce_to_list",
"(",
"cats",
")",
":",
"sources",
".",
"extend",
"(",
"[",
"entry",
"for",
"entry",
"in",
"cat",
".",
"_entries",
".",
"values",
"(",... | Set sources from a list of cats | [
"Set",
"sources",
"from",
"a",
"list",
"of",
"cats"
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/gui/source/select.py#L88-L93 | train | 224,251 |
intake/intake | intake/cli/client/__main__.py | main | def main(argv=None):
''' Execute the "intake" command line program.
'''
from intake.cli.bootstrap import main as _main
return _main('Intake Catalog CLI', subcommands.all, argv or sys.argv) | python | def main(argv=None):
''' Execute the "intake" command line program.
'''
from intake.cli.bootstrap import main as _main
return _main('Intake Catalog CLI', subcommands.all, argv or sys.argv) | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"from",
"intake",
".",
"cli",
".",
"bootstrap",
"import",
"main",
"as",
"_main",
"return",
"_main",
"(",
"'Intake Catalog CLI'",
",",
"subcommands",
".",
"all",
",",
"argv",
"or",
"sys",
".",
"argv",
"... | Execute the "intake" command line program. | [
"Execute",
"the",
"intake",
"command",
"line",
"program",
"."
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/cli/client/__main__.py#L27-L33 | train | 224,252 |
intake/intake | intake/source/base.py | DataSource._load_metadata | def _load_metadata(self):
"""load metadata only if needed"""
if self._schema is None:
self._schema = self._get_schema()
self.datashape = self._schema.datashape
self.dtype = self._schema.dtype
self.shape = self._schema.shape
self.npartitions = self._schema.npartitions
self.metadata.update(self._schema.extra_metadata) | python | def _load_metadata(self):
"""load metadata only if needed"""
if self._schema is None:
self._schema = self._get_schema()
self.datashape = self._schema.datashape
self.dtype = self._schema.dtype
self.shape = self._schema.shape
self.npartitions = self._schema.npartitions
self.metadata.update(self._schema.extra_metadata) | [
"def",
"_load_metadata",
"(",
"self",
")",
":",
"if",
"self",
".",
"_schema",
"is",
"None",
":",
"self",
".",
"_schema",
"=",
"self",
".",
"_get_schema",
"(",
")",
"self",
".",
"datashape",
"=",
"self",
".",
"_schema",
".",
"datashape",
"self",
".",
... | load metadata only if needed | [
"load",
"metadata",
"only",
"if",
"needed"
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/source/base.py#L114-L122 | train | 224,253 |
intake/intake | intake/source/base.py | DataSource.yaml | def yaml(self, with_plugin=False):
"""Return YAML representation of this data-source
The output may be roughly appropriate for inclusion in a YAML
catalog. This is a best-effort implementation
Parameters
----------
with_plugin: bool
If True, create a "plugins" section, for cases where this source
is created with a plugin not expected to be in the global Intake
registry.
"""
from yaml import dump
data = self._yaml(with_plugin=with_plugin)
return dump(data, default_flow_style=False) | python | def yaml(self, with_plugin=False):
"""Return YAML representation of this data-source
The output may be roughly appropriate for inclusion in a YAML
catalog. This is a best-effort implementation
Parameters
----------
with_plugin: bool
If True, create a "plugins" section, for cases where this source
is created with a plugin not expected to be in the global Intake
registry.
"""
from yaml import dump
data = self._yaml(with_plugin=with_plugin)
return dump(data, default_flow_style=False) | [
"def",
"yaml",
"(",
"self",
",",
"with_plugin",
"=",
"False",
")",
":",
"from",
"yaml",
"import",
"dump",
"data",
"=",
"self",
".",
"_yaml",
"(",
"with_plugin",
"=",
"with_plugin",
")",
"return",
"dump",
"(",
"data",
",",
"default_flow_style",
"=",
"Fals... | Return YAML representation of this data-source
The output may be roughly appropriate for inclusion in a YAML
catalog. This is a best-effort implementation
Parameters
----------
with_plugin: bool
If True, create a "plugins" section, for cases where this source
is created with a plugin not expected to be in the global Intake
registry. | [
"Return",
"YAML",
"representation",
"of",
"this",
"data",
"-",
"source"
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/source/base.py#L145-L160 | train | 224,254 |
intake/intake | intake/source/base.py | DataSource.discover | def discover(self):
"""Open resource and populate the source attributes."""
self._load_metadata()
return dict(datashape=self.datashape,
dtype=self.dtype,
shape=self.shape,
npartitions=self.npartitions,
metadata=self.metadata) | python | def discover(self):
"""Open resource and populate the source attributes."""
self._load_metadata()
return dict(datashape=self.datashape,
dtype=self.dtype,
shape=self.shape,
npartitions=self.npartitions,
metadata=self.metadata) | [
"def",
"discover",
"(",
"self",
")",
":",
"self",
".",
"_load_metadata",
"(",
")",
"return",
"dict",
"(",
"datashape",
"=",
"self",
".",
"datashape",
",",
"dtype",
"=",
"self",
".",
"dtype",
",",
"shape",
"=",
"self",
".",
"shape",
",",
"npartitions",
... | Open resource and populate the source attributes. | [
"Open",
"resource",
"and",
"populate",
"the",
"source",
"attributes",
"."
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/source/base.py#L167-L175 | train | 224,255 |
intake/intake | intake/source/base.py | DataSource.read_chunked | def read_chunked(self):
"""Return iterator over container fragments of data source"""
self._load_metadata()
for i in range(self.npartitions):
yield self._get_partition(i) | python | def read_chunked(self):
"""Return iterator over container fragments of data source"""
self._load_metadata()
for i in range(self.npartitions):
yield self._get_partition(i) | [
"def",
"read_chunked",
"(",
"self",
")",
":",
"self",
".",
"_load_metadata",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"npartitions",
")",
":",
"yield",
"self",
".",
"_get_partition",
"(",
"i",
")"
] | Return iterator over container fragments of data source | [
"Return",
"iterator",
"over",
"container",
"fragments",
"of",
"data",
"source"
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/source/base.py#L184-L188 | train | 224,256 |
intake/intake | intake/source/base.py | DataSource.read_partition | def read_partition(self, i):
"""Return a part of the data corresponding to i-th partition.
By default, assumes i should be an integer between zero and npartitions;
override for more complex indexing schemes.
"""
self._load_metadata()
if i < 0 or i >= self.npartitions:
raise IndexError('%d is out of range' % i)
return self._get_partition(i) | python | def read_partition(self, i):
"""Return a part of the data corresponding to i-th partition.
By default, assumes i should be an integer between zero and npartitions;
override for more complex indexing schemes.
"""
self._load_metadata()
if i < 0 or i >= self.npartitions:
raise IndexError('%d is out of range' % i)
return self._get_partition(i) | [
"def",
"read_partition",
"(",
"self",
",",
"i",
")",
":",
"self",
".",
"_load_metadata",
"(",
")",
"if",
"i",
"<",
"0",
"or",
"i",
">=",
"self",
".",
"npartitions",
":",
"raise",
"IndexError",
"(",
"'%d is out of range'",
"%",
"i",
")",
"return",
"self... | Return a part of the data corresponding to i-th partition.
By default, assumes i should be an integer between zero and npartitions;
override for more complex indexing schemes. | [
"Return",
"a",
"part",
"of",
"the",
"data",
"corresponding",
"to",
"i",
"-",
"th",
"partition",
"."
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/source/base.py#L190-L200 | train | 224,257 |
intake/intake | intake/source/base.py | DataSource.plot | def plot(self):
"""
Returns a hvPlot object to provide a high-level plotting API.
To display in a notebook, be sure to run ``intake.output_notebook()``
first.
"""
try:
from hvplot import hvPlot
except ImportError:
raise ImportError("The intake plotting API requires hvplot."
"hvplot may be installed with:\n\n"
"`conda install -c pyviz hvplot` or "
"`pip install hvplot`.")
metadata = self.metadata.get('plot', {})
fields = self.metadata.get('fields', {})
for attrs in fields.values():
if 'range' in attrs:
attrs['range'] = tuple(attrs['range'])
metadata['fields'] = fields
plots = self.metadata.get('plots', {})
return hvPlot(self, custom_plots=plots, **metadata) | python | def plot(self):
"""
Returns a hvPlot object to provide a high-level plotting API.
To display in a notebook, be sure to run ``intake.output_notebook()``
first.
"""
try:
from hvplot import hvPlot
except ImportError:
raise ImportError("The intake plotting API requires hvplot."
"hvplot may be installed with:\n\n"
"`conda install -c pyviz hvplot` or "
"`pip install hvplot`.")
metadata = self.metadata.get('plot', {})
fields = self.metadata.get('fields', {})
for attrs in fields.values():
if 'range' in attrs:
attrs['range'] = tuple(attrs['range'])
metadata['fields'] = fields
plots = self.metadata.get('plots', {})
return hvPlot(self, custom_plots=plots, **metadata) | [
"def",
"plot",
"(",
"self",
")",
":",
"try",
":",
"from",
"hvplot",
"import",
"hvPlot",
"except",
"ImportError",
":",
"raise",
"ImportError",
"(",
"\"The intake plotting API requires hvplot.\"",
"\"hvplot may be installed with:\\n\\n\"",
"\"`conda install -c pyviz hvplot` or ... | Returns a hvPlot object to provide a high-level plotting API.
To display in a notebook, be sure to run ``intake.output_notebook()``
first. | [
"Returns",
"a",
"hvPlot",
"object",
"to",
"provide",
"a",
"high",
"-",
"level",
"plotting",
"API",
"."
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/source/base.py#L231-L252 | train | 224,258 |
intake/intake | intake/source/base.py | DataSource.persist | def persist(self, ttl=None, **kwargs):
"""Save data from this source to local persistent storage"""
from ..container import container_map
from ..container.persist import PersistStore
import time
if 'original_tok' in self.metadata:
raise ValueError('Cannot persist a source taken from the persist '
'store')
method = container_map[self.container]._persist
store = PersistStore()
out = method(self, path=store.getdir(self), **kwargs)
out.description = self.description
metadata = {'timestamp': time.time(),
'original_metadata': self.metadata,
'original_source': self.__getstate__(),
'original_name': self.name,
'original_tok': self._tok,
'persist_kwargs': kwargs,
'ttl': ttl,
'cat': {} if self.cat is None else self.cat.__getstate__()}
out.metadata = metadata
out.name = self.name
store.add(self._tok, out)
return out | python | def persist(self, ttl=None, **kwargs):
"""Save data from this source to local persistent storage"""
from ..container import container_map
from ..container.persist import PersistStore
import time
if 'original_tok' in self.metadata:
raise ValueError('Cannot persist a source taken from the persist '
'store')
method = container_map[self.container]._persist
store = PersistStore()
out = method(self, path=store.getdir(self), **kwargs)
out.description = self.description
metadata = {'timestamp': time.time(),
'original_metadata': self.metadata,
'original_source': self.__getstate__(),
'original_name': self.name,
'original_tok': self._tok,
'persist_kwargs': kwargs,
'ttl': ttl,
'cat': {} if self.cat is None else self.cat.__getstate__()}
out.metadata = metadata
out.name = self.name
store.add(self._tok, out)
return out | [
"def",
"persist",
"(",
"self",
",",
"ttl",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
".",
".",
"container",
"import",
"container_map",
"from",
".",
".",
"container",
".",
"persist",
"import",
"PersistStore",
"import",
"time",
"if",
"'origin... | Save data from this source to local persistent storage | [
"Save",
"data",
"from",
"this",
"source",
"to",
"local",
"persistent",
"storage"
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/source/base.py#L261-L284 | train | 224,259 |
intake/intake | intake/source/base.py | DataSource.export | def export(self, path, **kwargs):
"""Save this data for sharing with other people
Creates a copy of the data in a format appropriate for its container,
in the location specified (which can be remote, e.g., s3). Returns
a YAML representation of this saved dataset, so that it can be put
into a catalog file.
"""
from ..container import container_map
import time
method = container_map[self.container]._persist
# may need to create path - access file-system method
out = method(self, path=path, **kwargs)
out.description = self.description
metadata = {'timestamp': time.time(),
'original_metadata': self.metadata,
'original_source': self.__getstate__(),
'original_name': self.name,
'original_tok': self._tok,
'persist_kwargs': kwargs}
out.metadata = metadata
out.name = self.name
return out.yaml() | python | def export(self, path, **kwargs):
"""Save this data for sharing with other people
Creates a copy of the data in a format appropriate for its container,
in the location specified (which can be remote, e.g., s3). Returns
a YAML representation of this saved dataset, so that it can be put
into a catalog file.
"""
from ..container import container_map
import time
method = container_map[self.container]._persist
# may need to create path - access file-system method
out = method(self, path=path, **kwargs)
out.description = self.description
metadata = {'timestamp': time.time(),
'original_metadata': self.metadata,
'original_source': self.__getstate__(),
'original_name': self.name,
'original_tok': self._tok,
'persist_kwargs': kwargs}
out.metadata = metadata
out.name = self.name
return out.yaml() | [
"def",
"export",
"(",
"self",
",",
"path",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
".",
".",
"container",
"import",
"container_map",
"import",
"time",
"method",
"=",
"container_map",
"[",
"self",
".",
"container",
"]",
".",
"_persist",
"# may need to cr... | Save this data for sharing with other people
Creates a copy of the data in a format appropriate for its container,
in the location specified (which can be remote, e.g., s3). Returns
a YAML representation of this saved dataset, so that it can be put
into a catalog file. | [
"Save",
"this",
"data",
"for",
"sharing",
"with",
"other",
"people"
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/source/base.py#L286-L308 | train | 224,260 |
intake/intake | intake/catalog/default.py | load_user_catalog | def load_user_catalog():
"""Return a catalog for the platform-specific user Intake directory"""
cat_dir = user_data_dir()
if not os.path.isdir(cat_dir):
return Catalog()
else:
return YAMLFilesCatalog(cat_dir) | python | def load_user_catalog():
"""Return a catalog for the platform-specific user Intake directory"""
cat_dir = user_data_dir()
if not os.path.isdir(cat_dir):
return Catalog()
else:
return YAMLFilesCatalog(cat_dir) | [
"def",
"load_user_catalog",
"(",
")",
":",
"cat_dir",
"=",
"user_data_dir",
"(",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"cat_dir",
")",
":",
"return",
"Catalog",
"(",
")",
"else",
":",
"return",
"YAMLFilesCatalog",
"(",
"cat_dir",
")"
] | Return a catalog for the platform-specific user Intake directory | [
"Return",
"a",
"catalog",
"for",
"the",
"platform",
"-",
"specific",
"user",
"Intake",
"directory"
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/catalog/default.py#L19-L25 | train | 224,261 |
intake/intake | intake/catalog/default.py | load_global_catalog | def load_global_catalog():
"""Return a catalog for the environment-specific Intake directory"""
cat_dir = global_data_dir()
if not os.path.isdir(cat_dir):
return Catalog()
else:
return YAMLFilesCatalog(cat_dir) | python | def load_global_catalog():
"""Return a catalog for the environment-specific Intake directory"""
cat_dir = global_data_dir()
if not os.path.isdir(cat_dir):
return Catalog()
else:
return YAMLFilesCatalog(cat_dir) | [
"def",
"load_global_catalog",
"(",
")",
":",
"cat_dir",
"=",
"global_data_dir",
"(",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"cat_dir",
")",
":",
"return",
"Catalog",
"(",
")",
"else",
":",
"return",
"YAMLFilesCatalog",
"(",
"cat_dir",
")... | Return a catalog for the environment-specific Intake directory | [
"Return",
"a",
"catalog",
"for",
"the",
"environment",
"-",
"specific",
"Intake",
"directory"
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/catalog/default.py#L33-L39 | train | 224,262 |
intake/intake | intake/catalog/default.py | global_data_dir | def global_data_dir():
"""Return the global Intake catalog dir for the current environment"""
prefix = False
if VIRTUALENV_VAR in os.environ:
prefix = os.environ[VIRTUALENV_VAR]
elif CONDA_VAR in os.environ:
prefix = sys.prefix
elif which('conda'):
# conda exists but is not activated
prefix = conda_prefix()
if prefix:
# conda and virtualenv use Linux-style directory pattern
return make_path_posix(os.path.join(prefix, 'share', 'intake'))
else:
return appdirs.site_data_dir(appname='intake', appauthor='intake') | python | def global_data_dir():
"""Return the global Intake catalog dir for the current environment"""
prefix = False
if VIRTUALENV_VAR in os.environ:
prefix = os.environ[VIRTUALENV_VAR]
elif CONDA_VAR in os.environ:
prefix = sys.prefix
elif which('conda'):
# conda exists but is not activated
prefix = conda_prefix()
if prefix:
# conda and virtualenv use Linux-style directory pattern
return make_path_posix(os.path.join(prefix, 'share', 'intake'))
else:
return appdirs.site_data_dir(appname='intake', appauthor='intake') | [
"def",
"global_data_dir",
"(",
")",
":",
"prefix",
"=",
"False",
"if",
"VIRTUALENV_VAR",
"in",
"os",
".",
"environ",
":",
"prefix",
"=",
"os",
".",
"environ",
"[",
"VIRTUALENV_VAR",
"]",
"elif",
"CONDA_VAR",
"in",
"os",
".",
"environ",
":",
"prefix",
"="... | Return the global Intake catalog dir for the current environment | [
"Return",
"the",
"global",
"Intake",
"catalog",
"dir",
"for",
"the",
"current",
"environment"
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/catalog/default.py#L61-L76 | train | 224,263 |
intake/intake | intake/catalog/default.py | load_combo_catalog | def load_combo_catalog():
"""Load a union of the user and global catalogs for convenience"""
user_dir = user_data_dir()
global_dir = global_data_dir()
desc = 'Generated from data packages found on your intake search path'
cat_dirs = []
if os.path.isdir(user_dir):
cat_dirs.append(user_dir + '/*.yaml')
cat_dirs.append(user_dir + '/*.yml')
if os.path.isdir(global_dir):
cat_dirs.append(global_dir + '/*.yaml')
cat_dirs.append(global_dir + '/*.yml')
for path_dir in conf.get('catalog_path', []):
if path_dir != '':
if not path_dir.endswith(('yaml', 'yml')):
cat_dirs.append(path_dir + '/*.yaml')
cat_dirs.append(path_dir + '/*.yml')
else:
cat_dirs.append(path_dir)
return YAMLFilesCatalog(cat_dirs, name='builtin', description=desc) | python | def load_combo_catalog():
"""Load a union of the user and global catalogs for convenience"""
user_dir = user_data_dir()
global_dir = global_data_dir()
desc = 'Generated from data packages found on your intake search path'
cat_dirs = []
if os.path.isdir(user_dir):
cat_dirs.append(user_dir + '/*.yaml')
cat_dirs.append(user_dir + '/*.yml')
if os.path.isdir(global_dir):
cat_dirs.append(global_dir + '/*.yaml')
cat_dirs.append(global_dir + '/*.yml')
for path_dir in conf.get('catalog_path', []):
if path_dir != '':
if not path_dir.endswith(('yaml', 'yml')):
cat_dirs.append(path_dir + '/*.yaml')
cat_dirs.append(path_dir + '/*.yml')
else:
cat_dirs.append(path_dir)
return YAMLFilesCatalog(cat_dirs, name='builtin', description=desc) | [
"def",
"load_combo_catalog",
"(",
")",
":",
"user_dir",
"=",
"user_data_dir",
"(",
")",
"global_dir",
"=",
"global_data_dir",
"(",
")",
"desc",
"=",
"'Generated from data packages found on your intake search path'",
"cat_dirs",
"=",
"[",
"]",
"if",
"os",
".",
"path"... | Load a union of the user and global catalogs for convenience | [
"Load",
"a",
"union",
"of",
"the",
"user",
"and",
"global",
"catalogs",
"for",
"convenience"
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/catalog/default.py#L79-L99 | train | 224,264 |
intake/intake | intake/catalog/base.py | Catalog.from_dict | def from_dict(cls, entries, **kwargs):
"""
Create Catalog from the given set of entries
Parameters
----------
entries : dict-like
A mapping of name:entry which supports dict-like functionality,
e.g., is derived from ``collections.abc.Mapping``.
kwargs : passed on the constructor
Things like metadata, name; see ``__init__``.
Returns
-------
Catalog instance
"""
from dask.base import tokenize
cat = cls(**kwargs)
cat._entries = entries
cat._tok = tokenize(kwargs, entries)
return cat | python | def from_dict(cls, entries, **kwargs):
"""
Create Catalog from the given set of entries
Parameters
----------
entries : dict-like
A mapping of name:entry which supports dict-like functionality,
e.g., is derived from ``collections.abc.Mapping``.
kwargs : passed on the constructor
Things like metadata, name; see ``__init__``.
Returns
-------
Catalog instance
"""
from dask.base import tokenize
cat = cls(**kwargs)
cat._entries = entries
cat._tok = tokenize(kwargs, entries)
return cat | [
"def",
"from_dict",
"(",
"cls",
",",
"entries",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"dask",
".",
"base",
"import",
"tokenize",
"cat",
"=",
"cls",
"(",
"*",
"*",
"kwargs",
")",
"cat",
".",
"_entries",
"=",
"entries",
"cat",
".",
"_tok",
"=",
... | Create Catalog from the given set of entries
Parameters
----------
entries : dict-like
A mapping of name:entry which supports dict-like functionality,
e.g., is derived from ``collections.abc.Mapping``.
kwargs : passed on the constructor
Things like metadata, name; see ``__init__``.
Returns
-------
Catalog instance | [
"Create",
"Catalog",
"from",
"the",
"given",
"set",
"of",
"entries"
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/catalog/base.py#L118-L138 | train | 224,265 |
intake/intake | intake/catalog/base.py | Catalog.reload | def reload(self):
"""Reload catalog if sufficient time has passed"""
if time.time() - self.updated > self.ttl:
self.force_reload() | python | def reload(self):
"""Reload catalog if sufficient time has passed"""
if time.time() - self.updated > self.ttl:
self.force_reload() | [
"def",
"reload",
"(",
"self",
")",
":",
"if",
"time",
".",
"time",
"(",
")",
"-",
"self",
".",
"updated",
">",
"self",
".",
"ttl",
":",
"self",
".",
"force_reload",
"(",
")"
] | Reload catalog if sufficient time has passed | [
"Reload",
"catalog",
"if",
"sufficient",
"time",
"has",
"passed"
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/catalog/base.py#L177-L180 | train | 224,266 |
intake/intake | intake/catalog/base.py | Catalog.filter | def filter(self, func):
"""Create a Catalog of a subset of entries based on a condition
Note that, whatever specific class this is performed on, the return
instance is a Catalog. The entries are passed unmodified, so they
will still reference the original catalog instance and include its
details such as directory,.
Parameters
----------
func : function
This should take a CatalogEntry and return True or False. Those
items returning True will be included in the new Catalog, with the
same entry names
Returns
-------
New Catalog
"""
return Catalog.from_dict({key: entry for key, entry in self.items()
if func(entry)}) | python | def filter(self, func):
"""Create a Catalog of a subset of entries based on a condition
Note that, whatever specific class this is performed on, the return
instance is a Catalog. The entries are passed unmodified, so they
will still reference the original catalog instance and include its
details such as directory,.
Parameters
----------
func : function
This should take a CatalogEntry and return True or False. Those
items returning True will be included in the new Catalog, with the
same entry names
Returns
-------
New Catalog
"""
return Catalog.from_dict({key: entry for key, entry in self.items()
if func(entry)}) | [
"def",
"filter",
"(",
"self",
",",
"func",
")",
":",
"return",
"Catalog",
".",
"from_dict",
"(",
"{",
"key",
":",
"entry",
"for",
"key",
",",
"entry",
"in",
"self",
".",
"items",
"(",
")",
"if",
"func",
"(",
"entry",
")",
"}",
")"
] | Create a Catalog of a subset of entries based on a condition
Note that, whatever specific class this is performed on, the return
instance is a Catalog. The entries are passed unmodified, so they
will still reference the original catalog instance and include its
details such as directory,.
Parameters
----------
func : function
This should take a CatalogEntry and return True or False. Those
items returning True will be included in the new Catalog, with the
same entry names
Returns
-------
New Catalog | [
"Create",
"a",
"Catalog",
"of",
"a",
"subset",
"of",
"entries",
"based",
"on",
"a",
"condition"
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/catalog/base.py#L208-L228 | train | 224,267 |
intake/intake | intake/catalog/base.py | Catalog.walk | def walk(self, sofar=None, prefix=None, depth=2):
"""Get all entries in this catalog and sub-catalogs
Parameters
----------
sofar: dict or None
Within recursion, use this dict for output
prefix: list of str or None
Names of levels already visited
depth: int
Number of levels to descend; needed to truncate circular references
and for cleaner output
Returns
-------
Dict where the keys are the entry names in dotted syntax, and the
values are entry instances.
"""
out = sofar if sofar is not None else {}
prefix = [] if prefix is None else prefix
for name, item in self._entries.items():
if item._container == 'catalog' and depth > 1:
# recurse with default open parameters
try:
item().walk(out, prefix + [name], depth-1)
except Exception as e:
print(e)
pass # ignore inability to descend
n = '.'.join(prefix + [name])
out[n] = item
return out | python | def walk(self, sofar=None, prefix=None, depth=2):
"""Get all entries in this catalog and sub-catalogs
Parameters
----------
sofar: dict or None
Within recursion, use this dict for output
prefix: list of str or None
Names of levels already visited
depth: int
Number of levels to descend; needed to truncate circular references
and for cleaner output
Returns
-------
Dict where the keys are the entry names in dotted syntax, and the
values are entry instances.
"""
out = sofar if sofar is not None else {}
prefix = [] if prefix is None else prefix
for name, item in self._entries.items():
if item._container == 'catalog' and depth > 1:
# recurse with default open parameters
try:
item().walk(out, prefix + [name], depth-1)
except Exception as e:
print(e)
pass # ignore inability to descend
n = '.'.join(prefix + [name])
out[n] = item
return out | [
"def",
"walk",
"(",
"self",
",",
"sofar",
"=",
"None",
",",
"prefix",
"=",
"None",
",",
"depth",
"=",
"2",
")",
":",
"out",
"=",
"sofar",
"if",
"sofar",
"is",
"not",
"None",
"else",
"{",
"}",
"prefix",
"=",
"[",
"]",
"if",
"prefix",
"is",
"None... | Get all entries in this catalog and sub-catalogs
Parameters
----------
sofar: dict or None
Within recursion, use this dict for output
prefix: list of str or None
Names of levels already visited
depth: int
Number of levels to descend; needed to truncate circular references
and for cleaner output
Returns
-------
Dict where the keys are the entry names in dotted syntax, and the
values are entry instances. | [
"Get",
"all",
"entries",
"in",
"this",
"catalog",
"and",
"sub",
"-",
"catalogs"
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/catalog/base.py#L231-L261 | train | 224,268 |
intake/intake | intake/catalog/base.py | Catalog.serialize | def serialize(self):
"""
Produce YAML version of this catalog.
Note that this is not the same as ``.yaml()``, which produces a YAML
block referring to this catalog.
"""
import yaml
output = {"metadata": self.metadata, "sources": {},
"name": self.name}
for key, entry in self.items():
output["sources"][key] = entry._captured_init_kwargs
return yaml.dump(output) | python | def serialize(self):
"""
Produce YAML version of this catalog.
Note that this is not the same as ``.yaml()``, which produces a YAML
block referring to this catalog.
"""
import yaml
output = {"metadata": self.metadata, "sources": {},
"name": self.name}
for key, entry in self.items():
output["sources"][key] = entry._captured_init_kwargs
return yaml.dump(output) | [
"def",
"serialize",
"(",
"self",
")",
":",
"import",
"yaml",
"output",
"=",
"{",
"\"metadata\"",
":",
"self",
".",
"metadata",
",",
"\"sources\"",
":",
"{",
"}",
",",
"\"name\"",
":",
"self",
".",
"name",
"}",
"for",
"key",
",",
"entry",
"in",
"self"... | Produce YAML version of this catalog.
Note that this is not the same as ``.yaml()``, which produces a YAML
block referring to this catalog. | [
"Produce",
"YAML",
"version",
"of",
"this",
"catalog",
"."
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/catalog/base.py#L267-L279 | train | 224,269 |
intake/intake | intake/catalog/base.py | Catalog.save | def save(self, url, storage_options=None):
"""
Output this catalog to a file as YAML
Parameters
----------
url : str
Location to save to, perhaps remote
storage_options : dict
Extra arguments for the file-system
"""
from dask.bytes import open_files
with open_files([url], **(storage_options or {}), mode='wt')[0] as f:
f.write(self.serialize()) | python | def save(self, url, storage_options=None):
"""
Output this catalog to a file as YAML
Parameters
----------
url : str
Location to save to, perhaps remote
storage_options : dict
Extra arguments for the file-system
"""
from dask.bytes import open_files
with open_files([url], **(storage_options or {}), mode='wt')[0] as f:
f.write(self.serialize()) | [
"def",
"save",
"(",
"self",
",",
"url",
",",
"storage_options",
"=",
"None",
")",
":",
"from",
"dask",
".",
"bytes",
"import",
"open_files",
"with",
"open_files",
"(",
"[",
"url",
"]",
",",
"*",
"*",
"(",
"storage_options",
"or",
"{",
"}",
")",
",",
... | Output this catalog to a file as YAML
Parameters
----------
url : str
Location to save to, perhaps remote
storage_options : dict
Extra arguments for the file-system | [
"Output",
"this",
"catalog",
"to",
"a",
"file",
"as",
"YAML"
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/catalog/base.py#L281-L294 | train | 224,270 |
intake/intake | intake/catalog/base.py | Entries.reset | def reset(self):
"Clear caches to force a reload."
self._page_cache.clear()
self._direct_lookup_cache.clear()
self._page_offset = 0
self.complete = self._catalog.page_size is None | python | def reset(self):
"Clear caches to force a reload."
self._page_cache.clear()
self._direct_lookup_cache.clear()
self._page_offset = 0
self.complete = self._catalog.page_size is None | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"_page_cache",
".",
"clear",
"(",
")",
"self",
".",
"_direct_lookup_cache",
".",
"clear",
"(",
")",
"self",
".",
"_page_offset",
"=",
"0",
"self",
".",
"complete",
"=",
"self",
".",
"_catalog",
".",
... | Clear caches to force a reload. | [
"Clear",
"caches",
"to",
"force",
"a",
"reload",
"."
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/catalog/base.py#L444-L449 | train | 224,271 |
intake/intake | intake/catalog/base.py | Entries.cached_items | def cached_items(self):
"""
Iterate over items that are already cached. Perform no requests.
"""
for item in six.iteritems(self._page_cache):
yield item
for item in six.iteritems(self._direct_lookup_cache):
yield item | python | def cached_items(self):
"""
Iterate over items that are already cached. Perform no requests.
"""
for item in six.iteritems(self._page_cache):
yield item
for item in six.iteritems(self._direct_lookup_cache):
yield item | [
"def",
"cached_items",
"(",
"self",
")",
":",
"for",
"item",
"in",
"six",
".",
"iteritems",
"(",
"self",
".",
"_page_cache",
")",
":",
"yield",
"item",
"for",
"item",
"in",
"six",
".",
"iteritems",
"(",
"self",
".",
"_direct_lookup_cache",
")",
":",
"y... | Iterate over items that are already cached. Perform no requests. | [
"Iterate",
"over",
"items",
"that",
"are",
"already",
"cached",
".",
"Perform",
"no",
"requests",
"."
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/catalog/base.py#L473-L480 | train | 224,272 |
intake/intake | intake/catalog/base.py | RemoteCatalog._get_http_args | def _get_http_args(self, params):
"""
Return a copy of the http_args
Adds auth headers and 'source_id', merges in params.
"""
# Add the auth headers to any other headers
headers = self.http_args.get('headers', {})
if self.auth is not None:
auth_headers = self.auth.get_headers()
headers.update(auth_headers)
# build new http args with these headers
http_args = self.http_args.copy()
if self._source_id is not None:
headers['source_id'] = self._source_id
http_args['headers'] = headers
# Merge in any params specified by the caller.
merged_params = http_args.get('params', {})
merged_params.update(params)
http_args['params'] = merged_params
return http_args | python | def _get_http_args(self, params):
"""
Return a copy of the http_args
Adds auth headers and 'source_id', merges in params.
"""
# Add the auth headers to any other headers
headers = self.http_args.get('headers', {})
if self.auth is not None:
auth_headers = self.auth.get_headers()
headers.update(auth_headers)
# build new http args with these headers
http_args = self.http_args.copy()
if self._source_id is not None:
headers['source_id'] = self._source_id
http_args['headers'] = headers
# Merge in any params specified by the caller.
merged_params = http_args.get('params', {})
merged_params.update(params)
http_args['params'] = merged_params
return http_args | [
"def",
"_get_http_args",
"(",
"self",
",",
"params",
")",
":",
"# Add the auth headers to any other headers",
"headers",
"=",
"self",
".",
"http_args",
".",
"get",
"(",
"'headers'",
",",
"{",
"}",
")",
"if",
"self",
".",
"auth",
"is",
"not",
"None",
":",
"... | Return a copy of the http_args
Adds auth headers and 'source_id', merges in params. | [
"Return",
"a",
"copy",
"of",
"the",
"http_args"
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/catalog/base.py#L650-L672 | train | 224,273 |
intake/intake | intake/catalog/base.py | RemoteCatalog._load | def _load(self):
"""Fetch metadata from remote. Entries are fetched lazily."""
# This will not immediately fetch any sources (entries). It will lazily
# fetch sources from the server in paginated blocks when this Catalog
# is iterated over. It will fetch specific sources when they are
# accessed in this Catalog via __getitem__.
if self.page_size is None:
# Fetch all source info.
params = {}
else:
# Just fetch the metadata now; fetch source info later in pages.
params = {'page_offset': 0, 'page_size': 0}
http_args = self._get_http_args(params)
response = requests.get(self.info_url, **http_args)
try:
response.raise_for_status()
except requests.HTTPError as err:
six.raise_from(RemoteCatalogError(
"Failed to fetch metadata."), err)
info = msgpack.unpackb(response.content, **unpack_kwargs)
self.metadata = info['metadata']
# The intake server now always provides a length, but the server may be
# running an older version of intake.
self._len = info.get('length')
self._entries.reset()
# If we are paginating (page_size is not None) and the server we are
# working with is new enough to support pagination, info['sources']
# should be empty. If either of those things is not true,
# info['sources'] will contain all the entries and we should cache them
# now.
if info['sources']:
# Signal that we are not paginating, even if we were asked to.
self._page_size = None
self._entries._page_cache.update(
{source['name']: RemoteCatalogEntry(
url=self.url,
getenv=self.getenv,
getshell=self.getshell,
auth=self.auth,
http_args=self.http_args, **source)
for source in info['sources']}) | python | def _load(self):
"""Fetch metadata from remote. Entries are fetched lazily."""
# This will not immediately fetch any sources (entries). It will lazily
# fetch sources from the server in paginated blocks when this Catalog
# is iterated over. It will fetch specific sources when they are
# accessed in this Catalog via __getitem__.
if self.page_size is None:
# Fetch all source info.
params = {}
else:
# Just fetch the metadata now; fetch source info later in pages.
params = {'page_offset': 0, 'page_size': 0}
http_args = self._get_http_args(params)
response = requests.get(self.info_url, **http_args)
try:
response.raise_for_status()
except requests.HTTPError as err:
six.raise_from(RemoteCatalogError(
"Failed to fetch metadata."), err)
info = msgpack.unpackb(response.content, **unpack_kwargs)
self.metadata = info['metadata']
# The intake server now always provides a length, but the server may be
# running an older version of intake.
self._len = info.get('length')
self._entries.reset()
# If we are paginating (page_size is not None) and the server we are
# working with is new enough to support pagination, info['sources']
# should be empty. If either of those things is not true,
# info['sources'] will contain all the entries and we should cache them
# now.
if info['sources']:
# Signal that we are not paginating, even if we were asked to.
self._page_size = None
self._entries._page_cache.update(
{source['name']: RemoteCatalogEntry(
url=self.url,
getenv=self.getenv,
getshell=self.getshell,
auth=self.auth,
http_args=self.http_args, **source)
for source in info['sources']}) | [
"def",
"_load",
"(",
"self",
")",
":",
"# This will not immediately fetch any sources (entries). It will lazily",
"# fetch sources from the server in paginated blocks when this Catalog",
"# is iterated over. It will fetch specific sources when they are",
"# accessed in this Catalog via __getitem__... | Fetch metadata from remote. Entries are fetched lazily. | [
"Fetch",
"metadata",
"from",
"remote",
".",
"Entries",
"are",
"fetched",
"lazily",
"."
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/catalog/base.py#L674-L715 | train | 224,274 |
intake/intake | intake/cli/util.py | nice_join | def nice_join(seq, sep=", ", conjunction="or"):
''' Join together sequences of strings into English-friendly phrases using
a conjunction when appropriate.
Args:
seq (seq[str]) : a sequence of strings to nicely join
sep (str, optional) : a sequence delimiter to use (default: ", ")
conjunction (str or None, optional) : a conjunction to use for the last
two items, or None to reproduce basic join behavior (default: "or")
Returns:
a joined string
Examples:
>>> nice_join(["a", "b", "c"])
'a, b or c'
'''
seq = [str(x) for x in seq]
if len(seq) <= 1 or conjunction is None:
return sep.join(seq)
else:
return "%s %s %s" % (sep.join(seq[:-1]), conjunction, seq[-1]) | python | def nice_join(seq, sep=", ", conjunction="or"):
''' Join together sequences of strings into English-friendly phrases using
a conjunction when appropriate.
Args:
seq (seq[str]) : a sequence of strings to nicely join
sep (str, optional) : a sequence delimiter to use (default: ", ")
conjunction (str or None, optional) : a conjunction to use for the last
two items, or None to reproduce basic join behavior (default: "or")
Returns:
a joined string
Examples:
>>> nice_join(["a", "b", "c"])
'a, b or c'
'''
seq = [str(x) for x in seq]
if len(seq) <= 1 or conjunction is None:
return sep.join(seq)
else:
return "%s %s %s" % (sep.join(seq[:-1]), conjunction, seq[-1]) | [
"def",
"nice_join",
"(",
"seq",
",",
"sep",
"=",
"\", \"",
",",
"conjunction",
"=",
"\"or\"",
")",
":",
"seq",
"=",
"[",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"seq",
"]",
"if",
"len",
"(",
"seq",
")",
"<=",
"1",
"or",
"conjunction",
"is",
"No... | Join together sequences of strings into English-friendly phrases using
a conjunction when appropriate.
Args:
seq (seq[str]) : a sequence of strings to nicely join
sep (str, optional) : a sequence delimiter to use (default: ", ")
conjunction (str or None, optional) : a conjunction to use for the last
two items, or None to reproduce basic join behavior (default: "or")
Returns:
a joined string
Examples:
>>> nice_join(["a", "b", "c"])
'a, b or c' | [
"Join",
"together",
"sequences",
"of",
"strings",
"into",
"English",
"-",
"friendly",
"phrases",
"using",
"a",
"conjunction",
"when",
"appropriate",
"."
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/cli/util.py#L46-L71 | train | 224,275 |
intake/intake | intake/__init__.py | output_notebook | def output_notebook(inline=True, logo=False):
"""
Load the notebook extension
Parameters
----------
inline : boolean (optional)
Whether to inline JS code or load it from a CDN
logo : boolean (optional)
Whether to show the logo(s)
"""
try:
import hvplot
except ImportError:
raise ImportError("The intake plotting API requires hvplot."
"hvplot may be installed with:\n\n"
"`conda install -c pyviz hvplot` or "
"`pip install hvplot`.")
import holoviews as hv
return hv.extension('bokeh', inline=inline, logo=logo) | python | def output_notebook(inline=True, logo=False):
"""
Load the notebook extension
Parameters
----------
inline : boolean (optional)
Whether to inline JS code or load it from a CDN
logo : boolean (optional)
Whether to show the logo(s)
"""
try:
import hvplot
except ImportError:
raise ImportError("The intake plotting API requires hvplot."
"hvplot may be installed with:\n\n"
"`conda install -c pyviz hvplot` or "
"`pip install hvplot`.")
import holoviews as hv
return hv.extension('bokeh', inline=inline, logo=logo) | [
"def",
"output_notebook",
"(",
"inline",
"=",
"True",
",",
"logo",
"=",
"False",
")",
":",
"try",
":",
"import",
"hvplot",
"except",
"ImportError",
":",
"raise",
"ImportError",
"(",
"\"The intake plotting API requires hvplot.\"",
"\"hvplot may be installed with:\\n\\n\"... | Load the notebook extension
Parameters
----------
inline : boolean (optional)
Whether to inline JS code or load it from a CDN
logo : boolean (optional)
Whether to show the logo(s) | [
"Load",
"the",
"notebook",
"extension"
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/__init__.py#L57-L76 | train | 224,276 |
intake/intake | intake/__init__.py | open_catalog | def open_catalog(uri=None, **kwargs):
"""Create a Catalog object
Can load YAML catalog files, connect to an intake server, or create any
arbitrary Catalog subclass instance. In the general case, the user should
supply ``driver=`` with a value from the plugins registry which has a
container type of catalog. File locations can generally be remote, if
specifying a URL protocol.
The default behaviour if not specifying the driver is as follows:
- if ``uri`` is a a single string ending in "yml" or "yaml", open it as a
catalog file
- if ``uri`` is a list of strings, a string containing a glob character
("*") or a string not ending in "y(a)ml", open as a set of catalog
files. In the latter case, assume it is a directory.
- if ``uri`` beings with protocol ``"intake:"``, connect to a remote
Intake server
- otherwise, create a base Catalog object without entries.
Parameters
----------
uri: str
Designator for the location of the catalog.
kwargs:
passed to subclass instance, see documentation of the individual
catalog classes. For example, ``yaml_files_cat`` (when specifying
multiple uris or a glob string) takes the additional
parameter ``flatten=True|False``, specifying whether all data sources
are merged in a single namespace, or each file becomes
a sub-catalog.
See also
--------
intake.open_yaml_files_cat, intake.open_yaml_file_cat,
intake.open_intake_remote
"""
driver = kwargs.pop('driver', None)
if driver is None:
if uri:
if ((isinstance(uri, str) and "*" in uri)
or ((isinstance(uri, (list, tuple))) and len(uri) > 1)):
# glob string or list of files/globs
driver = 'yaml_files_cat'
elif isinstance(uri, (list, tuple)) and len(uri) == 1:
uri = uri[0]
if "*" in uri[0]:
# single glob string in a list
driver = 'yaml_files_cat'
else:
# single filename in a list
driver = 'yaml_file_cat'
elif isinstance(uri, str):
# single URL
if uri.startswith('intake:'):
# server
driver = 'intake_remote'
else:
if uri.endswith(('.yml', '.yaml')):
driver = 'yaml_file_cat'
else:
uri = uri.rstrip('/') + '/*.y*ml'
driver = 'yaml_files_cat'
else:
# empty cat
driver = 'catalog'
if driver not in registry:
raise ValueError('Unknown catalog driver (%s), supply one of: %s'
% (driver, list(sorted(registry))))
return registry[driver](uri, **kwargs) | python | def open_catalog(uri=None, **kwargs):
"""Create a Catalog object
Can load YAML catalog files, connect to an intake server, or create any
arbitrary Catalog subclass instance. In the general case, the user should
supply ``driver=`` with a value from the plugins registry which has a
container type of catalog. File locations can generally be remote, if
specifying a URL protocol.
The default behaviour if not specifying the driver is as follows:
- if ``uri`` is a a single string ending in "yml" or "yaml", open it as a
catalog file
- if ``uri`` is a list of strings, a string containing a glob character
("*") or a string not ending in "y(a)ml", open as a set of catalog
files. In the latter case, assume it is a directory.
- if ``uri`` beings with protocol ``"intake:"``, connect to a remote
Intake server
- otherwise, create a base Catalog object without entries.
Parameters
----------
uri: str
Designator for the location of the catalog.
kwargs:
passed to subclass instance, see documentation of the individual
catalog classes. For example, ``yaml_files_cat`` (when specifying
multiple uris or a glob string) takes the additional
parameter ``flatten=True|False``, specifying whether all data sources
are merged in a single namespace, or each file becomes
a sub-catalog.
See also
--------
intake.open_yaml_files_cat, intake.open_yaml_file_cat,
intake.open_intake_remote
"""
driver = kwargs.pop('driver', None)
if driver is None:
if uri:
if ((isinstance(uri, str) and "*" in uri)
or ((isinstance(uri, (list, tuple))) and len(uri) > 1)):
# glob string or list of files/globs
driver = 'yaml_files_cat'
elif isinstance(uri, (list, tuple)) and len(uri) == 1:
uri = uri[0]
if "*" in uri[0]:
# single glob string in a list
driver = 'yaml_files_cat'
else:
# single filename in a list
driver = 'yaml_file_cat'
elif isinstance(uri, str):
# single URL
if uri.startswith('intake:'):
# server
driver = 'intake_remote'
else:
if uri.endswith(('.yml', '.yaml')):
driver = 'yaml_file_cat'
else:
uri = uri.rstrip('/') + '/*.y*ml'
driver = 'yaml_files_cat'
else:
# empty cat
driver = 'catalog'
if driver not in registry:
raise ValueError('Unknown catalog driver (%s), supply one of: %s'
% (driver, list(sorted(registry))))
return registry[driver](uri, **kwargs) | [
"def",
"open_catalog",
"(",
"uri",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"driver",
"=",
"kwargs",
".",
"pop",
"(",
"'driver'",
",",
"None",
")",
"if",
"driver",
"is",
"None",
":",
"if",
"uri",
":",
"if",
"(",
"(",
"isinstance",
"(",
"ur... | Create a Catalog object
Can load YAML catalog files, connect to an intake server, or create any
arbitrary Catalog subclass instance. In the general case, the user should
supply ``driver=`` with a value from the plugins registry which has a
container type of catalog. File locations can generally be remote, if
specifying a URL protocol.
The default behaviour if not specifying the driver is as follows:
- if ``uri`` is a a single string ending in "yml" or "yaml", open it as a
catalog file
- if ``uri`` is a list of strings, a string containing a glob character
("*") or a string not ending in "y(a)ml", open as a set of catalog
files. In the latter case, assume it is a directory.
- if ``uri`` beings with protocol ``"intake:"``, connect to a remote
Intake server
- otherwise, create a base Catalog object without entries.
Parameters
----------
uri: str
Designator for the location of the catalog.
kwargs:
passed to subclass instance, see documentation of the individual
catalog classes. For example, ``yaml_files_cat`` (when specifying
multiple uris or a glob string) takes the additional
parameter ``flatten=True|False``, specifying whether all data sources
are merged in a single namespace, or each file becomes
a sub-catalog.
See also
--------
intake.open_yaml_files_cat, intake.open_yaml_file_cat,
intake.open_intake_remote | [
"Create",
"a",
"Catalog",
"object"
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/__init__.py#L83-L152 | train | 224,277 |
intake/intake | intake/container/dataframe.py | RemoteDataFrame._persist | def _persist(source, path, **kwargs):
"""Save dataframe to local persistent store
Makes a parquet dataset out of the data using dask.dataframe.to_parquet.
This then becomes a data entry in the persisted datasets catalog.
Parameters
----------
source: a DataSource instance to save
name: str or None
Key to refer to this persisted dataset by. If not given, will
attempt to get from the source's name
kwargs: passed on to dask.dataframe.to_parquet
"""
try:
from intake_parquet import ParquetSource
except ImportError:
raise ImportError("Please install intake-parquet to use persistence"
" on dataframe container sources.")
try:
df = source.to_dask()
except NotImplementedError:
import dask.dataframe as dd
df = dd.from_pandas(source.read(), 1)
df.to_parquet(path, **kwargs)
source = ParquetSource(path, meta={})
return source | python | def _persist(source, path, **kwargs):
"""Save dataframe to local persistent store
Makes a parquet dataset out of the data using dask.dataframe.to_parquet.
This then becomes a data entry in the persisted datasets catalog.
Parameters
----------
source: a DataSource instance to save
name: str or None
Key to refer to this persisted dataset by. If not given, will
attempt to get from the source's name
kwargs: passed on to dask.dataframe.to_parquet
"""
try:
from intake_parquet import ParquetSource
except ImportError:
raise ImportError("Please install intake-parquet to use persistence"
" on dataframe container sources.")
try:
df = source.to_dask()
except NotImplementedError:
import dask.dataframe as dd
df = dd.from_pandas(source.read(), 1)
df.to_parquet(path, **kwargs)
source = ParquetSource(path, meta={})
return source | [
"def",
"_persist",
"(",
"source",
",",
"path",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"from",
"intake_parquet",
"import",
"ParquetSource",
"except",
"ImportError",
":",
"raise",
"ImportError",
"(",
"\"Please install intake-parquet to use persistence\"",
"\" ... | Save dataframe to local persistent store
Makes a parquet dataset out of the data using dask.dataframe.to_parquet.
This then becomes a data entry in the persisted datasets catalog.
Parameters
----------
source: a DataSource instance to save
name: str or None
Key to refer to this persisted dataset by. If not given, will
attempt to get from the source's name
kwargs: passed on to dask.dataframe.to_parquet | [
"Save",
"dataframe",
"to",
"local",
"persistent",
"store"
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/container/dataframe.py#L61-L87 | train | 224,278 |
intake/intake | intake/config.py | save_conf | def save_conf(fn=None):
"""Save current configuration to file as YAML
If not given, uses current config directory, ``confdir``, which can be
set by INTAKE_CONF_DIR.
"""
if fn is None:
fn = cfile()
try:
os.makedirs(os.path.dirname(fn))
except (OSError, IOError):
pass
with open(fn, 'w') as f:
yaml.dump(conf, f) | python | def save_conf(fn=None):
"""Save current configuration to file as YAML
If not given, uses current config directory, ``confdir``, which can be
set by INTAKE_CONF_DIR.
"""
if fn is None:
fn = cfile()
try:
os.makedirs(os.path.dirname(fn))
except (OSError, IOError):
pass
with open(fn, 'w') as f:
yaml.dump(conf, f) | [
"def",
"save_conf",
"(",
"fn",
"=",
"None",
")",
":",
"if",
"fn",
"is",
"None",
":",
"fn",
"=",
"cfile",
"(",
")",
"try",
":",
"os",
".",
"makedirs",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"fn",
")",
")",
"except",
"(",
"OSError",
",",
... | Save current configuration to file as YAML
If not given, uses current config directory, ``confdir``, which can be
set by INTAKE_CONF_DIR. | [
"Save",
"current",
"configuration",
"to",
"file",
"as",
"YAML"
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/config.py#L46-L59 | train | 224,279 |
intake/intake | intake/config.py | load_conf | def load_conf(fn=None):
"""Update global config from YAML file
If fn is None, looks in global config directory, which is either defined
by the INTAKE_CONF_DIR env-var or is ~/.intake/ .
"""
if fn is None:
fn = cfile()
if os.path.isfile(fn):
with open(fn) as f:
try:
conf.update(yaml_load(f))
except Exception as e:
logger.warning('Failure to load config file "{fn}": {e}'
''.format(fn=fn, e=e)) | python | def load_conf(fn=None):
"""Update global config from YAML file
If fn is None, looks in global config directory, which is either defined
by the INTAKE_CONF_DIR env-var or is ~/.intake/ .
"""
if fn is None:
fn = cfile()
if os.path.isfile(fn):
with open(fn) as f:
try:
conf.update(yaml_load(f))
except Exception as e:
logger.warning('Failure to load config file "{fn}": {e}'
''.format(fn=fn, e=e)) | [
"def",
"load_conf",
"(",
"fn",
"=",
"None",
")",
":",
"if",
"fn",
"is",
"None",
":",
"fn",
"=",
"cfile",
"(",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"fn",
")",
":",
"with",
"open",
"(",
"fn",
")",
"as",
"f",
":",
"try",
":",
"con... | Update global config from YAML file
If fn is None, looks in global config directory, which is either defined
by the INTAKE_CONF_DIR env-var or is ~/.intake/ . | [
"Update",
"global",
"config",
"from",
"YAML",
"file"
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/config.py#L62-L76 | train | 224,280 |
intake/intake | intake/config.py | intake_path_dirs | def intake_path_dirs(path):
"""Return a list of directories from the intake path.
If a string, perhaps taken from an environment variable, then the
list of paths will be split on the character ":" for posix of ";" for
windows. Protocol indicators ("protocol://") will be ignored.
"""
if isinstance(path, (list, tuple)):
return path
import re
pattern = re.compile(";" if os.name == 'nt' else r"(?<!:):(?![:/])")
return pattern.split(path) | python | def intake_path_dirs(path):
"""Return a list of directories from the intake path.
If a string, perhaps taken from an environment variable, then the
list of paths will be split on the character ":" for posix of ";" for
windows. Protocol indicators ("protocol://") will be ignored.
"""
if isinstance(path, (list, tuple)):
return path
import re
pattern = re.compile(";" if os.name == 'nt' else r"(?<!:):(?![:/])")
return pattern.split(path) | [
"def",
"intake_path_dirs",
"(",
"path",
")",
":",
"if",
"isinstance",
"(",
"path",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"return",
"path",
"import",
"re",
"pattern",
"=",
"re",
".",
"compile",
"(",
"\";\"",
"if",
"os",
".",
"name",
"==",
"... | Return a list of directories from the intake path.
If a string, perhaps taken from an environment variable, then the
list of paths will be split on the character ":" for posix of ";" for
windows. Protocol indicators ("protocol://") will be ignored. | [
"Return",
"a",
"list",
"of",
"directories",
"from",
"the",
"intake",
"path",
"."
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/config.py#L79-L90 | train | 224,281 |
intake/intake | intake/config.py | load_env | def load_env():
"""Analyse enviroment variables and update conf accordingly"""
# environment variables take precedence over conf file
for key, envvar in [['cache_dir', 'INTAKE_CACHE_DIR'],
['catalog_path', 'INTAKE_PATH'],
['persist_path', 'INTAKE_PERSIST_PATH']]:
if envvar in os.environ:
conf[key] = make_path_posix(os.environ[envvar])
conf['catalog_path'] = intake_path_dirs(conf['catalog_path'])
for key, envvar in [['cache_disabled', 'INTAKE_DISABLE_CACHING'],
['cache_download_progress', 'INTAKE_CACHE_PROGRESS']]:
if envvar in os.environ:
conf[key] = os.environ[envvar].lower() in ['true', 't', 'y', 'yes']
if 'INTAKE_LOG_LEVEL' in os.environ:
conf['logging'] = os.environ['INTAKE_LOG_LEVEL'] | python | def load_env():
"""Analyse enviroment variables and update conf accordingly"""
# environment variables take precedence over conf file
for key, envvar in [['cache_dir', 'INTAKE_CACHE_DIR'],
['catalog_path', 'INTAKE_PATH'],
['persist_path', 'INTAKE_PERSIST_PATH']]:
if envvar in os.environ:
conf[key] = make_path_posix(os.environ[envvar])
conf['catalog_path'] = intake_path_dirs(conf['catalog_path'])
for key, envvar in [['cache_disabled', 'INTAKE_DISABLE_CACHING'],
['cache_download_progress', 'INTAKE_CACHE_PROGRESS']]:
if envvar in os.environ:
conf[key] = os.environ[envvar].lower() in ['true', 't', 'y', 'yes']
if 'INTAKE_LOG_LEVEL' in os.environ:
conf['logging'] = os.environ['INTAKE_LOG_LEVEL'] | [
"def",
"load_env",
"(",
")",
":",
"# environment variables take precedence over conf file",
"for",
"key",
",",
"envvar",
"in",
"[",
"[",
"'cache_dir'",
",",
"'INTAKE_CACHE_DIR'",
"]",
",",
"[",
"'catalog_path'",
",",
"'INTAKE_PATH'",
"]",
",",
"[",
"'persist_path'",... | Analyse enviroment variables and update conf accordingly | [
"Analyse",
"enviroment",
"variables",
"and",
"update",
"conf",
"accordingly"
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/config.py#L93-L107 | train | 224,282 |
intake/intake | intake/gui/source/description.py | Description.source | def source(self, source):
"""When the source gets updated, update the pane object"""
BaseView.source.fset(self, source)
if self.main_pane:
self.main_pane.object = self.contents
self.label_pane.object = self.label | python | def source(self, source):
"""When the source gets updated, update the pane object"""
BaseView.source.fset(self, source)
if self.main_pane:
self.main_pane.object = self.contents
self.label_pane.object = self.label | [
"def",
"source",
"(",
"self",
",",
"source",
")",
":",
"BaseView",
".",
"source",
".",
"fset",
"(",
"self",
",",
"source",
")",
"if",
"self",
".",
"main_pane",
":",
"self",
".",
"main_pane",
".",
"object",
"=",
"self",
".",
"contents",
"self",
".",
... | When the source gets updated, update the pane object | [
"When",
"the",
"source",
"gets",
"updated",
"update",
"the",
"pane",
"object"
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/gui/source/description.py#L52-L57 | train | 224,283 |
intake/intake | intake/gui/source/description.py | Description.contents | def contents(self):
"""String representation of the source's description"""
if not self._source:
return ' ' * 100 # HACK - make sure that area is big
contents = self.source.describe()
return pretty_describe(contents) | python | def contents(self):
"""String representation of the source's description"""
if not self._source:
return ' ' * 100 # HACK - make sure that area is big
contents = self.source.describe()
return pretty_describe(contents) | [
"def",
"contents",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_source",
":",
"return",
"' '",
"*",
"100",
"# HACK - make sure that area is big",
"contents",
"=",
"self",
".",
"source",
".",
"describe",
"(",
")",
"return",
"pretty_describe",
"(",
"cont... | String representation of the source's description | [
"String",
"representation",
"of",
"the",
"source",
"s",
"description"
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/gui/source/description.py#L60-L65 | train | 224,284 |
intake/intake | intake/source/utils.py | _get_parts_of_format_string | def _get_parts_of_format_string(resolved_string, literal_texts, format_specs):
"""
Inner function of reverse_format, returns the resolved value for each
field in pattern.
"""
_text = resolved_string
bits = []
if literal_texts[-1] != '' and _text.endswith(literal_texts[-1]):
_text = _text[:-len(literal_texts[-1])]
literal_texts = literal_texts[:-1]
format_specs = format_specs[:-1]
for i, literal_text in enumerate(literal_texts):
if literal_text != '':
if literal_text not in _text:
raise ValueError(("Resolved string must match pattern. "
"'{}' not found.".format(literal_text)))
bit, _text = _text.split(literal_text, 1)
if bit:
bits.append(bit)
elif i == 0:
continue
else:
try:
format_spec = _validate_format_spec(format_specs[i-1])
bits.append(_text[0:format_spec])
_text = _text[format_spec:]
except:
if i == len(format_specs) - 1:
format_spec = _validate_format_spec(format_specs[i])
bits.append(_text[:-format_spec])
bits.append(_text[-format_spec:])
_text = []
else:
_validate_format_spec(format_specs[i-1])
if _text:
bits.append(_text)
if len(bits) > len([fs for fs in format_specs if fs is not None]):
bits = bits[1:]
return bits | python | def _get_parts_of_format_string(resolved_string, literal_texts, format_specs):
"""
Inner function of reverse_format, returns the resolved value for each
field in pattern.
"""
_text = resolved_string
bits = []
if literal_texts[-1] != '' and _text.endswith(literal_texts[-1]):
_text = _text[:-len(literal_texts[-1])]
literal_texts = literal_texts[:-1]
format_specs = format_specs[:-1]
for i, literal_text in enumerate(literal_texts):
if literal_text != '':
if literal_text not in _text:
raise ValueError(("Resolved string must match pattern. "
"'{}' not found.".format(literal_text)))
bit, _text = _text.split(literal_text, 1)
if bit:
bits.append(bit)
elif i == 0:
continue
else:
try:
format_spec = _validate_format_spec(format_specs[i-1])
bits.append(_text[0:format_spec])
_text = _text[format_spec:]
except:
if i == len(format_specs) - 1:
format_spec = _validate_format_spec(format_specs[i])
bits.append(_text[:-format_spec])
bits.append(_text[-format_spec:])
_text = []
else:
_validate_format_spec(format_specs[i-1])
if _text:
bits.append(_text)
if len(bits) > len([fs for fs in format_specs if fs is not None]):
bits = bits[1:]
return bits | [
"def",
"_get_parts_of_format_string",
"(",
"resolved_string",
",",
"literal_texts",
",",
"format_specs",
")",
":",
"_text",
"=",
"resolved_string",
"bits",
"=",
"[",
"]",
"if",
"literal_texts",
"[",
"-",
"1",
"]",
"!=",
"''",
"and",
"_text",
".",
"endswith",
... | Inner function of reverse_format, returns the resolved value for each
field in pattern. | [
"Inner",
"function",
"of",
"reverse_format",
"returns",
"the",
"resolved",
"value",
"for",
"each",
"field",
"in",
"pattern",
"."
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/source/utils.py#L26-L66 | train | 224,285 |
intake/intake | intake/source/utils.py | reverse_formats | def reverse_formats(format_string, resolved_strings):
"""
Reverse the string method format for a list of strings.
Given format_string and resolved_strings, for each resolved string
find arguments that would give
``format_string.format(**arguments) == resolved_string``.
Each item in the output corresponds to a new column with the key setting
the name and the values representing a mapping from list of resolved_strings
to the related value.
Parameters
----------
format_strings : str
Format template string as used with str.format method
resolved_strings : list
List of strings with same pattern as format_string but with fields
filled out.
Returns
-------
args : dict
Dict of the form ``{field: [value_0, ..., value_n], ...}`` where values are in
the same order as resolved_strings, so:
``format_sting.format(**{f: v[0] for f, v in args.items()}) == resolved_strings[0]``
Examples
--------
>>> paths = ['data_2014_01_03.csv', 'data_2014_02_03.csv', 'data_2015_12_03.csv']
>>> reverse_formats('data_{year}_{month}_{day}.csv', paths)
{'year': ['2014', '2014', '2015'],
'month': ['01', '02', '12'],
'day': ['03', '03', '03']}
>>> reverse_formats('data_{year:d}_{month:d}_{day:d}.csv', paths)
{'year': [2014, 2014, 2015], 'month': [1, 2, 12], 'day': [3, 3, 3]}
>>> reverse_formats('data_{date:%Y_%m_%d}.csv', paths)
{'date': [datetime.datetime(2014, 1, 3, 0, 0),
datetime.datetime(2014, 2, 3, 0, 0),
datetime.datetime(2015, 12, 3, 0, 0)]}
>>> reverse_formats('{state:2}{zip:5}', ['PA19104', 'PA19143', 'MA02534'])
{'state': ['PA', 'PA', 'MA'], 'zip': ['19104', '19143', '02534']}
See also
--------
str.format : method that this reverses
reverse_format : method for reversing just one string using a pattern
"""
from string import Formatter
fmt = Formatter()
# get the fields from the format_string
field_names = [i[1] for i in fmt.parse(format_string) if i[1]]
# itialize the args dict with an empty dict for each field
args = {field_name: [] for field_name in field_names}
for resolved_string in resolved_strings:
for field, value in reverse_format(format_string, resolved_string).items():
args[field].append(value)
return args | python | def reverse_formats(format_string, resolved_strings):
"""
Reverse the string method format for a list of strings.
Given format_string and resolved_strings, for each resolved string
find arguments that would give
``format_string.format(**arguments) == resolved_string``.
Each item in the output corresponds to a new column with the key setting
the name and the values representing a mapping from list of resolved_strings
to the related value.
Parameters
----------
format_strings : str
Format template string as used with str.format method
resolved_strings : list
List of strings with same pattern as format_string but with fields
filled out.
Returns
-------
args : dict
Dict of the form ``{field: [value_0, ..., value_n], ...}`` where values are in
the same order as resolved_strings, so:
``format_sting.format(**{f: v[0] for f, v in args.items()}) == resolved_strings[0]``
Examples
--------
>>> paths = ['data_2014_01_03.csv', 'data_2014_02_03.csv', 'data_2015_12_03.csv']
>>> reverse_formats('data_{year}_{month}_{day}.csv', paths)
{'year': ['2014', '2014', '2015'],
'month': ['01', '02', '12'],
'day': ['03', '03', '03']}
>>> reverse_formats('data_{year:d}_{month:d}_{day:d}.csv', paths)
{'year': [2014, 2014, 2015], 'month': [1, 2, 12], 'day': [3, 3, 3]}
>>> reverse_formats('data_{date:%Y_%m_%d}.csv', paths)
{'date': [datetime.datetime(2014, 1, 3, 0, 0),
datetime.datetime(2014, 2, 3, 0, 0),
datetime.datetime(2015, 12, 3, 0, 0)]}
>>> reverse_formats('{state:2}{zip:5}', ['PA19104', 'PA19143', 'MA02534'])
{'state': ['PA', 'PA', 'MA'], 'zip': ['19104', '19143', '02534']}
See also
--------
str.format : method that this reverses
reverse_format : method for reversing just one string using a pattern
"""
from string import Formatter
fmt = Formatter()
# get the fields from the format_string
field_names = [i[1] for i in fmt.parse(format_string) if i[1]]
# itialize the args dict with an empty dict for each field
args = {field_name: [] for field_name in field_names}
for resolved_string in resolved_strings:
for field, value in reverse_format(format_string, resolved_string).items():
args[field].append(value)
return args | [
"def",
"reverse_formats",
"(",
"format_string",
",",
"resolved_strings",
")",
":",
"from",
"string",
"import",
"Formatter",
"fmt",
"=",
"Formatter",
"(",
")",
"# get the fields from the format_string",
"field_names",
"=",
"[",
"i",
"[",
"1",
"]",
"for",
"i",
"in... | Reverse the string method format for a list of strings.
Given format_string and resolved_strings, for each resolved string
find arguments that would give
``format_string.format(**arguments) == resolved_string``.
Each item in the output corresponds to a new column with the key setting
the name and the values representing a mapping from list of resolved_strings
to the related value.
Parameters
----------
format_strings : str
Format template string as used with str.format method
resolved_strings : list
List of strings with same pattern as format_string but with fields
filled out.
Returns
-------
args : dict
Dict of the form ``{field: [value_0, ..., value_n], ...}`` where values are in
the same order as resolved_strings, so:
``format_sting.format(**{f: v[0] for f, v in args.items()}) == resolved_strings[0]``
Examples
--------
>>> paths = ['data_2014_01_03.csv', 'data_2014_02_03.csv', 'data_2015_12_03.csv']
>>> reverse_formats('data_{year}_{month}_{day}.csv', paths)
{'year': ['2014', '2014', '2015'],
'month': ['01', '02', '12'],
'day': ['03', '03', '03']}
>>> reverse_formats('data_{year:d}_{month:d}_{day:d}.csv', paths)
{'year': [2014, 2014, 2015], 'month': [1, 2, 12], 'day': [3, 3, 3]}
>>> reverse_formats('data_{date:%Y_%m_%d}.csv', paths)
{'date': [datetime.datetime(2014, 1, 3, 0, 0),
datetime.datetime(2014, 2, 3, 0, 0),
datetime.datetime(2015, 12, 3, 0, 0)]}
>>> reverse_formats('{state:2}{zip:5}', ['PA19104', 'PA19143', 'MA02534'])
{'state': ['PA', 'PA', 'MA'], 'zip': ['19104', '19143', '02534']}
See also
--------
str.format : method that this reverses
reverse_format : method for reversing just one string using a pattern | [
"Reverse",
"the",
"string",
"method",
"format",
"for",
"a",
"list",
"of",
"strings",
"."
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/source/utils.py#L69-L131 | train | 224,286 |
intake/intake | intake/source/utils.py | reverse_format | def reverse_format(format_string, resolved_string):
"""
Reverse the string method format.
Given format_string and resolved_string, find arguments that would
give ``format_string.format(**arguments) == resolved_string``
Parameters
----------
format_string : str
Format template string as used with str.format method
resolved_string : str
String with same pattern as format_string but with fields
filled out.
Returns
-------
args : dict
Dict of the form {field_name: value} such that
``format_string.(**args) == resolved_string``
Examples
--------
>>> reverse_format('data_{year}_{month}_{day}.csv', 'data_2014_01_03.csv')
{'year': '2014', 'month': '01', 'day': '03'}
>>> reverse_format('data_{year:d}_{month:d}_{day:d}.csv', 'data_2014_01_03.csv')
{'year': 2014, 'month': 1, 'day': 3}
>>> reverse_format('data_{date:%Y_%m_%d}.csv', 'data_2016_10_01.csv')
{'date': datetime.datetime(2016, 10, 1, 0, 0)}
>>> reverse_format('{state:2}{zip:5}', 'PA19104')
{'state': 'PA', 'zip': '19104'}
See also
--------
str.format : method that this reverses
reverse_formats : method for reversing a list of strings using one pattern
"""
from string import Formatter
from datetime import datetime
fmt = Formatter()
args = {}
# ensure that format_string is in posix format
format_string = make_path_posix(format_string)
# split the string into bits
literal_texts, field_names, format_specs, conversions = zip(*fmt.parse(format_string))
if not any(field_names):
return {}
for i, conversion in enumerate(conversions):
if conversion:
raise ValueError(('Conversion not allowed. Found on {}.'
.format(field_names[i])))
# ensure that resolved string is in posix format
resolved_string = make_path_posix(resolved_string)
# get a list of the parts that matter
bits = _get_parts_of_format_string(resolved_string, literal_texts, format_specs)
for i, (field_name, format_spec) in enumerate(zip(field_names, format_specs)):
if field_name:
try:
if format_spec.startswith('%'):
args[field_name] = datetime.strptime(bits[i], format_spec)
elif format_spec[-1] in list('bcdoxX'):
args[field_name] = int(bits[i])
elif format_spec[-1] in list('eEfFgGn'):
args[field_name] = float(bits[i])
elif format_spec[-1] == '%':
args[field_name] = float(bits[i][:-1])/100
else:
args[field_name] = fmt.format_field(bits[i], format_spec)
except:
args[field_name] = bits[i]
return args | python | def reverse_format(format_string, resolved_string):
"""
Reverse the string method format.
Given format_string and resolved_string, find arguments that would
give ``format_string.format(**arguments) == resolved_string``
Parameters
----------
format_string : str
Format template string as used with str.format method
resolved_string : str
String with same pattern as format_string but with fields
filled out.
Returns
-------
args : dict
Dict of the form {field_name: value} such that
``format_string.(**args) == resolved_string``
Examples
--------
>>> reverse_format('data_{year}_{month}_{day}.csv', 'data_2014_01_03.csv')
{'year': '2014', 'month': '01', 'day': '03'}
>>> reverse_format('data_{year:d}_{month:d}_{day:d}.csv', 'data_2014_01_03.csv')
{'year': 2014, 'month': 1, 'day': 3}
>>> reverse_format('data_{date:%Y_%m_%d}.csv', 'data_2016_10_01.csv')
{'date': datetime.datetime(2016, 10, 1, 0, 0)}
>>> reverse_format('{state:2}{zip:5}', 'PA19104')
{'state': 'PA', 'zip': '19104'}
See also
--------
str.format : method that this reverses
reverse_formats : method for reversing a list of strings using one pattern
"""
from string import Formatter
from datetime import datetime
fmt = Formatter()
args = {}
# ensure that format_string is in posix format
format_string = make_path_posix(format_string)
# split the string into bits
literal_texts, field_names, format_specs, conversions = zip(*fmt.parse(format_string))
if not any(field_names):
return {}
for i, conversion in enumerate(conversions):
if conversion:
raise ValueError(('Conversion not allowed. Found on {}.'
.format(field_names[i])))
# ensure that resolved string is in posix format
resolved_string = make_path_posix(resolved_string)
# get a list of the parts that matter
bits = _get_parts_of_format_string(resolved_string, literal_texts, format_specs)
for i, (field_name, format_spec) in enumerate(zip(field_names, format_specs)):
if field_name:
try:
if format_spec.startswith('%'):
args[field_name] = datetime.strptime(bits[i], format_spec)
elif format_spec[-1] in list('bcdoxX'):
args[field_name] = int(bits[i])
elif format_spec[-1] in list('eEfFgGn'):
args[field_name] = float(bits[i])
elif format_spec[-1] == '%':
args[field_name] = float(bits[i][:-1])/100
else:
args[field_name] = fmt.format_field(bits[i], format_spec)
except:
args[field_name] = bits[i]
return args | [
"def",
"reverse_format",
"(",
"format_string",
",",
"resolved_string",
")",
":",
"from",
"string",
"import",
"Formatter",
"from",
"datetime",
"import",
"datetime",
"fmt",
"=",
"Formatter",
"(",
")",
"args",
"=",
"{",
"}",
"# ensure that format_string is in posix for... | Reverse the string method format.
Given format_string and resolved_string, find arguments that would
give ``format_string.format(**arguments) == resolved_string``
Parameters
----------
format_string : str
Format template string as used with str.format method
resolved_string : str
String with same pattern as format_string but with fields
filled out.
Returns
-------
args : dict
Dict of the form {field_name: value} such that
``format_string.(**args) == resolved_string``
Examples
--------
>>> reverse_format('data_{year}_{month}_{day}.csv', 'data_2014_01_03.csv')
{'year': '2014', 'month': '01', 'day': '03'}
>>> reverse_format('data_{year:d}_{month:d}_{day:d}.csv', 'data_2014_01_03.csv')
{'year': 2014, 'month': 1, 'day': 3}
>>> reverse_format('data_{date:%Y_%m_%d}.csv', 'data_2016_10_01.csv')
{'date': datetime.datetime(2016, 10, 1, 0, 0)}
>>> reverse_format('{state:2}{zip:5}', 'PA19104')
{'state': 'PA', 'zip': '19104'}
See also
--------
str.format : method that this reverses
reverse_formats : method for reversing a list of strings using one pattern | [
"Reverse",
"the",
"string",
"method",
"format",
"."
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/source/utils.py#L134-L213 | train | 224,287 |
intake/intake | intake/source/utils.py | path_to_glob | def path_to_glob(path):
"""
Convert pattern style paths to glob style paths
Returns path if path is not str
Parameters
----------
path : str
Path to data optionally containing format_strings
Returns
-------
glob : str
Path with any format strings replaced with *
Examples
--------
>>> path_to_glob('{year}/{month}/{day}.csv')
'*/*/*.csv'
>>> path_to_glob('data/{year:4}{month:02}{day:02}.csv')
'data/*.csv'
>>> path_to_glob('data/*.csv')
'data/*.csv'
"""
from string import Formatter
fmt = Formatter()
if not isinstance(path, str):
return path
# Get just the real bits of the urlpath
literal_texts = [i[0] for i in fmt.parse(path)]
# Only use a star for first empty string in literal_texts
index_of_empty = [i for i, lt in enumerate(literal_texts) if lt == '' and i != 0]
glob = '*'.join([literal_texts[i] for i in range(len(literal_texts)) if i not in index_of_empty])
return glob | python | def path_to_glob(path):
"""
Convert pattern style paths to glob style paths
Returns path if path is not str
Parameters
----------
path : str
Path to data optionally containing format_strings
Returns
-------
glob : str
Path with any format strings replaced with *
Examples
--------
>>> path_to_glob('{year}/{month}/{day}.csv')
'*/*/*.csv'
>>> path_to_glob('data/{year:4}{month:02}{day:02}.csv')
'data/*.csv'
>>> path_to_glob('data/*.csv')
'data/*.csv'
"""
from string import Formatter
fmt = Formatter()
if not isinstance(path, str):
return path
# Get just the real bits of the urlpath
literal_texts = [i[0] for i in fmt.parse(path)]
# Only use a star for first empty string in literal_texts
index_of_empty = [i for i, lt in enumerate(literal_texts) if lt == '' and i != 0]
glob = '*'.join([literal_texts[i] for i in range(len(literal_texts)) if i not in index_of_empty])
return glob | [
"def",
"path_to_glob",
"(",
"path",
")",
":",
"from",
"string",
"import",
"Formatter",
"fmt",
"=",
"Formatter",
"(",
")",
"if",
"not",
"isinstance",
"(",
"path",
",",
"str",
")",
":",
"return",
"path",
"# Get just the real bits of the urlpath",
"literal_texts",
... | Convert pattern style paths to glob style paths
Returns path if path is not str
Parameters
----------
path : str
Path to data optionally containing format_strings
Returns
-------
glob : str
Path with any format strings replaced with *
Examples
--------
>>> path_to_glob('{year}/{month}/{day}.csv')
'*/*/*.csv'
>>> path_to_glob('data/{year:4}{month:02}{day:02}.csv')
'data/*.csv'
>>> path_to_glob('data/*.csv')
'data/*.csv' | [
"Convert",
"pattern",
"style",
"paths",
"to",
"glob",
"style",
"paths"
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/source/utils.py#L215-L255 | train | 224,288 |
intake/intake | intake/source/utils.py | path_to_pattern | def path_to_pattern(path, metadata=None):
"""
Remove source information from path when using chaching
Returns None if path is not str
Parameters
----------
path : str
Path to data optionally containing format_strings
metadata : dict, optional
Extra arguments to the class, contains any cache information
Returns
-------
pattern : str
Pattern style path stripped of everything to the left of cache regex.
"""
if not isinstance(path, str):
return
pattern = path
if metadata:
cache = metadata.get('cache')
if cache:
regex = next(c.get('regex') for c in cache if c.get('argkey') == 'urlpath')
pattern = pattern.split(regex)[-1]
return pattern | python | def path_to_pattern(path, metadata=None):
"""
Remove source information from path when using chaching
Returns None if path is not str
Parameters
----------
path : str
Path to data optionally containing format_strings
metadata : dict, optional
Extra arguments to the class, contains any cache information
Returns
-------
pattern : str
Pattern style path stripped of everything to the left of cache regex.
"""
if not isinstance(path, str):
return
pattern = path
if metadata:
cache = metadata.get('cache')
if cache:
regex = next(c.get('regex') for c in cache if c.get('argkey') == 'urlpath')
pattern = pattern.split(regex)[-1]
return pattern | [
"def",
"path_to_pattern",
"(",
"path",
",",
"metadata",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"path",
",",
"str",
")",
":",
"return",
"pattern",
"=",
"path",
"if",
"metadata",
":",
"cache",
"=",
"metadata",
".",
"get",
"(",
"'cache'",
... | Remove source information from path when using chaching
Returns None if path is not str
Parameters
----------
path : str
Path to data optionally containing format_strings
metadata : dict, optional
Extra arguments to the class, contains any cache information
Returns
-------
pattern : str
Pattern style path stripped of everything to the left of cache regex. | [
"Remove",
"source",
"information",
"from",
"path",
"when",
"using",
"chaching"
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/source/utils.py#L258-L285 | train | 224,289 |
intake/intake | intake/container/base.py | get_partition | def get_partition(url, headers, source_id, container, partition):
"""Serializable function for fetching a data source partition
Parameters
----------
url: str
Server address
headers: dict
HTTP header parameters
source_id: str
ID of the source in the server's cache (unique per user)
container: str
Type of data, like "dataframe" one of ``intake.container.container_map``
partition: serializable
Part of data to fetch, e.g., an integer for a dataframe.
"""
accepted_formats = list(serializer.format_registry.keys())
accepted_compression = list(serializer.compression_registry.keys())
payload = dict(action='read',
source_id=source_id,
accepted_formats=accepted_formats,
accepted_compression=accepted_compression)
if partition is not None:
payload['partition'] = partition
try:
resp = requests.post(urljoin(url, '/v1/source'),
data=msgpack.packb(payload, use_bin_type=True),
**headers)
if resp.status_code != 200:
raise Exception('Error reading data')
msg = msgpack.unpackb(resp.content, **unpack_kwargs)
format = msg['format']
compression = msg['compression']
compressor = serializer.compression_registry[compression]
encoder = serializer.format_registry[format]
chunk = encoder.decode(compressor.decompress(msg['data']),
container)
return chunk
finally:
if resp is not None:
resp.close() | python | def get_partition(url, headers, source_id, container, partition):
"""Serializable function for fetching a data source partition
Parameters
----------
url: str
Server address
headers: dict
HTTP header parameters
source_id: str
ID of the source in the server's cache (unique per user)
container: str
Type of data, like "dataframe" one of ``intake.container.container_map``
partition: serializable
Part of data to fetch, e.g., an integer for a dataframe.
"""
accepted_formats = list(serializer.format_registry.keys())
accepted_compression = list(serializer.compression_registry.keys())
payload = dict(action='read',
source_id=source_id,
accepted_formats=accepted_formats,
accepted_compression=accepted_compression)
if partition is not None:
payload['partition'] = partition
try:
resp = requests.post(urljoin(url, '/v1/source'),
data=msgpack.packb(payload, use_bin_type=True),
**headers)
if resp.status_code != 200:
raise Exception('Error reading data')
msg = msgpack.unpackb(resp.content, **unpack_kwargs)
format = msg['format']
compression = msg['compression']
compressor = serializer.compression_registry[compression]
encoder = serializer.format_registry[format]
chunk = encoder.decode(compressor.decompress(msg['data']),
container)
return chunk
finally:
if resp is not None:
resp.close() | [
"def",
"get_partition",
"(",
"url",
",",
"headers",
",",
"source_id",
",",
"container",
",",
"partition",
")",
":",
"accepted_formats",
"=",
"list",
"(",
"serializer",
".",
"format_registry",
".",
"keys",
"(",
")",
")",
"accepted_compression",
"=",
"list",
"... | Serializable function for fetching a data source partition
Parameters
----------
url: str
Server address
headers: dict
HTTP header parameters
source_id: str
ID of the source in the server's cache (unique per user)
container: str
Type of data, like "dataframe" one of ``intake.container.container_map``
partition: serializable
Part of data to fetch, e.g., an integer for a dataframe. | [
"Serializable",
"function",
"for",
"fetching",
"a",
"data",
"source",
"partition"
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/container/base.py#L81-L124 | train | 224,290 |
intake/intake | intake/catalog/utils.py | flatten | def flatten(iterable):
"""Flatten an arbitrarily deep list"""
# likely not used
iterable = iter(iterable)
while True:
try:
item = next(iterable)
except StopIteration:
break
if isinstance(item, six.string_types):
yield item
continue
try:
data = iter(item)
iterable = itertools.chain(data, iterable)
except:
yield item | python | def flatten(iterable):
"""Flatten an arbitrarily deep list"""
# likely not used
iterable = iter(iterable)
while True:
try:
item = next(iterable)
except StopIteration:
break
if isinstance(item, six.string_types):
yield item
continue
try:
data = iter(item)
iterable = itertools.chain(data, iterable)
except:
yield item | [
"def",
"flatten",
"(",
"iterable",
")",
":",
"# likely not used",
"iterable",
"=",
"iter",
"(",
"iterable",
")",
"while",
"True",
":",
"try",
":",
"item",
"=",
"next",
"(",
"iterable",
")",
"except",
"StopIteration",
":",
"break",
"if",
"isinstance",
"(",
... | Flatten an arbitrarily deep list | [
"Flatten",
"an",
"arbitrarily",
"deep",
"list"
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/catalog/utils.py#L20-L38 | train | 224,291 |
intake/intake | intake/catalog/utils.py | clamp | def clamp(value, lower=0, upper=sys.maxsize):
"""Clamp float between given range"""
return max(lower, min(upper, value)) | python | def clamp(value, lower=0, upper=sys.maxsize):
"""Clamp float between given range"""
return max(lower, min(upper, value)) | [
"def",
"clamp",
"(",
"value",
",",
"lower",
"=",
"0",
",",
"upper",
"=",
"sys",
".",
"maxsize",
")",
":",
"return",
"max",
"(",
"lower",
",",
"min",
"(",
"upper",
",",
"value",
")",
")"
] | Clamp float between given range | [
"Clamp",
"float",
"between",
"given",
"range"
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/catalog/utils.py#L50-L52 | train | 224,292 |
intake/intake | intake/catalog/utils.py | expand_templates | def expand_templates(pars, context, return_left=False, client=False,
getenv=True, getshell=True):
"""
Render variables in context into the set of parameters with jinja2.
For variables that are not strings, nothing happens.
Parameters
----------
pars: dict
values are strings containing some jinja2 controls
context: dict
values to use while rendering
return_left: bool
whether to return the set of variables in context that were not used
in rendering parameters
Returns
-------
dict with the same keys as ``pars``, but updated values; optionally also
return set of unused parameter names.
"""
all_vars = set(context)
out = _expand(pars, context, all_vars, client, getenv, getshell)
if return_left:
return out, all_vars
return out | python | def expand_templates(pars, context, return_left=False, client=False,
getenv=True, getshell=True):
"""
Render variables in context into the set of parameters with jinja2.
For variables that are not strings, nothing happens.
Parameters
----------
pars: dict
values are strings containing some jinja2 controls
context: dict
values to use while rendering
return_left: bool
whether to return the set of variables in context that were not used
in rendering parameters
Returns
-------
dict with the same keys as ``pars``, but updated values; optionally also
return set of unused parameter names.
"""
all_vars = set(context)
out = _expand(pars, context, all_vars, client, getenv, getshell)
if return_left:
return out, all_vars
return out | [
"def",
"expand_templates",
"(",
"pars",
",",
"context",
",",
"return_left",
"=",
"False",
",",
"client",
"=",
"False",
",",
"getenv",
"=",
"True",
",",
"getshell",
"=",
"True",
")",
":",
"all_vars",
"=",
"set",
"(",
"context",
")",
"out",
"=",
"_expand... | Render variables in context into the set of parameters with jinja2.
For variables that are not strings, nothing happens.
Parameters
----------
pars: dict
values are strings containing some jinja2 controls
context: dict
values to use while rendering
return_left: bool
whether to return the set of variables in context that were not used
in rendering parameters
Returns
-------
dict with the same keys as ``pars``, but updated values; optionally also
return set of unused parameter names. | [
"Render",
"variables",
"in",
"context",
"into",
"the",
"set",
"of",
"parameters",
"with",
"jinja2",
"."
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/catalog/utils.py#L109-L135 | train | 224,293 |
intake/intake | intake/catalog/utils.py | merge_pars | def merge_pars(params, user_inputs, spec_pars, client=False, getenv=True,
getshell=True):
"""Produce open arguments by merging various inputs
This function is called in the context of a catalog entry, when finalising
the arguments for instantiating the corresponding data source.
The three sets of inputs to be considered are:
- the arguments section of the original spec (params)
- UserParameters associated with the entry (spec_pars)
- explicit arguments provided at instantiation time, like entry(arg=value)
(user_inputs)
Both spec_pars and user_inputs can be considered as template variables and
used in expanding string values in params.
The default value of a spec_par, if given, may have embedded env and shell
functions, which will be evaluated before use, if the default is used and
the corresponding getenv/getsgell are set. Similarly, string value params
will also have access to these functions within jinja template groups,
as well as full jinja processing.
Where a key exists in both the spec_pars and the user_inputs, the
user_input wins. Where user_inputs contains keys not seen elsewhere, they
are regarded as extra kwargs to pass to the data source.
Where spec pars have the same name as keys in params, their type, max/min
and allowed fields are used to validate the final values of the
corresponding arguments.
Parameters
----------
params : dict
From the entry's original spec
user_inputs : dict
Provided by the user/calling function
spec_pars : list of UserParameters
Default and validation instances
client : bool
Whether this is all running on a client to a remote server - sets
which of the env/shell functions are in operation.
getenv : bool
Whether to allow pulling environment variables. If False, the
template blocks will pass through unevaluated
getshell : bool
Whether or not to allow executing of shell commands. If False, the
template blocks will pass through unevaluated
Returns
-------
Final parameter dict
"""
context = params.copy()
for par in spec_pars:
val = user_inputs.get(par.name, par.default)
if val is not None:
if isinstance(val, six.string_types):
val = expand_defaults(val, getenv=getenv, getshell=getshell,
client=client)
context[par.name] = par.validate(val)
context.update({k: v for k, v in user_inputs.items() if k not in context})
out, left = expand_templates(params, context, True, client, getenv,
getshell)
context = {k: v for k, v in context.items() if k in left}
for par in spec_pars:
if par.name in context:
# coerces to type
context[par.name] = par.validate(context[par.name])
left.remove(par.name)
params.update(out)
user_inputs = expand_templates(user_inputs, context, False, client, getenv,
getshell)
params.update({k: v for k, v in user_inputs.items() if k in left})
params.pop('CATALOG_DIR')
for k, v in params.copy().items():
# final validation/coersion
for sp in [p for p in spec_pars if p.name == k]:
params[k] = sp.validate(params[k])
return params | python | def merge_pars(params, user_inputs, spec_pars, client=False, getenv=True,
getshell=True):
"""Produce open arguments by merging various inputs
This function is called in the context of a catalog entry, when finalising
the arguments for instantiating the corresponding data source.
The three sets of inputs to be considered are:
- the arguments section of the original spec (params)
- UserParameters associated with the entry (spec_pars)
- explicit arguments provided at instantiation time, like entry(arg=value)
(user_inputs)
Both spec_pars and user_inputs can be considered as template variables and
used in expanding string values in params.
The default value of a spec_par, if given, may have embedded env and shell
functions, which will be evaluated before use, if the default is used and
the corresponding getenv/getsgell are set. Similarly, string value params
will also have access to these functions within jinja template groups,
as well as full jinja processing.
Where a key exists in both the spec_pars and the user_inputs, the
user_input wins. Where user_inputs contains keys not seen elsewhere, they
are regarded as extra kwargs to pass to the data source.
Where spec pars have the same name as keys in params, their type, max/min
and allowed fields are used to validate the final values of the
corresponding arguments.
Parameters
----------
params : dict
From the entry's original spec
user_inputs : dict
Provided by the user/calling function
spec_pars : list of UserParameters
Default and validation instances
client : bool
Whether this is all running on a client to a remote server - sets
which of the env/shell functions are in operation.
getenv : bool
Whether to allow pulling environment variables. If False, the
template blocks will pass through unevaluated
getshell : bool
Whether or not to allow executing of shell commands. If False, the
template blocks will pass through unevaluated
Returns
-------
Final parameter dict
"""
context = params.copy()
for par in spec_pars:
val = user_inputs.get(par.name, par.default)
if val is not None:
if isinstance(val, six.string_types):
val = expand_defaults(val, getenv=getenv, getshell=getshell,
client=client)
context[par.name] = par.validate(val)
context.update({k: v for k, v in user_inputs.items() if k not in context})
out, left = expand_templates(params, context, True, client, getenv,
getshell)
context = {k: v for k, v in context.items() if k in left}
for par in spec_pars:
if par.name in context:
# coerces to type
context[par.name] = par.validate(context[par.name])
left.remove(par.name)
params.update(out)
user_inputs = expand_templates(user_inputs, context, False, client, getenv,
getshell)
params.update({k: v for k, v in user_inputs.items() if k in left})
params.pop('CATALOG_DIR')
for k, v in params.copy().items():
# final validation/coersion
for sp in [p for p in spec_pars if p.name == k]:
params[k] = sp.validate(params[k])
return params | [
"def",
"merge_pars",
"(",
"params",
",",
"user_inputs",
",",
"spec_pars",
",",
"client",
"=",
"False",
",",
"getenv",
"=",
"True",
",",
"getshell",
"=",
"True",
")",
":",
"context",
"=",
"params",
".",
"copy",
"(",
")",
"for",
"par",
"in",
"spec_pars",... | Produce open arguments by merging various inputs
This function is called in the context of a catalog entry, when finalising
the arguments for instantiating the corresponding data source.
The three sets of inputs to be considered are:
- the arguments section of the original spec (params)
- UserParameters associated with the entry (spec_pars)
- explicit arguments provided at instantiation time, like entry(arg=value)
(user_inputs)
Both spec_pars and user_inputs can be considered as template variables and
used in expanding string values in params.
The default value of a spec_par, if given, may have embedded env and shell
functions, which will be evaluated before use, if the default is used and
the corresponding getenv/getsgell are set. Similarly, string value params
will also have access to these functions within jinja template groups,
as well as full jinja processing.
Where a key exists in both the spec_pars and the user_inputs, the
user_input wins. Where user_inputs contains keys not seen elsewhere, they
are regarded as extra kwargs to pass to the data source.
Where spec pars have the same name as keys in params, their type, max/min
and allowed fields are used to validate the final values of the
corresponding arguments.
Parameters
----------
params : dict
From the entry's original spec
user_inputs : dict
Provided by the user/calling function
spec_pars : list of UserParameters
Default and validation instances
client : bool
Whether this is all running on a client to a remote server - sets
which of the env/shell functions are in operation.
getenv : bool
Whether to allow pulling environment variables. If False, the
template blocks will pass through unevaluated
getshell : bool
Whether or not to allow executing of shell commands. If False, the
template blocks will pass through unevaluated
Returns
-------
Final parameter dict | [
"Produce",
"open",
"arguments",
"by",
"merging",
"various",
"inputs"
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/catalog/utils.py#L177-L257 | train | 224,294 |
intake/intake | intake/catalog/utils.py | coerce | def coerce(dtype, value):
"""
Convert a value to a specific type.
If the value is already the given type, then the original value is
returned. If the value is None, then the default value given by the
type constructor is returned. Otherwise, the type constructor converts
and returns the value.
"""
if dtype is None:
return value
if type(value).__name__ == dtype:
return value
op = COERCION_RULES[dtype]
return op() if value is None else op(value) | python | def coerce(dtype, value):
"""
Convert a value to a specific type.
If the value is already the given type, then the original value is
returned. If the value is None, then the default value given by the
type constructor is returned. Otherwise, the type constructor converts
and returns the value.
"""
if dtype is None:
return value
if type(value).__name__ == dtype:
return value
op = COERCION_RULES[dtype]
return op() if value is None else op(value) | [
"def",
"coerce",
"(",
"dtype",
",",
"value",
")",
":",
"if",
"dtype",
"is",
"None",
":",
"return",
"value",
"if",
"type",
"(",
"value",
")",
".",
"__name__",
"==",
"dtype",
":",
"return",
"value",
"op",
"=",
"COERCION_RULES",
"[",
"dtype",
"]",
"retu... | Convert a value to a specific type.
If the value is already the given type, then the original value is
returned. If the value is None, then the default value given by the
type constructor is returned. Otherwise, the type constructor converts
and returns the value. | [
"Convert",
"a",
"value",
"to",
"a",
"specific",
"type",
"."
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/catalog/utils.py#L276-L290 | train | 224,295 |
intake/intake | intake/catalog/remote.py | open_remote | def open_remote(url, entry, container, user_parameters, description, http_args,
page_size=None, auth=None, getenv=None, getshell=None):
"""Create either local direct data source or remote streamed source"""
from intake.container import container_map
if url.startswith('intake://'):
url = url[len('intake://'):]
payload = dict(action='open',
name=entry,
parameters=user_parameters,
available_plugins=list(plugin_registry.keys()))
req = requests.post(urljoin(url, '/v1/source'),
data=msgpack.packb(payload, use_bin_type=True),
**http_args)
if req.ok:
response = msgpack.unpackb(req.content, **unpack_kwargs)
if 'plugin' in response:
pl = response['plugin']
pl = [pl] if isinstance(pl, str) else pl
# Direct access
for p in pl:
if p in plugin_registry:
source = plugin_registry[p](**response['args'])
proxy = False
break
else:
proxy = True
else:
proxy = True
if proxy:
response.pop('container')
response.update({'name': entry, 'parameters': user_parameters})
if container == 'catalog':
response.update({'auth': auth,
'getenv': getenv,
'getshell': getshell,
'page_size': page_size
# TODO ttl?
# TODO storage_options?
})
source = container_map[container](url, http_args, **response)
source.description = description
return source
else:
raise Exception('Server error: %d, %s' % (req.status_code, req.reason)) | python | def open_remote(url, entry, container, user_parameters, description, http_args,
page_size=None, auth=None, getenv=None, getshell=None):
"""Create either local direct data source or remote streamed source"""
from intake.container import container_map
if url.startswith('intake://'):
url = url[len('intake://'):]
payload = dict(action='open',
name=entry,
parameters=user_parameters,
available_plugins=list(plugin_registry.keys()))
req = requests.post(urljoin(url, '/v1/source'),
data=msgpack.packb(payload, use_bin_type=True),
**http_args)
if req.ok:
response = msgpack.unpackb(req.content, **unpack_kwargs)
if 'plugin' in response:
pl = response['plugin']
pl = [pl] if isinstance(pl, str) else pl
# Direct access
for p in pl:
if p in plugin_registry:
source = plugin_registry[p](**response['args'])
proxy = False
break
else:
proxy = True
else:
proxy = True
if proxy:
response.pop('container')
response.update({'name': entry, 'parameters': user_parameters})
if container == 'catalog':
response.update({'auth': auth,
'getenv': getenv,
'getshell': getshell,
'page_size': page_size
# TODO ttl?
# TODO storage_options?
})
source = container_map[container](url, http_args, **response)
source.description = description
return source
else:
raise Exception('Server error: %d, %s' % (req.status_code, req.reason)) | [
"def",
"open_remote",
"(",
"url",
",",
"entry",
",",
"container",
",",
"user_parameters",
",",
"description",
",",
"http_args",
",",
"page_size",
"=",
"None",
",",
"auth",
"=",
"None",
",",
"getenv",
"=",
"None",
",",
"getshell",
"=",
"None",
")",
":",
... | Create either local direct data source or remote streamed source | [
"Create",
"either",
"local",
"direct",
"data",
"source",
"or",
"remote",
"streamed",
"source"
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/catalog/remote.py#L92-L137 | train | 224,296 |
intake/intake | intake/container/semistructured.py | RemoteSequenceSource._persist | def _persist(source, path, encoder=None):
"""Save list to files using encoding
encoder : None or one of str|json|pickle
None is equivalent to str
"""
import posixpath
from dask.bytes import open_files
import dask
import pickle
import json
from intake.source.textfiles import TextFilesSource
encoder = {None: str, 'str': str, 'json': json.dumps,
'pickle': pickle.dumps}[encoder]
try:
b = source.to_dask()
except NotImplementedError:
import dask.bag as db
b = db.from_sequence(source.read(), npartitions=1)
files = open_files(posixpath.join(path, 'part.*'), mode='wt',
num=b.npartitions)
dwrite = dask.delayed(write_file)
out = [dwrite(part, f, encoder)
for part, f in zip(b.to_delayed(), files)]
dask.compute(out)
s = TextFilesSource(posixpath.join(path, 'part.*'))
return s | python | def _persist(source, path, encoder=None):
"""Save list to files using encoding
encoder : None or one of str|json|pickle
None is equivalent to str
"""
import posixpath
from dask.bytes import open_files
import dask
import pickle
import json
from intake.source.textfiles import TextFilesSource
encoder = {None: str, 'str': str, 'json': json.dumps,
'pickle': pickle.dumps}[encoder]
try:
b = source.to_dask()
except NotImplementedError:
import dask.bag as db
b = db.from_sequence(source.read(), npartitions=1)
files = open_files(posixpath.join(path, 'part.*'), mode='wt',
num=b.npartitions)
dwrite = dask.delayed(write_file)
out = [dwrite(part, f, encoder)
for part, f in zip(b.to_delayed(), files)]
dask.compute(out)
s = TextFilesSource(posixpath.join(path, 'part.*'))
return s | [
"def",
"_persist",
"(",
"source",
",",
"path",
",",
"encoder",
"=",
"None",
")",
":",
"import",
"posixpath",
"from",
"dask",
".",
"bytes",
"import",
"open_files",
"import",
"dask",
"import",
"pickle",
"import",
"json",
"from",
"intake",
".",
"source",
".",... | Save list to files using encoding
encoder : None or one of str|json|pickle
None is equivalent to str | [
"Save",
"list",
"to",
"files",
"using",
"encoding"
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/container/semistructured.py#L55-L81 | train | 224,297 |
intake/intake | intake/catalog/entry.py | CatalogEntry._ipython_display_ | def _ipython_display_(self):
"""Display the entry as a rich object in an IPython session."""
contents = self.describe()
display({ # noqa: F821
'application/json': contents,
'text/plain': pretty_describe(contents)
}, metadata={
'application/json': {'root': contents["name"]}
}, raw=True) | python | def _ipython_display_(self):
"""Display the entry as a rich object in an IPython session."""
contents = self.describe()
display({ # noqa: F821
'application/json': contents,
'text/plain': pretty_describe(contents)
}, metadata={
'application/json': {'root': contents["name"]}
}, raw=True) | [
"def",
"_ipython_display_",
"(",
"self",
")",
":",
"contents",
"=",
"self",
".",
"describe",
"(",
")",
"display",
"(",
"{",
"# noqa: F821",
"'application/json'",
":",
"contents",
",",
"'text/plain'",
":",
"pretty_describe",
"(",
"contents",
")",
"}",
",",
"m... | Display the entry as a rich object in an IPython session. | [
"Display",
"the",
"entry",
"as",
"a",
"rich",
"object",
"in",
"an",
"IPython",
"session",
"."
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/catalog/entry.py#L103-L111 | train | 224,298 |
intake/intake | intake/source/discovery.py | autodiscover | def autodiscover(path=None, plugin_prefix='intake_'):
"""Scan for Intake plugin packages and return a dict of plugins.
This function searches path (or sys.path) for packages with names that
start with plugin_prefix. Those modules will be imported and scanned for
subclasses of intake.source.base.Plugin. Any subclasses found will be
instantiated and returned in a dictionary, with the plugin's name attribute
as the key.
"""
plugins = {}
for importer, name, ispkg in pkgutil.iter_modules(path=path):
if name.startswith(plugin_prefix):
t = time.time()
new_plugins = load_plugins_from_module(name)
for plugin_name, plugin in new_plugins.items():
if plugin_name in plugins:
orig_path = inspect.getfile(plugins[plugin_name])
new_path = inspect.getfile(plugin)
warnings.warn('Plugin name collision for "%s" from'
'\n %s'
'\nand'
'\n %s'
'\nKeeping plugin from first location.'
% (plugin_name, orig_path, new_path))
else:
plugins[plugin_name] = plugin
logger.debug("Import %s took: %7.2f s" % (name, time.time() - t))
return plugins | python | def autodiscover(path=None, plugin_prefix='intake_'):
"""Scan for Intake plugin packages and return a dict of plugins.
This function searches path (or sys.path) for packages with names that
start with plugin_prefix. Those modules will be imported and scanned for
subclasses of intake.source.base.Plugin. Any subclasses found will be
instantiated and returned in a dictionary, with the plugin's name attribute
as the key.
"""
plugins = {}
for importer, name, ispkg in pkgutil.iter_modules(path=path):
if name.startswith(plugin_prefix):
t = time.time()
new_plugins = load_plugins_from_module(name)
for plugin_name, plugin in new_plugins.items():
if plugin_name in plugins:
orig_path = inspect.getfile(plugins[plugin_name])
new_path = inspect.getfile(plugin)
warnings.warn('Plugin name collision for "%s" from'
'\n %s'
'\nand'
'\n %s'
'\nKeeping plugin from first location.'
% (plugin_name, orig_path, new_path))
else:
plugins[plugin_name] = plugin
logger.debug("Import %s took: %7.2f s" % (name, time.time() - t))
return plugins | [
"def",
"autodiscover",
"(",
"path",
"=",
"None",
",",
"plugin_prefix",
"=",
"'intake_'",
")",
":",
"plugins",
"=",
"{",
"}",
"for",
"importer",
",",
"name",
",",
"ispkg",
"in",
"pkgutil",
".",
"iter_modules",
"(",
"path",
"=",
"path",
")",
":",
"if",
... | Scan for Intake plugin packages and return a dict of plugins.
This function searches path (or sys.path) for packages with names that
start with plugin_prefix. Those modules will be imported and scanned for
subclasses of intake.source.base.Plugin. Any subclasses found will be
instantiated and returned in a dictionary, with the plugin's name attribute
as the key. | [
"Scan",
"for",
"Intake",
"plugin",
"packages",
"and",
"return",
"a",
"dict",
"of",
"plugins",
"."
] | 277b96bfdee39d8a3048ea5408c6d6716d568336 | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/source/discovery.py#L20-L51 | train | 224,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.