Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import print_function
cli = click.CommandCollection(
sources=[
top_account,
top_config,
top_execute,
top_hosting,
top_init,
top_instance,
top_level,
top_migrate,
top_sync,
top_sockets,
],
)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import click
from click import ClickException
from syncano.exceptions import SyncanoException
from syncano_cli.account.commands import top_account
from syncano_cli.base.exceptions import CLIBaseException, SyncanoLibraryException
from syncano_cli.commands import top_level
from syncano_cli.config_commands.commands import top_config
from syncano_cli.custom_sockets.commands import top_sockets
from syncano_cli.execute.commands import top_execute
from syncano_cli.hosting.commands import top_hosting
from syncano_cli.init.commands import top_init
from syncano_cli.instance.commands import top_instance
from syncano_cli.parse_to_syncano.commands import top_migrate
from syncano_cli.sync.commands import top_sync
and context:
# Path: syncano_cli/account/commands.py
# @click.group()
# def top_account():
# pass
#
# Path: syncano_cli/base/exceptions.py
# class CLIBaseException(ClickException):
#
# default_message = u'A CLI processing exception.'
#
# def __init__(self, message=None, format_args=None):
# message = message or self.default_message
# if format_args:
# message = message.format(*format_args)
# super(CLIBaseException, self).__init__(message)
#
# def show(self, file=None):
# formatter = Formatter()
# formatter.write('Error: %s' % self.format_message(), ErrorOpt(), SpacedOpt())
#
# class SyncanoLibraryException(CLIBaseException):
# pass
#
# Path: syncano_cli/commands.py
# @click.group()
# def top_level():
# pass
#
# Path: syncano_cli/config_commands/commands.py
# @click.group()
# def top_config():
# pass
#
# Path: syncano_cli/custom_sockets/commands.py
# @click.group()
# def top_sockets():
# pass
#
# Path: syncano_cli/execute/commands.py
# @click.group()
# def top_execute():
# pass
#
# Path: syncano_cli/hosting/commands.py
# @click.group()
# def top_hosting():
# pass
#
# Path: syncano_cli/init/commands.py
# @click.group()
# def top_init():
# pass
#
# Path: syncano_cli/instance/commands.py
# @click.group()
# def top_instance():
# pass
#
# Path: syncano_cli/parse_to_syncano/commands.py
# @click.group()
# def top_migrate():
# pass
#
# Path: syncano_cli/sync/commands.py
# @click.group()
# def top_sync():
# pass
which might include code, classes, or functions. Output only the next line. | def main(): |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import print_function
cli = click.CommandCollection(
sources=[
top_account,
top_config,
top_execute,
top_hosting,
top_init,
top_instance,
top_level,
top_migrate,
top_sync,
top_sockets,
],
)
def main():
<|code_end|>
with the help of current file imports:
import click
from click import ClickException
from syncano.exceptions import SyncanoException
from syncano_cli.account.commands import top_account
from syncano_cli.base.exceptions import CLIBaseException, SyncanoLibraryException
from syncano_cli.commands import top_level
from syncano_cli.config_commands.commands import top_config
from syncano_cli.custom_sockets.commands import top_sockets
from syncano_cli.execute.commands import top_execute
from syncano_cli.hosting.commands import top_hosting
from syncano_cli.init.commands import top_init
from syncano_cli.instance.commands import top_instance
from syncano_cli.parse_to_syncano.commands import top_migrate
from syncano_cli.sync.commands import top_sync
and context from other files:
# Path: syncano_cli/account/commands.py
# @click.group()
# def top_account():
# pass
#
# Path: syncano_cli/base/exceptions.py
# class CLIBaseException(ClickException):
#
# default_message = u'A CLI processing exception.'
#
# def __init__(self, message=None, format_args=None):
# message = message or self.default_message
# if format_args:
# message = message.format(*format_args)
# super(CLIBaseException, self).__init__(message)
#
# def show(self, file=None):
# formatter = Formatter()
# formatter.write('Error: %s' % self.format_message(), ErrorOpt(), SpacedOpt())
#
# class SyncanoLibraryException(CLIBaseException):
# pass
#
# Path: syncano_cli/commands.py
# @click.group()
# def top_level():
# pass
#
# Path: syncano_cli/config_commands/commands.py
# @click.group()
# def top_config():
# pass
#
# Path: syncano_cli/custom_sockets/commands.py
# @click.group()
# def top_sockets():
# pass
#
# Path: syncano_cli/execute/commands.py
# @click.group()
# def top_execute():
# pass
#
# Path: syncano_cli/hosting/commands.py
# @click.group()
# def top_hosting():
# pass
#
# Path: syncano_cli/init/commands.py
# @click.group()
# def top_init():
# pass
#
# Path: syncano_cli/instance/commands.py
# @click.group()
# def top_instance():
# pass
#
# Path: syncano_cli/parse_to_syncano/commands.py
# @click.group()
# def top_migrate():
# pass
#
# Path: syncano_cli/sync/commands.py
# @click.group()
# def top_sync():
# pass
, which may contain function names, class names, or code. Output only the next line. | try: |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import print_function
cli = click.CommandCollection(
sources=[
top_account,
top_config,
top_execute,
top_hosting,
top_init,
top_instance,
top_level,
top_migrate,
top_sync,
top_sockets,
],
)
def main():
try:
cli(obj={})
except SyncanoException as e:
raise SyncanoLibraryException(e.reason)
<|code_end|>
, generate the next line using the imports in this file:
import click
from click import ClickException
from syncano.exceptions import SyncanoException
from syncano_cli.account.commands import top_account
from syncano_cli.base.exceptions import CLIBaseException, SyncanoLibraryException
from syncano_cli.commands import top_level
from syncano_cli.config_commands.commands import top_config
from syncano_cli.custom_sockets.commands import top_sockets
from syncano_cli.execute.commands import top_execute
from syncano_cli.hosting.commands import top_hosting
from syncano_cli.init.commands import top_init
from syncano_cli.instance.commands import top_instance
from syncano_cli.parse_to_syncano.commands import top_migrate
from syncano_cli.sync.commands import top_sync
and context (functions, classes, or occasionally code) from other files:
# Path: syncano_cli/account/commands.py
# @click.group()
# def top_account():
# pass
#
# Path: syncano_cli/base/exceptions.py
# class CLIBaseException(ClickException):
#
# default_message = u'A CLI processing exception.'
#
# def __init__(self, message=None, format_args=None):
# message = message or self.default_message
# if format_args:
# message = message.format(*format_args)
# super(CLIBaseException, self).__init__(message)
#
# def show(self, file=None):
# formatter = Formatter()
# formatter.write('Error: %s' % self.format_message(), ErrorOpt(), SpacedOpt())
#
# class SyncanoLibraryException(CLIBaseException):
# pass
#
# Path: syncano_cli/commands.py
# @click.group()
# def top_level():
# pass
#
# Path: syncano_cli/config_commands/commands.py
# @click.group()
# def top_config():
# pass
#
# Path: syncano_cli/custom_sockets/commands.py
# @click.group()
# def top_sockets():
# pass
#
# Path: syncano_cli/execute/commands.py
# @click.group()
# def top_execute():
# pass
#
# Path: syncano_cli/hosting/commands.py
# @click.group()
# def top_hosting():
# pass
#
# Path: syncano_cli/init/commands.py
# @click.group()
# def top_init():
# pass
#
# Path: syncano_cli/instance/commands.py
# @click.group()
# def top_instance():
# pass
#
# Path: syncano_cli/parse_to_syncano/commands.py
# @click.group()
# def top_migrate():
# pass
#
# Path: syncano_cli/sync/commands.py
# @click.group()
# def top_sync():
# pass
. Output only the next line. | except ClickException: |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
from __future__ import print_function
cli = click.CommandCollection(
sources=[
top_account,
top_config,
top_execute,
top_hosting,
top_init,
top_instance,
top_level,
top_migrate,
top_sync,
top_sockets,
<|code_end|>
. Use current file imports:
(import click
from click import ClickException
from syncano.exceptions import SyncanoException
from syncano_cli.account.commands import top_account
from syncano_cli.base.exceptions import CLIBaseException, SyncanoLibraryException
from syncano_cli.commands import top_level
from syncano_cli.config_commands.commands import top_config
from syncano_cli.custom_sockets.commands import top_sockets
from syncano_cli.execute.commands import top_execute
from syncano_cli.hosting.commands import top_hosting
from syncano_cli.init.commands import top_init
from syncano_cli.instance.commands import top_instance
from syncano_cli.parse_to_syncano.commands import top_migrate
from syncano_cli.sync.commands import top_sync)
and context including class names, function names, or small code snippets from other files:
# Path: syncano_cli/account/commands.py
# @click.group()
# def top_account():
# pass
#
# Path: syncano_cli/base/exceptions.py
# class CLIBaseException(ClickException):
#
# default_message = u'A CLI processing exception.'
#
# def __init__(self, message=None, format_args=None):
# message = message or self.default_message
# if format_args:
# message = message.format(*format_args)
# super(CLIBaseException, self).__init__(message)
#
# def show(self, file=None):
# formatter = Formatter()
# formatter.write('Error: %s' % self.format_message(), ErrorOpt(), SpacedOpt())
#
# class SyncanoLibraryException(CLIBaseException):
# pass
#
# Path: syncano_cli/commands.py
# @click.group()
# def top_level():
# pass
#
# Path: syncano_cli/config_commands/commands.py
# @click.group()
# def top_config():
# pass
#
# Path: syncano_cli/custom_sockets/commands.py
# @click.group()
# def top_sockets():
# pass
#
# Path: syncano_cli/execute/commands.py
# @click.group()
# def top_execute():
# pass
#
# Path: syncano_cli/hosting/commands.py
# @click.group()
# def top_hosting():
# pass
#
# Path: syncano_cli/init/commands.py
# @click.group()
# def top_init():
# pass
#
# Path: syncano_cli/instance/commands.py
# @click.group()
# def top_instance():
# pass
#
# Path: syncano_cli/parse_to_syncano/commands.py
# @click.group()
# def top_migrate():
# pass
#
# Path: syncano_cli/sync/commands.py
# @click.group()
# def top_sync():
# pass
. Output only the next line. | ], |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import print_function
cli = click.CommandCollection(
sources=[
top_account,
top_config,
top_execute,
top_hosting,
top_init,
top_instance,
top_level,
top_migrate,
top_sync,
top_sockets,
],
)
def main():
<|code_end|>
. Use current file imports:
import click
from click import ClickException
from syncano.exceptions import SyncanoException
from syncano_cli.account.commands import top_account
from syncano_cli.base.exceptions import CLIBaseException, SyncanoLibraryException
from syncano_cli.commands import top_level
from syncano_cli.config_commands.commands import top_config
from syncano_cli.custom_sockets.commands import top_sockets
from syncano_cli.execute.commands import top_execute
from syncano_cli.hosting.commands import top_hosting
from syncano_cli.init.commands import top_init
from syncano_cli.instance.commands import top_instance
from syncano_cli.parse_to_syncano.commands import top_migrate
from syncano_cli.sync.commands import top_sync
and context (classes, functions, or code) from other files:
# Path: syncano_cli/account/commands.py
# @click.group()
# def top_account():
# pass
#
# Path: syncano_cli/base/exceptions.py
# class CLIBaseException(ClickException):
#
# default_message = u'A CLI processing exception.'
#
# def __init__(self, message=None, format_args=None):
# message = message or self.default_message
# if format_args:
# message = message.format(*format_args)
# super(CLIBaseException, self).__init__(message)
#
# def show(self, file=None):
# formatter = Formatter()
# formatter.write('Error: %s' % self.format_message(), ErrorOpt(), SpacedOpt())
#
# class SyncanoLibraryException(CLIBaseException):
# pass
#
# Path: syncano_cli/commands.py
# @click.group()
# def top_level():
# pass
#
# Path: syncano_cli/config_commands/commands.py
# @click.group()
# def top_config():
# pass
#
# Path: syncano_cli/custom_sockets/commands.py
# @click.group()
# def top_sockets():
# pass
#
# Path: syncano_cli/execute/commands.py
# @click.group()
# def top_execute():
# pass
#
# Path: syncano_cli/hosting/commands.py
# @click.group()
# def top_hosting():
# pass
#
# Path: syncano_cli/init/commands.py
# @click.group()
# def top_init():
# pass
#
# Path: syncano_cli/instance/commands.py
# @click.group()
# def top_instance():
# pass
#
# Path: syncano_cli/parse_to_syncano/commands.py
# @click.group()
# def top_migrate():
# pass
#
# Path: syncano_cli/sync/commands.py
# @click.group()
# def top_sync():
# pass
. Output only the next line. | try: |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
from __future__ import print_function
cli = click.CommandCollection(
sources=[
top_account,
top_config,
top_execute,
top_hosting,
top_init,
top_instance,
top_level,
top_migrate,
top_sync,
top_sockets,
],
)
def main():
try:
<|code_end|>
. Use current file imports:
(import click
from click import ClickException
from syncano.exceptions import SyncanoException
from syncano_cli.account.commands import top_account
from syncano_cli.base.exceptions import CLIBaseException, SyncanoLibraryException
from syncano_cli.commands import top_level
from syncano_cli.config_commands.commands import top_config
from syncano_cli.custom_sockets.commands import top_sockets
from syncano_cli.execute.commands import top_execute
from syncano_cli.hosting.commands import top_hosting
from syncano_cli.init.commands import top_init
from syncano_cli.instance.commands import top_instance
from syncano_cli.parse_to_syncano.commands import top_migrate
from syncano_cli.sync.commands import top_sync)
and context including class names, function names, or small code snippets from other files:
# Path: syncano_cli/account/commands.py
# @click.group()
# def top_account():
# pass
#
# Path: syncano_cli/base/exceptions.py
# class CLIBaseException(ClickException):
#
# default_message = u'A CLI processing exception.'
#
# def __init__(self, message=None, format_args=None):
# message = message or self.default_message
# if format_args:
# message = message.format(*format_args)
# super(CLIBaseException, self).__init__(message)
#
# def show(self, file=None):
# formatter = Formatter()
# formatter.write('Error: %s' % self.format_message(), ErrorOpt(), SpacedOpt())
#
# class SyncanoLibraryException(CLIBaseException):
# pass
#
# Path: syncano_cli/commands.py
# @click.group()
# def top_level():
# pass
#
# Path: syncano_cli/config_commands/commands.py
# @click.group()
# def top_config():
# pass
#
# Path: syncano_cli/custom_sockets/commands.py
# @click.group()
# def top_sockets():
# pass
#
# Path: syncano_cli/execute/commands.py
# @click.group()
# def top_execute():
# pass
#
# Path: syncano_cli/hosting/commands.py
# @click.group()
# def top_hosting():
# pass
#
# Path: syncano_cli/init/commands.py
# @click.group()
# def top_init():
# pass
#
# Path: syncano_cli/instance/commands.py
# @click.group()
# def top_instance():
# pass
#
# Path: syncano_cli/parse_to_syncano/commands.py
# @click.group()
# def top_migrate():
# pass
#
# Path: syncano_cli/sync/commands.py
# @click.group()
# def top_sync():
# pass
. Output only the next line. | cli(obj={}) |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import print_function
cli = click.CommandCollection(
sources=[
top_account,
top_config,
top_execute,
top_hosting,
top_init,
top_instance,
top_level,
top_migrate,
top_sync,
top_sockets,
],
<|code_end|>
, determine the next line of code. You have imports:
import click
from click import ClickException
from syncano.exceptions import SyncanoException
from syncano_cli.account.commands import top_account
from syncano_cli.base.exceptions import CLIBaseException, SyncanoLibraryException
from syncano_cli.commands import top_level
from syncano_cli.config_commands.commands import top_config
from syncano_cli.custom_sockets.commands import top_sockets
from syncano_cli.execute.commands import top_execute
from syncano_cli.hosting.commands import top_hosting
from syncano_cli.init.commands import top_init
from syncano_cli.instance.commands import top_instance
from syncano_cli.parse_to_syncano.commands import top_migrate
from syncano_cli.sync.commands import top_sync
and context (class names, function names, or code) available:
# Path: syncano_cli/account/commands.py
# @click.group()
# def top_account():
# pass
#
# Path: syncano_cli/base/exceptions.py
# class CLIBaseException(ClickException):
#
# default_message = u'A CLI processing exception.'
#
# def __init__(self, message=None, format_args=None):
# message = message or self.default_message
# if format_args:
# message = message.format(*format_args)
# super(CLIBaseException, self).__init__(message)
#
# def show(self, file=None):
# formatter = Formatter()
# formatter.write('Error: %s' % self.format_message(), ErrorOpt(), SpacedOpt())
#
# class SyncanoLibraryException(CLIBaseException):
# pass
#
# Path: syncano_cli/commands.py
# @click.group()
# def top_level():
# pass
#
# Path: syncano_cli/config_commands/commands.py
# @click.group()
# def top_config():
# pass
#
# Path: syncano_cli/custom_sockets/commands.py
# @click.group()
# def top_sockets():
# pass
#
# Path: syncano_cli/execute/commands.py
# @click.group()
# def top_execute():
# pass
#
# Path: syncano_cli/hosting/commands.py
# @click.group()
# def top_hosting():
# pass
#
# Path: syncano_cli/init/commands.py
# @click.group()
# def top_init():
# pass
#
# Path: syncano_cli/instance/commands.py
# @click.group()
# def top_instance():
# pass
#
# Path: syncano_cli/parse_to_syncano/commands.py
# @click.group()
# def top_migrate():
# pass
#
# Path: syncano_cli/sync/commands.py
# @click.group()
# def top_sync():
# pass
. Output only the next line. | ) |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import print_function
cli = click.CommandCollection(
sources=[
top_account,
top_config,
top_execute,
top_hosting,
top_init,
top_instance,
top_level,
top_migrate,
top_sync,
top_sockets,
],
<|code_end|>
, predict the immediate next line with the help of imports:
import click
from click import ClickException
from syncano.exceptions import SyncanoException
from syncano_cli.account.commands import top_account
from syncano_cli.base.exceptions import CLIBaseException, SyncanoLibraryException
from syncano_cli.commands import top_level
from syncano_cli.config_commands.commands import top_config
from syncano_cli.custom_sockets.commands import top_sockets
from syncano_cli.execute.commands import top_execute
from syncano_cli.hosting.commands import top_hosting
from syncano_cli.init.commands import top_init
from syncano_cli.instance.commands import top_instance
from syncano_cli.parse_to_syncano.commands import top_migrate
from syncano_cli.sync.commands import top_sync
and context (classes, functions, sometimes code) from other files:
# Path: syncano_cli/account/commands.py
# @click.group()
# def top_account():
# pass
#
# Path: syncano_cli/base/exceptions.py
# class CLIBaseException(ClickException):
#
# default_message = u'A CLI processing exception.'
#
# def __init__(self, message=None, format_args=None):
# message = message or self.default_message
# if format_args:
# message = message.format(*format_args)
# super(CLIBaseException, self).__init__(message)
#
# def show(self, file=None):
# formatter = Formatter()
# formatter.write('Error: %s' % self.format_message(), ErrorOpt(), SpacedOpt())
#
# class SyncanoLibraryException(CLIBaseException):
# pass
#
# Path: syncano_cli/commands.py
# @click.group()
# def top_level():
# pass
#
# Path: syncano_cli/config_commands/commands.py
# @click.group()
# def top_config():
# pass
#
# Path: syncano_cli/custom_sockets/commands.py
# @click.group()
# def top_sockets():
# pass
#
# Path: syncano_cli/execute/commands.py
# @click.group()
# def top_execute():
# pass
#
# Path: syncano_cli/hosting/commands.py
# @click.group()
# def top_hosting():
# pass
#
# Path: syncano_cli/init/commands.py
# @click.group()
# def top_init():
# pass
#
# Path: syncano_cli/instance/commands.py
# @click.group()
# def top_instance():
# pass
#
# Path: syncano_cli/parse_to_syncano/commands.py
# @click.group()
# def top_migrate():
# pass
#
# Path: syncano_cli/sync/commands.py
# @click.group()
# def top_sync():
# pass
. Output only the next line. | ) |
Using the snippet: <|code_start|> def _process_field_with_type(cls, key, value, processed_object, files, reference_map):
if value['__type'] == ParseFieldTypeE.DATE:
processed_object[key.lower()] = value['iso']
elif value['__type'] == ParseFieldTypeE.POINTER:
processed_object[key.lower()] = reference_map.get(value['objectId'])
elif value['__type'] == ParseFieldTypeE.FILE:
file_data = requests.get(value['url'])
file_path = '/tmp/{}'.format(value['name'])
with open(file_path, 'wb+') as file_d:
file_d.write(file_data.content)
file_descriptor = open(file_path, 'rb')
files[key] = file_descriptor
elif value['__type'] == ParseFieldTypeE.GEO_POINT:
processed_object[key.lower()] = {'longitude': value['longitude'], 'latitude': value['latitude']}
@classmethod
def _process_array_field(cls, key, value, processed_object):
for i, item in enumerate(value):
if isinstance(item, dict):
if item.get('__type') == ParseFieldTypeE.POINTER:
Formatter().write('Array of pointers not supported, writing: {}'.format(item.get('objectId')))
value[i] = item['objectId']
values_list = json.dumps(value)
processed_object[key.lower()] = values_list
@classmethod
def _process_other_fields(cls, key, value, processed_object, syncano_fields):
if key.lower() in syncano_fields:
if key in ['createdAt', 'updatedAt']:
processed_object[cls.original_datetime_label.format(key.lower())] = value
<|code_end|>
, determine the next line of code. You have imports:
import json
import requests
import six
from syncano_cli.base.formatters import Formatter
from syncano_cli.parse_to_syncano.migrations.aggregation import ClassAggregate
from syncano_cli.parse_to_syncano.parse.constants import ParseFieldTypeE
and context (class names, function names, or code) available:
# Path: syncano_cli/base/formatters.py
# class Formatter(object):
#
# indent = ' '
# not_set = '-- not set --'
#
# def write(self, single_line, *options):
# option = self.get_options(options)
# styles = option.map_click()
# single_line = self._indent(single_line, option)
# self._write(single_line, option, **styles)
#
# def write_lines(self, lines, *options):
# lines = lines.splitlines() if isinstance(lines, six.string_types) else lines
# for line in lines:
# self.write(line, *options)
#
# def write_block(self, lines, *options):
# self.write_lines(lines, *options)
# self.separator()
#
# @classmethod
# def empty_line(cls):
# click.echo()
#
# def separator(self, size=70, indent=1):
# self.write(size * '-', DefaultOpt(indent=indent), WarningOpt(), BottomSpacedOpt())
#
# def display_config(self, config):
# for name, value in six.iteritems(config):
# self.write('{}{:20} {}'.format(
# self.indent,
# click.style(name, fg=ColorSchema.PROMPT),
# click.style(value, fg=ColorSchema.INFO)
# ))
# if not config:
# self.write('No config specified yet.', DefaultOpt(indent=2))
# self.empty_line()
#
# def get_options(self, options):
# option_list = list(options) or []
# option_list.insert(0, DefaultOpt())
# return OptionsBase.build_options(option_list)
#
# def format_object(self, dictionary, indent=1, skip_fields=None):
# skip_fields = skip_fields or []
# indent += 1
# for key, value in six.iteritems(dictionary):
# if isinstance(value, dict):
# self.write('{}:'.format(click.style(key, fg=ColorSchema.PROMPT)), DefaultOpt(indent=indent))
# self.format_object(value, indent=indent, skip_fields=skip_fields)
# elif isinstance(value, list):
# self.format_list(value, key=key, indent=indent)
# else:
# if key in skip_fields:
# continue
# self.write('{}: {}'.format(
# click.style(key, fg=ColorSchema.PROMPT),
# click.style(value, fg=ColorSchema.INFO)
# ), DefaultOpt(indent=indent))
#
# def format_list(self, data_list, key=None, indent=2, skip_fields=None):
# skip_fields = skip_fields or []
# for el in data_list:
# if isinstance(el, dict):
# self.format_object(el, indent=indent, skip_fields=skip_fields)
# else:
# if key:
# self.write('{}: {}'.format(
# click.style(key, fg=ColorSchema.PROMPT),
# click.style(el, fg=ColorSchema.INFO)
# ), DefaultOpt(indent=indent))
# else:
# self.write('{}'.format(el), DefaultOpt(indent=indent))
# self.empty_line()
#
# def _write(self, line, options, **styles):
# if options.space_top:
# self.empty_line()
#
# click.echo(click.style(line, **styles))
#
# if options.space_bottom:
# self.empty_line()
#
# def _indent(self, line, options):
# return '{}{}'.format(self.indent * options.indent, line)
#
# Path: syncano_cli/parse_to_syncano/migrations/aggregation.py
# class ClassAggregate(object):
#
# def __init__(self, syncano_name, syncano_schema, parse_name, parse_schema):
# self.syncano_name = syncano_name
# self.syncano_schema = syncano_schema
# self.parse_name = parse_name
# self.parse_schema = parse_schema
#
# Path: syncano_cli/parse_to_syncano/parse/constants.py
# class ParseFieldTypeE(object):
# DATE = 'Date'
# POINTER = 'Pointer'
# ARRAY = 'Array'
# OBJECT = 'Object'
# FILE = 'File'
# GEO_POINT = 'GeoPoint'
# RELATION = 'Relation'
. Output only the next line. | else: |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
class SyncanoSchema(object):
def __init__(self, class_name, schema, relations):
self.class_name = class_name
self.schema = schema
self.relations = relations
def process_relations(self):
pass
@property
def has_relations(self):
return bool(self.relations)
class ClassProcessor(object):
<|code_end|>
. Use current file imports:
(import json
import requests
import six
from syncano_cli.base.formatters import Formatter
from syncano_cli.parse_to_syncano.migrations.aggregation import ClassAggregate
from syncano_cli.parse_to_syncano.parse.constants import ParseFieldTypeE)
and context including class names, function names, or small code snippets from other files:
# Path: syncano_cli/base/formatters.py
# class Formatter(object):
#
# indent = ' '
# not_set = '-- not set --'
#
# def write(self, single_line, *options):
# option = self.get_options(options)
# styles = option.map_click()
# single_line = self._indent(single_line, option)
# self._write(single_line, option, **styles)
#
# def write_lines(self, lines, *options):
# lines = lines.splitlines() if isinstance(lines, six.string_types) else lines
# for line in lines:
# self.write(line, *options)
#
# def write_block(self, lines, *options):
# self.write_lines(lines, *options)
# self.separator()
#
# @classmethod
# def empty_line(cls):
# click.echo()
#
# def separator(self, size=70, indent=1):
# self.write(size * '-', DefaultOpt(indent=indent), WarningOpt(), BottomSpacedOpt())
#
# def display_config(self, config):
# for name, value in six.iteritems(config):
# self.write('{}{:20} {}'.format(
# self.indent,
# click.style(name, fg=ColorSchema.PROMPT),
# click.style(value, fg=ColorSchema.INFO)
# ))
# if not config:
# self.write('No config specified yet.', DefaultOpt(indent=2))
# self.empty_line()
#
# def get_options(self, options):
# option_list = list(options) or []
# option_list.insert(0, DefaultOpt())
# return OptionsBase.build_options(option_list)
#
# def format_object(self, dictionary, indent=1, skip_fields=None):
# skip_fields = skip_fields or []
# indent += 1
# for key, value in six.iteritems(dictionary):
# if isinstance(value, dict):
# self.write('{}:'.format(click.style(key, fg=ColorSchema.PROMPT)), DefaultOpt(indent=indent))
# self.format_object(value, indent=indent, skip_fields=skip_fields)
# elif isinstance(value, list):
# self.format_list(value, key=key, indent=indent)
# else:
# if key in skip_fields:
# continue
# self.write('{}: {}'.format(
# click.style(key, fg=ColorSchema.PROMPT),
# click.style(value, fg=ColorSchema.INFO)
# ), DefaultOpt(indent=indent))
#
# def format_list(self, data_list, key=None, indent=2, skip_fields=None):
# skip_fields = skip_fields or []
# for el in data_list:
# if isinstance(el, dict):
# self.format_object(el, indent=indent, skip_fields=skip_fields)
# else:
# if key:
# self.write('{}: {}'.format(
# click.style(key, fg=ColorSchema.PROMPT),
# click.style(el, fg=ColorSchema.INFO)
# ), DefaultOpt(indent=indent))
# else:
# self.write('{}'.format(el), DefaultOpt(indent=indent))
# self.empty_line()
#
# def _write(self, line, options, **styles):
# if options.space_top:
# self.empty_line()
#
# click.echo(click.style(line, **styles))
#
# if options.space_bottom:
# self.empty_line()
#
# def _indent(self, line, options):
# return '{}{}'.format(self.indent * options.indent, line)
#
# Path: syncano_cli/parse_to_syncano/migrations/aggregation.py
# class ClassAggregate(object):
#
# def __init__(self, syncano_name, syncano_schema, parse_name, parse_schema):
# self.syncano_name = syncano_name
# self.syncano_schema = syncano_schema
# self.parse_name = parse_name
# self.parse_schema = parse_schema
#
# Path: syncano_cli/parse_to_syncano/parse/constants.py
# class ParseFieldTypeE(object):
# DATE = 'Date'
# POINTER = 'Pointer'
# ARRAY = 'Array'
# OBJECT = 'Object'
# FILE = 'File'
# GEO_POINT = 'GeoPoint'
# RELATION = 'Relation'
. Output only the next line. | map = { |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
class SyncanoSchema(object):
def __init__(self, class_name, schema, relations):
self.class_name = class_name
self.schema = schema
self.relations = relations
def process_relations(self):
pass
@property
def has_relations(self):
return bool(self.relations)
class ClassProcessor(object):
map = {
'Number': 'integer',
<|code_end|>
, determine the next line of code. You have imports:
import json
import requests
import six
from syncano_cli.base.formatters import Formatter
from syncano_cli.parse_to_syncano.migrations.aggregation import ClassAggregate
from syncano_cli.parse_to_syncano.parse.constants import ParseFieldTypeE
and context (class names, function names, or code) available:
# Path: syncano_cli/base/formatters.py
# class Formatter(object):
#
# indent = ' '
# not_set = '-- not set --'
#
# def write(self, single_line, *options):
# option = self.get_options(options)
# styles = option.map_click()
# single_line = self._indent(single_line, option)
# self._write(single_line, option, **styles)
#
# def write_lines(self, lines, *options):
# lines = lines.splitlines() if isinstance(lines, six.string_types) else lines
# for line in lines:
# self.write(line, *options)
#
# def write_block(self, lines, *options):
# self.write_lines(lines, *options)
# self.separator()
#
# @classmethod
# def empty_line(cls):
# click.echo()
#
# def separator(self, size=70, indent=1):
# self.write(size * '-', DefaultOpt(indent=indent), WarningOpt(), BottomSpacedOpt())
#
# def display_config(self, config):
# for name, value in six.iteritems(config):
# self.write('{}{:20} {}'.format(
# self.indent,
# click.style(name, fg=ColorSchema.PROMPT),
# click.style(value, fg=ColorSchema.INFO)
# ))
# if not config:
# self.write('No config specified yet.', DefaultOpt(indent=2))
# self.empty_line()
#
# def get_options(self, options):
# option_list = list(options) or []
# option_list.insert(0, DefaultOpt())
# return OptionsBase.build_options(option_list)
#
# def format_object(self, dictionary, indent=1, skip_fields=None):
# skip_fields = skip_fields or []
# indent += 1
# for key, value in six.iteritems(dictionary):
# if isinstance(value, dict):
# self.write('{}:'.format(click.style(key, fg=ColorSchema.PROMPT)), DefaultOpt(indent=indent))
# self.format_object(value, indent=indent, skip_fields=skip_fields)
# elif isinstance(value, list):
# self.format_list(value, key=key, indent=indent)
# else:
# if key in skip_fields:
# continue
# self.write('{}: {}'.format(
# click.style(key, fg=ColorSchema.PROMPT),
# click.style(value, fg=ColorSchema.INFO)
# ), DefaultOpt(indent=indent))
#
# def format_list(self, data_list, key=None, indent=2, skip_fields=None):
# skip_fields = skip_fields or []
# for el in data_list:
# if isinstance(el, dict):
# self.format_object(el, indent=indent, skip_fields=skip_fields)
# else:
# if key:
# self.write('{}: {}'.format(
# click.style(key, fg=ColorSchema.PROMPT),
# click.style(el, fg=ColorSchema.INFO)
# ), DefaultOpt(indent=indent))
# else:
# self.write('{}'.format(el), DefaultOpt(indent=indent))
# self.empty_line()
#
# def _write(self, line, options, **styles):
# if options.space_top:
# self.empty_line()
#
# click.echo(click.style(line, **styles))
#
# if options.space_bottom:
# self.empty_line()
#
# def _indent(self, line, options):
# return '{}{}'.format(self.indent * options.indent, line)
#
# Path: syncano_cli/parse_to_syncano/migrations/aggregation.py
# class ClassAggregate(object):
#
# def __init__(self, syncano_name, syncano_schema, parse_name, parse_schema):
# self.syncano_name = syncano_name
# self.syncano_schema = syncano_schema
# self.parse_name = parse_name
# self.parse_schema = parse_schema
#
# Path: syncano_cli/parse_to_syncano/parse/constants.py
# class ParseFieldTypeE(object):
# DATE = 'Date'
# POINTER = 'Pointer'
# ARRAY = 'Array'
# OBJECT = 'Object'
# FILE = 'File'
# GEO_POINT = 'GeoPoint'
# RELATION = 'Relation'
. Output only the next line. | 'Date': 'datetime', |
Given the code snippet: <|code_start|># coding=UTF8
from __future__ import print_function, unicode_literals
ALLOWED_TYPES = {"array", "boolean", "datetime", "file", "float", "geopoint",
"integer", "object", "reference", "relation", "string",
"text"}
ALLOWED_PERMISIONS = ('none', 'read', 'create_objects')
formatter = Formatter()
def field_schema_to_str(schema):
out = schema['type']
if schema['type'] == 'reference' and schema['target']:
out += ' ' + schema['target']
if schema.get('filter_index', False):
out += " filtered"
if schema.get('order_index', False):
out += " ordered"
return out
def expect(tokens, regexp, message=''):
try:
<|code_end|>
, generate the next line using the imports in this file:
import re
import six
from syncano_cli.base.formatters import Formatter
and context (functions, classes, or occasionally code) from other files:
# Path: syncano_cli/base/formatters.py
# class Formatter(object):
#
# indent = ' '
# not_set = '-- not set --'
#
# def write(self, single_line, *options):
# option = self.get_options(options)
# styles = option.map_click()
# single_line = self._indent(single_line, option)
# self._write(single_line, option, **styles)
#
# def write_lines(self, lines, *options):
# lines = lines.splitlines() if isinstance(lines, six.string_types) else lines
# for line in lines:
# self.write(line, *options)
#
# def write_block(self, lines, *options):
# self.write_lines(lines, *options)
# self.separator()
#
# @classmethod
# def empty_line(cls):
# click.echo()
#
# def separator(self, size=70, indent=1):
# self.write(size * '-', DefaultOpt(indent=indent), WarningOpt(), BottomSpacedOpt())
#
# def display_config(self, config):
# for name, value in six.iteritems(config):
# self.write('{}{:20} {}'.format(
# self.indent,
# click.style(name, fg=ColorSchema.PROMPT),
# click.style(value, fg=ColorSchema.INFO)
# ))
# if not config:
# self.write('No config specified yet.', DefaultOpt(indent=2))
# self.empty_line()
#
# def get_options(self, options):
# option_list = list(options) or []
# option_list.insert(0, DefaultOpt())
# return OptionsBase.build_options(option_list)
#
# def format_object(self, dictionary, indent=1, skip_fields=None):
# skip_fields = skip_fields or []
# indent += 1
# for key, value in six.iteritems(dictionary):
# if isinstance(value, dict):
# self.write('{}:'.format(click.style(key, fg=ColorSchema.PROMPT)), DefaultOpt(indent=indent))
# self.format_object(value, indent=indent, skip_fields=skip_fields)
# elif isinstance(value, list):
# self.format_list(value, key=key, indent=indent)
# else:
# if key in skip_fields:
# continue
# self.write('{}: {}'.format(
# click.style(key, fg=ColorSchema.PROMPT),
# click.style(value, fg=ColorSchema.INFO)
# ), DefaultOpt(indent=indent))
#
# def format_list(self, data_list, key=None, indent=2, skip_fields=None):
# skip_fields = skip_fields or []
# for el in data_list:
# if isinstance(el, dict):
# self.format_object(el, indent=indent, skip_fields=skip_fields)
# else:
# if key:
# self.write('{}: {}'.format(
# click.style(key, fg=ColorSchema.PROMPT),
# click.style(el, fg=ColorSchema.INFO)
# ), DefaultOpt(indent=indent))
# else:
# self.write('{}'.format(el), DefaultOpt(indent=indent))
# self.empty_line()
#
# def _write(self, line, options, **styles):
# if options.space_top:
# self.empty_line()
#
# click.echo(click.style(line, **styles))
#
# if options.space_bottom:
# self.empty_line()
#
# def _indent(self, line, options):
# return '{}{}'.format(self.indent * options.indent, line)
. Output only the next line. | value = tokens.pop(0).lower() |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
@click.group()
def top_level():
pass
<|code_end|>
, generate the next line using the imports in this file:
import os
import click
import syncano
from syncano.exceptions import SyncanoException
from syncano_cli.base.command import BaseCommand
from syncano_cli.base.exceptions import BadCredentialsException
from syncano_cli.base.options import SpacedOpt
from syncano_cli.config import ACCOUNT_CONFIG, ACCOUNT_CONFIG_PATH
and context (functions, classes, or occasionally code) from other files:
# Path: syncano_cli/base/command.py
# class BaseCommand(RegisterMixin):
# """
# Base command class. Provides utilities for register/loging (setup an account);
# Has a predefined class for prompting and format output nicely in the console;
# Stores also meta information about global config. Defines structures for command like config, eg.: hosting;
# """
#
# def __init__(self, config_path):
# self.config_path = config_path
# self.connection = create_connection(config_path)
#
# formatter = Formatter()
# prompter = Prompter()
#
# META_CONFIG = {
# 'default': [
# {
# 'name': 'key',
# 'required': True,
# 'info': ''
# },
# {
# 'name': 'instance_name',
# 'required': False,
# 'info': 'You can setup it using following command: syncano instances default <instance_name>.'
# },
# ]
# }
# DEFAULT_SECTION = 'DEFAULT'
#
# COMMAND_CONFIG = None
# COMMAND_SECTION = None
# COMMAND_CONFIG_PATH = None
#
# def has_setup(self):
# has_global = self.has_global_setup()
# has_command = self.has_command_setup(self.COMMAND_CONFIG_PATH)
# if has_global and has_command:
# return True
#
# if not has_global:
# self.formatter.write('Login or create an account in Syncano.', SpacedOpt())
# email = self.prompter.prompt('email')
# password = self.prompter.prompt('password', hide_input=True)
# repeat_password = self.prompter.prompt('repeat password', hide_input=True)
# password = self.validate_password(password, repeat_password)
# self.do_login_or_register(email, password, self.config_path)
#
# if not has_command:
# self.setup_command_config(self.config_path)
#
# return False
#
# def has_command_setup(self, config_path):
# if not config_path:
# return True
# return False
#
# def setup_command_config(self, config_path): # noqa;
# # override this in the child class;
# return True
#
# def has_global_setup(self):
# if os.path.isfile(self.config_path):
# ACCOUNT_CONFIG.read(self.config_path)
# return self.check_section(ACCOUNT_CONFIG)
#
# return False
#
# @classmethod
# def check_section(cls, config_parser, section=None):
# section = section or cls.DEFAULT_SECTION
# try:
# config_parser.get(cls.DEFAULT_SECTION, 'key')
# except NoOptionError:
# return False
#
# config_vars = []
# config_vars.extend(cls.META_CONFIG[cls.DEFAULT_SECTION.lower()])
# if cls.COMMAND_CONFIG:
# config_vars.extend(cls.COMMAND_CONFIG.get(cls.COMMAND_SECTION) or {})
# for config_meta in config_vars:
# var_name = config_meta['name']
# required = config_meta['required']
# if required and not config_parser.has_option(section, var_name):
# return False
# elif not required and not config_parser.has_option(section, var_name):
# cls.formatter.write(
# 'Missing "{}" in default config. {}'.format(var_name, config_meta['info']),
# WarningOpt(), SpacedOpt()
# )
#
# return True
#
# Path: syncano_cli/base/exceptions.py
# class BadCredentialsException(CLIBaseException):
# default_message = u'Wrong login credentials provided.'
#
# Path: syncano_cli/base/options.py
# class SpacedOpt(OptionsBase):
# OPTIONS = ['space_top', 'space_bottom']
#
# def __init__(self, space_top=True, space_bottom=True, **kwargs):
# super(SpacedOpt, self).__init__(space_top=space_top, space_bottom=space_bottom, **kwargs)
#
# Path: syncano_cli/config.py
# ACCOUNT_CONFIG = ConfigParser()
#
# ACCOUNT_CONFIG_PATH = os.path.join(os.path.expanduser('~'), '.syncano')
. Output only the next line. | @top_level.command() |
Predict the next line after this snippet: <|code_start|>
def _create_script_endpoint(self, source, name_prefix):
script = self.instance.scripts.create(
label='test_script',
source=source,
runtime_name=RuntimeChoices.PYTHON_V5_0,
)
self.instance.script_endpoints.create(
name='{}_test_script_endpoint'.format(name_prefix),
script=script.id
)
def test_script_endpoint_error(self):
name_prefix = 'error_response'
self._create_script_endpoint(
source='print(12/0)',
name_prefix=name_prefix
)
result = self.runner.invoke(cli, args=[
'execute', '{}_test_script_endpoint'.format(name_prefix)
], obj={})
self.assertIn('ZeroDivisionError', result.output)
def test_script_endpoint(self):
name_prefix = 'normal_response'
self._create_script_endpoint(
source='print(12)',
<|code_end|>
using the current file's imports:
from syncano.models import RuntimeChoices
from syncano_cli.main import cli
from tests.base import BaseCLITest
and any relevant context from other files:
# Path: syncano_cli/main.py
# def main():
#
# Path: tests/base.py
# class BaseCLITest(InstanceMixin, IntegrationTest):
#
# @classmethod
# def setUpClass(cls):
# super(BaseCLITest, cls).setUpClass()
# cls.yml_file = 'syncano.yml'
# cls.scripts_dir = 'scripts/'
#
# def setUp(self):
# self.runner.invoke(cli, args=['login', '--instance-name', self.instance.name], obj={})
# self.assert_config_variable_exists(ACCOUNT_CONFIG, 'DEFAULT', 'key')
# self.assert_config_variable_exists(ACCOUNT_CONFIG, 'DEFAULT', 'instance_name')
#
# def tearDown(self):
# # remove the .syncano file
# if os.path.isfile(ACCOUNT_CONFIG_PATH):
# os.remove(ACCOUNT_CONFIG_PATH)
# self.assertFalse(os.path.isfile(ACCOUNT_CONFIG_PATH))
#
# def assert_file_exists(self, path):
# self.assertTrue(os.path.isfile(path))
#
# def assert_config_variable_exists(self, config, section, key):
# self.assertTrue(config.get(section, key))
#
# def assert_config_variable_equal(self, config, section, key, value):
# self.assertEqual(config.get(section, key), value)
#
# def assert_class_yml_file(self, unique):
# with open(self.yml_file) as syncano_yml:
# yml_content = yaml.safe_load(syncano_yml)
# self.assertIn('test_class{unique}'.format(unique=unique), yml_content['classes'])
# self.assertIn('test_field{unique}'.format(unique=unique),
# yml_content['classes']['test_class{unique}'.format(unique=unique)]['fields'])
#
# def assert_field_in_schema(self, syncano_class, unique):
# has_field = False
# for field_schema in syncano_class.schema:
# if field_schema['name'] == 'test_field{unique}'.format(unique=unique) and field_schema['type'] == 'string':
# has_field = True
# break
#
# self.assertTrue(has_field)
#
# def assert_script_source(self, script_path, assert_source):
# with open(script_path, 'r+') as f:
# source = f.read()
# self.assertEqual(source, assert_source)
#
# def assert_script_remote(self, script_name, source):
# is_script = False
# check_script = None
# scripts = self.instance.scripts.all()
# for script in scripts:
# if script.label == script_name:
# is_script = True
# check_script = script # be explicit;
# break
# self.assertTrue(is_script)
# self.assertEqual(check_script.source, source)
#
# def get_script_path(self, unique):
# return '{dir_name}{script_name}.py'.format(
# dir_name=self.scripts_dir,
# script_name='script_{unique}'.format(unique=unique)
# )
#
# def modify_yml_file(self, key, object, operation='update'):
# with open(self.yml_file, 'rb') as f:
# yml_syncano = yaml.safe_load(f)
# if operation == 'update':
# yml_syncano[key].update(object)
# elif operation == 'append':
# yml_syncano[key].append(object)
# else:
# raise Exception('not supported operation')
#
# with open(self.yml_file, 'wt') as f:
# f.write(yaml.safe_dump(yml_syncano, default_flow_style=False))
#
# def create_syncano_class(self, unique):
# self.instance.classes.create(
# name='test_class{unique}'.format(unique=unique),
# schema=[
# {'name': 'test_field{unique}'.format(unique=unique), 'type': 'string'}
# ]
# )
#
# def get_class_object_dict(self, unique):
# return {
# 'test_class{unique}'.format(unique=unique): {
# 'fields': {
# 'test_field{unique}'.format(unique=unique): 'string'
# }
# }
# }
#
# def get_syncano_class(self, unique):
# return self.instance.classes.get(name='test_class{unique}'.format(unique=unique))
#
# def create_script(self, unique):
# self.instance.scripts.create(
# runtime_name=RuntimeChoices.PYTHON_V5_0,
# source='print(12)',
# label='script_{unique}'.format(unique=unique)
# )
#
# def create_script_locally(self, source, unique):
# script_path = 'scripts/script_{unique}.py'.format(unique=unique)
# new_script = {
# 'runtime': 'python_library_v5.0',
# 'label': 'script_{unique}'.format(unique=unique),
# 'script': script_path
# }
#
# self.modify_yml_file('scripts', new_script, operation='append')
#
# # create a file also;
# with open(script_path, 'w+') as f:
# f.write(source)
. Output only the next line. | name_prefix=name_prefix |
Here is a snippet: <|code_start|>
def test_script_endpoint(self):
name_prefix = 'normal_response'
self._create_script_endpoint(
source='print(12)',
name_prefix=name_prefix
)
result = self.runner.invoke(cli, args=[
'execute', '{}_test_script_endpoint'.format(name_prefix)
], obj={})
self.assertIn('12\n', result.output)
def test_script_endpoint_with_payload(self):
name_prefix = 'payload_response'
self._create_script_endpoint(
source="print(ARGS['POST']['data'])",
name_prefix=name_prefix
)
result = self.runner.invoke(cli, args=[
'execute', '{}_test_script_endpoint'.format(name_prefix),
'-d', 'data=some_nice_string'
], obj={})
self.assertIn('some_nice_string\n', result.output)
def test_script_endpoint_custom_response(self):
<|code_end|>
. Write the next line using the current file imports:
from syncano.models import RuntimeChoices
from syncano_cli.main import cli
from tests.base import BaseCLITest
and context from other files:
# Path: syncano_cli/main.py
# def main():
#
# Path: tests/base.py
# class BaseCLITest(InstanceMixin, IntegrationTest):
#
# @classmethod
# def setUpClass(cls):
# super(BaseCLITest, cls).setUpClass()
# cls.yml_file = 'syncano.yml'
# cls.scripts_dir = 'scripts/'
#
# def setUp(self):
# self.runner.invoke(cli, args=['login', '--instance-name', self.instance.name], obj={})
# self.assert_config_variable_exists(ACCOUNT_CONFIG, 'DEFAULT', 'key')
# self.assert_config_variable_exists(ACCOUNT_CONFIG, 'DEFAULT', 'instance_name')
#
# def tearDown(self):
# # remove the .syncano file
# if os.path.isfile(ACCOUNT_CONFIG_PATH):
# os.remove(ACCOUNT_CONFIG_PATH)
# self.assertFalse(os.path.isfile(ACCOUNT_CONFIG_PATH))
#
# def assert_file_exists(self, path):
# self.assertTrue(os.path.isfile(path))
#
# def assert_config_variable_exists(self, config, section, key):
# self.assertTrue(config.get(section, key))
#
# def assert_config_variable_equal(self, config, section, key, value):
# self.assertEqual(config.get(section, key), value)
#
# def assert_class_yml_file(self, unique):
# with open(self.yml_file) as syncano_yml:
# yml_content = yaml.safe_load(syncano_yml)
# self.assertIn('test_class{unique}'.format(unique=unique), yml_content['classes'])
# self.assertIn('test_field{unique}'.format(unique=unique),
# yml_content['classes']['test_class{unique}'.format(unique=unique)]['fields'])
#
# def assert_field_in_schema(self, syncano_class, unique):
# has_field = False
# for field_schema in syncano_class.schema:
# if field_schema['name'] == 'test_field{unique}'.format(unique=unique) and field_schema['type'] == 'string':
# has_field = True
# break
#
# self.assertTrue(has_field)
#
# def assert_script_source(self, script_path, assert_source):
# with open(script_path, 'r+') as f:
# source = f.read()
# self.assertEqual(source, assert_source)
#
# def assert_script_remote(self, script_name, source):
# is_script = False
# check_script = None
# scripts = self.instance.scripts.all()
# for script in scripts:
# if script.label == script_name:
# is_script = True
# check_script = script # be explicit;
# break
# self.assertTrue(is_script)
# self.assertEqual(check_script.source, source)
#
# def get_script_path(self, unique):
# return '{dir_name}{script_name}.py'.format(
# dir_name=self.scripts_dir,
# script_name='script_{unique}'.format(unique=unique)
# )
#
# def modify_yml_file(self, key, object, operation='update'):
# with open(self.yml_file, 'rb') as f:
# yml_syncano = yaml.safe_load(f)
# if operation == 'update':
# yml_syncano[key].update(object)
# elif operation == 'append':
# yml_syncano[key].append(object)
# else:
# raise Exception('not supported operation')
#
# with open(self.yml_file, 'wt') as f:
# f.write(yaml.safe_dump(yml_syncano, default_flow_style=False))
#
# def create_syncano_class(self, unique):
# self.instance.classes.create(
# name='test_class{unique}'.format(unique=unique),
# schema=[
# {'name': 'test_field{unique}'.format(unique=unique), 'type': 'string'}
# ]
# )
#
# def get_class_object_dict(self, unique):
# return {
# 'test_class{unique}'.format(unique=unique): {
# 'fields': {
# 'test_field{unique}'.format(unique=unique): 'string'
# }
# }
# }
#
# def get_syncano_class(self, unique):
# return self.instance.classes.get(name='test_class{unique}'.format(unique=unique))
#
# def create_script(self, unique):
# self.instance.scripts.create(
# runtime_name=RuntimeChoices.PYTHON_V5_0,
# source='print(12)',
# label='script_{unique}'.format(unique=unique)
# )
#
# def create_script_locally(self, source, unique):
# script_path = 'scripts/script_{unique}.py'.format(unique=unique)
# new_script = {
# 'runtime': 'python_library_v5.0',
# 'label': 'script_{unique}'.format(unique=unique),
# 'script': script_path
# }
#
# self.modify_yml_file('scripts', new_script, operation='append')
#
# # create a file also;
# with open(script_path, 'w+') as f:
# f.write(source)
, which may include functions, classes, or code. Output only the next line. | name_prefix = 'custom_response' |
Predict the next line after this snippet: <|code_start|>
@click.group()
def top_account():
pass
<|code_end|>
using the current file's imports:
import click
from syncano_cli.account.command import AccountCommands
from syncano_cli.base.options import ColorSchema, SpacedOpt, WarningOpt
from syncano_cli.config import ACCOUNT_CONFIG_PATH
and any relevant context from other files:
# Path: syncano_cli/account/command.py
# class AccountCommands(BaseCommand):
#
# def __init__(self, config_path):
# self.connection = syncano.connect()
# self.config_path = config_path
#
# def register(self, email, password, first_name=None, last_name=None):
# api_key = self.connection.connection().register(
# email=email,
# password=password,
# first_name=first_name,
# last_name=last_name,
# )
#
# ACCOUNT_CONFIG.set('DEFAULT', 'key', api_key)
# with open(self.config_path, 'wt') as fp:
# ACCOUNT_CONFIG.write(fp)
#
# Path: syncano_cli/base/options.py
# class ColorSchema(object):
# INFO = 'green'
# PROMPT = 'cyan'
# WARNING = 'yellow'
# ERROR = 'red'
#
# class SpacedOpt(OptionsBase):
# OPTIONS = ['space_top', 'space_bottom']
#
# def __init__(self, space_top=True, space_bottom=True, **kwargs):
# super(SpacedOpt, self).__init__(space_top=space_top, space_bottom=space_bottom, **kwargs)
#
# class WarningOpt(OptionsBase):
# OPTIONS = ['color']
#
# def __init__(self, color=ColorSchema.WARNING, **kwargs):
# super(WarningOpt, self).__init__(color=color, **kwargs)
#
# Path: syncano_cli/config.py
# ACCOUNT_CONFIG_PATH = os.path.join(os.path.expanduser('~'), '.syncano')
. Output only the next line. | @top_account.group() |
Given the following code snippet before the placeholder: <|code_start|>
@click.group()
def top_account():
pass
<|code_end|>
, predict the next line using imports from the current file:
import click
from syncano_cli.account.command import AccountCommands
from syncano_cli.base.options import ColorSchema, SpacedOpt, WarningOpt
from syncano_cli.config import ACCOUNT_CONFIG_PATH
and context including class names, function names, and sometimes code from other files:
# Path: syncano_cli/account/command.py
# class AccountCommands(BaseCommand):
#
# def __init__(self, config_path):
# self.connection = syncano.connect()
# self.config_path = config_path
#
# def register(self, email, password, first_name=None, last_name=None):
# api_key = self.connection.connection().register(
# email=email,
# password=password,
# first_name=first_name,
# last_name=last_name,
# )
#
# ACCOUNT_CONFIG.set('DEFAULT', 'key', api_key)
# with open(self.config_path, 'wt') as fp:
# ACCOUNT_CONFIG.write(fp)
#
# Path: syncano_cli/base/options.py
# class ColorSchema(object):
# INFO = 'green'
# PROMPT = 'cyan'
# WARNING = 'yellow'
# ERROR = 'red'
#
# class SpacedOpt(OptionsBase):
# OPTIONS = ['space_top', 'space_bottom']
#
# def __init__(self, space_top=True, space_bottom=True, **kwargs):
# super(SpacedOpt, self).__init__(space_top=space_top, space_bottom=space_bottom, **kwargs)
#
# class WarningOpt(OptionsBase):
# OPTIONS = ['color']
#
# def __init__(self, color=ColorSchema.WARNING, **kwargs):
# super(WarningOpt, self).__init__(color=color, **kwargs)
#
# Path: syncano_cli/config.py
# ACCOUNT_CONFIG_PATH = os.path.join(os.path.expanduser('~'), '.syncano')
. Output only the next line. | @top_account.group() |
Here is a snippet: <|code_start|>
@click.group()
def top_account():
pass
@top_account.group()
@click.pass_context
@click.option('--config', help=u'Account configuration file.')
<|code_end|>
. Write the next line using the current file imports:
import click
from syncano_cli.account.command import AccountCommands
from syncano_cli.base.options import ColorSchema, SpacedOpt, WarningOpt
from syncano_cli.config import ACCOUNT_CONFIG_PATH
and context from other files:
# Path: syncano_cli/account/command.py
# class AccountCommands(BaseCommand):
#
# def __init__(self, config_path):
# self.connection = syncano.connect()
# self.config_path = config_path
#
# def register(self, email, password, first_name=None, last_name=None):
# api_key = self.connection.connection().register(
# email=email,
# password=password,
# first_name=first_name,
# last_name=last_name,
# )
#
# ACCOUNT_CONFIG.set('DEFAULT', 'key', api_key)
# with open(self.config_path, 'wt') as fp:
# ACCOUNT_CONFIG.write(fp)
#
# Path: syncano_cli/base/options.py
# class ColorSchema(object):
# INFO = 'green'
# PROMPT = 'cyan'
# WARNING = 'yellow'
# ERROR = 'red'
#
# class SpacedOpt(OptionsBase):
# OPTIONS = ['space_top', 'space_bottom']
#
# def __init__(self, space_top=True, space_bottom=True, **kwargs):
# super(SpacedOpt, self).__init__(space_top=space_top, space_bottom=space_bottom, **kwargs)
#
# class WarningOpt(OptionsBase):
# OPTIONS = ['color']
#
# def __init__(self, color=ColorSchema.WARNING, **kwargs):
# super(WarningOpt, self).__init__(color=color, **kwargs)
#
# Path: syncano_cli/config.py
# ACCOUNT_CONFIG_PATH = os.path.join(os.path.expanduser('~'), '.syncano')
, which may include functions, classes, or code. Output only the next line. | def accounts(ctx, config): |
Here is a snippet: <|code_start|> @classmethod
def setUpClass(cls):
super(MigrateCommandsTest, cls).setUpClass()
# do a login first;
cls.runner.invoke(cli, args=['login', '--instance-name', cls.instance.name], obj={})
# and make setup;
cls.old_key = cls.connection.connection().api_key
cls._set_up_configuration()
@classmethod
def _set_up_configuration(cls):
SYNCANO_ADMIN_API_KEY = ACCOUNT_CONFIG.get("DEFAULT", "key")
if not ACCOUNT_CONFIG.has_section("P2S"):
ACCOUNT_CONFIG.add_section("P2S")
ACCOUNT_CONFIG.set("P2S", "PARSE_APPLICATION_ID", "xxx")
ACCOUNT_CONFIG.set("P2S", "PARSE_MASTER_KEY", "xxx")
ACCOUNT_CONFIG.set("P2S", "SYNCANO_INSTANCE_NAME", cls.instance.name)
ACCOUNT_CONFIG.set("P2S", "SYNCANO_ADMIN_API_KEY", SYNCANO_ADMIN_API_KEY)
def test_configure(self):
result = self.runner.invoke(cli, args=['migrate', 'configure'], obj={})
self.assertIn('PARSE_MASTER_KEY', result.output)
result = self.runner.invoke(cli, args=['migrate', 'configure', '--force'], input='xxx\nxxx\n{}\n{}\n'.format(
ACCOUNT_CONFIG.get("DEFAULT", "key"),
self.instance.name,
), obj={})
self.assertIn('PARSE_MASTER_KEY', result.output)
result = self.runner.invoke(cli, args=['migrate', 'configure', '--current'], obj={})
<|code_end|>
. Write the next line using the current file imports:
import json
import mock
from syncano_cli.config import ACCOUNT_CONFIG
from syncano_cli.main import cli
from syncano_cli.parse_to_syncano.processors.push_notifications import DEVICE_CHANNELS_CLASS_NAME
from tests.base import InstanceMixin, IntegrationTest
and context from other files:
# Path: syncano_cli/config.py
# ACCOUNT_CONFIG = ConfigParser()
#
# Path: syncano_cli/main.py
# def main():
#
# Path: syncano_cli/parse_to_syncano/processors/push_notifications.py
# DEVICE_CHANNELS_CLASS_NAME = 'internal_device_channels'
#
# Path: tests/base.py
# class InstanceMixin(object):
#
# @classmethod
# def setUpClass(cls):
# super(InstanceMixin, cls).setUpClass()
#
# cls.instance = cls.connection.Instance.please.create(
# name='test-cli-i%s' % cls.generate_hash()[:10],
# description='IntegrationTest %s' % datetime.now(),
# )
#
# @classmethod
# def tearDownClass(cls):
# cls.instance.delete()
# super(InstanceMixin, cls).tearDownClass()
#
# class IntegrationTest(unittest.TestCase):
#
# @classmethod
# def setUpClass(cls):
# cls.runner = CliRunner()
# cls.API_KEY = os.getenv('INTEGRATION_API_KEY')
# cls.API_EMAIL = os.getenv('INTEGRATION_API_EMAIL')
# cls.API_PASSWORD = os.getenv('INTEGRATION_API_PASSWORD')
# cls.API_ROOT = os.getenv('INTEGRATION_API_ROOT')
#
# cls.connection = syncano.connect(
# host=cls.API_ROOT,
# email=cls.API_EMAIL,
# password=cls.API_PASSWORD,
# api_key=cls.API_KEY
# )
#
# @classmethod
# def tearDownClass(cls):
# cls.connection = None
#
# @classmethod
# def generate_hash(cls):
# hash_feed = '{}{}'.format(uuid4(), datetime.now())
# return md5(hash_feed.encode('ascii')).hexdigest()
, which may include functions, classes, or code. Output only the next line. | self.assertIn('PARSE_MASTER_KEY', result.output) |
Continue the code snippet: <|code_start|> mock.MagicMock(return_value=None))
@mock.patch('syncano_cli.parse_to_syncano.migrations.transfer.SyncanoTransfer.transfer_files',
mock.MagicMock(return_value=None))
def test_class_migrations(self, request_mock):
with open('tests/json_migrate_mocks/schema.json', 'r+') as f:
request_mock.return_value = json.loads(f.read())
self.assertFalse(request_mock.called)
self.runner.invoke(cli, args=['migrate', 'parse'], obj={}, input='y\n')
self.assertTrue(request_mock.called)
syncano_class = self.instance.classes.get(name='test_class_1234')
self.assertTrue(syncano_class)
syncano_class = self.instance.classes.get(name='blu_bla')
self.assertTrue(syncano_class)
@mock.patch('syncano_cli.parse_to_syncano.parse.connection.ParseConnection.request')
def test_object_migrations(self, request_mock):
# create Classes first;
with open('tests/json_migrate_mocks/schema.json', 'r+') as f:
classes = json.loads(f.read())
with open('tests/json_migrate_mocks/class_objects.json', 'r+') as f:
objects = json.loads(f.read())
with open('tests/json_migrate_mocks/installations.json', 'r+') as f:
parse_installations = json.loads(f.read())
# remove blu_bla Class from Classes;
<|code_end|>
. Use current file imports:
import json
import mock
from syncano_cli.config import ACCOUNT_CONFIG
from syncano_cli.main import cli
from syncano_cli.parse_to_syncano.processors.push_notifications import DEVICE_CHANNELS_CLASS_NAME
from tests.base import InstanceMixin, IntegrationTest
and context (classes, functions, or code) from other files:
# Path: syncano_cli/config.py
# ACCOUNT_CONFIG = ConfigParser()
#
# Path: syncano_cli/main.py
# def main():
#
# Path: syncano_cli/parse_to_syncano/processors/push_notifications.py
# DEVICE_CHANNELS_CLASS_NAME = 'internal_device_channels'
#
# Path: tests/base.py
# class InstanceMixin(object):
#
# @classmethod
# def setUpClass(cls):
# super(InstanceMixin, cls).setUpClass()
#
# cls.instance = cls.connection.Instance.please.create(
# name='test-cli-i%s' % cls.generate_hash()[:10],
# description='IntegrationTest %s' % datetime.now(),
# )
#
# @classmethod
# def tearDownClass(cls):
# cls.instance.delete()
# super(InstanceMixin, cls).tearDownClass()
#
# class IntegrationTest(unittest.TestCase):
#
# @classmethod
# def setUpClass(cls):
# cls.runner = CliRunner()
# cls.API_KEY = os.getenv('INTEGRATION_API_KEY')
# cls.API_EMAIL = os.getenv('INTEGRATION_API_EMAIL')
# cls.API_PASSWORD = os.getenv('INTEGRATION_API_PASSWORD')
# cls.API_ROOT = os.getenv('INTEGRATION_API_ROOT')
#
# cls.connection = syncano.connect(
# host=cls.API_ROOT,
# email=cls.API_EMAIL,
# password=cls.API_PASSWORD,
# api_key=cls.API_KEY
# )
#
# @classmethod
# def tearDownClass(cls):
# cls.connection = None
#
# @classmethod
# def generate_hash(cls):
# hash_feed = '{}{}'.format(uuid4(), datetime.now())
# return md5(hash_feed.encode('ascii')).hexdigest()
. Output only the next line. | classes['results'] = classes['results'][1:] |
Predict the next line for this snippet: <|code_start|>
@mock.patch('syncano_cli.parse_to_syncano.parse.connection.ParseConnection.request')
def test_object_migrations(self, request_mock):
# create Classes first;
with open('tests/json_migrate_mocks/schema.json', 'r+') as f:
classes = json.loads(f.read())
with open('tests/json_migrate_mocks/class_objects.json', 'r+') as f:
objects = json.loads(f.read())
with open('tests/json_migrate_mocks/installations.json', 'r+') as f:
parse_installations = json.loads(f.read())
# remove blu_bla Class from Classes;
classes['results'] = classes['results'][1:]
# Class schemas, objects, break the objects fetch, installations
request_mock.side_effect = [classes, objects, {'results': []}, parse_installations]
self.assertFalse(request_mock.called)
self.runner.invoke(cli, args=['migrate', 'parse'], obj={}, input='y\n')
self.assertTrue(request_mock.called)
objects_list = self.instance.classes.get(name='test_class_1234').objects.all()
self.assertEqual(len([data_object for data_object in objects_list]), 10)
object_to_test = self.instance.classes.get(name='test_class_1234').objects.filter(
objectid__eq='ZfowBYpvpw'
).first()
self.assertListEqual(object_to_test.testarray, ["a", "b", "c", "d"])
<|code_end|>
with the help of current file imports:
import json
import mock
from syncano_cli.config import ACCOUNT_CONFIG
from syncano_cli.main import cli
from syncano_cli.parse_to_syncano.processors.push_notifications import DEVICE_CHANNELS_CLASS_NAME
from tests.base import InstanceMixin, IntegrationTest
and context from other files:
# Path: syncano_cli/config.py
# ACCOUNT_CONFIG = ConfigParser()
#
# Path: syncano_cli/main.py
# def main():
#
# Path: syncano_cli/parse_to_syncano/processors/push_notifications.py
# DEVICE_CHANNELS_CLASS_NAME = 'internal_device_channels'
#
# Path: tests/base.py
# class InstanceMixin(object):
#
# @classmethod
# def setUpClass(cls):
# super(InstanceMixin, cls).setUpClass()
#
# cls.instance = cls.connection.Instance.please.create(
# name='test-cli-i%s' % cls.generate_hash()[:10],
# description='IntegrationTest %s' % datetime.now(),
# )
#
# @classmethod
# def tearDownClass(cls):
# cls.instance.delete()
# super(InstanceMixin, cls).tearDownClass()
#
# class IntegrationTest(unittest.TestCase):
#
# @classmethod
# def setUpClass(cls):
# cls.runner = CliRunner()
# cls.API_KEY = os.getenv('INTEGRATION_API_KEY')
# cls.API_EMAIL = os.getenv('INTEGRATION_API_EMAIL')
# cls.API_PASSWORD = os.getenv('INTEGRATION_API_PASSWORD')
# cls.API_ROOT = os.getenv('INTEGRATION_API_ROOT')
#
# cls.connection = syncano.connect(
# host=cls.API_ROOT,
# email=cls.API_EMAIL,
# password=cls.API_PASSWORD,
# api_key=cls.API_KEY
# )
#
# @classmethod
# def tearDownClass(cls):
# cls.connection = None
#
# @classmethod
# def generate_hash(cls):
# hash_feed = '{}{}'.format(uuid4(), datetime.now())
# return md5(hash_feed.encode('ascii')).hexdigest()
, which may contain function names, class names, or code. Output only the next line. | self.assertEqual(object_to_test.barg, 12) |
Based on the snippet: <|code_start|> self.assertIn('Transfer aborted.', result.output)
@mock.patch('syncano_cli.parse_to_syncano.parse.connection.ParseConnection.request')
@mock.patch('syncano_cli.parse_to_syncano.migrations.transfer.SyncanoTransfer.process_relations',
mock.MagicMock(return_value=None))
@mock.patch('syncano_cli.parse_to_syncano.migrations.transfer.SyncanoTransfer.transfer_objects',
mock.MagicMock(return_value=None))
@mock.patch('syncano_cli.parse_to_syncano.migrations.transfer.SyncanoTransfer.transfer_files',
mock.MagicMock(return_value=None))
def test_class_migrations(self, request_mock):
with open('tests/json_migrate_mocks/schema.json', 'r+') as f:
request_mock.return_value = json.loads(f.read())
self.assertFalse(request_mock.called)
self.runner.invoke(cli, args=['migrate', 'parse'], obj={}, input='y\n')
self.assertTrue(request_mock.called)
syncano_class = self.instance.classes.get(name='test_class_1234')
self.assertTrue(syncano_class)
syncano_class = self.instance.classes.get(name='blu_bla')
self.assertTrue(syncano_class)
@mock.patch('syncano_cli.parse_to_syncano.parse.connection.ParseConnection.request')
def test_object_migrations(self, request_mock):
# create Classes first;
with open('tests/json_migrate_mocks/schema.json', 'r+') as f:
classes = json.loads(f.read())
with open('tests/json_migrate_mocks/class_objects.json', 'r+') as f:
<|code_end|>
, predict the immediate next line with the help of imports:
import json
import mock
from syncano_cli.config import ACCOUNT_CONFIG
from syncano_cli.main import cli
from syncano_cli.parse_to_syncano.processors.push_notifications import DEVICE_CHANNELS_CLASS_NAME
from tests.base import InstanceMixin, IntegrationTest
and context (classes, functions, sometimes code) from other files:
# Path: syncano_cli/config.py
# ACCOUNT_CONFIG = ConfigParser()
#
# Path: syncano_cli/main.py
# def main():
#
# Path: syncano_cli/parse_to_syncano/processors/push_notifications.py
# DEVICE_CHANNELS_CLASS_NAME = 'internal_device_channels'
#
# Path: tests/base.py
# class InstanceMixin(object):
#
# @classmethod
# def setUpClass(cls):
# super(InstanceMixin, cls).setUpClass()
#
# cls.instance = cls.connection.Instance.please.create(
# name='test-cli-i%s' % cls.generate_hash()[:10],
# description='IntegrationTest %s' % datetime.now(),
# )
#
# @classmethod
# def tearDownClass(cls):
# cls.instance.delete()
# super(InstanceMixin, cls).tearDownClass()
#
# class IntegrationTest(unittest.TestCase):
#
# @classmethod
# def setUpClass(cls):
# cls.runner = CliRunner()
# cls.API_KEY = os.getenv('INTEGRATION_API_KEY')
# cls.API_EMAIL = os.getenv('INTEGRATION_API_EMAIL')
# cls.API_PASSWORD = os.getenv('INTEGRATION_API_PASSWORD')
# cls.API_ROOT = os.getenv('INTEGRATION_API_ROOT')
#
# cls.connection = syncano.connect(
# host=cls.API_ROOT,
# email=cls.API_EMAIL,
# password=cls.API_PASSWORD,
# api_key=cls.API_KEY
# )
#
# @classmethod
# def tearDownClass(cls):
# cls.connection = None
#
# @classmethod
# def generate_hash(cls):
# hash_feed = '{}{}'.format(uuid4(), datetime.now())
# return md5(hash_feed.encode('ascii')).hexdigest()
. Output only the next line. | objects = json.loads(f.read()) |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
def force_config_value(config, config_var_name, section='P2S'):
prompter = Prompter()
config_var = prompter.prompt('{}'.format(config_var_name))
if not config.has_section(section):
config.add_section(section)
config.set(section, config_var_name, config_var)
def check_config_value(config, config_var_name, silent, section='P2S'):
formatter = Formatter()
if not config.has_option(section, config_var_name):
<|code_end|>
. Use current file imports:
(import click
from syncano_cli.base.formatters import Formatter
from syncano_cli.base.options import ColorSchema
from syncano_cli.base.prompter import Prompter
from syncano_cli.config import ACCOUNT_CONFIG_PATH
from syncano_cli.parse_to_syncano.config import CONFIG_VARIABLES_NAMES)
and context including class names, function names, or small code snippets from other files:
# Path: syncano_cli/base/formatters.py
# class Formatter(object):
#
# indent = ' '
# not_set = '-- not set --'
#
# def write(self, single_line, *options):
# option = self.get_options(options)
# styles = option.map_click()
# single_line = self._indent(single_line, option)
# self._write(single_line, option, **styles)
#
# def write_lines(self, lines, *options):
# lines = lines.splitlines() if isinstance(lines, six.string_types) else lines
# for line in lines:
# self.write(line, *options)
#
# def write_block(self, lines, *options):
# self.write_lines(lines, *options)
# self.separator()
#
# @classmethod
# def empty_line(cls):
# click.echo()
#
# def separator(self, size=70, indent=1):
# self.write(size * '-', DefaultOpt(indent=indent), WarningOpt(), BottomSpacedOpt())
#
# def display_config(self, config):
# for name, value in six.iteritems(config):
# self.write('{}{:20} {}'.format(
# self.indent,
# click.style(name, fg=ColorSchema.PROMPT),
# click.style(value, fg=ColorSchema.INFO)
# ))
# if not config:
# self.write('No config specified yet.', DefaultOpt(indent=2))
# self.empty_line()
#
# def get_options(self, options):
# option_list = list(options) or []
# option_list.insert(0, DefaultOpt())
# return OptionsBase.build_options(option_list)
#
# def format_object(self, dictionary, indent=1, skip_fields=None):
# skip_fields = skip_fields or []
# indent += 1
# for key, value in six.iteritems(dictionary):
# if isinstance(value, dict):
# self.write('{}:'.format(click.style(key, fg=ColorSchema.PROMPT)), DefaultOpt(indent=indent))
# self.format_object(value, indent=indent, skip_fields=skip_fields)
# elif isinstance(value, list):
# self.format_list(value, key=key, indent=indent)
# else:
# if key in skip_fields:
# continue
# self.write('{}: {}'.format(
# click.style(key, fg=ColorSchema.PROMPT),
# click.style(value, fg=ColorSchema.INFO)
# ), DefaultOpt(indent=indent))
#
# def format_list(self, data_list, key=None, indent=2, skip_fields=None):
# skip_fields = skip_fields or []
# for el in data_list:
# if isinstance(el, dict):
# self.format_object(el, indent=indent, skip_fields=skip_fields)
# else:
# if key:
# self.write('{}: {}'.format(
# click.style(key, fg=ColorSchema.PROMPT),
# click.style(el, fg=ColorSchema.INFO)
# ), DefaultOpt(indent=indent))
# else:
# self.write('{}'.format(el), DefaultOpt(indent=indent))
# self.empty_line()
#
# def _write(self, line, options, **styles):
# if options.space_top:
# self.empty_line()
#
# click.echo(click.style(line, **styles))
#
# if options.space_bottom:
# self.empty_line()
#
# def _indent(self, line, options):
# return '{}{}'.format(self.indent * options.indent, line)
#
# Path: syncano_cli/base/options.py
# class ColorSchema(object):
# INFO = 'green'
# PROMPT = 'cyan'
# WARNING = 'yellow'
# ERROR = 'red'
#
# Path: syncano_cli/base/prompter.py
# class Prompter(object):
# indent = ' '
#
# def prompt(self, text, color=None, **kwargs):
# styles_kwargs = {'fg': color or ColorSchema.PROMPT}
# return click.prompt(click.style("{}{}".format(self.indent, text), **styles_kwargs), **kwargs)
#
# def confirm(self, text, color=None, **kwargs):
# styles_kwargs = {'fg': color or ColorSchema.PROMPT}
# return click.confirm(click.style("{}{}".format(self.indent, text), **styles_kwargs), **kwargs)
#
# Path: syncano_cli/config.py
# ACCOUNT_CONFIG_PATH = os.path.join(os.path.expanduser('~'), '.syncano')
#
# Path: syncano_cli/parse_to_syncano/config.py
# CONFIG_VARIABLES_NAMES = ['PARSE_MASTER_KEY', 'PARSE_APPLICATION_ID',
# 'SYNCANO_ADMIN_API_KEY', 'SYNCANO_INSTANCE_NAME']
. Output only the next line. | force_config_value(config, config_var_name) |
Here is a snippet: <|code_start|>
def write_config_to_file(config):
with open(ACCOUNT_CONFIG_PATH, 'wt') as config_file:
config.write(config_file)
def check_configuration(config, silent=False):
for config_var_name in CONFIG_VARIABLES_NAMES:
check_config_value(config, config_var_name, silent=silent)
write_config_to_file(config)
def force_configuration_overwrite(config):
for config_var_name in CONFIG_VARIABLES_NAMES:
force_config_value(config, config_var_name)
write_config_to_file(config)
def print_configuration(config):
formatter = Formatter()
if not config.has_section('P2S'):
config.add_section('P2S')
for config_var_name in CONFIG_VARIABLES_NAMES:
if not config.has_option('P2S', config_var_name):
config_var = "-- NOT SET --"
else:
config_var = config.get('P2S', config_var_name)
<|code_end|>
. Write the next line using the current file imports:
import click
from syncano_cli.base.formatters import Formatter
from syncano_cli.base.options import ColorSchema
from syncano_cli.base.prompter import Prompter
from syncano_cli.config import ACCOUNT_CONFIG_PATH
from syncano_cli.parse_to_syncano.config import CONFIG_VARIABLES_NAMES
and context from other files:
# Path: syncano_cli/base/formatters.py
# class Formatter(object):
#
# indent = ' '
# not_set = '-- not set --'
#
# def write(self, single_line, *options):
# option = self.get_options(options)
# styles = option.map_click()
# single_line = self._indent(single_line, option)
# self._write(single_line, option, **styles)
#
# def write_lines(self, lines, *options):
# lines = lines.splitlines() if isinstance(lines, six.string_types) else lines
# for line in lines:
# self.write(line, *options)
#
# def write_block(self, lines, *options):
# self.write_lines(lines, *options)
# self.separator()
#
# @classmethod
# def empty_line(cls):
# click.echo()
#
# def separator(self, size=70, indent=1):
# self.write(size * '-', DefaultOpt(indent=indent), WarningOpt(), BottomSpacedOpt())
#
# def display_config(self, config):
# for name, value in six.iteritems(config):
# self.write('{}{:20} {}'.format(
# self.indent,
# click.style(name, fg=ColorSchema.PROMPT),
# click.style(value, fg=ColorSchema.INFO)
# ))
# if not config:
# self.write('No config specified yet.', DefaultOpt(indent=2))
# self.empty_line()
#
# def get_options(self, options):
# option_list = list(options) or []
# option_list.insert(0, DefaultOpt())
# return OptionsBase.build_options(option_list)
#
# def format_object(self, dictionary, indent=1, skip_fields=None):
# skip_fields = skip_fields or []
# indent += 1
# for key, value in six.iteritems(dictionary):
# if isinstance(value, dict):
# self.write('{}:'.format(click.style(key, fg=ColorSchema.PROMPT)), DefaultOpt(indent=indent))
# self.format_object(value, indent=indent, skip_fields=skip_fields)
# elif isinstance(value, list):
# self.format_list(value, key=key, indent=indent)
# else:
# if key in skip_fields:
# continue
# self.write('{}: {}'.format(
# click.style(key, fg=ColorSchema.PROMPT),
# click.style(value, fg=ColorSchema.INFO)
# ), DefaultOpt(indent=indent))
#
# def format_list(self, data_list, key=None, indent=2, skip_fields=None):
# skip_fields = skip_fields or []
# for el in data_list:
# if isinstance(el, dict):
# self.format_object(el, indent=indent, skip_fields=skip_fields)
# else:
# if key:
# self.write('{}: {}'.format(
# click.style(key, fg=ColorSchema.PROMPT),
# click.style(el, fg=ColorSchema.INFO)
# ), DefaultOpt(indent=indent))
# else:
# self.write('{}'.format(el), DefaultOpt(indent=indent))
# self.empty_line()
#
# def _write(self, line, options, **styles):
# if options.space_top:
# self.empty_line()
#
# click.echo(click.style(line, **styles))
#
# if options.space_bottom:
# self.empty_line()
#
# def _indent(self, line, options):
# return '{}{}'.format(self.indent * options.indent, line)
#
# Path: syncano_cli/base/options.py
# class ColorSchema(object):
# INFO = 'green'
# PROMPT = 'cyan'
# WARNING = 'yellow'
# ERROR = 'red'
#
# Path: syncano_cli/base/prompter.py
# class Prompter(object):
# indent = ' '
#
# def prompt(self, text, color=None, **kwargs):
# styles_kwargs = {'fg': color or ColorSchema.PROMPT}
# return click.prompt(click.style("{}{}".format(self.indent, text), **styles_kwargs), **kwargs)
#
# def confirm(self, text, color=None, **kwargs):
# styles_kwargs = {'fg': color or ColorSchema.PROMPT}
# return click.confirm(click.style("{}{}".format(self.indent, text), **styles_kwargs), **kwargs)
#
# Path: syncano_cli/config.py
# ACCOUNT_CONFIG_PATH = os.path.join(os.path.expanduser('~'), '.syncano')
#
# Path: syncano_cli/parse_to_syncano/config.py
# CONFIG_VARIABLES_NAMES = ['PARSE_MASTER_KEY', 'PARSE_APPLICATION_ID',
# 'SYNCANO_ADMIN_API_KEY', 'SYNCANO_INSTANCE_NAME']
, which may include functions, classes, or code. Output only the next line. | formatter.write("{config_var_name}: {config_var}".format( |
Based on the snippet: <|code_start|> else:
if not silent:
formatter.write("{config_var_name}: {config_var}".format(
config_var_name=click.style(config_var_name, fg=ColorSchema.PROMPT),
config_var=click.style(config.get(section, config_var_name), fg=ColorSchema.INFO)
))
def write_config_to_file(config):
with open(ACCOUNT_CONFIG_PATH, 'wt') as config_file:
config.write(config_file)
def check_configuration(config, silent=False):
for config_var_name in CONFIG_VARIABLES_NAMES:
check_config_value(config, config_var_name, silent=silent)
write_config_to_file(config)
def force_configuration_overwrite(config):
for config_var_name in CONFIG_VARIABLES_NAMES:
force_config_value(config, config_var_name)
write_config_to_file(config)
def print_configuration(config):
formatter = Formatter()
if not config.has_section('P2S'):
<|code_end|>
, predict the immediate next line with the help of imports:
import click
from syncano_cli.base.formatters import Formatter
from syncano_cli.base.options import ColorSchema
from syncano_cli.base.prompter import Prompter
from syncano_cli.config import ACCOUNT_CONFIG_PATH
from syncano_cli.parse_to_syncano.config import CONFIG_VARIABLES_NAMES
and context (classes, functions, sometimes code) from other files:
# Path: syncano_cli/base/formatters.py
# class Formatter(object):
#
# indent = ' '
# not_set = '-- not set --'
#
# def write(self, single_line, *options):
# option = self.get_options(options)
# styles = option.map_click()
# single_line = self._indent(single_line, option)
# self._write(single_line, option, **styles)
#
# def write_lines(self, lines, *options):
# lines = lines.splitlines() if isinstance(lines, six.string_types) else lines
# for line in lines:
# self.write(line, *options)
#
# def write_block(self, lines, *options):
# self.write_lines(lines, *options)
# self.separator()
#
# @classmethod
# def empty_line(cls):
# click.echo()
#
# def separator(self, size=70, indent=1):
# self.write(size * '-', DefaultOpt(indent=indent), WarningOpt(), BottomSpacedOpt())
#
# def display_config(self, config):
# for name, value in six.iteritems(config):
# self.write('{}{:20} {}'.format(
# self.indent,
# click.style(name, fg=ColorSchema.PROMPT),
# click.style(value, fg=ColorSchema.INFO)
# ))
# if not config:
# self.write('No config specified yet.', DefaultOpt(indent=2))
# self.empty_line()
#
# def get_options(self, options):
# option_list = list(options) or []
# option_list.insert(0, DefaultOpt())
# return OptionsBase.build_options(option_list)
#
# def format_object(self, dictionary, indent=1, skip_fields=None):
# skip_fields = skip_fields or []
# indent += 1
# for key, value in six.iteritems(dictionary):
# if isinstance(value, dict):
# self.write('{}:'.format(click.style(key, fg=ColorSchema.PROMPT)), DefaultOpt(indent=indent))
# self.format_object(value, indent=indent, skip_fields=skip_fields)
# elif isinstance(value, list):
# self.format_list(value, key=key, indent=indent)
# else:
# if key in skip_fields:
# continue
# self.write('{}: {}'.format(
# click.style(key, fg=ColorSchema.PROMPT),
# click.style(value, fg=ColorSchema.INFO)
# ), DefaultOpt(indent=indent))
#
# def format_list(self, data_list, key=None, indent=2, skip_fields=None):
# skip_fields = skip_fields or []
# for el in data_list:
# if isinstance(el, dict):
# self.format_object(el, indent=indent, skip_fields=skip_fields)
# else:
# if key:
# self.write('{}: {}'.format(
# click.style(key, fg=ColorSchema.PROMPT),
# click.style(el, fg=ColorSchema.INFO)
# ), DefaultOpt(indent=indent))
# else:
# self.write('{}'.format(el), DefaultOpt(indent=indent))
# self.empty_line()
#
# def _write(self, line, options, **styles):
# if options.space_top:
# self.empty_line()
#
# click.echo(click.style(line, **styles))
#
# if options.space_bottom:
# self.empty_line()
#
# def _indent(self, line, options):
# return '{}{}'.format(self.indent * options.indent, line)
#
# Path: syncano_cli/base/options.py
# class ColorSchema(object):
# INFO = 'green'
# PROMPT = 'cyan'
# WARNING = 'yellow'
# ERROR = 'red'
#
# Path: syncano_cli/base/prompter.py
# class Prompter(object):
# indent = ' '
#
# def prompt(self, text, color=None, **kwargs):
# styles_kwargs = {'fg': color or ColorSchema.PROMPT}
# return click.prompt(click.style("{}{}".format(self.indent, text), **styles_kwargs), **kwargs)
#
# def confirm(self, text, color=None, **kwargs):
# styles_kwargs = {'fg': color or ColorSchema.PROMPT}
# return click.confirm(click.style("{}{}".format(self.indent, text), **styles_kwargs), **kwargs)
#
# Path: syncano_cli/config.py
# ACCOUNT_CONFIG_PATH = os.path.join(os.path.expanduser('~'), '.syncano')
#
# Path: syncano_cli/parse_to_syncano/config.py
# CONFIG_VARIABLES_NAMES = ['PARSE_MASTER_KEY', 'PARSE_APPLICATION_ID',
# 'SYNCANO_ADMIN_API_KEY', 'SYNCANO_INSTANCE_NAME']
. Output only the next line. | config.add_section('P2S') |
Here is a snippet: <|code_start|> config.write(config_file)
def check_configuration(config, silent=False):
for config_var_name in CONFIG_VARIABLES_NAMES:
check_config_value(config, config_var_name, silent=silent)
write_config_to_file(config)
def force_configuration_overwrite(config):
for config_var_name in CONFIG_VARIABLES_NAMES:
force_config_value(config, config_var_name)
write_config_to_file(config)
def print_configuration(config):
formatter = Formatter()
if not config.has_section('P2S'):
config.add_section('P2S')
for config_var_name in CONFIG_VARIABLES_NAMES:
if not config.has_option('P2S', config_var_name):
config_var = "-- NOT SET --"
else:
config_var = config.get('P2S', config_var_name)
formatter.write("{config_var_name}: {config_var}".format(
config_var_name=click.style(config_var_name, fg=ColorSchema.PROMPT),
config_var=click.style(config_var, fg=ColorSchema.INFO)
<|code_end|>
. Write the next line using the current file imports:
import click
from syncano_cli.base.formatters import Formatter
from syncano_cli.base.options import ColorSchema
from syncano_cli.base.prompter import Prompter
from syncano_cli.config import ACCOUNT_CONFIG_PATH
from syncano_cli.parse_to_syncano.config import CONFIG_VARIABLES_NAMES
and context from other files:
# Path: syncano_cli/base/formatters.py
# class Formatter(object):
#
# indent = ' '
# not_set = '-- not set --'
#
# def write(self, single_line, *options):
# option = self.get_options(options)
# styles = option.map_click()
# single_line = self._indent(single_line, option)
# self._write(single_line, option, **styles)
#
# def write_lines(self, lines, *options):
# lines = lines.splitlines() if isinstance(lines, six.string_types) else lines
# for line in lines:
# self.write(line, *options)
#
# def write_block(self, lines, *options):
# self.write_lines(lines, *options)
# self.separator()
#
# @classmethod
# def empty_line(cls):
# click.echo()
#
# def separator(self, size=70, indent=1):
# self.write(size * '-', DefaultOpt(indent=indent), WarningOpt(), BottomSpacedOpt())
#
# def display_config(self, config):
# for name, value in six.iteritems(config):
# self.write('{}{:20} {}'.format(
# self.indent,
# click.style(name, fg=ColorSchema.PROMPT),
# click.style(value, fg=ColorSchema.INFO)
# ))
# if not config:
# self.write('No config specified yet.', DefaultOpt(indent=2))
# self.empty_line()
#
# def get_options(self, options):
# option_list = list(options) or []
# option_list.insert(0, DefaultOpt())
# return OptionsBase.build_options(option_list)
#
# def format_object(self, dictionary, indent=1, skip_fields=None):
# skip_fields = skip_fields or []
# indent += 1
# for key, value in six.iteritems(dictionary):
# if isinstance(value, dict):
# self.write('{}:'.format(click.style(key, fg=ColorSchema.PROMPT)), DefaultOpt(indent=indent))
# self.format_object(value, indent=indent, skip_fields=skip_fields)
# elif isinstance(value, list):
# self.format_list(value, key=key, indent=indent)
# else:
# if key in skip_fields:
# continue
# self.write('{}: {}'.format(
# click.style(key, fg=ColorSchema.PROMPT),
# click.style(value, fg=ColorSchema.INFO)
# ), DefaultOpt(indent=indent))
#
# def format_list(self, data_list, key=None, indent=2, skip_fields=None):
# skip_fields = skip_fields or []
# for el in data_list:
# if isinstance(el, dict):
# self.format_object(el, indent=indent, skip_fields=skip_fields)
# else:
# if key:
# self.write('{}: {}'.format(
# click.style(key, fg=ColorSchema.PROMPT),
# click.style(el, fg=ColorSchema.INFO)
# ), DefaultOpt(indent=indent))
# else:
# self.write('{}'.format(el), DefaultOpt(indent=indent))
# self.empty_line()
#
# def _write(self, line, options, **styles):
# if options.space_top:
# self.empty_line()
#
# click.echo(click.style(line, **styles))
#
# if options.space_bottom:
# self.empty_line()
#
# def _indent(self, line, options):
# return '{}{}'.format(self.indent * options.indent, line)
#
# Path: syncano_cli/base/options.py
# class ColorSchema(object):
# INFO = 'green'
# PROMPT = 'cyan'
# WARNING = 'yellow'
# ERROR = 'red'
#
# Path: syncano_cli/base/prompter.py
# class Prompter(object):
# indent = ' '
#
# def prompt(self, text, color=None, **kwargs):
# styles_kwargs = {'fg': color or ColorSchema.PROMPT}
# return click.prompt(click.style("{}{}".format(self.indent, text), **styles_kwargs), **kwargs)
#
# def confirm(self, text, color=None, **kwargs):
# styles_kwargs = {'fg': color or ColorSchema.PROMPT}
# return click.confirm(click.style("{}{}".format(self.indent, text), **styles_kwargs), **kwargs)
#
# Path: syncano_cli/config.py
# ACCOUNT_CONFIG_PATH = os.path.join(os.path.expanduser('~'), '.syncano')
#
# Path: syncano_cli/parse_to_syncano/config.py
# CONFIG_VARIABLES_NAMES = ['PARSE_MASTER_KEY', 'PARSE_APPLICATION_ID',
# 'SYNCANO_ADMIN_API_KEY', 'SYNCANO_INSTANCE_NAME']
, which may include functions, classes, or code. Output only the next line. | )) |
Predict the next line for this snippet: <|code_start|> config_var=click.style(config.get(section, config_var_name), fg=ColorSchema.INFO)
))
def write_config_to_file(config):
with open(ACCOUNT_CONFIG_PATH, 'wt') as config_file:
config.write(config_file)
def check_configuration(config, silent=False):
for config_var_name in CONFIG_VARIABLES_NAMES:
check_config_value(config, config_var_name, silent=silent)
write_config_to_file(config)
def force_configuration_overwrite(config):
for config_var_name in CONFIG_VARIABLES_NAMES:
force_config_value(config, config_var_name)
write_config_to_file(config)
def print_configuration(config):
formatter = Formatter()
if not config.has_section('P2S'):
config.add_section('P2S')
for config_var_name in CONFIG_VARIABLES_NAMES:
if not config.has_option('P2S', config_var_name):
config_var = "-- NOT SET --"
<|code_end|>
with the help of current file imports:
import click
from syncano_cli.base.formatters import Formatter
from syncano_cli.base.options import ColorSchema
from syncano_cli.base.prompter import Prompter
from syncano_cli.config import ACCOUNT_CONFIG_PATH
from syncano_cli.parse_to_syncano.config import CONFIG_VARIABLES_NAMES
and context from other files:
# Path: syncano_cli/base/formatters.py
# class Formatter(object):
#
# indent = ' '
# not_set = '-- not set --'
#
# def write(self, single_line, *options):
# option = self.get_options(options)
# styles = option.map_click()
# single_line = self._indent(single_line, option)
# self._write(single_line, option, **styles)
#
# def write_lines(self, lines, *options):
# lines = lines.splitlines() if isinstance(lines, six.string_types) else lines
# for line in lines:
# self.write(line, *options)
#
# def write_block(self, lines, *options):
# self.write_lines(lines, *options)
# self.separator()
#
# @classmethod
# def empty_line(cls):
# click.echo()
#
# def separator(self, size=70, indent=1):
# self.write(size * '-', DefaultOpt(indent=indent), WarningOpt(), BottomSpacedOpt())
#
# def display_config(self, config):
# for name, value in six.iteritems(config):
# self.write('{}{:20} {}'.format(
# self.indent,
# click.style(name, fg=ColorSchema.PROMPT),
# click.style(value, fg=ColorSchema.INFO)
# ))
# if not config:
# self.write('No config specified yet.', DefaultOpt(indent=2))
# self.empty_line()
#
# def get_options(self, options):
# option_list = list(options) or []
# option_list.insert(0, DefaultOpt())
# return OptionsBase.build_options(option_list)
#
# def format_object(self, dictionary, indent=1, skip_fields=None):
# skip_fields = skip_fields or []
# indent += 1
# for key, value in six.iteritems(dictionary):
# if isinstance(value, dict):
# self.write('{}:'.format(click.style(key, fg=ColorSchema.PROMPT)), DefaultOpt(indent=indent))
# self.format_object(value, indent=indent, skip_fields=skip_fields)
# elif isinstance(value, list):
# self.format_list(value, key=key, indent=indent)
# else:
# if key in skip_fields:
# continue
# self.write('{}: {}'.format(
# click.style(key, fg=ColorSchema.PROMPT),
# click.style(value, fg=ColorSchema.INFO)
# ), DefaultOpt(indent=indent))
#
# def format_list(self, data_list, key=None, indent=2, skip_fields=None):
# skip_fields = skip_fields or []
# for el in data_list:
# if isinstance(el, dict):
# self.format_object(el, indent=indent, skip_fields=skip_fields)
# else:
# if key:
# self.write('{}: {}'.format(
# click.style(key, fg=ColorSchema.PROMPT),
# click.style(el, fg=ColorSchema.INFO)
# ), DefaultOpt(indent=indent))
# else:
# self.write('{}'.format(el), DefaultOpt(indent=indent))
# self.empty_line()
#
# def _write(self, line, options, **styles):
# if options.space_top:
# self.empty_line()
#
# click.echo(click.style(line, **styles))
#
# if options.space_bottom:
# self.empty_line()
#
# def _indent(self, line, options):
# return '{}{}'.format(self.indent * options.indent, line)
#
# Path: syncano_cli/base/options.py
# class ColorSchema(object):
# INFO = 'green'
# PROMPT = 'cyan'
# WARNING = 'yellow'
# ERROR = 'red'
#
# Path: syncano_cli/base/prompter.py
# class Prompter(object):
# indent = ' '
#
# def prompt(self, text, color=None, **kwargs):
# styles_kwargs = {'fg': color or ColorSchema.PROMPT}
# return click.prompt(click.style("{}{}".format(self.indent, text), **styles_kwargs), **kwargs)
#
# def confirm(self, text, color=None, **kwargs):
# styles_kwargs = {'fg': color or ColorSchema.PROMPT}
# return click.confirm(click.style("{}{}".format(self.indent, text), **styles_kwargs), **kwargs)
#
# Path: syncano_cli/config.py
# ACCOUNT_CONFIG_PATH = os.path.join(os.path.expanduser('~'), '.syncano')
#
# Path: syncano_cli/parse_to_syncano/config.py
# CONFIG_VARIABLES_NAMES = ['PARSE_MASTER_KEY', 'PARSE_APPLICATION_ID',
# 'SYNCANO_ADMIN_API_KEY', 'SYNCANO_INSTANCE_NAME']
, which may contain function names, class names, or code. Output only the next line. | else: |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
class ParseConnection(object):
BASE_URL = 'https://api.parse.com/{url}/'
def __init__(self, application_id, master_key):
<|code_end|>
, determine the next line of code. You have imports:
import json
import requests
from syncano_cli.parse_to_syncano.parse.rest_map import PARSE_API_MAP
and context (class names, function names, or code) available:
# Path: syncano_cli/parse_to_syncano/parse/rest_map.py
# PARSE_API_MAP = {
# 'schemas': '1/schemas/',
# 'classes': '1/classes/{class_name}',
# 'installations': '1/installations/'
# }
. Output only the next line. | self.application_id = application_id |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
class DependencyTypeE():
CLASS = 'class'
SCRIPT = 'script'
class SocketJsonYml(object):
SOCKET_FIELDS = ['name', 'description', 'endpoints', 'dependencies']
ENDPOINT_TYPES = ['script']
<|code_end|>
. Use current file imports:
import os
import six
import yaml
from collections import defaultdict
from syncano_cli.custom_sockets.exceptions import BadYAMLDefinitionInEndpointsException
from syncano_cli.sync.scripts import ALLOWED_RUNTIMES
and context (classes, functions, or code) from other files:
# Path: syncano_cli/custom_sockets/exceptions.py
# class BadYAMLDefinitionInEndpointsException(CLIBaseException):
# default_message = u'Specify one general endpoint or specify endpoints for each method.'
#
# Path: syncano_cli/sync/scripts.py
# ALLOWED_RUNTIMES = {
# 'golang': '.go',
# 'nodejs': '.js',
# 'nodejs_library_v0.4': '.js',
# 'nodejs_library_v1.0': '.js',
# 'php': '.php',
# 'python': '.py',
# 'python3': '.py',
# 'python_library_v4.2': '.py',
# 'python_library_v5.0': '.py',
# 'ruby': '.rb',
# 'swift': '.swift',
# }
. Output only the next line. | HTTP_METHODS = ['GET', 'POST', 'DELETE', 'PUT', 'PATCH'] |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
class DependencyTypeE():
CLASS = 'class'
SCRIPT = 'script'
class SocketJsonYml(object):
SOCKET_FIELDS = ['name', 'description', 'endpoints', 'dependencies']
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import six
import yaml
from collections import defaultdict
from syncano_cli.custom_sockets.exceptions import BadYAMLDefinitionInEndpointsException
from syncano_cli.sync.scripts import ALLOWED_RUNTIMES
and context:
# Path: syncano_cli/custom_sockets/exceptions.py
# class BadYAMLDefinitionInEndpointsException(CLIBaseException):
# default_message = u'Specify one general endpoint or specify endpoints for each method.'
#
# Path: syncano_cli/sync/scripts.py
# ALLOWED_RUNTIMES = {
# 'golang': '.go',
# 'nodejs': '.js',
# 'nodejs_library_v0.4': '.js',
# 'nodejs_library_v1.0': '.js',
# 'php': '.php',
# 'python': '.py',
# 'python3': '.py',
# 'python_library_v4.2': '.py',
# 'python_library_v5.0': '.py',
# 'ruby': '.rb',
# 'swift': '.swift',
# }
which might include code, classes, or functions. Output only the next line. | ENDPOINT_TYPES = ['script'] |
Based on the snippet: <|code_start|> connection = syncano.connect().connection()
api_key = connection.authenticate(email=email, password=password)
ACCOUNT_CONFIG.set('DEFAULT', 'key', api_key)
with open(config_path, 'wt') as fp:
ACCOUNT_CONFIG.write(fp)
def do_register(self, exc, email, password, config_path):
if exc.status_code == 401:
if 'email' in exc.message:
account_command = AccountCommands(config_path=config_path)
account_command.register(email=email, password=password)
self.formatter.write('Account created for email: {}'.format(email),
TopSpacedOpt())
elif 'password' in exc.message:
self.formatter.write('Invalid login: you have provided wrong password.', ErrorOpt())
sys.exit(1)
def create_instance(self, instance_commands):
instance_name = random_instance_name()
return instance_commands.create(instance_name=instance_name)
def do_login_or_register(self, email, password, config_path):
try:
self.do_login(email, password, config_path)
except SyncanoRequestError as exc:
self.do_register(exc, email, password, config_path)
instance_commands = InstanceCommands(self.config_path)
instances = [i for i in instance_commands.api_list()]
instance_name = instances[0].name if instances else self.create_instance(instance_commands).name
<|code_end|>
, predict the immediate next line with the help of imports:
import sys
import syncano
from syncano.exceptions import SyncanoRequestError
from syncano_cli.base.options import ErrorOpt, SpacedOpt, TopSpacedOpt
from syncano_cli.config import ACCOUNT_CONFIG
from syncano_cli.init.helpers import random_instance_name
from syncano_cli.account.command import AccountCommands
from syncano_cli.instance.command import InstanceCommands
and context (classes, functions, sometimes code) from other files:
# Path: syncano_cli/base/options.py
# class ErrorOpt(OptionsBase):
# OPTIONS = ['color']
#
# def __init__(self, color=ColorSchema.ERROR, **kwargs):
# super(ErrorOpt, self).__init__(color=color, **kwargs)
#
# class SpacedOpt(OptionsBase):
# OPTIONS = ['space_top', 'space_bottom']
#
# def __init__(self, space_top=True, space_bottom=True, **kwargs):
# super(SpacedOpt, self).__init__(space_top=space_top, space_bottom=space_bottom, **kwargs)
#
# class TopSpacedOpt(OptionsBase):
# OPTIONS = ['space_top']
#
# def __init__(self, space_top=True, **kwargs):
# super(TopSpacedOpt, self).__init__(space_top=space_top, **kwargs)
#
# Path: syncano_cli/config.py
# ACCOUNT_CONFIG = ConfigParser()
#
# Path: syncano_cli/init/helpers.py
# def random_instance_name():
# return '{adj}-{noun}-{rnd}'.format(
# adj=random.choice(INSTANCE_NAME_ADJECTIVES),
# noun=random.choice(INSTANCE_NAME_NOUNS),
# rnd=random.randint(1000, 9999),
# )
. Output only the next line. | self.set_instance_as_default(config_path, instance_name, instance_commands) |
Using the snippet: <|code_start|>
class RegisterMixin(object):
def do_login(self, email, password, config_path):
connection = syncano.connect().connection()
api_key = connection.authenticate(email=email, password=password)
ACCOUNT_CONFIG.set('DEFAULT', 'key', api_key)
with open(config_path, 'wt') as fp:
ACCOUNT_CONFIG.write(fp)
def do_register(self, exc, email, password, config_path):
if exc.status_code == 401:
if 'email' in exc.message:
account_command = AccountCommands(config_path=config_path)
account_command.register(email=email, password=password)
self.formatter.write('Account created for email: {}'.format(email),
TopSpacedOpt())
elif 'password' in exc.message:
self.formatter.write('Invalid login: you have provided wrong password.', ErrorOpt())
sys.exit(1)
def create_instance(self, instance_commands):
instance_name = random_instance_name()
return instance_commands.create(instance_name=instance_name)
def do_login_or_register(self, email, password, config_path):
try:
self.do_login(email, password, config_path)
except SyncanoRequestError as exc:
<|code_end|>
, determine the next line of code. You have imports:
import sys
import syncano
from syncano.exceptions import SyncanoRequestError
from syncano_cli.base.options import ErrorOpt, SpacedOpt, TopSpacedOpt
from syncano_cli.config import ACCOUNT_CONFIG
from syncano_cli.init.helpers import random_instance_name
from syncano_cli.account.command import AccountCommands
from syncano_cli.instance.command import InstanceCommands
and context (class names, function names, or code) available:
# Path: syncano_cli/base/options.py
# class ErrorOpt(OptionsBase):
# OPTIONS = ['color']
#
# def __init__(self, color=ColorSchema.ERROR, **kwargs):
# super(ErrorOpt, self).__init__(color=color, **kwargs)
#
# class SpacedOpt(OptionsBase):
# OPTIONS = ['space_top', 'space_bottom']
#
# def __init__(self, space_top=True, space_bottom=True, **kwargs):
# super(SpacedOpt, self).__init__(space_top=space_top, space_bottom=space_bottom, **kwargs)
#
# class TopSpacedOpt(OptionsBase):
# OPTIONS = ['space_top']
#
# def __init__(self, space_top=True, **kwargs):
# super(TopSpacedOpt, self).__init__(space_top=space_top, **kwargs)
#
# Path: syncano_cli/config.py
# ACCOUNT_CONFIG = ConfigParser()
#
# Path: syncano_cli/init/helpers.py
# def random_instance_name():
# return '{adj}-{noun}-{rnd}'.format(
# adj=random.choice(INSTANCE_NAME_ADJECTIVES),
# noun=random.choice(INSTANCE_NAME_NOUNS),
# rnd=random.randint(1000, 9999),
# )
. Output only the next line. | self.do_register(exc, email, password, config_path) |
Given the code snippet: <|code_start|> account_command.register(email=email, password=password)
self.formatter.write('Account created for email: {}'.format(email),
TopSpacedOpt())
elif 'password' in exc.message:
self.formatter.write('Invalid login: you have provided wrong password.', ErrorOpt())
sys.exit(1)
def create_instance(self, instance_commands):
instance_name = random_instance_name()
return instance_commands.create(instance_name=instance_name)
def do_login_or_register(self, email, password, config_path):
try:
self.do_login(email, password, config_path)
except SyncanoRequestError as exc:
self.do_register(exc, email, password, config_path)
instance_commands = InstanceCommands(self.config_path)
instances = [i for i in instance_commands.api_list()]
instance_name = instances[0].name if instances else self.create_instance(instance_commands).name
self.set_instance_as_default(config_path, instance_name, instance_commands)
def set_instance_as_default(self, config_path, instance_name, instance_commands):
self.formatter.write('Instance `{}` set as default.'.format(instance_name), TopSpacedOpt())
instance_commands.set_default(instance_name=instance_name, config_path=config_path)
def validate_password(self, password, repeat_password):
while password != repeat_password:
self.formatter.write('Password and repeat password are not the same. Please correct:', ErrorOpt(),
SpacedOpt())
<|code_end|>
, generate the next line using the imports in this file:
import sys
import syncano
from syncano.exceptions import SyncanoRequestError
from syncano_cli.base.options import ErrorOpt, SpacedOpt, TopSpacedOpt
from syncano_cli.config import ACCOUNT_CONFIG
from syncano_cli.init.helpers import random_instance_name
from syncano_cli.account.command import AccountCommands
from syncano_cli.instance.command import InstanceCommands
and context (functions, classes, or occasionally code) from other files:
# Path: syncano_cli/base/options.py
# class ErrorOpt(OptionsBase):
# OPTIONS = ['color']
#
# def __init__(self, color=ColorSchema.ERROR, **kwargs):
# super(ErrorOpt, self).__init__(color=color, **kwargs)
#
# class SpacedOpt(OptionsBase):
# OPTIONS = ['space_top', 'space_bottom']
#
# def __init__(self, space_top=True, space_bottom=True, **kwargs):
# super(SpacedOpt, self).__init__(space_top=space_top, space_bottom=space_bottom, **kwargs)
#
# class TopSpacedOpt(OptionsBase):
# OPTIONS = ['space_top']
#
# def __init__(self, space_top=True, **kwargs):
# super(TopSpacedOpt, self).__init__(space_top=space_top, **kwargs)
#
# Path: syncano_cli/config.py
# ACCOUNT_CONFIG = ConfigParser()
#
# Path: syncano_cli/init/helpers.py
# def random_instance_name():
# return '{adj}-{noun}-{rnd}'.format(
# adj=random.choice(INSTANCE_NAME_ADJECTIVES),
# noun=random.choice(INSTANCE_NAME_NOUNS),
# rnd=random.randint(1000, 9999),
# )
. Output only the next line. | password = self.prompter.prompt('password', hide_input=True) |
Using the snippet: <|code_start|> def do_login(self, email, password, config_path):
connection = syncano.connect().connection()
api_key = connection.authenticate(email=email, password=password)
ACCOUNT_CONFIG.set('DEFAULT', 'key', api_key)
with open(config_path, 'wt') as fp:
ACCOUNT_CONFIG.write(fp)
def do_register(self, exc, email, password, config_path):
if exc.status_code == 401:
if 'email' in exc.message:
account_command = AccountCommands(config_path=config_path)
account_command.register(email=email, password=password)
self.formatter.write('Account created for email: {}'.format(email),
TopSpacedOpt())
elif 'password' in exc.message:
self.formatter.write('Invalid login: you have provided wrong password.', ErrorOpt())
sys.exit(1)
def create_instance(self, instance_commands):
instance_name = random_instance_name()
return instance_commands.create(instance_name=instance_name)
def do_login_or_register(self, email, password, config_path):
try:
self.do_login(email, password, config_path)
except SyncanoRequestError as exc:
self.do_register(exc, email, password, config_path)
instance_commands = InstanceCommands(self.config_path)
instances = [i for i in instance_commands.api_list()]
<|code_end|>
, determine the next line of code. You have imports:
import sys
import syncano
from syncano.exceptions import SyncanoRequestError
from syncano_cli.base.options import ErrorOpt, SpacedOpt, TopSpacedOpt
from syncano_cli.config import ACCOUNT_CONFIG
from syncano_cli.init.helpers import random_instance_name
from syncano_cli.account.command import AccountCommands
from syncano_cli.instance.command import InstanceCommands
and context (class names, function names, or code) available:
# Path: syncano_cli/base/options.py
# class ErrorOpt(OptionsBase):
# OPTIONS = ['color']
#
# def __init__(self, color=ColorSchema.ERROR, **kwargs):
# super(ErrorOpt, self).__init__(color=color, **kwargs)
#
# class SpacedOpt(OptionsBase):
# OPTIONS = ['space_top', 'space_bottom']
#
# def __init__(self, space_top=True, space_bottom=True, **kwargs):
# super(SpacedOpt, self).__init__(space_top=space_top, space_bottom=space_bottom, **kwargs)
#
# class TopSpacedOpt(OptionsBase):
# OPTIONS = ['space_top']
#
# def __init__(self, space_top=True, **kwargs):
# super(TopSpacedOpt, self).__init__(space_top=space_top, **kwargs)
#
# Path: syncano_cli/config.py
# ACCOUNT_CONFIG = ConfigParser()
#
# Path: syncano_cli/init/helpers.py
# def random_instance_name():
# return '{adj}-{noun}-{rnd}'.format(
# adj=random.choice(INSTANCE_NAME_ADJECTIVES),
# noun=random.choice(INSTANCE_NAME_NOUNS),
# rnd=random.randint(1000, 9999),
# )
. Output only the next line. | instance_name = instances[0].name if instances else self.create_instance(instance_commands).name |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
class RegisterMixin(object):
def do_login(self, email, password, config_path):
connection = syncano.connect().connection()
api_key = connection.authenticate(email=email, password=password)
ACCOUNT_CONFIG.set('DEFAULT', 'key', api_key)
with open(config_path, 'wt') as fp:
ACCOUNT_CONFIG.write(fp)
def do_register(self, exc, email, password, config_path):
if exc.status_code == 401:
if 'email' in exc.message:
account_command = AccountCommands(config_path=config_path)
account_command.register(email=email, password=password)
self.formatter.write('Account created for email: {}'.format(email),
TopSpacedOpt())
elif 'password' in exc.message:
self.formatter.write('Invalid login: you have provided wrong password.', ErrorOpt())
sys.exit(1)
def create_instance(self, instance_commands):
instance_name = random_instance_name()
return instance_commands.create(instance_name=instance_name)
<|code_end|>
, predict the next line using imports from the current file:
import sys
import syncano
from syncano.exceptions import SyncanoRequestError
from syncano_cli.base.options import ErrorOpt, SpacedOpt, TopSpacedOpt
from syncano_cli.config import ACCOUNT_CONFIG
from syncano_cli.init.helpers import random_instance_name
from syncano_cli.account.command import AccountCommands
from syncano_cli.instance.command import InstanceCommands
and context including class names, function names, and sometimes code from other files:
# Path: syncano_cli/base/options.py
# class ErrorOpt(OptionsBase):
# OPTIONS = ['color']
#
# def __init__(self, color=ColorSchema.ERROR, **kwargs):
# super(ErrorOpt, self).__init__(color=color, **kwargs)
#
# class SpacedOpt(OptionsBase):
# OPTIONS = ['space_top', 'space_bottom']
#
# def __init__(self, space_top=True, space_bottom=True, **kwargs):
# super(SpacedOpt, self).__init__(space_top=space_top, space_bottom=space_bottom, **kwargs)
#
# class TopSpacedOpt(OptionsBase):
# OPTIONS = ['space_top']
#
# def __init__(self, space_top=True, **kwargs):
# super(TopSpacedOpt, self).__init__(space_top=space_top, **kwargs)
#
# Path: syncano_cli/config.py
# ACCOUNT_CONFIG = ConfigParser()
#
# Path: syncano_cli/init/helpers.py
# def random_instance_name():
# return '{adj}-{noun}-{rnd}'.format(
# adj=random.choice(INSTANCE_NAME_ADJECTIVES),
# noun=random.choice(INSTANCE_NAME_NOUNS),
# rnd=random.randint(1000, 9999),
# )
. Output only the next line. | def do_login_or_register(self, email, password, config_path): |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
class MissingRequestDataException(CLIBaseException):
default_message = u'--data option should be provided when method {} is used'
class EndpointNotFoundException(CLIBaseException):
default_message = u'Endpoint `{}` not found'
class SocketYMLParseException(CLIBaseException):
default_message = u'Can not parse yml file.'
class SocketFileFetchException(CLIBaseException):
default_message = u'Can not fetch the file: {}.'
class BadConfigFormatException(CLIBaseException):
<|code_end|>
, predict the next line using imports from the current file:
from syncano_cli.base.exceptions import CLIBaseException
and context including class names, function names, and sometimes code from other files:
# Path: syncano_cli/base/exceptions.py
# class CLIBaseException(ClickException):
#
# default_message = u'A CLI processing exception.'
#
# def __init__(self, message=None, format_args=None):
# message = message or self.default_message
# if format_args:
# message = message.format(*format_args)
# super(CLIBaseException, self).__init__(message)
#
# def show(self, file=None):
# formatter = Formatter()
# formatter.write('Error: %s' % self.format_message(), ErrorOpt(), SpacedOpt())
. Output only the next line. | default_message = u'Bad config format.' |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
class SocketConfigParser(object):
PROMPT_FIELD = 'prompt'
VALUE_FIELD = 'value'
def __init__(self, socket_yml):
<|code_end|>
using the current file's imports:
import click
import six
from syncano_cli.custom_sockets.exceptions import BadConfigFormatException
and any relevant context from other files:
# Path: syncano_cli/custom_sockets/exceptions.py
# class BadConfigFormatException(CLIBaseException):
# default_message = u'Bad config format.'
. Output only the next line. | self.config = socket_yml.get('config', {}) |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
if six.PY2:
elif six.PY3:
else:
raise ImportError()
class InstanceCommands(BaseCommand):
def list(self):
return self.api_list()
def api_list(self):
return self.connection.Instance.please.all()
def details(self, instance_name):
return self.display_details(self.connection.Instance.please.get(name=instance_name))
def delete(self, instance_name):
self.connection.Instance.please.delete(name=instance_name)
self.formatter.write('Instance `{}` deleted.'.format(instance_name), WarningOpt(), SpacedOpt())
@classmethod
def set_default(cls, instance_name, config_path):
ACCOUNT_CONFIG.set('DEFAULT', 'instance_name', instance_name)
with open(config_path, 'wt') as fp:
ACCOUNT_CONFIG.write(fp)
<|code_end|>
. Use current file imports:
import click
import six
from syncano_cli.base.command import BaseCommand
from syncano_cli.base.options import BottomSpacedOpt, ColorSchema, SpacedOpt, TopSpacedOpt, WarningOpt
from syncano_cli.config import ACCOUNT_CONFIG
from ConfigParser import NoOptionError
from configparser import NoOptionError
and context (classes, functions, or code) from other files:
# Path: syncano_cli/base/command.py
# class BaseCommand(RegisterMixin):
# """
# Base command class. Provides utilities for register/loging (setup an account);
# Has a predefined class for prompting and format output nicely in the console;
# Stores also meta information about global config. Defines structures for command like config, eg.: hosting;
# """
#
# def __init__(self, config_path):
# self.config_path = config_path
# self.connection = create_connection(config_path)
#
# formatter = Formatter()
# prompter = Prompter()
#
# META_CONFIG = {
# 'default': [
# {
# 'name': 'key',
# 'required': True,
# 'info': ''
# },
# {
# 'name': 'instance_name',
# 'required': False,
# 'info': 'You can setup it using following command: syncano instances default <instance_name>.'
# },
# ]
# }
# DEFAULT_SECTION = 'DEFAULT'
#
# COMMAND_CONFIG = None
# COMMAND_SECTION = None
# COMMAND_CONFIG_PATH = None
#
# def has_setup(self):
# has_global = self.has_global_setup()
# has_command = self.has_command_setup(self.COMMAND_CONFIG_PATH)
# if has_global and has_command:
# return True
#
# if not has_global:
# self.formatter.write('Login or create an account in Syncano.', SpacedOpt())
# email = self.prompter.prompt('email')
# password = self.prompter.prompt('password', hide_input=True)
# repeat_password = self.prompter.prompt('repeat password', hide_input=True)
# password = self.validate_password(password, repeat_password)
# self.do_login_or_register(email, password, self.config_path)
#
# if not has_command:
# self.setup_command_config(self.config_path)
#
# return False
#
# def has_command_setup(self, config_path):
# if not config_path:
# return True
# return False
#
# def setup_command_config(self, config_path): # noqa;
# # override this in the child class;
# return True
#
# def has_global_setup(self):
# if os.path.isfile(self.config_path):
# ACCOUNT_CONFIG.read(self.config_path)
# return self.check_section(ACCOUNT_CONFIG)
#
# return False
#
# @classmethod
# def check_section(cls, config_parser, section=None):
# section = section or cls.DEFAULT_SECTION
# try:
# config_parser.get(cls.DEFAULT_SECTION, 'key')
# except NoOptionError:
# return False
#
# config_vars = []
# config_vars.extend(cls.META_CONFIG[cls.DEFAULT_SECTION.lower()])
# if cls.COMMAND_CONFIG:
# config_vars.extend(cls.COMMAND_CONFIG.get(cls.COMMAND_SECTION) or {})
# for config_meta in config_vars:
# var_name = config_meta['name']
# required = config_meta['required']
# if required and not config_parser.has_option(section, var_name):
# return False
# elif not required and not config_parser.has_option(section, var_name):
# cls.formatter.write(
# 'Missing "{}" in default config. {}'.format(var_name, config_meta['info']),
# WarningOpt(), SpacedOpt()
# )
#
# return True
#
# Path: syncano_cli/base/options.py
# class BottomSpacedOpt(OptionsBase):
# OPTIONS = ['space_bottom']
#
# def __init__(self, space_bottom=True, **kwargs):
# super(BottomSpacedOpt, self).__init__(space_bottom=space_bottom, **kwargs)
#
# class ColorSchema(object):
# INFO = 'green'
# PROMPT = 'cyan'
# WARNING = 'yellow'
# ERROR = 'red'
#
# class SpacedOpt(OptionsBase):
# OPTIONS = ['space_top', 'space_bottom']
#
# def __init__(self, space_top=True, space_bottom=True, **kwargs):
# super(SpacedOpt, self).__init__(space_top=space_top, space_bottom=space_bottom, **kwargs)
#
# class TopSpacedOpt(OptionsBase):
# OPTIONS = ['space_top']
#
# def __init__(self, space_top=True, **kwargs):
# super(TopSpacedOpt, self).__init__(space_top=space_top, **kwargs)
#
# class WarningOpt(OptionsBase):
# OPTIONS = ['color']
#
# def __init__(self, color=ColorSchema.WARNING, **kwargs):
# super(WarningOpt, self).__init__(color=color, **kwargs)
#
# Path: syncano_cli/config.py
# ACCOUNT_CONFIG = ConfigParser()
. Output only the next line. | def create(self, instance_name, description=None): |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
if six.PY2:
elif six.PY3:
else:
<|code_end|>
using the current file's imports:
import click
import six
from syncano_cli.base.command import BaseCommand
from syncano_cli.base.options import BottomSpacedOpt, ColorSchema, SpacedOpt, TopSpacedOpt, WarningOpt
from syncano_cli.config import ACCOUNT_CONFIG
from ConfigParser import NoOptionError
from configparser import NoOptionError
and any relevant context from other files:
# Path: syncano_cli/base/command.py
# class BaseCommand(RegisterMixin):
# """
# Base command class. Provides utilities for register/loging (setup an account);
# Has a predefined class for prompting and format output nicely in the console;
# Stores also meta information about global config. Defines structures for command like config, eg.: hosting;
# """
#
# def __init__(self, config_path):
# self.config_path = config_path
# self.connection = create_connection(config_path)
#
# formatter = Formatter()
# prompter = Prompter()
#
# META_CONFIG = {
# 'default': [
# {
# 'name': 'key',
# 'required': True,
# 'info': ''
# },
# {
# 'name': 'instance_name',
# 'required': False,
# 'info': 'You can setup it using following command: syncano instances default <instance_name>.'
# },
# ]
# }
# DEFAULT_SECTION = 'DEFAULT'
#
# COMMAND_CONFIG = None
# COMMAND_SECTION = None
# COMMAND_CONFIG_PATH = None
#
# def has_setup(self):
# has_global = self.has_global_setup()
# has_command = self.has_command_setup(self.COMMAND_CONFIG_PATH)
# if has_global and has_command:
# return True
#
# if not has_global:
# self.formatter.write('Login or create an account in Syncano.', SpacedOpt())
# email = self.prompter.prompt('email')
# password = self.prompter.prompt('password', hide_input=True)
# repeat_password = self.prompter.prompt('repeat password', hide_input=True)
# password = self.validate_password(password, repeat_password)
# self.do_login_or_register(email, password, self.config_path)
#
# if not has_command:
# self.setup_command_config(self.config_path)
#
# return False
#
# def has_command_setup(self, config_path):
# if not config_path:
# return True
# return False
#
# def setup_command_config(self, config_path): # noqa;
# # override this in the child class;
# return True
#
# def has_global_setup(self):
# if os.path.isfile(self.config_path):
# ACCOUNT_CONFIG.read(self.config_path)
# return self.check_section(ACCOUNT_CONFIG)
#
# return False
#
# @classmethod
# def check_section(cls, config_parser, section=None):
# section = section or cls.DEFAULT_SECTION
# try:
# config_parser.get(cls.DEFAULT_SECTION, 'key')
# except NoOptionError:
# return False
#
# config_vars = []
# config_vars.extend(cls.META_CONFIG[cls.DEFAULT_SECTION.lower()])
# if cls.COMMAND_CONFIG:
# config_vars.extend(cls.COMMAND_CONFIG.get(cls.COMMAND_SECTION) or {})
# for config_meta in config_vars:
# var_name = config_meta['name']
# required = config_meta['required']
# if required and not config_parser.has_option(section, var_name):
# return False
# elif not required and not config_parser.has_option(section, var_name):
# cls.formatter.write(
# 'Missing "{}" in default config. {}'.format(var_name, config_meta['info']),
# WarningOpt(), SpacedOpt()
# )
#
# return True
#
# Path: syncano_cli/base/options.py
# class BottomSpacedOpt(OptionsBase):
# OPTIONS = ['space_bottom']
#
# def __init__(self, space_bottom=True, **kwargs):
# super(BottomSpacedOpt, self).__init__(space_bottom=space_bottom, **kwargs)
#
# class ColorSchema(object):
# INFO = 'green'
# PROMPT = 'cyan'
# WARNING = 'yellow'
# ERROR = 'red'
#
# class SpacedOpt(OptionsBase):
# OPTIONS = ['space_top', 'space_bottom']
#
# def __init__(self, space_top=True, space_bottom=True, **kwargs):
# super(SpacedOpt, self).__init__(space_top=space_top, space_bottom=space_bottom, **kwargs)
#
# class TopSpacedOpt(OptionsBase):
# OPTIONS = ['space_top']
#
# def __init__(self, space_top=True, **kwargs):
# super(TopSpacedOpt, self).__init__(space_top=space_top, **kwargs)
#
# class WarningOpt(OptionsBase):
# OPTIONS = ['color']
#
# def __init__(self, color=ColorSchema.WARNING, **kwargs):
# super(WarningOpt, self).__init__(color=color, **kwargs)
#
# Path: syncano_cli/config.py
# ACCOUNT_CONFIG = ConfigParser()
. Output only the next line. | raise ImportError() |
Given snippet: <|code_start|>if six.PY2:
elif six.PY3:
else:
raise ImportError()
class InstanceCommands(BaseCommand):
def list(self):
return self.api_list()
def api_list(self):
return self.connection.Instance.please.all()
def details(self, instance_name):
return self.display_details(self.connection.Instance.please.get(name=instance_name))
def delete(self, instance_name):
self.connection.Instance.please.delete(name=instance_name)
self.formatter.write('Instance `{}` deleted.'.format(instance_name), WarningOpt(), SpacedOpt())
@classmethod
def set_default(cls, instance_name, config_path):
ACCOUNT_CONFIG.set('DEFAULT', 'instance_name', instance_name)
with open(config_path, 'wt') as fp:
ACCOUNT_CONFIG.write(fp)
def create(self, instance_name, description=None):
kwargs = {
'name': instance_name
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import click
import six
from syncano_cli.base.command import BaseCommand
from syncano_cli.base.options import BottomSpacedOpt, ColorSchema, SpacedOpt, TopSpacedOpt, WarningOpt
from syncano_cli.config import ACCOUNT_CONFIG
from ConfigParser import NoOptionError
from configparser import NoOptionError
and context:
# Path: syncano_cli/base/command.py
# class BaseCommand(RegisterMixin):
# """
# Base command class. Provides utilities for register/loging (setup an account);
# Has a predefined class for prompting and format output nicely in the console;
# Stores also meta information about global config. Defines structures for command like config, eg.: hosting;
# """
#
# def __init__(self, config_path):
# self.config_path = config_path
# self.connection = create_connection(config_path)
#
# formatter = Formatter()
# prompter = Prompter()
#
# META_CONFIG = {
# 'default': [
# {
# 'name': 'key',
# 'required': True,
# 'info': ''
# },
# {
# 'name': 'instance_name',
# 'required': False,
# 'info': 'You can setup it using following command: syncano instances default <instance_name>.'
# },
# ]
# }
# DEFAULT_SECTION = 'DEFAULT'
#
# COMMAND_CONFIG = None
# COMMAND_SECTION = None
# COMMAND_CONFIG_PATH = None
#
# def has_setup(self):
# has_global = self.has_global_setup()
# has_command = self.has_command_setup(self.COMMAND_CONFIG_PATH)
# if has_global and has_command:
# return True
#
# if not has_global:
# self.formatter.write('Login or create an account in Syncano.', SpacedOpt())
# email = self.prompter.prompt('email')
# password = self.prompter.prompt('password', hide_input=True)
# repeat_password = self.prompter.prompt('repeat password', hide_input=True)
# password = self.validate_password(password, repeat_password)
# self.do_login_or_register(email, password, self.config_path)
#
# if not has_command:
# self.setup_command_config(self.config_path)
#
# return False
#
# def has_command_setup(self, config_path):
# if not config_path:
# return True
# return False
#
# def setup_command_config(self, config_path): # noqa;
# # override this in the child class;
# return True
#
# def has_global_setup(self):
# if os.path.isfile(self.config_path):
# ACCOUNT_CONFIG.read(self.config_path)
# return self.check_section(ACCOUNT_CONFIG)
#
# return False
#
# @classmethod
# def check_section(cls, config_parser, section=None):
# section = section or cls.DEFAULT_SECTION
# try:
# config_parser.get(cls.DEFAULT_SECTION, 'key')
# except NoOptionError:
# return False
#
# config_vars = []
# config_vars.extend(cls.META_CONFIG[cls.DEFAULT_SECTION.lower()])
# if cls.COMMAND_CONFIG:
# config_vars.extend(cls.COMMAND_CONFIG.get(cls.COMMAND_SECTION) or {})
# for config_meta in config_vars:
# var_name = config_meta['name']
# required = config_meta['required']
# if required and not config_parser.has_option(section, var_name):
# return False
# elif not required and not config_parser.has_option(section, var_name):
# cls.formatter.write(
# 'Missing "{}" in default config. {}'.format(var_name, config_meta['info']),
# WarningOpt(), SpacedOpt()
# )
#
# return True
#
# Path: syncano_cli/base/options.py
# class BottomSpacedOpt(OptionsBase):
# OPTIONS = ['space_bottom']
#
# def __init__(self, space_bottom=True, **kwargs):
# super(BottomSpacedOpt, self).__init__(space_bottom=space_bottom, **kwargs)
#
# class ColorSchema(object):
# INFO = 'green'
# PROMPT = 'cyan'
# WARNING = 'yellow'
# ERROR = 'red'
#
# class SpacedOpt(OptionsBase):
# OPTIONS = ['space_top', 'space_bottom']
#
# def __init__(self, space_top=True, space_bottom=True, **kwargs):
# super(SpacedOpt, self).__init__(space_top=space_top, space_bottom=space_bottom, **kwargs)
#
# class TopSpacedOpt(OptionsBase):
# OPTIONS = ['space_top']
#
# def __init__(self, space_top=True, **kwargs):
# super(TopSpacedOpt, self).__init__(space_top=space_top, **kwargs)
#
# class WarningOpt(OptionsBase):
# OPTIONS = ['color']
#
# def __init__(self, color=ColorSchema.WARNING, **kwargs):
# super(WarningOpt, self).__init__(color=color, **kwargs)
#
# Path: syncano_cli/config.py
# ACCOUNT_CONFIG = ConfigParser()
which might include code, classes, or functions. Output only the next line. | } |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
if six.PY2:
elif six.PY3:
else:
raise ImportError()
class InstanceCommands(BaseCommand):
def list(self):
return self.api_list()
def api_list(self):
return self.connection.Instance.please.all()
def details(self, instance_name):
return self.display_details(self.connection.Instance.please.get(name=instance_name))
def delete(self, instance_name):
self.connection.Instance.please.delete(name=instance_name)
self.formatter.write('Instance `{}` deleted.'.format(instance_name), WarningOpt(), SpacedOpt())
@classmethod
def set_default(cls, instance_name, config_path):
ACCOUNT_CONFIG.set('DEFAULT', 'instance_name', instance_name)
with open(config_path, 'wt') as fp:
ACCOUNT_CONFIG.write(fp)
<|code_end|>
with the help of current file imports:
import click
import six
from syncano_cli.base.command import BaseCommand
from syncano_cli.base.options import BottomSpacedOpt, ColorSchema, SpacedOpt, TopSpacedOpt, WarningOpt
from syncano_cli.config import ACCOUNT_CONFIG
from ConfigParser import NoOptionError
from configparser import NoOptionError
and context from other files:
# Path: syncano_cli/base/command.py
# class BaseCommand(RegisterMixin):
# """
# Base command class. Provides utilities for register/loging (setup an account);
# Has a predefined class for prompting and format output nicely in the console;
# Stores also meta information about global config. Defines structures for command like config, eg.: hosting;
# """
#
# def __init__(self, config_path):
# self.config_path = config_path
# self.connection = create_connection(config_path)
#
# formatter = Formatter()
# prompter = Prompter()
#
# META_CONFIG = {
# 'default': [
# {
# 'name': 'key',
# 'required': True,
# 'info': ''
# },
# {
# 'name': 'instance_name',
# 'required': False,
# 'info': 'You can setup it using following command: syncano instances default <instance_name>.'
# },
# ]
# }
# DEFAULT_SECTION = 'DEFAULT'
#
# COMMAND_CONFIG = None
# COMMAND_SECTION = None
# COMMAND_CONFIG_PATH = None
#
# def has_setup(self):
# has_global = self.has_global_setup()
# has_command = self.has_command_setup(self.COMMAND_CONFIG_PATH)
# if has_global and has_command:
# return True
#
# if not has_global:
# self.formatter.write('Login or create an account in Syncano.', SpacedOpt())
# email = self.prompter.prompt('email')
# password = self.prompter.prompt('password', hide_input=True)
# repeat_password = self.prompter.prompt('repeat password', hide_input=True)
# password = self.validate_password(password, repeat_password)
# self.do_login_or_register(email, password, self.config_path)
#
# if not has_command:
# self.setup_command_config(self.config_path)
#
# return False
#
# def has_command_setup(self, config_path):
# if not config_path:
# return True
# return False
#
# def setup_command_config(self, config_path): # noqa;
# # override this in the child class;
# return True
#
# def has_global_setup(self):
# if os.path.isfile(self.config_path):
# ACCOUNT_CONFIG.read(self.config_path)
# return self.check_section(ACCOUNT_CONFIG)
#
# return False
#
# @classmethod
# def check_section(cls, config_parser, section=None):
# section = section or cls.DEFAULT_SECTION
# try:
# config_parser.get(cls.DEFAULT_SECTION, 'key')
# except NoOptionError:
# return False
#
# config_vars = []
# config_vars.extend(cls.META_CONFIG[cls.DEFAULT_SECTION.lower()])
# if cls.COMMAND_CONFIG:
# config_vars.extend(cls.COMMAND_CONFIG.get(cls.COMMAND_SECTION) or {})
# for config_meta in config_vars:
# var_name = config_meta['name']
# required = config_meta['required']
# if required and not config_parser.has_option(section, var_name):
# return False
# elif not required and not config_parser.has_option(section, var_name):
# cls.formatter.write(
# 'Missing "{}" in default config. {}'.format(var_name, config_meta['info']),
# WarningOpt(), SpacedOpt()
# )
#
# return True
#
# Path: syncano_cli/base/options.py
# class BottomSpacedOpt(OptionsBase):
# OPTIONS = ['space_bottom']
#
# def __init__(self, space_bottom=True, **kwargs):
# super(BottomSpacedOpt, self).__init__(space_bottom=space_bottom, **kwargs)
#
# class ColorSchema(object):
# INFO = 'green'
# PROMPT = 'cyan'
# WARNING = 'yellow'
# ERROR = 'red'
#
# class SpacedOpt(OptionsBase):
# OPTIONS = ['space_top', 'space_bottom']
#
# def __init__(self, space_top=True, space_bottom=True, **kwargs):
# super(SpacedOpt, self).__init__(space_top=space_top, space_bottom=space_bottom, **kwargs)
#
# class TopSpacedOpt(OptionsBase):
# OPTIONS = ['space_top']
#
# def __init__(self, space_top=True, **kwargs):
# super(TopSpacedOpt, self).__init__(space_top=space_top, **kwargs)
#
# class WarningOpt(OptionsBase):
# OPTIONS = ['color']
#
# def __init__(self, color=ColorSchema.WARNING, **kwargs):
# super(WarningOpt, self).__init__(color=color, **kwargs)
#
# Path: syncano_cli/config.py
# ACCOUNT_CONFIG = ConfigParser()
, which may contain function names, class names, or code. Output only the next line. | def create(self, instance_name, description=None): |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
if six.PY2:
elif six.PY3:
else:
raise ImportError()
class InstanceCommands(BaseCommand):
def list(self):
return self.api_list()
<|code_end|>
, predict the immediate next line with the help of imports:
import click
import six
from syncano_cli.base.command import BaseCommand
from syncano_cli.base.options import BottomSpacedOpt, ColorSchema, SpacedOpt, TopSpacedOpt, WarningOpt
from syncano_cli.config import ACCOUNT_CONFIG
from ConfigParser import NoOptionError
from configparser import NoOptionError
and context (classes, functions, sometimes code) from other files:
# Path: syncano_cli/base/command.py
# class BaseCommand(RegisterMixin):
# """
# Base command class. Provides utilities for register/loging (setup an account);
# Has a predefined class for prompting and format output nicely in the console;
# Stores also meta information about global config. Defines structures for command like config, eg.: hosting;
# """
#
# def __init__(self, config_path):
# self.config_path = config_path
# self.connection = create_connection(config_path)
#
# formatter = Formatter()
# prompter = Prompter()
#
# META_CONFIG = {
# 'default': [
# {
# 'name': 'key',
# 'required': True,
# 'info': ''
# },
# {
# 'name': 'instance_name',
# 'required': False,
# 'info': 'You can setup it using following command: syncano instances default <instance_name>.'
# },
# ]
# }
# DEFAULT_SECTION = 'DEFAULT'
#
# COMMAND_CONFIG = None
# COMMAND_SECTION = None
# COMMAND_CONFIG_PATH = None
#
# def has_setup(self):
# has_global = self.has_global_setup()
# has_command = self.has_command_setup(self.COMMAND_CONFIG_PATH)
# if has_global and has_command:
# return True
#
# if not has_global:
# self.formatter.write('Login or create an account in Syncano.', SpacedOpt())
# email = self.prompter.prompt('email')
# password = self.prompter.prompt('password', hide_input=True)
# repeat_password = self.prompter.prompt('repeat password', hide_input=True)
# password = self.validate_password(password, repeat_password)
# self.do_login_or_register(email, password, self.config_path)
#
# if not has_command:
# self.setup_command_config(self.config_path)
#
# return False
#
# def has_command_setup(self, config_path):
# if not config_path:
# return True
# return False
#
# def setup_command_config(self, config_path): # noqa;
# # override this in the child class;
# return True
#
# def has_global_setup(self):
# if os.path.isfile(self.config_path):
# ACCOUNT_CONFIG.read(self.config_path)
# return self.check_section(ACCOUNT_CONFIG)
#
# return False
#
# @classmethod
# def check_section(cls, config_parser, section=None):
# section = section or cls.DEFAULT_SECTION
# try:
# config_parser.get(cls.DEFAULT_SECTION, 'key')
# except NoOptionError:
# return False
#
# config_vars = []
# config_vars.extend(cls.META_CONFIG[cls.DEFAULT_SECTION.lower()])
# if cls.COMMAND_CONFIG:
# config_vars.extend(cls.COMMAND_CONFIG.get(cls.COMMAND_SECTION) or {})
# for config_meta in config_vars:
# var_name = config_meta['name']
# required = config_meta['required']
# if required and not config_parser.has_option(section, var_name):
# return False
# elif not required and not config_parser.has_option(section, var_name):
# cls.formatter.write(
# 'Missing "{}" in default config. {}'.format(var_name, config_meta['info']),
# WarningOpt(), SpacedOpt()
# )
#
# return True
#
# Path: syncano_cli/base/options.py
# class BottomSpacedOpt(OptionsBase):
# OPTIONS = ['space_bottom']
#
# def __init__(self, space_bottom=True, **kwargs):
# super(BottomSpacedOpt, self).__init__(space_bottom=space_bottom, **kwargs)
#
# class ColorSchema(object):
# INFO = 'green'
# PROMPT = 'cyan'
# WARNING = 'yellow'
# ERROR = 'red'
#
# class SpacedOpt(OptionsBase):
# OPTIONS = ['space_top', 'space_bottom']
#
# def __init__(self, space_top=True, space_bottom=True, **kwargs):
# super(SpacedOpt, self).__init__(space_top=space_top, space_bottom=space_bottom, **kwargs)
#
# class TopSpacedOpt(OptionsBase):
# OPTIONS = ['space_top']
#
# def __init__(self, space_top=True, **kwargs):
# super(TopSpacedOpt, self).__init__(space_top=space_top, **kwargs)
#
# class WarningOpt(OptionsBase):
# OPTIONS = ['color']
#
# def __init__(self, color=ColorSchema.WARNING, **kwargs):
# super(WarningOpt, self).__init__(color=color, **kwargs)
#
# Path: syncano_cli/config.py
# ACCOUNT_CONFIG = ConfigParser()
. Output only the next line. | def api_list(self): |
Given snippet: <|code_start|> if not socket_list:
self.write('Sockets not defined for `{}` instance.'.format(instance_name),
WarningOpt(), SpacedOpt())
sys.exit(1)
self.write('Sockets for `{}` instance.'.format(instance_name), SpacedOpt())
for cs in socket_list:
lines = self._display_list_details(custom_socket=cs)
lines.append('See: `syncano sockets details {}` for details.'.format(cs.name))
self.write_block(lines, DefaultOpt(indent=2))
def display_socket_details(self, custom_socket, api_key):
self.write_block(
[
'Details for Socket `{}` in `{}` instance.'.format(
custom_socket.name,
custom_socket.instance_name
)
],
SpacedOpt()
)
lines = self._display_list_details(custom_socket)
self.write_block(lines)
for socket_field in self.SOCKET_DETAILS_FIELDS:
self.display_block(
socket_field,
custom_socket,
base_link=custom_socket.links.links_dict['endpoints'],
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import sys
import click
import six
from syncano_cli.base.formatters import Formatter
from syncano_cli.base.options import BottomSpacedOpt, ColorSchema, DefaultOpt, SpacedOpt, TopSpacedOpt, WarningOpt
and context:
# Path: syncano_cli/base/formatters.py
# class Formatter(object):
#
# indent = ' '
# not_set = '-- not set --'
#
# def write(self, single_line, *options):
# option = self.get_options(options)
# styles = option.map_click()
# single_line = self._indent(single_line, option)
# self._write(single_line, option, **styles)
#
# def write_lines(self, lines, *options):
# lines = lines.splitlines() if isinstance(lines, six.string_types) else lines
# for line in lines:
# self.write(line, *options)
#
# def write_block(self, lines, *options):
# self.write_lines(lines, *options)
# self.separator()
#
# @classmethod
# def empty_line(cls):
# click.echo()
#
# def separator(self, size=70, indent=1):
# self.write(size * '-', DefaultOpt(indent=indent), WarningOpt(), BottomSpacedOpt())
#
# def display_config(self, config):
# for name, value in six.iteritems(config):
# self.write('{}{:20} {}'.format(
# self.indent,
# click.style(name, fg=ColorSchema.PROMPT),
# click.style(value, fg=ColorSchema.INFO)
# ))
# if not config:
# self.write('No config specified yet.', DefaultOpt(indent=2))
# self.empty_line()
#
# def get_options(self, options):
# option_list = list(options) or []
# option_list.insert(0, DefaultOpt())
# return OptionsBase.build_options(option_list)
#
# def format_object(self, dictionary, indent=1, skip_fields=None):
# skip_fields = skip_fields or []
# indent += 1
# for key, value in six.iteritems(dictionary):
# if isinstance(value, dict):
# self.write('{}:'.format(click.style(key, fg=ColorSchema.PROMPT)), DefaultOpt(indent=indent))
# self.format_object(value, indent=indent, skip_fields=skip_fields)
# elif isinstance(value, list):
# self.format_list(value, key=key, indent=indent)
# else:
# if key in skip_fields:
# continue
# self.write('{}: {}'.format(
# click.style(key, fg=ColorSchema.PROMPT),
# click.style(value, fg=ColorSchema.INFO)
# ), DefaultOpt(indent=indent))
#
# def format_list(self, data_list, key=None, indent=2, skip_fields=None):
# skip_fields = skip_fields or []
# for el in data_list:
# if isinstance(el, dict):
# self.format_object(el, indent=indent, skip_fields=skip_fields)
# else:
# if key:
# self.write('{}: {}'.format(
# click.style(key, fg=ColorSchema.PROMPT),
# click.style(el, fg=ColorSchema.INFO)
# ), DefaultOpt(indent=indent))
# else:
# self.write('{}'.format(el), DefaultOpt(indent=indent))
# self.empty_line()
#
# def _write(self, line, options, **styles):
# if options.space_top:
# self.empty_line()
#
# click.echo(click.style(line, **styles))
#
# if options.space_bottom:
# self.empty_line()
#
# def _indent(self, line, options):
# return '{}{}'.format(self.indent * options.indent, line)
#
# Path: syncano_cli/base/options.py
# class BottomSpacedOpt(OptionsBase):
# OPTIONS = ['space_bottom']
#
# def __init__(self, space_bottom=True, **kwargs):
# super(BottomSpacedOpt, self).__init__(space_bottom=space_bottom, **kwargs)
#
# class ColorSchema(object):
# INFO = 'green'
# PROMPT = 'cyan'
# WARNING = 'yellow'
# ERROR = 'red'
#
# class DefaultOpt(OptionsBase):
# color = ColorSchema.INFO
# indent = 1
# space_top = False
# space_bottom = False
#
# class SpacedOpt(OptionsBase):
# OPTIONS = ['space_top', 'space_bottom']
#
# def __init__(self, space_top=True, space_bottom=True, **kwargs):
# super(SpacedOpt, self).__init__(space_top=space_top, space_bottom=space_bottom, **kwargs)
#
# class TopSpacedOpt(OptionsBase):
# OPTIONS = ['space_top']
#
# def __init__(self, space_top=True, **kwargs):
# super(TopSpacedOpt, self).__init__(space_top=space_top, **kwargs)
#
# class WarningOpt(OptionsBase):
# OPTIONS = ['color']
#
# def __init__(self, color=ColorSchema.WARNING, **kwargs):
# super(WarningOpt, self).__init__(color=color, **kwargs)
which might include code, classes, or functions. Output only the next line. | api_key=api_key, |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
class SocketFormatter(Formatter):
SOCKET_LIST_FIELDS = ['name', 'description', 'status', 'status_info', 'endpoints']
SOCKET_DETAILS_FIELDS = ['config', 'endpoints', 'dependencies', 'metadata']
ENDPOINT_FIELDS = ['calls', 'acl', 'metadata']
def display_socket_list(self, socket_list, instance_name):
if not socket_list:
self.write('Sockets not defined for `{}` instance.'.format(instance_name),
WarningOpt(), SpacedOpt())
sys.exit(1)
self.write('Sockets for `{}` instance.'.format(instance_name), SpacedOpt())
for cs in socket_list:
lines = self._display_list_details(custom_socket=cs)
lines.append('See: `syncano sockets details {}` for details.'.format(cs.name))
self.write_block(lines, DefaultOpt(indent=2))
def display_socket_details(self, custom_socket, api_key):
self.write_block(
[
'Details for Socket `{}` in `{}` instance.'.format(
custom_socket.name,
<|code_end|>
, determine the next line of code. You have imports:
import sys
import click
import six
from syncano_cli.base.formatters import Formatter
from syncano_cli.base.options import BottomSpacedOpt, ColorSchema, DefaultOpt, SpacedOpt, TopSpacedOpt, WarningOpt
and context (class names, function names, or code) available:
# Path: syncano_cli/base/formatters.py
# class Formatter(object):
#
# indent = ' '
# not_set = '-- not set --'
#
# def write(self, single_line, *options):
# option = self.get_options(options)
# styles = option.map_click()
# single_line = self._indent(single_line, option)
# self._write(single_line, option, **styles)
#
# def write_lines(self, lines, *options):
# lines = lines.splitlines() if isinstance(lines, six.string_types) else lines
# for line in lines:
# self.write(line, *options)
#
# def write_block(self, lines, *options):
# self.write_lines(lines, *options)
# self.separator()
#
# @classmethod
# def empty_line(cls):
# click.echo()
#
# def separator(self, size=70, indent=1):
# self.write(size * '-', DefaultOpt(indent=indent), WarningOpt(), BottomSpacedOpt())
#
# def display_config(self, config):
# for name, value in six.iteritems(config):
# self.write('{}{:20} {}'.format(
# self.indent,
# click.style(name, fg=ColorSchema.PROMPT),
# click.style(value, fg=ColorSchema.INFO)
# ))
# if not config:
# self.write('No config specified yet.', DefaultOpt(indent=2))
# self.empty_line()
#
# def get_options(self, options):
# option_list = list(options) or []
# option_list.insert(0, DefaultOpt())
# return OptionsBase.build_options(option_list)
#
# def format_object(self, dictionary, indent=1, skip_fields=None):
# skip_fields = skip_fields or []
# indent += 1
# for key, value in six.iteritems(dictionary):
# if isinstance(value, dict):
# self.write('{}:'.format(click.style(key, fg=ColorSchema.PROMPT)), DefaultOpt(indent=indent))
# self.format_object(value, indent=indent, skip_fields=skip_fields)
# elif isinstance(value, list):
# self.format_list(value, key=key, indent=indent)
# else:
# if key in skip_fields:
# continue
# self.write('{}: {}'.format(
# click.style(key, fg=ColorSchema.PROMPT),
# click.style(value, fg=ColorSchema.INFO)
# ), DefaultOpt(indent=indent))
#
# def format_list(self, data_list, key=None, indent=2, skip_fields=None):
# skip_fields = skip_fields or []
# for el in data_list:
# if isinstance(el, dict):
# self.format_object(el, indent=indent, skip_fields=skip_fields)
# else:
# if key:
# self.write('{}: {}'.format(
# click.style(key, fg=ColorSchema.PROMPT),
# click.style(el, fg=ColorSchema.INFO)
# ), DefaultOpt(indent=indent))
# else:
# self.write('{}'.format(el), DefaultOpt(indent=indent))
# self.empty_line()
#
# def _write(self, line, options, **styles):
# if options.space_top:
# self.empty_line()
#
# click.echo(click.style(line, **styles))
#
# if options.space_bottom:
# self.empty_line()
#
# def _indent(self, line, options):
# return '{}{}'.format(self.indent * options.indent, line)
#
# Path: syncano_cli/base/options.py
# class BottomSpacedOpt(OptionsBase):
# OPTIONS = ['space_bottom']
#
# def __init__(self, space_bottom=True, **kwargs):
# super(BottomSpacedOpt, self).__init__(space_bottom=space_bottom, **kwargs)
#
# class ColorSchema(object):
# INFO = 'green'
# PROMPT = 'cyan'
# WARNING = 'yellow'
# ERROR = 'red'
#
# class DefaultOpt(OptionsBase):
# color = ColorSchema.INFO
# indent = 1
# space_top = False
# space_bottom = False
#
# class SpacedOpt(OptionsBase):
# OPTIONS = ['space_top', 'space_bottom']
#
# def __init__(self, space_top=True, space_bottom=True, **kwargs):
# super(SpacedOpt, self).__init__(space_top=space_top, space_bottom=space_bottom, **kwargs)
#
# class TopSpacedOpt(OptionsBase):
# OPTIONS = ['space_top']
#
# def __init__(self, space_top=True, **kwargs):
# super(TopSpacedOpt, self).__init__(space_top=space_top, **kwargs)
#
# class WarningOpt(OptionsBase):
# OPTIONS = ['color']
#
# def __init__(self, color=ColorSchema.WARNING, **kwargs):
# super(WarningOpt, self).__init__(color=color, **kwargs)
. Output only the next line. | custom_socket.instance_name |
Next line prediction: <|code_start|> )
],
SpacedOpt()
)
lines = self._display_list_details(custom_socket)
self.write_block(lines)
for socket_field in self.SOCKET_DETAILS_FIELDS:
self.display_block(
socket_field,
custom_socket,
base_link=custom_socket.links.links_dict['endpoints'],
api_key=api_key,
indent=1,
skip_fields=['source']
)
def display_block(self, block_name, socket, **kwargs):
handler, kw_names = self.display_handlers[block_name]
self.write(block_name.capitalize())
socket_data = getattr(socket, block_name)
new_kwargs = {key: value for key, value in six.iteritems(kwargs) if key in kw_names}
handler(socket_data, **new_kwargs)
self.separator()
@property
def display_handlers(self):
handlers = [
(self.display_config, ()),
<|code_end|>
. Use current file imports:
(import sys
import click
import six
from syncano_cli.base.formatters import Formatter
from syncano_cli.base.options import BottomSpacedOpt, ColorSchema, DefaultOpt, SpacedOpt, TopSpacedOpt, WarningOpt)
and context including class names, function names, or small code snippets from other files:
# Path: syncano_cli/base/formatters.py
# class Formatter(object):
#
# indent = ' '
# not_set = '-- not set --'
#
# def write(self, single_line, *options):
# option = self.get_options(options)
# styles = option.map_click()
# single_line = self._indent(single_line, option)
# self._write(single_line, option, **styles)
#
# def write_lines(self, lines, *options):
# lines = lines.splitlines() if isinstance(lines, six.string_types) else lines
# for line in lines:
# self.write(line, *options)
#
# def write_block(self, lines, *options):
# self.write_lines(lines, *options)
# self.separator()
#
# @classmethod
# def empty_line(cls):
# click.echo()
#
# def separator(self, size=70, indent=1):
# self.write(size * '-', DefaultOpt(indent=indent), WarningOpt(), BottomSpacedOpt())
#
# def display_config(self, config):
# for name, value in six.iteritems(config):
# self.write('{}{:20} {}'.format(
# self.indent,
# click.style(name, fg=ColorSchema.PROMPT),
# click.style(value, fg=ColorSchema.INFO)
# ))
# if not config:
# self.write('No config specified yet.', DefaultOpt(indent=2))
# self.empty_line()
#
# def get_options(self, options):
# option_list = list(options) or []
# option_list.insert(0, DefaultOpt())
# return OptionsBase.build_options(option_list)
#
# def format_object(self, dictionary, indent=1, skip_fields=None):
# skip_fields = skip_fields or []
# indent += 1
# for key, value in six.iteritems(dictionary):
# if isinstance(value, dict):
# self.write('{}:'.format(click.style(key, fg=ColorSchema.PROMPT)), DefaultOpt(indent=indent))
# self.format_object(value, indent=indent, skip_fields=skip_fields)
# elif isinstance(value, list):
# self.format_list(value, key=key, indent=indent)
# else:
# if key in skip_fields:
# continue
# self.write('{}: {}'.format(
# click.style(key, fg=ColorSchema.PROMPT),
# click.style(value, fg=ColorSchema.INFO)
# ), DefaultOpt(indent=indent))
#
# def format_list(self, data_list, key=None, indent=2, skip_fields=None):
# skip_fields = skip_fields or []
# for el in data_list:
# if isinstance(el, dict):
# self.format_object(el, indent=indent, skip_fields=skip_fields)
# else:
# if key:
# self.write('{}: {}'.format(
# click.style(key, fg=ColorSchema.PROMPT),
# click.style(el, fg=ColorSchema.INFO)
# ), DefaultOpt(indent=indent))
# else:
# self.write('{}'.format(el), DefaultOpt(indent=indent))
# self.empty_line()
#
# def _write(self, line, options, **styles):
# if options.space_top:
# self.empty_line()
#
# click.echo(click.style(line, **styles))
#
# if options.space_bottom:
# self.empty_line()
#
# def _indent(self, line, options):
# return '{}{}'.format(self.indent * options.indent, line)
#
# Path: syncano_cli/base/options.py
# class BottomSpacedOpt(OptionsBase):
# OPTIONS = ['space_bottom']
#
# def __init__(self, space_bottom=True, **kwargs):
# super(BottomSpacedOpt, self).__init__(space_bottom=space_bottom, **kwargs)
#
# class ColorSchema(object):
# INFO = 'green'
# PROMPT = 'cyan'
# WARNING = 'yellow'
# ERROR = 'red'
#
# class DefaultOpt(OptionsBase):
# color = ColorSchema.INFO
# indent = 1
# space_top = False
# space_bottom = False
#
# class SpacedOpt(OptionsBase):
# OPTIONS = ['space_top', 'space_bottom']
#
# def __init__(self, space_top=True, space_bottom=True, **kwargs):
# super(SpacedOpt, self).__init__(space_top=space_top, space_bottom=space_bottom, **kwargs)
#
# class TopSpacedOpt(OptionsBase):
# OPTIONS = ['space_top']
#
# def __init__(self, space_top=True, **kwargs):
# super(TopSpacedOpt, self).__init__(space_top=space_top, **kwargs)
#
# class WarningOpt(OptionsBase):
# OPTIONS = ['color']
#
# def __init__(self, color=ColorSchema.WARNING, **kwargs):
# super(WarningOpt, self).__init__(color=color, **kwargs)
. Output only the next line. | (self.display_endpoints, ('base_link', 'api_key')), |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
class PathNotFoundException(CLIBaseException):
default_message = u'File `{}` not found.'
class UnicodeInPathException(CLIBaseException):
<|code_end|>
with the help of current file imports:
from syncano_cli.base.exceptions import CLIBaseException
and context from other files:
# Path: syncano_cli/base/exceptions.py
# class CLIBaseException(ClickException):
#
# default_message = u'A CLI processing exception.'
#
# def __init__(self, message=None, format_args=None):
# message = message or self.default_message
# if format_args:
# message = message.format(*format_args)
# super(CLIBaseException, self).__init__(message)
#
# def show(self, file=None):
# formatter = Formatter()
# formatter.write('Error: %s' % self.format_message(), ErrorOpt(), SpacedOpt())
, which may contain function names, class names, or code. Output only the next line. | default_message = u'Unicode characters in path are not supported. Check the files names.' |
Given snippet: <|code_start|>
class Formatter(object):
indent = ' '
not_set = '-- not set --'
def write(self, single_line, *options):
option = self.get_options(options)
styles = option.map_click()
single_line = self._indent(single_line, option)
self._write(single_line, option, **styles)
def write_lines(self, lines, *options):
lines = lines.splitlines() if isinstance(lines, six.string_types) else lines
for line in lines:
self.write(line, *options)
def write_block(self, lines, *options):
self.write_lines(lines, *options)
self.separator()
@classmethod
def empty_line(cls):
click.echo()
def separator(self, size=70, indent=1):
self.write(size * '-', DefaultOpt(indent=indent), WarningOpt(), BottomSpacedOpt())
def display_config(self, config):
for name, value in six.iteritems(config):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import click
import six
from syncano_cli.base.options import BottomSpacedOpt, ColorSchema, DefaultOpt, OptionsBase, WarningOpt
and context:
# Path: syncano_cli/base/options.py
# class BottomSpacedOpt(OptionsBase):
# OPTIONS = ['space_bottom']
#
# def __init__(self, space_bottom=True, **kwargs):
# super(BottomSpacedOpt, self).__init__(space_bottom=space_bottom, **kwargs)
#
# class ColorSchema(object):
# INFO = 'green'
# PROMPT = 'cyan'
# WARNING = 'yellow'
# ERROR = 'red'
#
# class DefaultOpt(OptionsBase):
# color = ColorSchema.INFO
# indent = 1
# space_top = False
# space_bottom = False
#
# class OptionsBase(object):
# CLICK_MAP = {
# 'color': 'fg'
# }
#
# OPTIONS = ['color', 'indent', 'space_top', 'space_bottom']
#
# def __init__(
# self,
# color=ColorSchema.INFO,
# indent=1,
# space_top=False,
# space_bottom=False):
# """Allows to override class attributes."""
# self.color = color
# self.indent = indent
# self.space_top = space_top
# self.space_bottom = space_bottom
#
# def map_click(self):
# return {click_name: getattr(self, option_name) for option_name, click_name in six.iteritems(self.CLICK_MAP)}
#
# def get_options(self):
# return {
# key: value for key, value in six.iteritems(self.__dict__) if key in self.OPTIONS
# }
#
# @classmethod
# def build_options(cls, option_list):
# options = {}
# for option in option_list:
# options.update(option.get_options())
# return cls(**options)
#
# class WarningOpt(OptionsBase):
# OPTIONS = ['color']
#
# def __init__(self, color=ColorSchema.WARNING, **kwargs):
# super(WarningOpt, self).__init__(color=color, **kwargs)
which might include code, classes, or functions. Output only the next line. | self.write('{}{:20} {}'.format( |
Using the snippet: <|code_start|>class Formatter(object):
indent = ' '
not_set = '-- not set --'
def write(self, single_line, *options):
option = self.get_options(options)
styles = option.map_click()
single_line = self._indent(single_line, option)
self._write(single_line, option, **styles)
def write_lines(self, lines, *options):
lines = lines.splitlines() if isinstance(lines, six.string_types) else lines
for line in lines:
self.write(line, *options)
def write_block(self, lines, *options):
self.write_lines(lines, *options)
self.separator()
@classmethod
def empty_line(cls):
click.echo()
def separator(self, size=70, indent=1):
self.write(size * '-', DefaultOpt(indent=indent), WarningOpt(), BottomSpacedOpt())
def display_config(self, config):
for name, value in six.iteritems(config):
self.write('{}{:20} {}'.format(
<|code_end|>
, determine the next line of code. You have imports:
import click
import six
from syncano_cli.base.options import BottomSpacedOpt, ColorSchema, DefaultOpt, OptionsBase, WarningOpt
and context (class names, function names, or code) available:
# Path: syncano_cli/base/options.py
# class BottomSpacedOpt(OptionsBase):
# OPTIONS = ['space_bottom']
#
# def __init__(self, space_bottom=True, **kwargs):
# super(BottomSpacedOpt, self).__init__(space_bottom=space_bottom, **kwargs)
#
# class ColorSchema(object):
# INFO = 'green'
# PROMPT = 'cyan'
# WARNING = 'yellow'
# ERROR = 'red'
#
# class DefaultOpt(OptionsBase):
# color = ColorSchema.INFO
# indent = 1
# space_top = False
# space_bottom = False
#
# class OptionsBase(object):
# CLICK_MAP = {
# 'color': 'fg'
# }
#
# OPTIONS = ['color', 'indent', 'space_top', 'space_bottom']
#
# def __init__(
# self,
# color=ColorSchema.INFO,
# indent=1,
# space_top=False,
# space_bottom=False):
# """Allows to override class attributes."""
# self.color = color
# self.indent = indent
# self.space_top = space_top
# self.space_bottom = space_bottom
#
# def map_click(self):
# return {click_name: getattr(self, option_name) for option_name, click_name in six.iteritems(self.CLICK_MAP)}
#
# def get_options(self):
# return {
# key: value for key, value in six.iteritems(self.__dict__) if key in self.OPTIONS
# }
#
# @classmethod
# def build_options(cls, option_list):
# options = {}
# for option in option_list:
# options.update(option.get_options())
# return cls(**options)
#
# class WarningOpt(OptionsBase):
# OPTIONS = ['color']
#
# def __init__(self, color=ColorSchema.WARNING, **kwargs):
# super(WarningOpt, self).__init__(color=color, **kwargs)
. Output only the next line. | self.indent, |
Predict the next line after this snippet: <|code_start|> for key, value in six.iteritems(dictionary):
if isinstance(value, dict):
self.write('{}:'.format(click.style(key, fg=ColorSchema.PROMPT)), DefaultOpt(indent=indent))
self.format_object(value, indent=indent, skip_fields=skip_fields)
elif isinstance(value, list):
self.format_list(value, key=key, indent=indent)
else:
if key in skip_fields:
continue
self.write('{}: {}'.format(
click.style(key, fg=ColorSchema.PROMPT),
click.style(value, fg=ColorSchema.INFO)
), DefaultOpt(indent=indent))
def format_list(self, data_list, key=None, indent=2, skip_fields=None):
skip_fields = skip_fields or []
for el in data_list:
if isinstance(el, dict):
self.format_object(el, indent=indent, skip_fields=skip_fields)
else:
if key:
self.write('{}: {}'.format(
click.style(key, fg=ColorSchema.PROMPT),
click.style(el, fg=ColorSchema.INFO)
), DefaultOpt(indent=indent))
else:
self.write('{}'.format(el), DefaultOpt(indent=indent))
self.empty_line()
def _write(self, line, options, **styles):
<|code_end|>
using the current file's imports:
import click
import six
from syncano_cli.base.options import BottomSpacedOpt, ColorSchema, DefaultOpt, OptionsBase, WarningOpt
and any relevant context from other files:
# Path: syncano_cli/base/options.py
# class BottomSpacedOpt(OptionsBase):
# OPTIONS = ['space_bottom']
#
# def __init__(self, space_bottom=True, **kwargs):
# super(BottomSpacedOpt, self).__init__(space_bottom=space_bottom, **kwargs)
#
# class ColorSchema(object):
# INFO = 'green'
# PROMPT = 'cyan'
# WARNING = 'yellow'
# ERROR = 'red'
#
# class DefaultOpt(OptionsBase):
# color = ColorSchema.INFO
# indent = 1
# space_top = False
# space_bottom = False
#
# class OptionsBase(object):
# CLICK_MAP = {
# 'color': 'fg'
# }
#
# OPTIONS = ['color', 'indent', 'space_top', 'space_bottom']
#
# def __init__(
# self,
# color=ColorSchema.INFO,
# indent=1,
# space_top=False,
# space_bottom=False):
# """Allows to override class attributes."""
# self.color = color
# self.indent = indent
# self.space_top = space_top
# self.space_bottom = space_bottom
#
# def map_click(self):
# return {click_name: getattr(self, option_name) for option_name, click_name in six.iteritems(self.CLICK_MAP)}
#
# def get_options(self):
# return {
# key: value for key, value in six.iteritems(self.__dict__) if key in self.OPTIONS
# }
#
# @classmethod
# def build_options(cls, option_list):
# options = {}
# for option in option_list:
# options.update(option.get_options())
# return cls(**options)
#
# class WarningOpt(OptionsBase):
# OPTIONS = ['color']
#
# def __init__(self, color=ColorSchema.WARNING, **kwargs):
# super(WarningOpt, self).__init__(color=color, **kwargs)
. Output only the next line. | if options.space_top: |
Predict the next line after this snippet: <|code_start|> click.style(name, fg=ColorSchema.PROMPT),
click.style(value, fg=ColorSchema.INFO)
))
if not config:
self.write('No config specified yet.', DefaultOpt(indent=2))
self.empty_line()
def get_options(self, options):
option_list = list(options) or []
option_list.insert(0, DefaultOpt())
return OptionsBase.build_options(option_list)
def format_object(self, dictionary, indent=1, skip_fields=None):
skip_fields = skip_fields or []
indent += 1
for key, value in six.iteritems(dictionary):
if isinstance(value, dict):
self.write('{}:'.format(click.style(key, fg=ColorSchema.PROMPT)), DefaultOpt(indent=indent))
self.format_object(value, indent=indent, skip_fields=skip_fields)
elif isinstance(value, list):
self.format_list(value, key=key, indent=indent)
else:
if key in skip_fields:
continue
self.write('{}: {}'.format(
click.style(key, fg=ColorSchema.PROMPT),
click.style(value, fg=ColorSchema.INFO)
), DefaultOpt(indent=indent))
def format_list(self, data_list, key=None, indent=2, skip_fields=None):
<|code_end|>
using the current file's imports:
import click
import six
from syncano_cli.base.options import BottomSpacedOpt, ColorSchema, DefaultOpt, OptionsBase, WarningOpt
and any relevant context from other files:
# Path: syncano_cli/base/options.py
# class BottomSpacedOpt(OptionsBase):
# OPTIONS = ['space_bottom']
#
# def __init__(self, space_bottom=True, **kwargs):
# super(BottomSpacedOpt, self).__init__(space_bottom=space_bottom, **kwargs)
#
# class ColorSchema(object):
# INFO = 'green'
# PROMPT = 'cyan'
# WARNING = 'yellow'
# ERROR = 'red'
#
# class DefaultOpt(OptionsBase):
# color = ColorSchema.INFO
# indent = 1
# space_top = False
# space_bottom = False
#
# class OptionsBase(object):
# CLICK_MAP = {
# 'color': 'fg'
# }
#
# OPTIONS = ['color', 'indent', 'space_top', 'space_bottom']
#
# def __init__(
# self,
# color=ColorSchema.INFO,
# indent=1,
# space_top=False,
# space_bottom=False):
# """Allows to override class attributes."""
# self.color = color
# self.indent = indent
# self.space_top = space_top
# self.space_bottom = space_bottom
#
# def map_click(self):
# return {click_name: getattr(self, option_name) for option_name, click_name in six.iteritems(self.CLICK_MAP)}
#
# def get_options(self):
# return {
# key: value for key, value in six.iteritems(self.__dict__) if key in self.OPTIONS
# }
#
# @classmethod
# def build_options(cls, option_list):
# options = {}
# for option in option_list:
# options.update(option.get_options())
# return cls(**options)
#
# class WarningOpt(OptionsBase):
# OPTIONS = ['color']
#
# def __init__(self, color=ColorSchema.WARNING, **kwargs):
# super(WarningOpt, self).__init__(color=color, **kwargs)
. Output only the next line. | skip_fields = skip_fields or [] |
Predict the next line after this snippet: <|code_start|>
@classmethod
def empty_line(cls):
click.echo()
def separator(self, size=70, indent=1):
self.write(size * '-', DefaultOpt(indent=indent), WarningOpt(), BottomSpacedOpt())
def display_config(self, config):
for name, value in six.iteritems(config):
self.write('{}{:20} {}'.format(
self.indent,
click.style(name, fg=ColorSchema.PROMPT),
click.style(value, fg=ColorSchema.INFO)
))
if not config:
self.write('No config specified yet.', DefaultOpt(indent=2))
self.empty_line()
def get_options(self, options):
option_list = list(options) or []
option_list.insert(0, DefaultOpt())
return OptionsBase.build_options(option_list)
def format_object(self, dictionary, indent=1, skip_fields=None):
skip_fields = skip_fields or []
indent += 1
for key, value in six.iteritems(dictionary):
if isinstance(value, dict):
self.write('{}:'.format(click.style(key, fg=ColorSchema.PROMPT)), DefaultOpt(indent=indent))
<|code_end|>
using the current file's imports:
import click
import six
from syncano_cli.base.options import BottomSpacedOpt, ColorSchema, DefaultOpt, OptionsBase, WarningOpt
and any relevant context from other files:
# Path: syncano_cli/base/options.py
# class BottomSpacedOpt(OptionsBase):
# OPTIONS = ['space_bottom']
#
# def __init__(self, space_bottom=True, **kwargs):
# super(BottomSpacedOpt, self).__init__(space_bottom=space_bottom, **kwargs)
#
# class ColorSchema(object):
# INFO = 'green'
# PROMPT = 'cyan'
# WARNING = 'yellow'
# ERROR = 'red'
#
# class DefaultOpt(OptionsBase):
# color = ColorSchema.INFO
# indent = 1
# space_top = False
# space_bottom = False
#
# class OptionsBase(object):
# CLICK_MAP = {
# 'color': 'fg'
# }
#
# OPTIONS = ['color', 'indent', 'space_top', 'space_bottom']
#
# def __init__(
# self,
# color=ColorSchema.INFO,
# indent=1,
# space_top=False,
# space_bottom=False):
# """Allows to override class attributes."""
# self.color = color
# self.indent = indent
# self.space_top = space_top
# self.space_bottom = space_bottom
#
# def map_click(self):
# return {click_name: getattr(self, option_name) for option_name, click_name in six.iteritems(self.CLICK_MAP)}
#
# def get_options(self):
# return {
# key: value for key, value in six.iteritems(self.__dict__) if key in self.OPTIONS
# }
#
# @classmethod
# def build_options(cls, option_list):
# options = {}
# for option in option_list:
# options.update(option.get_options())
# return cls(**options)
#
# class WarningOpt(OptionsBase):
# OPTIONS = ['color']
#
# def __init__(self, color=ColorSchema.WARNING, **kwargs):
# super(WarningOpt, self).__init__(color=color, **kwargs)
. Output only the next line. | self.format_object(value, indent=indent, skip_fields=skip_fields) |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
class AccountCommandsTest(BaseCLITest):
def test_register(self):
# remove file with connection data:
if os.path.isfile(ACCOUNT_CONFIG_PATH):
os.remove(ACCOUNT_CONFIG_PATH)
self.assertFalse(os.path.isfile(ACCOUNT_CONFIG_PATH))
# old api key;
old_key = self.connection.connection().api_key
# make register;
<|code_end|>
. Use current file imports:
import os
import random
from syncano_cli.config import ACCOUNT_CONFIG, ACCOUNT_CONFIG_PATH
from syncano_cli.main import cli
from tests.base import BaseCLITest
and context (classes, functions, or code) from other files:
# Path: syncano_cli/config.py
# ACCOUNT_CONFIG = ConfigParser()
#
# ACCOUNT_CONFIG_PATH = os.path.join(os.path.expanduser('~'), '.syncano')
#
# Path: syncano_cli/main.py
# def main():
#
# Path: tests/base.py
# class BaseCLITest(InstanceMixin, IntegrationTest):
#
# @classmethod
# def setUpClass(cls):
# super(BaseCLITest, cls).setUpClass()
# cls.yml_file = 'syncano.yml'
# cls.scripts_dir = 'scripts/'
#
# def setUp(self):
# self.runner.invoke(cli, args=['login', '--instance-name', self.instance.name], obj={})
# self.assert_config_variable_exists(ACCOUNT_CONFIG, 'DEFAULT', 'key')
# self.assert_config_variable_exists(ACCOUNT_CONFIG, 'DEFAULT', 'instance_name')
#
# def tearDown(self):
# # remove the .syncano file
# if os.path.isfile(ACCOUNT_CONFIG_PATH):
# os.remove(ACCOUNT_CONFIG_PATH)
# self.assertFalse(os.path.isfile(ACCOUNT_CONFIG_PATH))
#
# def assert_file_exists(self, path):
# self.assertTrue(os.path.isfile(path))
#
# def assert_config_variable_exists(self, config, section, key):
# self.assertTrue(config.get(section, key))
#
# def assert_config_variable_equal(self, config, section, key, value):
# self.assertEqual(config.get(section, key), value)
#
# def assert_class_yml_file(self, unique):
# with open(self.yml_file) as syncano_yml:
# yml_content = yaml.safe_load(syncano_yml)
# self.assertIn('test_class{unique}'.format(unique=unique), yml_content['classes'])
# self.assertIn('test_field{unique}'.format(unique=unique),
# yml_content['classes']['test_class{unique}'.format(unique=unique)]['fields'])
#
# def assert_field_in_schema(self, syncano_class, unique):
# has_field = False
# for field_schema in syncano_class.schema:
# if field_schema['name'] == 'test_field{unique}'.format(unique=unique) and field_schema['type'] == 'string':
# has_field = True
# break
#
# self.assertTrue(has_field)
#
# def assert_script_source(self, script_path, assert_source):
# with open(script_path, 'r+') as f:
# source = f.read()
# self.assertEqual(source, assert_source)
#
# def assert_script_remote(self, script_name, source):
# is_script = False
# check_script = None
# scripts = self.instance.scripts.all()
# for script in scripts:
# if script.label == script_name:
# is_script = True
# check_script = script # be explicit;
# break
# self.assertTrue(is_script)
# self.assertEqual(check_script.source, source)
#
# def get_script_path(self, unique):
# return '{dir_name}{script_name}.py'.format(
# dir_name=self.scripts_dir,
# script_name='script_{unique}'.format(unique=unique)
# )
#
# def modify_yml_file(self, key, object, operation='update'):
# with open(self.yml_file, 'rb') as f:
# yml_syncano = yaml.safe_load(f)
# if operation == 'update':
# yml_syncano[key].update(object)
# elif operation == 'append':
# yml_syncano[key].append(object)
# else:
# raise Exception('not supported operation')
#
# with open(self.yml_file, 'wt') as f:
# f.write(yaml.safe_dump(yml_syncano, default_flow_style=False))
#
# def create_syncano_class(self, unique):
# self.instance.classes.create(
# name='test_class{unique}'.format(unique=unique),
# schema=[
# {'name': 'test_field{unique}'.format(unique=unique), 'type': 'string'}
# ]
# )
#
# def get_class_object_dict(self, unique):
# return {
# 'test_class{unique}'.format(unique=unique): {
# 'fields': {
# 'test_field{unique}'.format(unique=unique): 'string'
# }
# }
# }
#
# def get_syncano_class(self, unique):
# return self.instance.classes.get(name='test_class{unique}'.format(unique=unique))
#
# def create_script(self, unique):
# self.instance.scripts.create(
# runtime_name=RuntimeChoices.PYTHON_V5_0,
# source='print(12)',
# label='script_{unique}'.format(unique=unique)
# )
#
# def create_script_locally(self, source, unique):
# script_path = 'scripts/script_{unique}.py'.format(unique=unique)
# new_script = {
# 'runtime': 'python_library_v5.0',
# 'label': 'script_{unique}'.format(unique=unique),
# 'script': script_path
# }
#
# self.modify_yml_file('scripts', new_script, operation='append')
#
# # create a file also;
# with open(script_path, 'w+') as f:
# f.write(source)
. Output only the next line. | email = 'syncano.bot+977999{}@syncano.com'.format(random.randint(100000, 50000000)) |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
class AccountCommandsTest(BaseCLITest):
def test_register(self):
# remove file with connection data:
if os.path.isfile(ACCOUNT_CONFIG_PATH):
os.remove(ACCOUNT_CONFIG_PATH)
self.assertFalse(os.path.isfile(ACCOUNT_CONFIG_PATH))
# old api key;
<|code_end|>
. Write the next line using the current file imports:
import os
import random
from syncano_cli.config import ACCOUNT_CONFIG, ACCOUNT_CONFIG_PATH
from syncano_cli.main import cli
from tests.base import BaseCLITest
and context from other files:
# Path: syncano_cli/config.py
# ACCOUNT_CONFIG = ConfigParser()
#
# ACCOUNT_CONFIG_PATH = os.path.join(os.path.expanduser('~'), '.syncano')
#
# Path: syncano_cli/main.py
# def main():
#
# Path: tests/base.py
# class BaseCLITest(InstanceMixin, IntegrationTest):
#
# @classmethod
# def setUpClass(cls):
# super(BaseCLITest, cls).setUpClass()
# cls.yml_file = 'syncano.yml'
# cls.scripts_dir = 'scripts/'
#
# def setUp(self):
# self.runner.invoke(cli, args=['login', '--instance-name', self.instance.name], obj={})
# self.assert_config_variable_exists(ACCOUNT_CONFIG, 'DEFAULT', 'key')
# self.assert_config_variable_exists(ACCOUNT_CONFIG, 'DEFAULT', 'instance_name')
#
# def tearDown(self):
# # remove the .syncano file
# if os.path.isfile(ACCOUNT_CONFIG_PATH):
# os.remove(ACCOUNT_CONFIG_PATH)
# self.assertFalse(os.path.isfile(ACCOUNT_CONFIG_PATH))
#
# def assert_file_exists(self, path):
# self.assertTrue(os.path.isfile(path))
#
# def assert_config_variable_exists(self, config, section, key):
# self.assertTrue(config.get(section, key))
#
# def assert_config_variable_equal(self, config, section, key, value):
# self.assertEqual(config.get(section, key), value)
#
# def assert_class_yml_file(self, unique):
# with open(self.yml_file) as syncano_yml:
# yml_content = yaml.safe_load(syncano_yml)
# self.assertIn('test_class{unique}'.format(unique=unique), yml_content['classes'])
# self.assertIn('test_field{unique}'.format(unique=unique),
# yml_content['classes']['test_class{unique}'.format(unique=unique)]['fields'])
#
# def assert_field_in_schema(self, syncano_class, unique):
# has_field = False
# for field_schema in syncano_class.schema:
# if field_schema['name'] == 'test_field{unique}'.format(unique=unique) and field_schema['type'] == 'string':
# has_field = True
# break
#
# self.assertTrue(has_field)
#
# def assert_script_source(self, script_path, assert_source):
# with open(script_path, 'r+') as f:
# source = f.read()
# self.assertEqual(source, assert_source)
#
# def assert_script_remote(self, script_name, source):
# is_script = False
# check_script = None
# scripts = self.instance.scripts.all()
# for script in scripts:
# if script.label == script_name:
# is_script = True
# check_script = script # be explicit;
# break
# self.assertTrue(is_script)
# self.assertEqual(check_script.source, source)
#
# def get_script_path(self, unique):
# return '{dir_name}{script_name}.py'.format(
# dir_name=self.scripts_dir,
# script_name='script_{unique}'.format(unique=unique)
# )
#
# def modify_yml_file(self, key, object, operation='update'):
# with open(self.yml_file, 'rb') as f:
# yml_syncano = yaml.safe_load(f)
# if operation == 'update':
# yml_syncano[key].update(object)
# elif operation == 'append':
# yml_syncano[key].append(object)
# else:
# raise Exception('not supported operation')
#
# with open(self.yml_file, 'wt') as f:
# f.write(yaml.safe_dump(yml_syncano, default_flow_style=False))
#
# def create_syncano_class(self, unique):
# self.instance.classes.create(
# name='test_class{unique}'.format(unique=unique),
# schema=[
# {'name': 'test_field{unique}'.format(unique=unique), 'type': 'string'}
# ]
# )
#
# def get_class_object_dict(self, unique):
# return {
# 'test_class{unique}'.format(unique=unique): {
# 'fields': {
# 'test_field{unique}'.format(unique=unique): 'string'
# }
# }
# }
#
# def get_syncano_class(self, unique):
# return self.instance.classes.get(name='test_class{unique}'.format(unique=unique))
#
# def create_script(self, unique):
# self.instance.scripts.create(
# runtime_name=RuntimeChoices.PYTHON_V5_0,
# source='print(12)',
# label='script_{unique}'.format(unique=unique)
# )
#
# def create_script_locally(self, source, unique):
# script_path = 'scripts/script_{unique}.py'.format(unique=unique)
# new_script = {
# 'runtime': 'python_library_v5.0',
# 'label': 'script_{unique}'.format(unique=unique),
# 'script': script_path
# }
#
# self.modify_yml_file('scripts', new_script, operation='append')
#
# # create a file also;
# with open(script_path, 'w+') as f:
# f.write(source)
, which may include functions, classes, or code. Output only the next line. | old_key = self.connection.connection().api_key |
Here is a snippet: <|code_start|># Copyright 2021 Google LLC
#
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file or at
# https://developers.google.com/open-source/licenses/bsd
class TestUtils(SpannerSimpleTestClass):
SQL_WITH_WHERE = "Select 1 from Table WHERE 1=1"
SQL_WITHOUT_WHERE = "Select 1 from Table"
# Only active LTS django versions (2.2.*, 3.2.*) are supported by this library right now.
<|code_end|>
. Write the next line using the current file imports:
from django_spanner.utils import check_django_compatability
from django.core.exceptions import ImproperlyConfigured
from django_spanner.utils import add_dummy_where
from tests.unit.django_spanner.simple_test import SpannerSimpleTestClass
import django
import django_spanner
and context from other files:
# Path: django_spanner/utils.py
# def check_django_compatability(supported_django_versions):
# """
# Verify that this version of django-spanner is compatible with the installed
# version of Django. For example, django-spanner is compatible
# with Django 2.2.y and 3.2.z
# """
# from . import __version__
#
# if django.VERSION[:2] not in supported_django_versions:
# raise ImproperlyConfigured(
# "You must use the latest version of django-spanner {A}.{B}.x "
# "with Django {A}.{B}.y (found django-spanner {C}).".format(
# A=django.VERSION[0], B=django.VERSION[1], C=__version__
# )
# )
#
# Path: django_spanner/utils.py
# def add_dummy_where(sql):
# """
# Cloud Spanner requires a WHERE clause on UPDATE and DELETE statements.
# Add a dummy WHERE clause if necessary.
#
# :type sql: str
# :param sql: A SQL statement.
#
# :rtype: str
# :returns: A SQL statement with dummy WHERE clause.
# """
# if any(
# isinstance(token, sqlparse.sql.Where)
# for token in sqlparse.parse(sql)[0]
# ):
# return sql
#
# return sql + " WHERE 1=1"
#
# Path: tests/unit/django_spanner/simple_test.py
# class SpannerSimpleTestClass(OpenTelemetryBase):
# @classmethod
# def setUpClass(cls):
# super(SpannerSimpleTestClass, cls).setUpClass()
# cls.PROJECT = os.environ["GOOGLE_CLOUD_PROJECT"]
#
# cls.INSTANCE_ID = "instance_id"
# cls.DATABASE_ID = "database_id"
# cls.USER_AGENT = "django_spanner/2.2.0a1"
# cls.OPTIONS = {"option": "dummy"}
#
# cls.settings_dict = {
# "PROJECT": cls.PROJECT,
# "INSTANCE": cls.INSTANCE_ID,
# "NAME": cls.DATABASE_ID,
# "user_agent": cls.USER_AGENT,
# "OPTIONS": cls.OPTIONS,
# }
# cls.db_client = DatabaseClient(cls.settings_dict)
# cls.db_wrapper = cls.connection = DatabaseWrapper(cls.settings_dict)
# cls.db_operations = DatabaseOperations(cls.connection)
, which may include functions, classes, or code. Output only the next line. | SUPPORTED_DJANGO_VERSIONS = [(2, 2), (3, 2)] |
Predict the next line after this snippet: <|code_start|># Copyright 2021 Google LLC
#
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file or at
# https://developers.google.com/open-source/licenses/bsd
class TestQueries(TransactionTestCase):
@classmethod
def setUpClass(cls):
setup_instance()
setup_database()
<|code_end|>
using the current file's imports:
from .models import Author
from django.test import TransactionTestCase
from django.db import connection
from decimal import Decimal
from .utils import (
setup_instance,
teardown_instance,
setup_database,
teardown_database,
)
and any relevant context from other files:
# Path: tests/system/django_spanner/models.py
# class Author(models.Model):
# first_name = models.CharField(max_length=20)
# last_name = models.CharField(max_length=20)
# rating = models.DecimalField()
#
# Path: tests/system/django_spanner/utils.py
# def setup_instance():
# if USE_EMULATOR:
# from google.auth.credentials import AnonymousCredentials
#
# Config.CLIENT = Client(
# project=PROJECT_ID, credentials=AnonymousCredentials()
# )
# else:
# Config.CLIENT = Client()
#
# retry = RetryErrors(exceptions.ServiceUnavailable)
#
# configs = list(retry(Config.CLIENT.list_instance_configs)())
#
# instances = retry(_list_instances)()
# EXISTING_INSTANCES[:] = instances
#
# # Delete test instances that are older than an hour.
# cutoff = int(time.time()) - 1 * 60 * 60
# instance_pbs = Config.CLIENT.list_instances(
# "labels.python-spanner-systests:true"
# )
# for instance_pb in instance_pbs:
# instance = Instance.from_pb(instance_pb, Config.CLIENT)
# if "created" not in instance.labels:
# continue
# create_time = int(instance.labels["created"])
# if create_time > cutoff:
# continue
# if not USE_EMULATOR:
# # Instance cannot be deleted while backups exist.
# for backup_pb in instance.list_backups():
# backup = Backup.from_pb(backup_pb, instance)
# backup.delete()
# instance.delete()
#
# if CREATE_INSTANCE:
# if not USE_EMULATOR:
# # Defend against back-end returning configs for regions we aren't
# # actually allowed to use.
# configs = [config for config in configs if "-us-" in config.name]
#
# if not configs:
# raise ValueError("List instance configs failed in module set up.")
#
# Config.INSTANCE_CONFIG = configs[0]
# config_name = configs[0].name
# create_time = str(int(time.time()))
# labels = {"django-spanner-systests": "true", "created": create_time}
#
# Config.INSTANCE = Config.CLIENT.instance(
# INSTANCE_ID, config_name, labels=labels
# )
# if not Config.INSTANCE.exists():
# created_op = Config.INSTANCE.create()
# created_op.result(
# SPANNER_OPERATION_TIMEOUT_IN_SECONDS
# ) # block until completion
# else:
# Config.INSTANCE.reload()
#
# else:
# Config.INSTANCE = Config.CLIENT.instance(INSTANCE_ID)
# Config.INSTANCE.reload()
#
# def teardown_instance():
# if CREATE_INSTANCE:
# Config.INSTANCE.delete()
#
# def setup_database():
# Config.DATABASE = Config.INSTANCE.database(DATABASE_NAME)
# if not Config.DATABASE.exists():
# creation = DatabaseCreation(connection)
# creation._create_test_db(verbosity=0, autoclobber=False, keepdb=True)
#
# # Running migrations on the db.
# call_command("migrate", interactive=False)
#
# def teardown_database():
# Config.DATABASE = Config.INSTANCE.database(DATABASE_NAME)
# if Config.DATABASE.exists():
# Config.DATABASE.drop()
. Output only the next line. | with connection.schema_editor() as editor: |
Predict the next line for this snippet: <|code_start|># Copyright 2021 Google LLC
#
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file or at
# https://developers.google.com/open-source/licenses/bsd
class TestQueries(TransactionTestCase):
@classmethod
def setUpClass(cls):
setup_instance()
setup_database()
with connection.schema_editor() as editor:
# Create the tables
editor.create_model(Author)
@classmethod
def tearDownClass(cls):
with connection.schema_editor() as editor:
# delete the table
editor.delete_model(Author)
teardown_database()
teardown_instance()
<|code_end|>
with the help of current file imports:
from .models import Author
from django.test import TransactionTestCase
from django.db import connection
from decimal import Decimal
from .utils import (
setup_instance,
teardown_instance,
setup_database,
teardown_database,
)
and context from other files:
# Path: tests/system/django_spanner/models.py
# class Author(models.Model):
# first_name = models.CharField(max_length=20)
# last_name = models.CharField(max_length=20)
# rating = models.DecimalField()
#
# Path: tests/system/django_spanner/utils.py
# def setup_instance():
# if USE_EMULATOR:
# from google.auth.credentials import AnonymousCredentials
#
# Config.CLIENT = Client(
# project=PROJECT_ID, credentials=AnonymousCredentials()
# )
# else:
# Config.CLIENT = Client()
#
# retry = RetryErrors(exceptions.ServiceUnavailable)
#
# configs = list(retry(Config.CLIENT.list_instance_configs)())
#
# instances = retry(_list_instances)()
# EXISTING_INSTANCES[:] = instances
#
# # Delete test instances that are older than an hour.
# cutoff = int(time.time()) - 1 * 60 * 60
# instance_pbs = Config.CLIENT.list_instances(
# "labels.python-spanner-systests:true"
# )
# for instance_pb in instance_pbs:
# instance = Instance.from_pb(instance_pb, Config.CLIENT)
# if "created" not in instance.labels:
# continue
# create_time = int(instance.labels["created"])
# if create_time > cutoff:
# continue
# if not USE_EMULATOR:
# # Instance cannot be deleted while backups exist.
# for backup_pb in instance.list_backups():
# backup = Backup.from_pb(backup_pb, instance)
# backup.delete()
# instance.delete()
#
# if CREATE_INSTANCE:
# if not USE_EMULATOR:
# # Defend against back-end returning configs for regions we aren't
# # actually allowed to use.
# configs = [config for config in configs if "-us-" in config.name]
#
# if not configs:
# raise ValueError("List instance configs failed in module set up.")
#
# Config.INSTANCE_CONFIG = configs[0]
# config_name = configs[0].name
# create_time = str(int(time.time()))
# labels = {"django-spanner-systests": "true", "created": create_time}
#
# Config.INSTANCE = Config.CLIENT.instance(
# INSTANCE_ID, config_name, labels=labels
# )
# if not Config.INSTANCE.exists():
# created_op = Config.INSTANCE.create()
# created_op.result(
# SPANNER_OPERATION_TIMEOUT_IN_SECONDS
# ) # block until completion
# else:
# Config.INSTANCE.reload()
#
# else:
# Config.INSTANCE = Config.CLIENT.instance(INSTANCE_ID)
# Config.INSTANCE.reload()
#
# def teardown_instance():
# if CREATE_INSTANCE:
# Config.INSTANCE.delete()
#
# def setup_database():
# Config.DATABASE = Config.INSTANCE.database(DATABASE_NAME)
# if not Config.DATABASE.exists():
# creation = DatabaseCreation(connection)
# creation._create_test_db(verbosity=0, autoclobber=False, keepdb=True)
#
# # Running migrations on the db.
# call_command("migrate", interactive=False)
#
# def teardown_database():
# Config.DATABASE = Config.INSTANCE.database(DATABASE_NAME)
# if Config.DATABASE.exists():
# Config.DATABASE.drop()
, which may contain function names, class names, or code. Output only the next line. | def test_insert_and_fetch_value(self): |
Next line prediction: <|code_start|># Copyright 2021 Google LLC
#
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file or at
# https://developers.google.com/open-source/licenses/bsd
class TestQueries(TransactionTestCase):
@classmethod
def setUpClass(cls):
setup_instance()
setup_database()
with connection.schema_editor() as editor:
# Create the tables
editor.create_model(Author)
@classmethod
def tearDownClass(cls):
with connection.schema_editor() as editor:
# delete the table
editor.delete_model(Author)
teardown_database()
teardown_instance()
<|code_end|>
. Use current file imports:
(from .models import Author
from django.test import TransactionTestCase
from django.db import connection
from decimal import Decimal
from .utils import (
setup_instance,
teardown_instance,
setup_database,
teardown_database,
))
and context including class names, function names, or small code snippets from other files:
# Path: tests/system/django_spanner/models.py
# class Author(models.Model):
# first_name = models.CharField(max_length=20)
# last_name = models.CharField(max_length=20)
# rating = models.DecimalField()
#
# Path: tests/system/django_spanner/utils.py
# def setup_instance():
# if USE_EMULATOR:
# from google.auth.credentials import AnonymousCredentials
#
# Config.CLIENT = Client(
# project=PROJECT_ID, credentials=AnonymousCredentials()
# )
# else:
# Config.CLIENT = Client()
#
# retry = RetryErrors(exceptions.ServiceUnavailable)
#
# configs = list(retry(Config.CLIENT.list_instance_configs)())
#
# instances = retry(_list_instances)()
# EXISTING_INSTANCES[:] = instances
#
# # Delete test instances that are older than an hour.
# cutoff = int(time.time()) - 1 * 60 * 60
# instance_pbs = Config.CLIENT.list_instances(
# "labels.python-spanner-systests:true"
# )
# for instance_pb in instance_pbs:
# instance = Instance.from_pb(instance_pb, Config.CLIENT)
# if "created" not in instance.labels:
# continue
# create_time = int(instance.labels["created"])
# if create_time > cutoff:
# continue
# if not USE_EMULATOR:
# # Instance cannot be deleted while backups exist.
# for backup_pb in instance.list_backups():
# backup = Backup.from_pb(backup_pb, instance)
# backup.delete()
# instance.delete()
#
# if CREATE_INSTANCE:
# if not USE_EMULATOR:
# # Defend against back-end returning configs for regions we aren't
# # actually allowed to use.
# configs = [config for config in configs if "-us-" in config.name]
#
# if not configs:
# raise ValueError("List instance configs failed in module set up.")
#
# Config.INSTANCE_CONFIG = configs[0]
# config_name = configs[0].name
# create_time = str(int(time.time()))
# labels = {"django-spanner-systests": "true", "created": create_time}
#
# Config.INSTANCE = Config.CLIENT.instance(
# INSTANCE_ID, config_name, labels=labels
# )
# if not Config.INSTANCE.exists():
# created_op = Config.INSTANCE.create()
# created_op.result(
# SPANNER_OPERATION_TIMEOUT_IN_SECONDS
# ) # block until completion
# else:
# Config.INSTANCE.reload()
#
# else:
# Config.INSTANCE = Config.CLIENT.instance(INSTANCE_ID)
# Config.INSTANCE.reload()
#
# def teardown_instance():
# if CREATE_INSTANCE:
# Config.INSTANCE.delete()
#
# def setup_database():
# Config.DATABASE = Config.INSTANCE.database(DATABASE_NAME)
# if not Config.DATABASE.exists():
# creation = DatabaseCreation(connection)
# creation._create_test_db(verbosity=0, autoclobber=False, keepdb=True)
#
# # Running migrations on the db.
# call_command("migrate", interactive=False)
#
# def teardown_database():
# Config.DATABASE = Config.INSTANCE.database(DATABASE_NAME)
# if Config.DATABASE.exists():
# Config.DATABASE.drop()
. Output only the next line. | def test_insert_and_fetch_value(self): |
Given the code snippet: <|code_start|> self.assertEqual(span.name, "CloudSpannerDjango.Test")
self.assertEqual(span.status.status_code, StatusCode.OK)
def test_trace_error(self):
extra_attributes = {"db.instance": "database_name"}
expected_attributes = {
"db.type": "spanner",
"db.engine": "django_spanner",
"db.project": os.environ["GOOGLE_CLOUD_PROJECT"],
"db.instance": "instance_id",
"db.name": "database_id",
}
expected_attributes.update(extra_attributes)
with self.assertRaises(GoogleAPICallError):
with _opentelemetry_tracing.trace_call(
"CloudSpannerDjango.Test",
_make_connection(),
extra_attributes,
) as span:
raise _make_rpc_error(InvalidArgument)
span_list = self.ot_exporter.get_finished_spans()
self.assertEqual(len(span_list), 1)
span = span_list[0]
self.assertEqual(span.kind, trace_api.SpanKind.CLIENT)
self.assertEqual(dict(span.attributes), expected_attributes)
self.assertEqual(span.name, "CloudSpannerDjango.Test")
<|code_end|>
, generate the next line using the imports in this file:
import importlib
import mock
import unittest
import sys
import os
import grpc
from opentelemetry import trace as trace_api
from opentelemetry.trace.status import StatusCode
from google.api_core.exceptions import GoogleAPICallError
from django_spanner import _opentelemetry_tracing
from tests._helpers import OpenTelemetryBase, HAS_OPENTELEMETRY_INSTALLED
from django_spanner.base import DatabaseWrapper
from google.api_core.exceptions import InvalidArgument
and context (functions, classes, or occasionally code) from other files:
# Path: django_spanner/_opentelemetry_tracing.py
# HAS_OPENTELEMETRY_INSTALLED = True
# HAS_OPENTELEMETRY_INSTALLED = False
# def trace_call(name, connection, extra_attributes=None):
#
# Path: tests/_helpers.py
# class OpenTelemetryBase(unittest.TestCase):
# @classmethod
# def setUpClass(cls):
# if HAS_OPENTELEMETRY_INSTALLED:
# use_test_ot_exporter()
# cls.ot_exporter = get_test_ot_exporter()
#
# def tearDown(self):
# if HAS_OPENTELEMETRY_INSTALLED:
# self.ot_exporter.clear()
#
# def assertNoSpans(self):
# if HAS_OPENTELEMETRY_INSTALLED:
# span_list = self.ot_exporter.get_finished_spans()
# self.assertEqual(len(span_list), 0)
#
# def assertSpanAttributes(
# self, name, status=StatusCode.OK, attributes=None, span=None
# ):
# if HAS_OPENTELEMETRY_INSTALLED:
# if not span:
# span_list = self.ot_exporter.get_finished_spans()
# self.assertEqual(len(span_list), 1)
# span = span_list[0]
#
# self.assertEqual(span.name, name)
# self.assertEqual(span.status.status_code, status)
# self.assertEqual(dict(span.attributes), attributes)
#
# HAS_OPENTELEMETRY_INSTALLED = True
. Output only the next line. | self.assertEqual(span.status.status_code, StatusCode.ERROR) |
Using the snippet: <|code_start|># Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file or at
# https://developers.google.com/open-source/licenses/bsd
try:
except ImportError:
pass
PROJECT = os.environ["GOOGLE_CLOUD_PROJECT"]
INSTANCE_ID = "instance_id"
DATABASE_ID = "database_id"
OPTIONS = {"option": "dummy"}
def _make_rpc_error(error_cls, trailing_metadata=None):
grpc_error = mock.create_autospec(grpc.Call, instance=True)
grpc_error.trailing_metadata.return_value = trailing_metadata
return error_cls("error", errors=(grpc_error,))
def _make_connection():
settings_dict = {
"PROJECT": PROJECT,
"INSTANCE": INSTANCE_ID,
"NAME": DATABASE_ID,
<|code_end|>
, determine the next line of code. You have imports:
import importlib
import mock
import unittest
import sys
import os
import grpc
from opentelemetry import trace as trace_api
from opentelemetry.trace.status import StatusCode
from google.api_core.exceptions import GoogleAPICallError
from django_spanner import _opentelemetry_tracing
from tests._helpers import OpenTelemetryBase, HAS_OPENTELEMETRY_INSTALLED
from django_spanner.base import DatabaseWrapper
from google.api_core.exceptions import InvalidArgument
and context (class names, function names, or code) available:
# Path: django_spanner/_opentelemetry_tracing.py
# HAS_OPENTELEMETRY_INSTALLED = True
# HAS_OPENTELEMETRY_INSTALLED = False
# def trace_call(name, connection, extra_attributes=None):
#
# Path: tests/_helpers.py
# class OpenTelemetryBase(unittest.TestCase):
# @classmethod
# def setUpClass(cls):
# if HAS_OPENTELEMETRY_INSTALLED:
# use_test_ot_exporter()
# cls.ot_exporter = get_test_ot_exporter()
#
# def tearDown(self):
# if HAS_OPENTELEMETRY_INSTALLED:
# self.ot_exporter.clear()
#
# def assertNoSpans(self):
# if HAS_OPENTELEMETRY_INSTALLED:
# span_list = self.ot_exporter.get_finished_spans()
# self.assertEqual(len(span_list), 0)
#
# def assertSpanAttributes(
# self, name, status=StatusCode.OK, attributes=None, span=None
# ):
# if HAS_OPENTELEMETRY_INSTALLED:
# if not span:
# span_list = self.ot_exporter.get_finished_spans()
# self.assertEqual(len(span_list), 1)
# span = span_list[0]
#
# self.assertEqual(span.name, name)
# self.assertEqual(span.status.status_code, status)
# self.assertEqual(dict(span.attributes), attributes)
#
# HAS_OPENTELEMETRY_INSTALLED = True
. Output only the next line. | "OPTIONS": OPTIONS, |
Next line prediction: <|code_start|># Copyright 2021 Google LLC
#
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file or at
# https://developers.google.com/open-source/licenses/bsd
try:
except ImportError:
pass
PROJECT = os.environ["GOOGLE_CLOUD_PROJECT"]
<|code_end|>
. Use current file imports:
(import importlib
import mock
import unittest
import sys
import os
import grpc
from opentelemetry import trace as trace_api
from opentelemetry.trace.status import StatusCode
from google.api_core.exceptions import GoogleAPICallError
from django_spanner import _opentelemetry_tracing
from tests._helpers import OpenTelemetryBase, HAS_OPENTELEMETRY_INSTALLED
from django_spanner.base import DatabaseWrapper
from google.api_core.exceptions import InvalidArgument)
and context including class names, function names, or small code snippets from other files:
# Path: django_spanner/_opentelemetry_tracing.py
# HAS_OPENTELEMETRY_INSTALLED = True
# HAS_OPENTELEMETRY_INSTALLED = False
# def trace_call(name, connection, extra_attributes=None):
#
# Path: tests/_helpers.py
# class OpenTelemetryBase(unittest.TestCase):
# @classmethod
# def setUpClass(cls):
# if HAS_OPENTELEMETRY_INSTALLED:
# use_test_ot_exporter()
# cls.ot_exporter = get_test_ot_exporter()
#
# def tearDown(self):
# if HAS_OPENTELEMETRY_INSTALLED:
# self.ot_exporter.clear()
#
# def assertNoSpans(self):
# if HAS_OPENTELEMETRY_INSTALLED:
# span_list = self.ot_exporter.get_finished_spans()
# self.assertEqual(len(span_list), 0)
#
# def assertSpanAttributes(
# self, name, status=StatusCode.OK, attributes=None, span=None
# ):
# if HAS_OPENTELEMETRY_INSTALLED:
# if not span:
# span_list = self.ot_exporter.get_finished_spans()
# self.assertEqual(len(span_list), 1)
# span = span_list[0]
#
# self.assertEqual(span.name, name)
# self.assertEqual(span.status.status_code, status)
# self.assertEqual(dict(span.attributes), attributes)
#
# HAS_OPENTELEMETRY_INSTALLED = True
. Output only the next line. | INSTANCE_ID = "instance_id" |
Given the code snippet: <|code_start|> def test_bulk_batch_size(self):
self.assertEqual(
self.db_operations.bulk_batch_size(fields=None, objs=None),
self.db_operations.connection.features.max_query_params,
)
def test_sql_flush(self):
self.assertEqual(
self.db_operations.sql_flush(
style=no_style(), tables=["Table1", "Table2"]
),
["DELETE FROM Table1", "DELETE FROM Table2"],
)
def test_sql_flush_empty_table_list(self):
self.assertEqual(
self.db_operations.sql_flush(style=no_style(), tables=[]), [],
)
def test_adapt_datefield_value(self):
self.assertIsInstance(
self.db_operations.adapt_datefield_value("dummy_date"), DateStr,
)
def test_adapt_datefield_value_none(self):
self.assertIsNone(
self.db_operations.adapt_datefield_value(value=None),
)
def test_adapt_decimalfield_value(self):
<|code_end|>
, generate the next line using the imports in this file:
from base64 import b64encode
from datetime import timedelta
from decimal import Decimal
from django.conf import settings
from django.core.management.color import no_style
from django.db.utils import DatabaseError
from google.cloud.spanner_dbapi.types import DateStr
from tests.unit.django_spanner.simple_test import SpannerSimpleTestClass
import uuid
and context (functions, classes, or occasionally code) from other files:
# Path: tests/unit/django_spanner/simple_test.py
# class SpannerSimpleTestClass(OpenTelemetryBase):
# @classmethod
# def setUpClass(cls):
# super(SpannerSimpleTestClass, cls).setUpClass()
# cls.PROJECT = os.environ["GOOGLE_CLOUD_PROJECT"]
#
# cls.INSTANCE_ID = "instance_id"
# cls.DATABASE_ID = "database_id"
# cls.USER_AGENT = "django_spanner/2.2.0a1"
# cls.OPTIONS = {"option": "dummy"}
#
# cls.settings_dict = {
# "PROJECT": cls.PROJECT,
# "INSTANCE": cls.INSTANCE_ID,
# "NAME": cls.DATABASE_ID,
# "user_agent": cls.USER_AGENT,
# "OPTIONS": cls.OPTIONS,
# }
# cls.db_client = DatabaseClient(cls.settings_dict)
# cls.db_wrapper = cls.connection = DatabaseWrapper(cls.settings_dict)
# cls.db_operations = DatabaseOperations(cls.connection)
. Output only the next line. | self.assertIsInstance( |
Predict the next line for this snippet: <|code_start|># Copyright 2021 Google LLC
#
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file or at
# https://developers.google.com/open-source/licenses/bsd
class TestExpressions(SpannerSimpleTestClass):
def test_order_by_sql_query_with_order_by_null_last(self):
qs1 = Report.objects.values("name").order_by(
F("name").desc(nulls_last=True)
)
compiler = SQLCompiler(qs1.query, self.connection, "default")
sql_compiled, _ = compiler.as_sql()
self.assertEqual(
sql_compiled,
"SELECT tests_report.name FROM tests_report ORDER BY "
+ "tests_report.name IS NULL, tests_report.name DESC",
)
def test_order_by_sql_query_with_order_by_null_first(self):
qs1 = Report.objects.values("name").order_by(
F("name").desc(nulls_first=True)
<|code_end|>
with the help of current file imports:
from django_spanner.compiler import SQLCompiler
from django.db.models import F
from tests.unit.django_spanner.simple_test import SpannerSimpleTestClass
from .models import Report
and context from other files:
# Path: django_spanner/compiler.py
# class SQLCompiler(BaseSQLCompiler):
# """
# A variation of the Django SQL compiler, adjusted for Spanner-specific
# functionality.
# """
#
# def get_combinator_sql(self, combinator, all):
# """Override the native Django method.
#
# Copied from the base class except for:
# combinator_sql += ' ALL' if all else ' DISTINCT'
# Cloud Spanner requires ALL or DISTINCT.
#
# :type combinator: str
# :param combinator: A type of the combinator for the operation.
#
# :type all: bool
# :param all: Bool option for the SQL statement.
#
# :rtype: tuple
# :returns: A tuple containing SQL statement(s) with some additional
# parameters.
# """
# features = self.connection.features
# compilers = [
# query.get_compiler(self.using, self.connection)
# for query in self.query.combined_queries
# if not query.is_empty()
# ]
# if not features.supports_slicing_ordering_in_compound:
# for query, compiler in zip(self.query.combined_queries, compilers):
# if query.low_mark or query.high_mark:
# raise DatabaseError(
# "LIMIT/OFFSET not allowed in subqueries of compound "
# "statements."
# )
# if compiler.get_order_by():
# raise DatabaseError(
# "ORDER BY not allowed in subqueries of compound "
# "statements."
# )
# parts = ()
# for compiler in compilers:
# try:
# # If the columns list is limited, then all combined queries
# # must have the same columns list. Set the selects defined on
# # the query on all combined queries, if not already set.
# if (
# not compiler.query.values_select
# and self.query.values_select
# ):
# compiler.query.set_values(
# (
# *self.query.extra_select,
# *self.query.values_select,
# *self.query.annotation_select,
# )
# )
# part_sql, part_args = compiler.as_sql()
# if compiler.query.combinator:
# # Wrap in a subquery if wrapping in parentheses isn't
# # supported.
# if not features.supports_parentheses_in_compound:
# part_sql = "SELECT * FROM ({})".format(part_sql)
# # Add parentheses when combining with compound query if not
# # already added for all compound queries.
# elif not features.supports_slicing_ordering_in_compound:
# part_sql = "({})".format(part_sql)
# parts += ((part_sql, part_args),)
# except EmptyResultSet:
# # Omit the empty queryset with UNION and with DIFFERENCE if the
# # first queryset is nonempty.
# if combinator == "union" or (
# combinator == "difference" and parts
# ):
# continue
# raise
# if not parts:
# raise EmptyResultSet
# combinator_sql = self.connection.ops.set_operators[combinator]
# combinator_sql += " ALL" if all else " DISTINCT"
# braces = (
# "({})" if features.supports_slicing_ordering_in_compound else "{}"
# )
# sql_parts, args_parts = zip(
# *((braces.format(sql), args) for sql, args in parts)
# )
# result = [" {} ".format(combinator_sql).join(sql_parts)]
# params = []
# for part in args_parts:
# params.extend(part)
#
# return result, params
#
# Path: tests/unit/django_spanner/simple_test.py
# class SpannerSimpleTestClass(OpenTelemetryBase):
# @classmethod
# def setUpClass(cls):
# super(SpannerSimpleTestClass, cls).setUpClass()
# cls.PROJECT = os.environ["GOOGLE_CLOUD_PROJECT"]
#
# cls.INSTANCE_ID = "instance_id"
# cls.DATABASE_ID = "database_id"
# cls.USER_AGENT = "django_spanner/2.2.0a1"
# cls.OPTIONS = {"option": "dummy"}
#
# cls.settings_dict = {
# "PROJECT": cls.PROJECT,
# "INSTANCE": cls.INSTANCE_ID,
# "NAME": cls.DATABASE_ID,
# "user_agent": cls.USER_AGENT,
# "OPTIONS": cls.OPTIONS,
# }
# cls.db_client = DatabaseClient(cls.settings_dict)
# cls.db_wrapper = cls.connection = DatabaseWrapper(cls.settings_dict)
# cls.db_operations = DatabaseOperations(cls.connection)
#
# Path: tests/unit/django_spanner/models.py
# class Report(models.Model):
# name = models.CharField(max_length=10)
# creator = models.ForeignKey(Author, models.CASCADE, null=True)
#
# class Meta:
# ordering = ["name"]
, which may contain function names, class names, or code. Output only the next line. | ) |
Here is a snippet: <|code_start|># Copyright 2021 Google LLC
#
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file or at
# https://developers.google.com/open-source/licenses/bsd
class TestExpressions(SpannerSimpleTestClass):
def test_order_by_sql_query_with_order_by_null_last(self):
qs1 = Report.objects.values("name").order_by(
F("name").desc(nulls_last=True)
)
compiler = SQLCompiler(qs1.query, self.connection, "default")
sql_compiled, _ = compiler.as_sql()
self.assertEqual(
sql_compiled,
"SELECT tests_report.name FROM tests_report ORDER BY "
+ "tests_report.name IS NULL, tests_report.name DESC",
)
def test_order_by_sql_query_with_order_by_null_first(self):
qs1 = Report.objects.values("name").order_by(
F("name").desc(nulls_first=True)
)
compiler = SQLCompiler(qs1.query, self.connection, "default")
<|code_end|>
. Write the next line using the current file imports:
from django_spanner.compiler import SQLCompiler
from django.db.models import F
from tests.unit.django_spanner.simple_test import SpannerSimpleTestClass
from .models import Report
and context from other files:
# Path: django_spanner/compiler.py
# class SQLCompiler(BaseSQLCompiler):
# """
# A variation of the Django SQL compiler, adjusted for Spanner-specific
# functionality.
# """
#
# def get_combinator_sql(self, combinator, all):
# """Override the native Django method.
#
# Copied from the base class except for:
# combinator_sql += ' ALL' if all else ' DISTINCT'
# Cloud Spanner requires ALL or DISTINCT.
#
# :type combinator: str
# :param combinator: A type of the combinator for the operation.
#
# :type all: bool
# :param all: Bool option for the SQL statement.
#
# :rtype: tuple
# :returns: A tuple containing SQL statement(s) with some additional
# parameters.
# """
# features = self.connection.features
# compilers = [
# query.get_compiler(self.using, self.connection)
# for query in self.query.combined_queries
# if not query.is_empty()
# ]
# if not features.supports_slicing_ordering_in_compound:
# for query, compiler in zip(self.query.combined_queries, compilers):
# if query.low_mark or query.high_mark:
# raise DatabaseError(
# "LIMIT/OFFSET not allowed in subqueries of compound "
# "statements."
# )
# if compiler.get_order_by():
# raise DatabaseError(
# "ORDER BY not allowed in subqueries of compound "
# "statements."
# )
# parts = ()
# for compiler in compilers:
# try:
# # If the columns list is limited, then all combined queries
# # must have the same columns list. Set the selects defined on
# # the query on all combined queries, if not already set.
# if (
# not compiler.query.values_select
# and self.query.values_select
# ):
# compiler.query.set_values(
# (
# *self.query.extra_select,
# *self.query.values_select,
# *self.query.annotation_select,
# )
# )
# part_sql, part_args = compiler.as_sql()
# if compiler.query.combinator:
# # Wrap in a subquery if wrapping in parentheses isn't
# # supported.
# if not features.supports_parentheses_in_compound:
# part_sql = "SELECT * FROM ({})".format(part_sql)
# # Add parentheses when combining with compound query if not
# # already added for all compound queries.
# elif not features.supports_slicing_ordering_in_compound:
# part_sql = "({})".format(part_sql)
# parts += ((part_sql, part_args),)
# except EmptyResultSet:
# # Omit the empty queryset with UNION and with DIFFERENCE if the
# # first queryset is nonempty.
# if combinator == "union" or (
# combinator == "difference" and parts
# ):
# continue
# raise
# if not parts:
# raise EmptyResultSet
# combinator_sql = self.connection.ops.set_operators[combinator]
# combinator_sql += " ALL" if all else " DISTINCT"
# braces = (
# "({})" if features.supports_slicing_ordering_in_compound else "{}"
# )
# sql_parts, args_parts = zip(
# *((braces.format(sql), args) for sql, args in parts)
# )
# result = [" {} ".format(combinator_sql).join(sql_parts)]
# params = []
# for part in args_parts:
# params.extend(part)
#
# return result, params
#
# Path: tests/unit/django_spanner/simple_test.py
# class SpannerSimpleTestClass(OpenTelemetryBase):
# @classmethod
# def setUpClass(cls):
# super(SpannerSimpleTestClass, cls).setUpClass()
# cls.PROJECT = os.environ["GOOGLE_CLOUD_PROJECT"]
#
# cls.INSTANCE_ID = "instance_id"
# cls.DATABASE_ID = "database_id"
# cls.USER_AGENT = "django_spanner/2.2.0a1"
# cls.OPTIONS = {"option": "dummy"}
#
# cls.settings_dict = {
# "PROJECT": cls.PROJECT,
# "INSTANCE": cls.INSTANCE_ID,
# "NAME": cls.DATABASE_ID,
# "user_agent": cls.USER_AGENT,
# "OPTIONS": cls.OPTIONS,
# }
# cls.db_client = DatabaseClient(cls.settings_dict)
# cls.db_wrapper = cls.connection = DatabaseWrapper(cls.settings_dict)
# cls.db_operations = DatabaseOperations(cls.connection)
#
# Path: tests/unit/django_spanner/models.py
# class Report(models.Model):
# name = models.CharField(max_length=10)
# creator = models.ForeignKey(Author, models.CASCADE, null=True)
#
# class Meta:
# ordering = ["name"]
, which may include functions, classes, or code. Output only the next line. | sql_compiled, _ = compiler.as_sql() |
Continue the code snippet: <|code_start|># Copyright 2021 Google LLC
#
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file or at
# https://developers.google.com/open-source/licenses/bsd
class TestExpressions(SpannerSimpleTestClass):
def test_order_by_sql_query_with_order_by_null_last(self):
qs1 = Report.objects.values("name").order_by(
F("name").desc(nulls_last=True)
)
compiler = SQLCompiler(qs1.query, self.connection, "default")
sql_compiled, _ = compiler.as_sql()
self.assertEqual(
sql_compiled,
<|code_end|>
. Use current file imports:
from django_spanner.compiler import SQLCompiler
from django.db.models import F
from tests.unit.django_spanner.simple_test import SpannerSimpleTestClass
from .models import Report
and context (classes, functions, or code) from other files:
# Path: django_spanner/compiler.py
# class SQLCompiler(BaseSQLCompiler):
# """
# A variation of the Django SQL compiler, adjusted for Spanner-specific
# functionality.
# """
#
# def get_combinator_sql(self, combinator, all):
# """Override the native Django method.
#
# Copied from the base class except for:
# combinator_sql += ' ALL' if all else ' DISTINCT'
# Cloud Spanner requires ALL or DISTINCT.
#
# :type combinator: str
# :param combinator: A type of the combinator for the operation.
#
# :type all: bool
# :param all: Bool option for the SQL statement.
#
# :rtype: tuple
# :returns: A tuple containing SQL statement(s) with some additional
# parameters.
# """
# features = self.connection.features
# compilers = [
# query.get_compiler(self.using, self.connection)
# for query in self.query.combined_queries
# if not query.is_empty()
# ]
# if not features.supports_slicing_ordering_in_compound:
# for query, compiler in zip(self.query.combined_queries, compilers):
# if query.low_mark or query.high_mark:
# raise DatabaseError(
# "LIMIT/OFFSET not allowed in subqueries of compound "
# "statements."
# )
# if compiler.get_order_by():
# raise DatabaseError(
# "ORDER BY not allowed in subqueries of compound "
# "statements."
# )
# parts = ()
# for compiler in compilers:
# try:
# # If the columns list is limited, then all combined queries
# # must have the same columns list. Set the selects defined on
# # the query on all combined queries, if not already set.
# if (
# not compiler.query.values_select
# and self.query.values_select
# ):
# compiler.query.set_values(
# (
# *self.query.extra_select,
# *self.query.values_select,
# *self.query.annotation_select,
# )
# )
# part_sql, part_args = compiler.as_sql()
# if compiler.query.combinator:
# # Wrap in a subquery if wrapping in parentheses isn't
# # supported.
# if not features.supports_parentheses_in_compound:
# part_sql = "SELECT * FROM ({})".format(part_sql)
# # Add parentheses when combining with compound query if not
# # already added for all compound queries.
# elif not features.supports_slicing_ordering_in_compound:
# part_sql = "({})".format(part_sql)
# parts += ((part_sql, part_args),)
# except EmptyResultSet:
# # Omit the empty queryset with UNION and with DIFFERENCE if the
# # first queryset is nonempty.
# if combinator == "union" or (
# combinator == "difference" and parts
# ):
# continue
# raise
# if not parts:
# raise EmptyResultSet
# combinator_sql = self.connection.ops.set_operators[combinator]
# combinator_sql += " ALL" if all else " DISTINCT"
# braces = (
# "({})" if features.supports_slicing_ordering_in_compound else "{}"
# )
# sql_parts, args_parts = zip(
# *((braces.format(sql), args) for sql, args in parts)
# )
# result = [" {} ".format(combinator_sql).join(sql_parts)]
# params = []
# for part in args_parts:
# params.extend(part)
#
# return result, params
#
# Path: tests/unit/django_spanner/simple_test.py
# class SpannerSimpleTestClass(OpenTelemetryBase):
# @classmethod
# def setUpClass(cls):
# super(SpannerSimpleTestClass, cls).setUpClass()
# cls.PROJECT = os.environ["GOOGLE_CLOUD_PROJECT"]
#
# cls.INSTANCE_ID = "instance_id"
# cls.DATABASE_ID = "database_id"
# cls.USER_AGENT = "django_spanner/2.2.0a1"
# cls.OPTIONS = {"option": "dummy"}
#
# cls.settings_dict = {
# "PROJECT": cls.PROJECT,
# "INSTANCE": cls.INSTANCE_ID,
# "NAME": cls.DATABASE_ID,
# "user_agent": cls.USER_AGENT,
# "OPTIONS": cls.OPTIONS,
# }
# cls.db_client = DatabaseClient(cls.settings_dict)
# cls.db_wrapper = cls.connection = DatabaseWrapper(cls.settings_dict)
# cls.db_operations = DatabaseOperations(cls.connection)
#
# Path: tests/unit/django_spanner/models.py
# class Report(models.Model):
# name = models.CharField(max_length=10)
# creator = models.ForeignKey(Author, models.CASCADE, null=True)
#
# class Meta:
# ordering = ["name"]
. Output only the next line. | "SELECT tests_report.name FROM tests_report ORDER BY " |
Continue the code snippet: <|code_start|> mock_instance.assert_called_once_with(self.INSTANCE_ID)
def test_property_nodb_connection(self):
with self.assertRaises(NotImplementedError):
self.db_wrapper._nodb_connection()
def test_get_connection_params(self):
params = self.db_wrapper.get_connection_params()
self.assertEqual(params["project"], self.PROJECT)
self.assertEqual(params["instance_id"], self.INSTANCE_ID)
self.assertEqual(params["database_id"], self.DATABASE_ID)
self.assertEqual(params["user_agent"], self.USER_AGENT)
self.assertEqual(params["option"], self.OPTIONS["option"])
def test_get_new_connection(self):
self.db_wrapper.Database = mock_database = mock.MagicMock()
mock_database.connect = mock_connection = mock.MagicMock()
conn_params = {"test_param": "dummy"}
self.db_wrapper.get_new_connection(conn_params)
mock_connection.assert_called_once_with(**conn_params)
def test_init_connection_state(self):
self.db_wrapper.connection = mock_connection = mock.MagicMock()
mock_connection.close = mock_close = mock.MagicMock()
self.db_wrapper.init_connection_state()
mock_close.assert_called_once_with()
def test_create_cursor(self):
self.db_wrapper.connection = mock_connection = mock.MagicMock()
<|code_end|>
. Use current file imports:
from unittest import mock
from tests.unit.django_spanner.simple_test import SpannerSimpleTestClass
from google.cloud.spanner_dbapi.exceptions import Error
and context (classes, functions, or code) from other files:
# Path: tests/unit/django_spanner/simple_test.py
# class SpannerSimpleTestClass(OpenTelemetryBase):
# @classmethod
# def setUpClass(cls):
# super(SpannerSimpleTestClass, cls).setUpClass()
# cls.PROJECT = os.environ["GOOGLE_CLOUD_PROJECT"]
#
# cls.INSTANCE_ID = "instance_id"
# cls.DATABASE_ID = "database_id"
# cls.USER_AGENT = "django_spanner/2.2.0a1"
# cls.OPTIONS = {"option": "dummy"}
#
# cls.settings_dict = {
# "PROJECT": cls.PROJECT,
# "INSTANCE": cls.INSTANCE_ID,
# "NAME": cls.DATABASE_ID,
# "user_agent": cls.USER_AGENT,
# "OPTIONS": cls.OPTIONS,
# }
# cls.db_client = DatabaseClient(cls.settings_dict)
# cls.db_wrapper = cls.connection = DatabaseWrapper(cls.settings_dict)
# cls.db_operations = DatabaseOperations(cls.connection)
. Output only the next line. | mock_connection.cursor = mock_cursor = mock.MagicMock() |
Next line prediction: <|code_start|> def setUpClass(cls):
setup_instance()
setup_database()
with connection.schema_editor() as editor:
# Create the tables
editor.create_model(Author)
editor.create_model(Number)
@classmethod
def tearDownClass(cls):
with connection.schema_editor() as editor:
# delete the table
editor.delete_model(Author)
editor.delete_model(Number)
teardown_database()
teardown_instance()
def rating_transform(self, value):
return value["rating"]
def values_transform(self, value):
return value.num
def assertValuesEqual(
self, queryset, expected_values, transformer, ordered=True
):
self.assertQuerysetEqual(
queryset, expected_values, transformer, ordered
)
<|code_end|>
. Use current file imports:
(from .models import Author, Number
from django.test import TransactionTestCase
from django.db import connection
from decimal import Decimal
from tests.system.django_spanner.utils import (
setup_instance,
teardown_instance,
setup_database,
teardown_database,
))
and context including class names, function names, or small code snippets from other files:
# Path: tests/system/django_spanner/models.py
# class Author(models.Model):
# first_name = models.CharField(max_length=20)
# last_name = models.CharField(max_length=20)
# rating = models.DecimalField()
#
# class Number(models.Model):
# num = models.DecimalField()
#
# def __str__(self):
# return str(self.num)
#
# Path: tests/system/django_spanner/utils.py
# def setup_instance():
# if USE_EMULATOR:
# from google.auth.credentials import AnonymousCredentials
#
# Config.CLIENT = Client(
# project=PROJECT_ID, credentials=AnonymousCredentials()
# )
# else:
# Config.CLIENT = Client()
#
# retry = RetryErrors(exceptions.ServiceUnavailable)
#
# configs = list(retry(Config.CLIENT.list_instance_configs)())
#
# instances = retry(_list_instances)()
# EXISTING_INSTANCES[:] = instances
#
# # Delete test instances that are older than an hour.
# cutoff = int(time.time()) - 1 * 60 * 60
# instance_pbs = Config.CLIENT.list_instances(
# "labels.python-spanner-systests:true"
# )
# for instance_pb in instance_pbs:
# instance = Instance.from_pb(instance_pb, Config.CLIENT)
# if "created" not in instance.labels:
# continue
# create_time = int(instance.labels["created"])
# if create_time > cutoff:
# continue
# if not USE_EMULATOR:
# # Instance cannot be deleted while backups exist.
# for backup_pb in instance.list_backups():
# backup = Backup.from_pb(backup_pb, instance)
# backup.delete()
# instance.delete()
#
# if CREATE_INSTANCE:
# if not USE_EMULATOR:
# # Defend against back-end returning configs for regions we aren't
# # actually allowed to use.
# configs = [config for config in configs if "-us-" in config.name]
#
# if not configs:
# raise ValueError("List instance configs failed in module set up.")
#
# Config.INSTANCE_CONFIG = configs[0]
# config_name = configs[0].name
# create_time = str(int(time.time()))
# labels = {"django-spanner-systests": "true", "created": create_time}
#
# Config.INSTANCE = Config.CLIENT.instance(
# INSTANCE_ID, config_name, labels=labels
# )
# if not Config.INSTANCE.exists():
# created_op = Config.INSTANCE.create()
# created_op.result(
# SPANNER_OPERATION_TIMEOUT_IN_SECONDS
# ) # block until completion
# else:
# Config.INSTANCE.reload()
#
# else:
# Config.INSTANCE = Config.CLIENT.instance(INSTANCE_ID)
# Config.INSTANCE.reload()
#
# def teardown_instance():
# if CREATE_INSTANCE:
# Config.INSTANCE.delete()
#
# def setup_database():
# Config.DATABASE = Config.INSTANCE.database(DATABASE_NAME)
# if not Config.DATABASE.exists():
# creation = DatabaseCreation(connection)
# creation._create_test_db(verbosity=0, autoclobber=False, keepdb=True)
#
# # Running migrations on the db.
# call_command("migrate", interactive=False)
#
# def teardown_database():
# Config.DATABASE = Config.INSTANCE.database(DATABASE_NAME)
# if Config.DATABASE.exists():
# Config.DATABASE.drop()
. Output only the next line. | def test_insert_and_search_decimal_value(self): |
Continue the code snippet: <|code_start|>class TestDecimal(TransactionTestCase):
@classmethod
def setUpClass(cls):
setup_instance()
setup_database()
with connection.schema_editor() as editor:
# Create the tables
editor.create_model(Author)
editor.create_model(Number)
@classmethod
def tearDownClass(cls):
with connection.schema_editor() as editor:
# delete the table
editor.delete_model(Author)
editor.delete_model(Number)
teardown_database()
teardown_instance()
def rating_transform(self, value):
return value["rating"]
def values_transform(self, value):
return value.num
def assertValuesEqual(
self, queryset, expected_values, transformer, ordered=True
):
self.assertQuerysetEqual(
queryset, expected_values, transformer, ordered
<|code_end|>
. Use current file imports:
from .models import Author, Number
from django.test import TransactionTestCase
from django.db import connection
from decimal import Decimal
from tests.system.django_spanner.utils import (
setup_instance,
teardown_instance,
setup_database,
teardown_database,
)
and context (classes, functions, or code) from other files:
# Path: tests/system/django_spanner/models.py
# class Author(models.Model):
# first_name = models.CharField(max_length=20)
# last_name = models.CharField(max_length=20)
# rating = models.DecimalField()
#
# class Number(models.Model):
# num = models.DecimalField()
#
# def __str__(self):
# return str(self.num)
#
# Path: tests/system/django_spanner/utils.py
# def setup_instance():
# if USE_EMULATOR:
# from google.auth.credentials import AnonymousCredentials
#
# Config.CLIENT = Client(
# project=PROJECT_ID, credentials=AnonymousCredentials()
# )
# else:
# Config.CLIENT = Client()
#
# retry = RetryErrors(exceptions.ServiceUnavailable)
#
# configs = list(retry(Config.CLIENT.list_instance_configs)())
#
# instances = retry(_list_instances)()
# EXISTING_INSTANCES[:] = instances
#
# # Delete test instances that are older than an hour.
# cutoff = int(time.time()) - 1 * 60 * 60
# instance_pbs = Config.CLIENT.list_instances(
# "labels.python-spanner-systests:true"
# )
# for instance_pb in instance_pbs:
# instance = Instance.from_pb(instance_pb, Config.CLIENT)
# if "created" not in instance.labels:
# continue
# create_time = int(instance.labels["created"])
# if create_time > cutoff:
# continue
# if not USE_EMULATOR:
# # Instance cannot be deleted while backups exist.
# for backup_pb in instance.list_backups():
# backup = Backup.from_pb(backup_pb, instance)
# backup.delete()
# instance.delete()
#
# if CREATE_INSTANCE:
# if not USE_EMULATOR:
# # Defend against back-end returning configs for regions we aren't
# # actually allowed to use.
# configs = [config for config in configs if "-us-" in config.name]
#
# if not configs:
# raise ValueError("List instance configs failed in module set up.")
#
# Config.INSTANCE_CONFIG = configs[0]
# config_name = configs[0].name
# create_time = str(int(time.time()))
# labels = {"django-spanner-systests": "true", "created": create_time}
#
# Config.INSTANCE = Config.CLIENT.instance(
# INSTANCE_ID, config_name, labels=labels
# )
# if not Config.INSTANCE.exists():
# created_op = Config.INSTANCE.create()
# created_op.result(
# SPANNER_OPERATION_TIMEOUT_IN_SECONDS
# ) # block until completion
# else:
# Config.INSTANCE.reload()
#
# else:
# Config.INSTANCE = Config.CLIENT.instance(INSTANCE_ID)
# Config.INSTANCE.reload()
#
# def teardown_instance():
# if CREATE_INSTANCE:
# Config.INSTANCE.delete()
#
# def setup_database():
# Config.DATABASE = Config.INSTANCE.database(DATABASE_NAME)
# if not Config.DATABASE.exists():
# creation = DatabaseCreation(connection)
# creation._create_test_db(verbosity=0, autoclobber=False, keepdb=True)
#
# # Running migrations on the db.
# call_command("migrate", interactive=False)
#
# def teardown_database():
# Config.DATABASE = Config.INSTANCE.database(DATABASE_NAME)
# if Config.DATABASE.exists():
# Config.DATABASE.drop()
. Output only the next line. | ) |
Continue the code snippet: <|code_start|> def setUpClass(cls):
setup_instance()
setup_database()
with connection.schema_editor() as editor:
# Create the tables
editor.create_model(Author)
editor.create_model(Number)
@classmethod
def tearDownClass(cls):
with connection.schema_editor() as editor:
# delete the table
editor.delete_model(Author)
editor.delete_model(Number)
teardown_database()
teardown_instance()
def rating_transform(self, value):
return value["rating"]
def values_transform(self, value):
return value.num
def assertValuesEqual(
self, queryset, expected_values, transformer, ordered=True
):
self.assertQuerysetEqual(
queryset, expected_values, transformer, ordered
)
<|code_end|>
. Use current file imports:
from .models import Author, Number
from django.test import TransactionTestCase
from django.db import connection
from decimal import Decimal
from tests.system.django_spanner.utils import (
setup_instance,
teardown_instance,
setup_database,
teardown_database,
)
and context (classes, functions, or code) from other files:
# Path: tests/system/django_spanner/models.py
# class Author(models.Model):
# first_name = models.CharField(max_length=20)
# last_name = models.CharField(max_length=20)
# rating = models.DecimalField()
#
# class Number(models.Model):
# num = models.DecimalField()
#
# def __str__(self):
# return str(self.num)
#
# Path: tests/system/django_spanner/utils.py
# def setup_instance():
# if USE_EMULATOR:
# from google.auth.credentials import AnonymousCredentials
#
# Config.CLIENT = Client(
# project=PROJECT_ID, credentials=AnonymousCredentials()
# )
# else:
# Config.CLIENT = Client()
#
# retry = RetryErrors(exceptions.ServiceUnavailable)
#
# configs = list(retry(Config.CLIENT.list_instance_configs)())
#
# instances = retry(_list_instances)()
# EXISTING_INSTANCES[:] = instances
#
# # Delete test instances that are older than an hour.
# cutoff = int(time.time()) - 1 * 60 * 60
# instance_pbs = Config.CLIENT.list_instances(
# "labels.python-spanner-systests:true"
# )
# for instance_pb in instance_pbs:
# instance = Instance.from_pb(instance_pb, Config.CLIENT)
# if "created" not in instance.labels:
# continue
# create_time = int(instance.labels["created"])
# if create_time > cutoff:
# continue
# if not USE_EMULATOR:
# # Instance cannot be deleted while backups exist.
# for backup_pb in instance.list_backups():
# backup = Backup.from_pb(backup_pb, instance)
# backup.delete()
# instance.delete()
#
# if CREATE_INSTANCE:
# if not USE_EMULATOR:
# # Defend against back-end returning configs for regions we aren't
# # actually allowed to use.
# configs = [config for config in configs if "-us-" in config.name]
#
# if not configs:
# raise ValueError("List instance configs failed in module set up.")
#
# Config.INSTANCE_CONFIG = configs[0]
# config_name = configs[0].name
# create_time = str(int(time.time()))
# labels = {"django-spanner-systests": "true", "created": create_time}
#
# Config.INSTANCE = Config.CLIENT.instance(
# INSTANCE_ID, config_name, labels=labels
# )
# if not Config.INSTANCE.exists():
# created_op = Config.INSTANCE.create()
# created_op.result(
# SPANNER_OPERATION_TIMEOUT_IN_SECONDS
# ) # block until completion
# else:
# Config.INSTANCE.reload()
#
# else:
# Config.INSTANCE = Config.CLIENT.instance(INSTANCE_ID)
# Config.INSTANCE.reload()
#
# def teardown_instance():
# if CREATE_INSTANCE:
# Config.INSTANCE.delete()
#
# def setup_database():
# Config.DATABASE = Config.INSTANCE.database(DATABASE_NAME)
# if not Config.DATABASE.exists():
# creation = DatabaseCreation(connection)
# creation._create_test_db(verbosity=0, autoclobber=False, keepdb=True)
#
# # Running migrations on the db.
# call_command("migrate", interactive=False)
#
# def teardown_database():
# Config.DATABASE = Config.INSTANCE.database(DATABASE_NAME)
# if Config.DATABASE.exists():
# Config.DATABASE.drop()
. Output only the next line. | def test_insert_and_search_decimal_value(self): |
Here is a snippet: <|code_start|># Copyright 2021 Google LLC
#
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file or at
# https://developers.google.com/open-source/licenses/bsd
class TestDecimal(TransactionTestCase):
@classmethod
def setUpClass(cls):
setup_instance()
setup_database()
with connection.schema_editor() as editor:
# Create the tables
editor.create_model(Author)
editor.create_model(Number)
@classmethod
def tearDownClass(cls):
with connection.schema_editor() as editor:
# delete the table
editor.delete_model(Author)
editor.delete_model(Number)
teardown_database()
teardown_instance()
def rating_transform(self, value):
<|code_end|>
. Write the next line using the current file imports:
from .models import Author, Number
from django.test import TransactionTestCase
from django.db import connection
from decimal import Decimal
from tests.system.django_spanner.utils import (
setup_instance,
teardown_instance,
setup_database,
teardown_database,
)
and context from other files:
# Path: tests/system/django_spanner/models.py
# class Author(models.Model):
# first_name = models.CharField(max_length=20)
# last_name = models.CharField(max_length=20)
# rating = models.DecimalField()
#
# class Number(models.Model):
# num = models.DecimalField()
#
# def __str__(self):
# return str(self.num)
#
# Path: tests/system/django_spanner/utils.py
# def setup_instance():
# if USE_EMULATOR:
# from google.auth.credentials import AnonymousCredentials
#
# Config.CLIENT = Client(
# project=PROJECT_ID, credentials=AnonymousCredentials()
# )
# else:
# Config.CLIENT = Client()
#
# retry = RetryErrors(exceptions.ServiceUnavailable)
#
# configs = list(retry(Config.CLIENT.list_instance_configs)())
#
# instances = retry(_list_instances)()
# EXISTING_INSTANCES[:] = instances
#
# # Delete test instances that are older than an hour.
# cutoff = int(time.time()) - 1 * 60 * 60
# instance_pbs = Config.CLIENT.list_instances(
# "labels.python-spanner-systests:true"
# )
# for instance_pb in instance_pbs:
# instance = Instance.from_pb(instance_pb, Config.CLIENT)
# if "created" not in instance.labels:
# continue
# create_time = int(instance.labels["created"])
# if create_time > cutoff:
# continue
# if not USE_EMULATOR:
# # Instance cannot be deleted while backups exist.
# for backup_pb in instance.list_backups():
# backup = Backup.from_pb(backup_pb, instance)
# backup.delete()
# instance.delete()
#
# if CREATE_INSTANCE:
# if not USE_EMULATOR:
# # Defend against back-end returning configs for regions we aren't
# # actually allowed to use.
# configs = [config for config in configs if "-us-" in config.name]
#
# if not configs:
# raise ValueError("List instance configs failed in module set up.")
#
# Config.INSTANCE_CONFIG = configs[0]
# config_name = configs[0].name
# create_time = str(int(time.time()))
# labels = {"django-spanner-systests": "true", "created": create_time}
#
# Config.INSTANCE = Config.CLIENT.instance(
# INSTANCE_ID, config_name, labels=labels
# )
# if not Config.INSTANCE.exists():
# created_op = Config.INSTANCE.create()
# created_op.result(
# SPANNER_OPERATION_TIMEOUT_IN_SECONDS
# ) # block until completion
# else:
# Config.INSTANCE.reload()
#
# else:
# Config.INSTANCE = Config.CLIENT.instance(INSTANCE_ID)
# Config.INSTANCE.reload()
#
# def teardown_instance():
# if CREATE_INSTANCE:
# Config.INSTANCE.delete()
#
# def setup_database():
# Config.DATABASE = Config.INSTANCE.database(DATABASE_NAME)
# if not Config.DATABASE.exists():
# creation = DatabaseCreation(connection)
# creation._create_test_db(verbosity=0, autoclobber=False, keepdb=True)
#
# # Running migrations on the db.
# call_command("migrate", interactive=False)
#
# def teardown_database():
# Config.DATABASE = Config.INSTANCE.database(DATABASE_NAME)
# if Config.DATABASE.exists():
# Config.DATABASE.drop()
, which may include functions, classes, or code. Output only the next line. | return value["rating"] |
Given the following code snippet before the placeholder: <|code_start|># Copyright 2021 Google LLC
#
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file or at
# https://developers.google.com/open-source/licenses/bsd
class TestDecimal(TransactionTestCase):
@classmethod
def setUpClass(cls):
setup_instance()
setup_database()
with connection.schema_editor() as editor:
# Create the tables
editor.create_model(Author)
editor.create_model(Number)
@classmethod
<|code_end|>
, predict the next line using imports from the current file:
from .models import Author, Number
from django.test import TransactionTestCase
from django.db import connection
from decimal import Decimal
from tests.system.django_spanner.utils import (
setup_instance,
teardown_instance,
setup_database,
teardown_database,
)
and context including class names, function names, and sometimes code from other files:
# Path: tests/system/django_spanner/models.py
# class Author(models.Model):
# first_name = models.CharField(max_length=20)
# last_name = models.CharField(max_length=20)
# rating = models.DecimalField()
#
# class Number(models.Model):
# num = models.DecimalField()
#
# def __str__(self):
# return str(self.num)
#
# Path: tests/system/django_spanner/utils.py
# def setup_instance():
# if USE_EMULATOR:
# from google.auth.credentials import AnonymousCredentials
#
# Config.CLIENT = Client(
# project=PROJECT_ID, credentials=AnonymousCredentials()
# )
# else:
# Config.CLIENT = Client()
#
# retry = RetryErrors(exceptions.ServiceUnavailable)
#
# configs = list(retry(Config.CLIENT.list_instance_configs)())
#
# instances = retry(_list_instances)()
# EXISTING_INSTANCES[:] = instances
#
# # Delete test instances that are older than an hour.
# cutoff = int(time.time()) - 1 * 60 * 60
# instance_pbs = Config.CLIENT.list_instances(
# "labels.python-spanner-systests:true"
# )
# for instance_pb in instance_pbs:
# instance = Instance.from_pb(instance_pb, Config.CLIENT)
# if "created" not in instance.labels:
# continue
# create_time = int(instance.labels["created"])
# if create_time > cutoff:
# continue
# if not USE_EMULATOR:
# # Instance cannot be deleted while backups exist.
# for backup_pb in instance.list_backups():
# backup = Backup.from_pb(backup_pb, instance)
# backup.delete()
# instance.delete()
#
# if CREATE_INSTANCE:
# if not USE_EMULATOR:
# # Defend against back-end returning configs for regions we aren't
# # actually allowed to use.
# configs = [config for config in configs if "-us-" in config.name]
#
# if not configs:
# raise ValueError("List instance configs failed in module set up.")
#
# Config.INSTANCE_CONFIG = configs[0]
# config_name = configs[0].name
# create_time = str(int(time.time()))
# labels = {"django-spanner-systests": "true", "created": create_time}
#
# Config.INSTANCE = Config.CLIENT.instance(
# INSTANCE_ID, config_name, labels=labels
# )
# if not Config.INSTANCE.exists():
# created_op = Config.INSTANCE.create()
# created_op.result(
# SPANNER_OPERATION_TIMEOUT_IN_SECONDS
# ) # block until completion
# else:
# Config.INSTANCE.reload()
#
# else:
# Config.INSTANCE = Config.CLIENT.instance(INSTANCE_ID)
# Config.INSTANCE.reload()
#
# def teardown_instance():
# if CREATE_INSTANCE:
# Config.INSTANCE.delete()
#
# def setup_database():
# Config.DATABASE = Config.INSTANCE.database(DATABASE_NAME)
# if not Config.DATABASE.exists():
# creation = DatabaseCreation(connection)
# creation._create_test_db(verbosity=0, autoclobber=False, keepdb=True)
#
# # Running migrations on the db.
# call_command("migrate", interactive=False)
#
# def teardown_database():
# Config.DATABASE = Config.INSTANCE.database(DATABASE_NAME)
# if Config.DATABASE.exists():
# Config.DATABASE.drop()
. Output only the next line. | def tearDownClass(cls): |
Given snippet: <|code_start|>#!/usr/bin/env python2
# -- coding: utf-8 --
token = get_api_key()
url = 'https://www.muckrock.com/api_v1/'
headers = {'Authorization': 'Token %s' % token, 'content-type': 'application/json'}
next_ = url + 'communication'
fields = (
"id",
"ffile",
"title",
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import requests
import unicodecsv
from utils import get_api_key
and context:
# Path: utils.py
# def get_api_key():
# return token
which might include code, classes, or functions. Output only the next line. | "date", |
Given snippet: <|code_start|>
while next_ is not None:
r = requests.get(next_, headers=headers)
try:
json = r.json()
next_ = json['next']
for datum in json['results']:
try:
items = []
print "Working on request with ID " + str(datum['id'])
for field in fields:
if field == 'jurisdiction' or field == 'jurisdiction_id' or field == 'level' or field == 'parent' or field == "agency_id":
four = 4 # I just need something on this line
elif field == 'agency':
items.append(datum['agency'])
agency_url = "https://www.muckrock.com/api_v1/agency/" + str(datum['agency']) + '/'
agency = requests.get(agency_url , headers=headers)
agency_data = agency.json()
agency_name = agency_data['name']
items.append(agency_name) ## Things work through here
items.append(str(agency_data["jurisdiction"]))
jurisdiction_url = "https://www.muckrock.com/api_v1/jurisdiction/" + str(agency_data["jurisdiction"]) + '/'
jurisdiction = requests.get(jurisdiction_url , headers=headers)
jurisdiction_data = jurisdiction.json()
items.append(jurisdiction_data['name']) ## Things work through here
items.append(jurisdiction_data['level'])
if jurisdiction_data['parent'] != None:
if jurisdiction_data['level'] == 's':
items.append(jurisdiction_data['name'])
else:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import requests
import unicodecsv
import utils
import datetime
import time
from utils import get_api_key
and context:
# Path: utils.py
# def get_api_key():
# return token
which might include code, classes, or functions. Output only the next line. | jurisdiction_url = "https://www.muckrock.com/api_v1/jurisdiction/" + str(jurisdiction_data['parent']) + '/' |
Continue the code snippet: <|code_start|> next_ = url + 'assignment-responses'
while next_ is not None:
r = requests.get(next_, headers=headers)
try:
json = r.json()
next_ = json['next']
for datum in json['results']:
csv_writer.writerow([datum[field] for field in fields])
print 'Page %d of %d' % (page, (json['count'] / 20) + 1)
page += 1
except Exception as e:
print e
submissions = pd.read_csv('assignment_responses.csv')
submissions.update(pd.to_datetime(submissions['datetime']).dt.strftime('%D')) # Drop the time from datetime
submissions_by_day = submissions.pivot_table(index = ['datetime'], columns = "crowdsource", values = "id", aggfunc='count')
submissions_by_day = submissions_by_day.fillna(0).cumsum()
submissions_list = []
for label in submissions_by_day:
submissions_list.append([label,int(submissions_by_day[label].iloc[-1] - submissions_by_day[label].iloc[-8]),int(submissions_by_day[label].iloc[-8] - submissions_by_day[label].iloc[-15]),int(submissions_by_day[label].iloc[-1])])
return submissions_list
def convertAssignmentLabel(assignmentNum):
converter = {
14: "Help us build an FCC complaint Twitter bot",
35: "MuckRock Events and Talks",
24: "Join the MuckRock FOIA Slack",
25: "Monday Check In",
30: "Help explore Donald Rumsfeld's Snowflakes",
<|code_end|>
. Use current file imports:
import urllib
import unicodecsv as csv
import datetime
import os.path
import requests
import json
import markdown
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import utils
import sys
from datetime import timedelta
from mailchimp3 import MailChimp
from utils import get_api_key
from dateutil import parser
and context (classes, functions, or code) from other files:
# Path: utils.py
# def get_api_key():
# return token
. Output only the next line. | 38: "Potential Stories and Records Issues", |
Given the code snippet: <|code_start|>headers = {'Authorization': 'Token %s' % token, 'content-type': 'application/json'}
next_ = url + 'statistics'
fields = (
"date",
"total_requests",
"total_requests_success",
"total_requests_denied",
"total_requests_draft",
"total_requests_submitted",
"total_requests_awaiting_ack",
"total_requests_awaiting_response",
"total_requests_awaiting_appeal",
"total_requests_fix_required",
"total_requests_payment_required",
"total_requests_no_docs",
"total_requests_partial",
"total_requests_abandoned",
"total_pages",
"total_users",
"total_agencies",
"total_fees",
"pro_users",
"pro_user_names",
"total_page_views",
"daily_requests_pro",
"daily_requests_basic",
"daily_requests_beta",
"daily_articles",
"total_tasks",
<|code_end|>
, generate the next line using the imports in this file:
import requests
import unicodecsv
from utils import get_api_key
and context (functions, classes, or occasionally code) from other files:
# Path: utils.py
# def get_api_key():
# return token
. Output only the next line. | "total_unresolved_tasks", |
Using the snippet: <|code_start|>jurisdiction_fields = (
'name',
'parent',
'level',
)
page = 1
# make this true while exporting data to not crash on errors
SUPRESS_ERRORS = False
# This allows you to cach jurisdiction look ups
jurisdictions = {}
def get_jurisdiction(jurisdiction_id):
global jurisdictions
if jurisdiction_id in jurisdictions:
return jurisdictions[jurisdiction_id]
else:
# print 'getting jurisdiction', jurisdiction_id
sleep(1) # rate limit
r = requests.get(url + 'jurisdiction/' + str(jurisdiction_id), headers=headers)
jurisdiction_json = r.json()
if jurisdiction_json['parent']: # USA has no paremt
parent = get_jurisdiction(jurisdiction_json['parent'])
jurisdiction_json['parent'] = parent['name'] # replace parent id with parent name in jurisdiction json
jurisdictions[jurisdiction_id] = jurisdiction_json
return jurisdiction_json
csv_file = open('agency_stats.csv', 'w')
<|code_end|>
, determine the next line of code. You have imports:
from time import sleep
from utils import get_api_key
import requests
import unicodecsv
and context (class names, function names, or code) available:
# Path: utils.py
# def get_api_key():
# return token
. Output only the next line. | csv_writer = unicodecsv.writer(csv_file) |
Here is a snippet: <|code_start|>#!/usr/bin/env python2
# -- coding: utf-8 --
token = get_api_key()
url = 'https://www.muckrock.com/api_v1/'
headers = {'Authorization': 'Token %s' % token, 'content-type': 'application/json'}
<|code_end|>
. Write the next line using the current file imports:
import requests
import unicodecsv
from utils import get_api_key
and context from other files:
# Path: utils.py
# def get_api_key():
# return token
, which may include functions, classes, or code. Output only the next line. | next_ = url + 'jurisdiction' |
Based on the snippet: <|code_start|>
## Need to install google-api-python-clientself.
## pip install --upgrade google-api-python-client
# GA_product = raw_input('What is your Google Analytics product Key? ')
token = get_api_key()
url = 'https://www.muckrock.com/api_v1/'
headers = {'Authorization': 'Token %s' % token, 'content-type': 'application/json'}
next_ = url + 'news'
fields = (
"id",
"authors",
"editors",
"pub_date",
"title",
"kicker",
"slug",
"summary",
"body",
"publish",
"image"
)
field_names = (
"id",
<|code_end|>
, predict the immediate next line with the help of imports:
import requests
import unicodecsv
from utils import get_api_key
from dateutil import parser
and context (classes, functions, sometimes code) from other files:
# Path: utils.py
# def get_api_key():
# return token
. Output only the next line. | "authors", |
Next line prediction: <|code_start|>#!/usr/bin/env python2
# -- coding: utf-8 --
token = get_api_key()
url = 'https://www.muckrock.com/api_v1/'
headers = {'Authorization': 'Token %s' % token, 'content-type': 'application/json'}
assignmentID = raw_input('What assignment are you trying to export? Look at the numbers at the end of the URL: ')
next_ = url + "assignment-responses/?crowdsource=" + str(assignmentID)
basic_fields = [
"id",
<|code_end|>
. Use current file imports:
(import requests
import unicodecsv
from utils import get_api_key)
and context including class names, function names, or small code snippets from other files:
# Path: utils.py
# def get_api_key():
# return token
. Output only the next line. | "user", |
Given the code snippet: <|code_start|>#!/usr/bin/python
# -*- coding: utf-8 -*-
__author__ = 'Arnaud'
class GoogleDriveHelper:
__clientInstance = None
<|code_end|>
, generate the next line using the imports in this file:
import multiprocessing
import operator
import httplib2
import logging
import random
import time
import dns.resolver
import re
from collections import Iterable
from apiclient import errors
from apiclient.discovery import build
from apiclient.http import BatchHttpRequest
from django.core.urlresolvers import reverse
from oauth2client.django_orm import Storage
from django import forms
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.sessions.backends.db import SessionStore
from django.contrib.sessions.models import Session
from django.core.paginator import Paginator, EmptyPage, InvalidPage
from django.db.models import Q
from sorl.thumbnail import get_thumbnail
from UniShared_python.website.models import Training, UserProfile, Organization, CredentialsModel
from django.core.files.images import ImageFile
and context (functions, classes, or occasionally code) from other files:
# Path: UniShared_python/website/models.py
# class Training(django_models.Model):
# type = django_models.CharField(max_length=30)
# resource_id = django_models.CharField(max_length=100, db_index=True)
# is_live = django_models.BooleanField()
# is_displayed = django_models.BooleanField()
# is_featured = django_models.BooleanField()
# is_deleted = django_models.BooleanField()
# last_updated = django_models.IntegerField(default=1327217400)
# title = django_models.CharField(max_length=256, db_index=True)
# creator = django_models.ForeignKey(User, related_name='creator')
# cowriters = django_models.ManyToManyField(User, related_name='cowriters')
# participants = django_models.ManyToManyField(User, related_name='participants')
# total_views = django_models.IntegerField(default=0)
# total_views_open25 = django_models.IntegerField(default=0)
#
# objects = BatchManager()
#
# class UserProfile(django_models.Model):
# user = django_models.ForeignKey(User, unique=True)
#
# organization = django_models.ForeignKey(Organization, null=True)
# is_organization_verified=django_models.BooleanField(default=True)
# isUniStar = django_models.BooleanField()
# is_student = django_models.NullBooleanField(default=True)
# is_email_verified = django_models.BooleanField()
# enable_notifications = django_models.BooleanField()
# about_me = django_models.TextField(blank=True)
# facebook_id = django_models.BigIntegerField(blank=True, unique=True, null=True)
# facebook_profile_url = django_models.TextField(blank=True)
# twitter_profile_url = django_models.TextField(blank=True)
# linkedin_profile_url = django_models.TextField(blank=True)
# website_url = django_models.TextField(blank=True)
# image = django_models.ImageField(upload_to='profile_images')
# last_seen = django_models.DateTimeField(null=True)
# last_activity_ip = django_models.IPAddressField(null=True)
# drive_folder_id = django_models.CharField(max_length=250, null=True)
# can_create = django_models.BooleanField(default=False)
#
# class Organization(django_models.Model):
# name = django_models.CharField(max_length=100)
# country = django_models.ForeignKey(Country, null=True)
# members_role = django_models.CharField(max_length=30)
#
# def natural_key(self):
# return (self.name,)
#
# def natural_key(self):
# return (self.name,)
#
# class CredentialsModel(django_models.Model):
# id = django_models.ForeignKey(User, primary_key=True)
# credential = CredentialsField()
. Output only the next line. | DOCUMENTS_LIST_API_BATCH_URL = 'https://docs.google.com/feeds/default/private/full/batch' |
Continue the code snippet: <|code_start|>#!/usr/bin/python
# -*- coding: utf-8 -*-
__author__ = 'Arnaud'
class GoogleDriveHelper:
__clientInstance = None
DOCUMENTS_LIST_API_BATCH_URL = 'https://docs.google.com/feeds/default/private/full/batch'
DOCUMENT_LIST_API_ITEM_TEMPLATE = 'https://docs.google.com/feeds/id/%s'
<|code_end|>
. Use current file imports:
import multiprocessing
import operator
import httplib2
import logging
import random
import time
import dns.resolver
import re
from collections import Iterable
from apiclient import errors
from apiclient.discovery import build
from apiclient.http import BatchHttpRequest
from django.core.urlresolvers import reverse
from oauth2client.django_orm import Storage
from django import forms
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.sessions.backends.db import SessionStore
from django.contrib.sessions.models import Session
from django.core.paginator import Paginator, EmptyPage, InvalidPage
from django.db.models import Q
from sorl.thumbnail import get_thumbnail
from UniShared_python.website.models import Training, UserProfile, Organization, CredentialsModel
from django.core.files.images import ImageFile
and context (classes, functions, or code) from other files:
# Path: UniShared_python/website/models.py
# class Training(django_models.Model):
# type = django_models.CharField(max_length=30)
# resource_id = django_models.CharField(max_length=100, db_index=True)
# is_live = django_models.BooleanField()
# is_displayed = django_models.BooleanField()
# is_featured = django_models.BooleanField()
# is_deleted = django_models.BooleanField()
# last_updated = django_models.IntegerField(default=1327217400)
# title = django_models.CharField(max_length=256, db_index=True)
# creator = django_models.ForeignKey(User, related_name='creator')
# cowriters = django_models.ManyToManyField(User, related_name='cowriters')
# participants = django_models.ManyToManyField(User, related_name='participants')
# total_views = django_models.IntegerField(default=0)
# total_views_open25 = django_models.IntegerField(default=0)
#
# objects = BatchManager()
#
# class UserProfile(django_models.Model):
# user = django_models.ForeignKey(User, unique=True)
#
# organization = django_models.ForeignKey(Organization, null=True)
# is_organization_verified=django_models.BooleanField(default=True)
# isUniStar = django_models.BooleanField()
# is_student = django_models.NullBooleanField(default=True)
# is_email_verified = django_models.BooleanField()
# enable_notifications = django_models.BooleanField()
# about_me = django_models.TextField(blank=True)
# facebook_id = django_models.BigIntegerField(blank=True, unique=True, null=True)
# facebook_profile_url = django_models.TextField(blank=True)
# twitter_profile_url = django_models.TextField(blank=True)
# linkedin_profile_url = django_models.TextField(blank=True)
# website_url = django_models.TextField(blank=True)
# image = django_models.ImageField(upload_to='profile_images')
# last_seen = django_models.DateTimeField(null=True)
# last_activity_ip = django_models.IPAddressField(null=True)
# drive_folder_id = django_models.CharField(max_length=250, null=True)
# can_create = django_models.BooleanField(default=False)
#
# class Organization(django_models.Model):
# name = django_models.CharField(max_length=100)
# country = django_models.ForeignKey(Country, null=True)
# members_role = django_models.CharField(max_length=30)
#
# def natural_key(self):
# return (self.name,)
#
# def natural_key(self):
# return (self.name,)
#
# class CredentialsModel(django_models.Model):
# id = django_models.ForeignKey(User, primary_key=True)
# credential = CredentialsField()
. Output only the next line. | RESOURCE_ID_REGEX = re.compile(DOCUMENT_LIST_API_ITEM_TEMPLATE % "document:([a-z0-9_-]+)", re.IGNORECASE) |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/python
# -*- coding: utf-8 -*-
__author__ = 'Arnaud'
class GoogleDriveHelper:
__clientInstance = None
DOCUMENTS_LIST_API_BATCH_URL = 'https://docs.google.com/feeds/default/private/full/batch'
DOCUMENT_LIST_API_ITEM_TEMPLATE = 'https://docs.google.com/feeds/id/%s'
RESOURCE_ID_REGEX = re.compile(DOCUMENT_LIST_API_ITEM_TEMPLATE % "document:([a-z0-9_-]+)", re.IGNORECASE)
<|code_end|>
with the help of current file imports:
import multiprocessing
import operator
import httplib2
import logging
import random
import time
import dns.resolver
import re
from collections import Iterable
from apiclient import errors
from apiclient.discovery import build
from apiclient.http import BatchHttpRequest
from django.core.urlresolvers import reverse
from oauth2client.django_orm import Storage
from django import forms
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.sessions.backends.db import SessionStore
from django.contrib.sessions.models import Session
from django.core.paginator import Paginator, EmptyPage, InvalidPage
from django.db.models import Q
from sorl.thumbnail import get_thumbnail
from UniShared_python.website.models import Training, UserProfile, Organization, CredentialsModel
from django.core.files.images import ImageFile
and context from other files:
# Path: UniShared_python/website/models.py
# class Training(django_models.Model):
# type = django_models.CharField(max_length=30)
# resource_id = django_models.CharField(max_length=100, db_index=True)
# is_live = django_models.BooleanField()
# is_displayed = django_models.BooleanField()
# is_featured = django_models.BooleanField()
# is_deleted = django_models.BooleanField()
# last_updated = django_models.IntegerField(default=1327217400)
# title = django_models.CharField(max_length=256, db_index=True)
# creator = django_models.ForeignKey(User, related_name='creator')
# cowriters = django_models.ManyToManyField(User, related_name='cowriters')
# participants = django_models.ManyToManyField(User, related_name='participants')
# total_views = django_models.IntegerField(default=0)
# total_views_open25 = django_models.IntegerField(default=0)
#
# objects = BatchManager()
#
# class UserProfile(django_models.Model):
# user = django_models.ForeignKey(User, unique=True)
#
# organization = django_models.ForeignKey(Organization, null=True)
# is_organization_verified=django_models.BooleanField(default=True)
# isUniStar = django_models.BooleanField()
# is_student = django_models.NullBooleanField(default=True)
# is_email_verified = django_models.BooleanField()
# enable_notifications = django_models.BooleanField()
# about_me = django_models.TextField(blank=True)
# facebook_id = django_models.BigIntegerField(blank=True, unique=True, null=True)
# facebook_profile_url = django_models.TextField(blank=True)
# twitter_profile_url = django_models.TextField(blank=True)
# linkedin_profile_url = django_models.TextField(blank=True)
# website_url = django_models.TextField(blank=True)
# image = django_models.ImageField(upload_to='profile_images')
# last_seen = django_models.DateTimeField(null=True)
# last_activity_ip = django_models.IPAddressField(null=True)
# drive_folder_id = django_models.CharField(max_length=250, null=True)
# can_create = django_models.BooleanField(default=False)
#
# class Organization(django_models.Model):
# name = django_models.CharField(max_length=100)
# country = django_models.ForeignKey(Country, null=True)
# members_role = django_models.CharField(max_length=30)
#
# def natural_key(self):
# return (self.name,)
#
# def natural_key(self):
# return (self.name,)
#
# class CredentialsModel(django_models.Model):
# id = django_models.ForeignKey(User, primary_key=True)
# credential = CredentialsField()
, which may contain function names, class names, or code. Output only the next line. | TITLE_FILTER = ['your new unishared\'s class', 'document title', 'untitled document', 'test', 'copy of template', 'unishared template', 'template'] |
Continue the code snippet: <|code_start|>#!/usr/bin/python
# -*- coding: utf-8 -*-
__author__ = 'Arnaud'
class GoogleDriveHelper:
__clientInstance = None
DOCUMENTS_LIST_API_BATCH_URL = 'https://docs.google.com/feeds/default/private/full/batch'
DOCUMENT_LIST_API_ITEM_TEMPLATE = 'https://docs.google.com/feeds/id/%s'
RESOURCE_ID_REGEX = re.compile(DOCUMENT_LIST_API_ITEM_TEMPLATE % "document:([a-z0-9_-]+)", re.IGNORECASE)
TITLE_FILTER = ['your new unishared\'s class', 'document title', 'untitled document', 'test', 'copy of template', 'unishared template', 'template']
<|code_end|>
. Use current file imports:
import multiprocessing
import operator
import httplib2
import logging
import random
import time
import dns.resolver
import re
from collections import Iterable
from apiclient import errors
from apiclient.discovery import build
from apiclient.http import BatchHttpRequest
from django.core.urlresolvers import reverse
from oauth2client.django_orm import Storage
from django import forms
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.sessions.backends.db import SessionStore
from django.contrib.sessions.models import Session
from django.core.paginator import Paginator, EmptyPage, InvalidPage
from django.db.models import Q
from sorl.thumbnail import get_thumbnail
from UniShared_python.website.models import Training, UserProfile, Organization, CredentialsModel
from django.core.files.images import ImageFile
and context (classes, functions, or code) from other files:
# Path: UniShared_python/website/models.py
# class Training(django_models.Model):
# type = django_models.CharField(max_length=30)
# resource_id = django_models.CharField(max_length=100, db_index=True)
# is_live = django_models.BooleanField()
# is_displayed = django_models.BooleanField()
# is_featured = django_models.BooleanField()
# is_deleted = django_models.BooleanField()
# last_updated = django_models.IntegerField(default=1327217400)
# title = django_models.CharField(max_length=256, db_index=True)
# creator = django_models.ForeignKey(User, related_name='creator')
# cowriters = django_models.ManyToManyField(User, related_name='cowriters')
# participants = django_models.ManyToManyField(User, related_name='participants')
# total_views = django_models.IntegerField(default=0)
# total_views_open25 = django_models.IntegerField(default=0)
#
# objects = BatchManager()
#
# class UserProfile(django_models.Model):
# user = django_models.ForeignKey(User, unique=True)
#
# organization = django_models.ForeignKey(Organization, null=True)
# is_organization_verified=django_models.BooleanField(default=True)
# isUniStar = django_models.BooleanField()
# is_student = django_models.NullBooleanField(default=True)
# is_email_verified = django_models.BooleanField()
# enable_notifications = django_models.BooleanField()
# about_me = django_models.TextField(blank=True)
# facebook_id = django_models.BigIntegerField(blank=True, unique=True, null=True)
# facebook_profile_url = django_models.TextField(blank=True)
# twitter_profile_url = django_models.TextField(blank=True)
# linkedin_profile_url = django_models.TextField(blank=True)
# website_url = django_models.TextField(blank=True)
# image = django_models.ImageField(upload_to='profile_images')
# last_seen = django_models.DateTimeField(null=True)
# last_activity_ip = django_models.IPAddressField(null=True)
# drive_folder_id = django_models.CharField(max_length=250, null=True)
# can_create = django_models.BooleanField(default=False)
#
# class Organization(django_models.Model):
# name = django_models.CharField(max_length=100)
# country = django_models.ForeignKey(Country, null=True)
# members_role = django_models.CharField(max_length=30)
#
# def natural_key(self):
# return (self.name,)
#
# def natural_key(self):
# return (self.name,)
#
# class CredentialsModel(django_models.Model):
# id = django_models.ForeignKey(User, primary_key=True)
# credential = CredentialsField()
. Output only the next line. | MAX_DOCUMENTS = 50 |
Based on the snippet: <|code_start|>
def get_user_avatar(backend, details, response, social_user, uid, user, *args, **kwargs):
url = None
if backend.__class__ == FacebookBackend:
url = "http://graph.facebook.com/%s/picture?type=large" % response['id']
<|code_end|>
, predict the immediate next line with the help of imports:
from datetime import datetime, timedelta
from urllib2 import urlopen
from django.core.files.base import ContentFile
from django.template.context import Context
from django.template.defaultfilters import slugify
from social_auth.backends import USERNAME
from social_auth.backends.facebook import FacebookBackend
from UniShared_python.settings import GAPPS_GROUP_NAME
from UniShared_python.website.tasks import email_task, google_apps_add_group_task
import hashlib
and context (classes, functions, sometimes code) from other files:
# Path: UniShared_python/website/tasks.py
# @task
# @only_one
# def email_task(subject, context, template, to, bcc=None, connection_label=None):
# if not to and not bcc:
# logger.debug('No recipients, adding managers')
# to = [a[1] for a in settings.MANAGERS]
# connection_label = 'gmail'
#
# logger.debug('Starting email task (subject: %s, template: %s, context: %s to: %s, bcc: %s, connection_label: %s',
# subject, template, context, to, bcc, connection_label)
#
# def filter_emails(emails):
# filtered_emails = []
#
# if emails:
# for email in emails:
# try:
# user_profile = User.objects.get(email=email).get_profile()
#
# if user_profile.is_email_verified is True and user_profile.enable_notifications is True:
# filtered_emails.append(email)
# except User.DoesNotExist:
# filtered_emails.append(email)
# return filtered_emails
#
# filtered_to = filter_emails(to)
# filtered_bcc = filter_emails(bcc)
#
# logger.debug('To length after filtering: %s', len(filtered_to))
# logger.debug('Bcc length after filtering: %s', len(filtered_bcc))
#
# if len(filtered_to) or len(filtered_bcc):
# if connection_label is None:
# connection_label = getattr(settings, 'EMAIL_CONNECTION_DEFAULT', None)
#
# try:
# connections = getattr(settings, 'EMAIL_CONNECTIONS')
# real_options = connections[connection_label]
# admin_options = connections['gmail']
# except KeyError, AttributeError:
# raise MissingConnectionException(
# 'Settings for connection "%s" were not found' % connection_label)
#
# context.update({'BASE_URL': settings.BASE_URL,
# 'link_underlined': 'border-bottom: 1px dashed #848484;text-decoration: none;',
# 'link_style_share': 'color: #3CBDEE;border-bottom: 1px dashed #3CBDEE;text-decoration: none;',
# 'link_style_participate': 'color: #F18C1B;text-decoration: none;border-bottom: 1px dashed #F18C1B;'})
# text_message = get_template('mails/{0}.txt'.format(template)).render(context)
#
# real_connection = get_connection(**real_options)
# real_connection.open()
#
# admin_connection = get_connection(**admin_options)
# admin_connection.open()
#
# from_email = u'"Clément from UniShared" <clement@unishared.com>'
# real_email = EmailMultiAlternatives(subject, text_message, from_email,
# filtered_to, filtered_bcc, real_connection)
# admin_email = EmailMultiAlternatives(subject, text_message, from_email,
# [a[1] for a in settings.ADMINS], None, admin_connection)
# try:
# html_message = get_template('mails/{0}.html'.format(template)).render(context)
# real_email.attach_alternative(html_message, 'text/html')
# admin_email.attach_alternative(html_message, 'text/html')
# except TemplateDoesNotExist:
# pass
#
# real_email.send(fail_silently=False)
# admin_email.send(fail_silently=False)
#
# real_connection.close()
# admin_connection.close()
#
# @task
# @only_one
# def google_apps_add_group_task(group_id, member_id):
# logger.debug('Starting Google Apps add to group task')
# try:
# logger.debug('Get GroupsProvisioningClient')
# clientInstance = GroupsProvisioningClient('unishared.com',
# OAuthHmacToken('unishared.com', '',
# '', '', ACCESS_TOKEN))
# clientInstance.ssl = True
# logger.debug('Add {0} to {1}'.format(member_id, group_id))
# clientInstance.AddMemberToGroup(group_id, member_id)
# return True
# except RequestError:
# LoggingHelper.getErrorLogger().debug("Request error while adding user to Google group", exc_info=1)
# return False
# except Exception:
# LoggingHelper.getErrorLogger().error("Error while adding user to Google group", exc_info=1)
# return False
. Output only the next line. | if url: |
Predict the next line for this snippet: <|code_start|>
def get_user_avatar(backend, details, response, social_user, uid, user, *args, **kwargs):
url = None
if backend.__class__ == FacebookBackend:
url = "http://graph.facebook.com/%s/picture?type=large" % response['id']
if url:
profile = user.get_profile()
if profile.image == '':
avatar = urlopen(url)
content = avatar.read()
md5 = hashlib.md5()
md5.update(content)
name = '{0}-{1}.jpg'.format(slugify(user.username + " social"), md5.hexdigest()[:12])
profile.image.save(name, ContentFile(content))
<|code_end|>
with the help of current file imports:
from datetime import datetime, timedelta
from urllib2 import urlopen
from django.core.files.base import ContentFile
from django.template.context import Context
from django.template.defaultfilters import slugify
from social_auth.backends import USERNAME
from social_auth.backends.facebook import FacebookBackend
from UniShared_python.settings import GAPPS_GROUP_NAME
from UniShared_python.website.tasks import email_task, google_apps_add_group_task
import hashlib
and context from other files:
# Path: UniShared_python/website/tasks.py
# @task
# @only_one
# def email_task(subject, context, template, to, bcc=None, connection_label=None):
# if not to and not bcc:
# logger.debug('No recipients, adding managers')
# to = [a[1] for a in settings.MANAGERS]
# connection_label = 'gmail'
#
# logger.debug('Starting email task (subject: %s, template: %s, context: %s to: %s, bcc: %s, connection_label: %s',
# subject, template, context, to, bcc, connection_label)
#
# def filter_emails(emails):
# filtered_emails = []
#
# if emails:
# for email in emails:
# try:
# user_profile = User.objects.get(email=email).get_profile()
#
# if user_profile.is_email_verified is True and user_profile.enable_notifications is True:
# filtered_emails.append(email)
# except User.DoesNotExist:
# filtered_emails.append(email)
# return filtered_emails
#
# filtered_to = filter_emails(to)
# filtered_bcc = filter_emails(bcc)
#
# logger.debug('To length after filtering: %s', len(filtered_to))
# logger.debug('Bcc length after filtering: %s', len(filtered_bcc))
#
# if len(filtered_to) or len(filtered_bcc):
# if connection_label is None:
# connection_label = getattr(settings, 'EMAIL_CONNECTION_DEFAULT', None)
#
# try:
# connections = getattr(settings, 'EMAIL_CONNECTIONS')
# real_options = connections[connection_label]
# admin_options = connections['gmail']
# except KeyError, AttributeError:
# raise MissingConnectionException(
# 'Settings for connection "%s" were not found' % connection_label)
#
# context.update({'BASE_URL': settings.BASE_URL,
# 'link_underlined': 'border-bottom: 1px dashed #848484;text-decoration: none;',
# 'link_style_share': 'color: #3CBDEE;border-bottom: 1px dashed #3CBDEE;text-decoration: none;',
# 'link_style_participate': 'color: #F18C1B;text-decoration: none;border-bottom: 1px dashed #F18C1B;'})
# text_message = get_template('mails/{0}.txt'.format(template)).render(context)
#
# real_connection = get_connection(**real_options)
# real_connection.open()
#
# admin_connection = get_connection(**admin_options)
# admin_connection.open()
#
# from_email = u'"Clément from UniShared" <clement@unishared.com>'
# real_email = EmailMultiAlternatives(subject, text_message, from_email,
# filtered_to, filtered_bcc, real_connection)
# admin_email = EmailMultiAlternatives(subject, text_message, from_email,
# [a[1] for a in settings.ADMINS], None, admin_connection)
# try:
# html_message = get_template('mails/{0}.html'.format(template)).render(context)
# real_email.attach_alternative(html_message, 'text/html')
# admin_email.attach_alternative(html_message, 'text/html')
# except TemplateDoesNotExist:
# pass
#
# real_email.send(fail_silently=False)
# admin_email.send(fail_silently=False)
#
# real_connection.close()
# admin_connection.close()
#
# @task
# @only_one
# def google_apps_add_group_task(group_id, member_id):
# logger.debug('Starting Google Apps add to group task')
# try:
# logger.debug('Get GroupsProvisioningClient')
# clientInstance = GroupsProvisioningClient('unishared.com',
# OAuthHmacToken('unishared.com', '',
# '', '', ACCESS_TOKEN))
# clientInstance.ssl = True
# logger.debug('Add {0} to {1}'.format(member_id, group_id))
# clientInstance.AddMemberToGroup(group_id, member_id)
# return True
# except RequestError:
# LoggingHelper.getErrorLogger().debug("Request error while adding user to Google group", exc_info=1)
# return False
# except Exception:
# LoggingHelper.getErrorLogger().error("Error while adding user to Google group", exc_info=1)
# return False
, which may contain function names, class names, or code. Output only the next line. | profile.save() |
Next line prediction: <|code_start|> imsi_list = map(lambda item: item['imsi'], result);
query = HLRDBSession.query(
Subscriber.imsi,
func.count(Sms.id).label('sms_count')
).filter((
(Sms.src_addr == Subscriber.extension) |
(Sms.dest_addr == Subscriber.extension)) &
(Sms.protocol_id != 64) &
(Subscriber.imsi.in_(imsi_list))
).group_by(
Subscriber.imsi
).all()
for record in query:
messages.append({
'imsi': int(record.imsi),
'count': record.sms_count
})
if 'jtSorting' in request.GET:
sorting_params = request.GET['jtSorting'].split(' ')
sorting_field = sorting_params[0]
reverse = sorting_params[1] == 'DESC'
result.sort(key=lambda x: x[sorting_field], reverse=reverse)
try:
gps_status = all(request.xmlrpc.get_current_gps())
gps_status = 'yes' if gps_status else 'no'
except (socket.error, xmlrpclib.Error) as e:
<|code_end|>
. Use current file imports:
(from datetime import datetime
from pyramid.view import view_config
from sqlalchemy import func
from model.models import (
DBSession,
Measure,
)
from model.hlr import (
HLRDBSession,
Sms,
Subscriber,
user_data_decode,
)
import time
import xmlrpclib
import socket)
and context including class names, function names, or small code snippets from other files:
# Path: model/models.py
# def bind_session(connection_string, echo=False):
# class Measure(Base):
# class Settings(Base):
#
# Path: model/hlr.py
# def bind_session(connection_string, echo=False):
# def user_data_decode(user_data, data_coding_scheme, ud_hdr_ind):
# def create_sms(src_addr, dest_addr, text, charset=None):
# class Subscriber(Base):
# class Sms(Base):
. Output only the next line. | gps_status = 'failed' |
Continue the code snippet: <|code_start|> (Subscriber.imsi.in_(imsi_list))
).group_by(
Subscriber.imsi
).all()
for record in query:
messages.append({
'imsi': int(record.imsi),
'count': record.sms_count
})
if 'jtSorting' in request.GET:
sorting_params = request.GET['jtSorting'].split(' ')
sorting_field = sorting_params[0]
reverse = sorting_params[1] == 'DESC'
result.sort(key=lambda x: x[sorting_field], reverse=reverse)
try:
gps_status = all(request.xmlrpc.get_current_gps())
gps_status = 'yes' if gps_status else 'no'
except (socket.error, xmlrpclib.Error) as e:
gps_status = 'failed'
return {
'Result': 'OK',
'Records': result,
'Messages': messages,
'GpsStatus': gps_status
<|code_end|>
. Use current file imports:
from datetime import datetime
from pyramid.view import view_config
from sqlalchemy import func
from model.models import (
DBSession,
Measure,
)
from model.hlr import (
HLRDBSession,
Sms,
Subscriber,
user_data_decode,
)
import time
import xmlrpclib
import socket
and context (classes, functions, or code) from other files:
# Path: model/models.py
# def bind_session(connection_string, echo=False):
# class Measure(Base):
# class Settings(Base):
#
# Path: model/hlr.py
# def bind_session(connection_string, echo=False):
# def user_data_decode(user_data, data_coding_scheme, ud_hdr_ind):
# def create_sms(src_addr, dest_addr, text, charset=None):
# class Subscriber(Base):
# class Sms(Base):
. Output only the next line. | } |
Continue the code snippet: <|code_start|> dest_subscriber_res = HLRDBSession.query(
Subscriber.imsi
).filter(
Subscriber.extension == obj.dest_addr
).all()
dest = "xx"
if len(dest_subscriber_res) > 0:
dest_imsi = int(dest_subscriber_res[0].imsi)
dest = "station" if dest_imsi == int(pimsi) else str(dest_imsi)
direction = 'to' if obj.src_addr == pfnum else 'from'
try:
msg_id, msg_part_num, msg_parts_count, msg_part_text = user_data_decode(obj.user_data, obj.data_coding_scheme, (obj.ud_hdr_ind == 1) )
except:
msg_id, msg_part_num, msg_parts_count, msg_part_text = -1, 1, 1, "--Failed to decode the message--"
if msg_id in multipart_massages:
multipart_massages[msg_id]['text'] += msg_part_text
else:
sms = {
'id': obj.id,
'text': msg_part_text,
'type': direction,
'ts': time.strftime('%d %b %Y, %H:%M:%S', obj.created.timetuple()),
'dest': dest,
}
if direction == 'to':
<|code_end|>
. Use current file imports:
from datetime import datetime
from pyramid.view import view_config
from sqlalchemy import func
from model.models import (
DBSession,
Measure,
)
from model.hlr import (
HLRDBSession,
Sms,
Subscriber,
user_data_decode,
)
import time
import xmlrpclib
import socket
and context (classes, functions, or code) from other files:
# Path: model/models.py
# def bind_session(connection_string, echo=False):
# class Measure(Base):
# class Settings(Base):
#
# Path: model/hlr.py
# def bind_session(connection_string, echo=False):
# def user_data_decode(user_data, data_coding_scheme, ud_hdr_ind):
# def create_sms(src_addr, dest_addr, text, charset=None):
# class Subscriber(Base):
# class Sms(Base):
. Output only the next line. | sms['sent'] = True if obj.sent else False |
Given the code snippet: <|code_start|> for circle in query.all():
result['circles'].append({
'center': [
circle.gps_lat,
circle.gps_lon
],
'radius': circle.distance,
'ts': time.mktime(circle.timestamp.timetuple())
})
return result
@view_config(route_name='send_imsi_message', request_method='POST', renderer='json')
def send_imsi_message(request):
result = {}
imsi = request.matchdict['imsi']
text = request.body
try:
sent = request.xmlrpc.send_sms(imsi, text)
result['status'] = 'sent' if sent else 'failed'
except (socket.error, xmlrpclib.Error) as e:
result['status'] = 'failed'
result['reason'] = e.strerror
return result
@view_config(route_name='start_tracking', request_method='GET', renderer='json')
def start_tracking(request):
<|code_end|>
, generate the next line using the imports in this file:
from datetime import datetime
from pyramid.view import view_config
from sqlalchemy import func
from model.models import (
DBSession,
Measure,
)
from model.hlr import (
HLRDBSession,
Sms,
Subscriber,
user_data_decode,
)
import time
import xmlrpclib
import socket
and context (functions, classes, or occasionally code) from other files:
# Path: model/models.py
# def bind_session(connection_string, echo=False):
# class Measure(Base):
# class Settings(Base):
#
# Path: model/hlr.py
# def bind_session(connection_string, echo=False):
# def user_data_decode(user_data, data_coding_scheme, ud_hdr_ind):
# def create_sms(src_addr, dest_addr, text, charset=None):
# class Subscriber(Base):
# class Sms(Base):
. Output only the next line. | result = {} |
Given the code snippet: <|code_start|>
dest = "xx"
if len(dest_subscriber_res) > 0:
dest_imsi = int(dest_subscriber_res[0].imsi)
dest = "station" if dest_imsi == int(pimsi) else str(dest_imsi)
direction = 'to' if obj.src_addr == pfnum else 'from'
try:
msg_id, msg_part_num, msg_parts_count, msg_part_text = user_data_decode(obj.user_data, obj.data_coding_scheme, (obj.ud_hdr_ind == 1) )
except:
msg_id, msg_part_num, msg_parts_count, msg_part_text = -1, 1, 1, "--Failed to decode the message--"
if msg_id in multipart_massages:
multipart_massages[msg_id]['text'] += msg_part_text
else:
sms = {
'id': obj.id,
'text': msg_part_text,
'type': direction,
'ts': time.strftime('%d %b %Y, %H:%M:%S', obj.created.timetuple()),
'dest': dest,
}
if direction == 'to':
sms['sent'] = True if obj.sent else False
result['sms'].append(sms)
if msg_parts_count > 1:
<|code_end|>
, generate the next line using the imports in this file:
from datetime import datetime
from pyramid.view import view_config
from sqlalchemy import func
from model.models import (
DBSession,
Measure,
)
from model.hlr import (
HLRDBSession,
Sms,
Subscriber,
user_data_decode,
)
import time
import xmlrpclib
import socket
and context (functions, classes, or occasionally code) from other files:
# Path: model/models.py
# def bind_session(connection_string, echo=False):
# class Measure(Base):
# class Settings(Base):
#
# Path: model/hlr.py
# def bind_session(connection_string, echo=False):
# def user_data_decode(user_data, data_coding_scheme, ud_hdr_ind):
# def create_sms(src_addr, dest_addr, text, charset=None):
# class Subscriber(Base):
# class Sms(Base):
. Output only the next line. | multipart_massages[msg_id] = result['sms'][-1] |
Given the following code snippet before the placeholder: <|code_start|>
@view_config(route_name='send_imsi_message', request_method='POST', renderer='json')
def send_imsi_message(request):
result = {}
imsi = request.matchdict['imsi']
text = request.body
try:
sent = request.xmlrpc.send_sms(imsi, text)
result['status'] = 'sent' if sent else 'failed'
except (socket.error, xmlrpclib.Error) as e:
result['status'] = 'failed'
result['reason'] = e.strerror
return result
@view_config(route_name='start_tracking', request_method='GET', renderer='json')
def start_tracking(request):
result = {}
try:
request.xmlrpc.start_tracking()
result['status'] = 'started'
except (socket.error, xmlrpclib.Error) as e:
result['status'] = 'failed'
result['reason'] = e.strerror
return result
@view_config(route_name='stop_tracking', request_method='GET', renderer='json')
def stop_tracking(request):
<|code_end|>
, predict the next line using imports from the current file:
from datetime import datetime
from pyramid.view import view_config
from sqlalchemy import func
from model.models import (
DBSession,
Measure,
)
from model.hlr import (
HLRDBSession,
Sms,
Subscriber,
user_data_decode,
)
import time
import xmlrpclib
import socket
and context including class names, function names, and sometimes code from other files:
# Path: model/models.py
# def bind_session(connection_string, echo=False):
# class Measure(Base):
# class Settings(Base):
#
# Path: model/hlr.py
# def bind_session(connection_string, echo=False):
# def user_data_decode(user_data, data_coding_scheme, ud_hdr_ind):
# def create_sms(src_addr, dest_addr, text, charset=None):
# class Subscriber(Base):
# class Sms(Base):
. Output only the next line. | result = {} |
Given the code snippet: <|code_start|>def main(argv=sys.argv):
if len(argv) != 2:
usage(argv)
config_uri = argv[1]
setup_logging(config_uri)
settings = get_appsettings(config_uri)
engine = engine_from_config(settings, 'sqlalchemy.pf.')
DBSession.configure(bind=engine)
Base.metadata.create_all(engine)
hlr_engine = engine_from_config(settings, 'sqlalchemy.hlr.')
HLRDBSession.configure(bind=hlr_engine)
# initial settings
with transaction.manager:
DBSession.add_all([
Settings(name='imsiUpdate', value=3000),
Settings(name='smsUpdate', value=3000),
Settings(name='silentSms', value=3000),
Settings(
name='welcomeMessage',
value='You are connected to a mobile search and rescue team. ' + \
'Please SMS to {ph_phone_number} to communicate. ' + \
'Your temporary phone number is {ms_phone_number}'
),
Settings(
name='replyMessage',
value='Your SMSs are being sent to a mobile search and rescue team. ' + \
'Reply to this message to communicate.'
),
<|code_end|>
, generate the next line using the imports in this file:
import os
import sys
import time
import datetime
import transaction
from sqlalchemy import engine_from_config
from pyramid.paster import (
get_appsettings,
setup_logging,
)
from model.hlr import (
HLRDBSession,
Subscriber
)
from model.models import (
DBSession,
Settings,
Base,
)
from com_interface.comms_interface_server import (
pf_subscriber_imsi,
pf_subscriber_extension,
pf_subscriber_name
)
and context (functions, classes, or occasionally code) from other files:
# Path: model/hlr.py
# def bind_session(connection_string, echo=False):
# def user_data_decode(user_data, data_coding_scheme, ud_hdr_ind):
# def create_sms(src_addr, dest_addr, text, charset=None):
# class Subscriber(Base):
# class Sms(Base):
#
# Path: model/models.py
# def bind_session(connection_string, echo=False):
# class Measure(Base):
# class Settings(Base):
#
# Path: com_interface/comms_interface_server.py
# class RequestHandler(SimpleXMLRPCRequestHandler):
# class CommsInterfaceServer(object):
# def __init__(self, configuration, measure_model, time_to_shutdown_event):
# def serve_forever(self):
# def start_new_session(self):
# def try_run_xmlrpc_server(self):
# def try_run_vty_client(self):
# def process_measure_worker(self):
# def process_measure(self, meas):
# def get_formated_welcome_message(self, **wargs):
# def get_formated_reply_message(self, **wargs):
# def get_last_measure(self, imsi):
# def save_measure_to_db(self, meas, extension):
# def __calculate_distance(self, ta):
# def process_unknown_adress_sms_worker(self):
# def start_tracking(self):
# def stop_tracking(self):
# def tracking_process(self):
# def prepare_ready_for_silent_sms(self):
# def vty_send_silent_sms(self, imsi):
# def send_sms(self, imsi, text):
# def send_sms_by_phone_number(self, extension, text):
. Output only the next line. | ]) |
Next line prediction: <|code_start|> hlr_engine = engine_from_config(settings, 'sqlalchemy.hlr.')
HLRDBSession.configure(bind=hlr_engine)
# initial settings
with transaction.manager:
DBSession.add_all([
Settings(name='imsiUpdate', value=3000),
Settings(name='smsUpdate', value=3000),
Settings(name='silentSms', value=3000),
Settings(
name='welcomeMessage',
value='You are connected to a mobile search and rescue team. ' + \
'Please SMS to {ph_phone_number} to communicate. ' + \
'Your temporary phone number is {ms_phone_number}'
),
Settings(
name='replyMessage',
value='Your SMSs are being sent to a mobile search and rescue team. ' + \
'Reply to this message to communicate.'
),
])
HLRDBSession.add_all([
Subscriber(
created=datetime.datetime.fromtimestamp(time.time()),
updated=datetime.datetime.fromtimestamp(time.time()),
imsi=pf_subscriber_imsi,
name=pf_subscriber_name,
extension=pf_subscriber_extension,
authorized=1,
<|code_end|>
. Use current file imports:
(import os
import sys
import time
import datetime
import transaction
from sqlalchemy import engine_from_config
from pyramid.paster import (
get_appsettings,
setup_logging,
)
from model.hlr import (
HLRDBSession,
Subscriber
)
from model.models import (
DBSession,
Settings,
Base,
)
from com_interface.comms_interface_server import (
pf_subscriber_imsi,
pf_subscriber_extension,
pf_subscriber_name
))
and context including class names, function names, or small code snippets from other files:
# Path: model/hlr.py
# def bind_session(connection_string, echo=False):
# def user_data_decode(user_data, data_coding_scheme, ud_hdr_ind):
# def create_sms(src_addr, dest_addr, text, charset=None):
# class Subscriber(Base):
# class Sms(Base):
#
# Path: model/models.py
# def bind_session(connection_string, echo=False):
# class Measure(Base):
# class Settings(Base):
#
# Path: com_interface/comms_interface_server.py
# class RequestHandler(SimpleXMLRPCRequestHandler):
# class CommsInterfaceServer(object):
# def __init__(self, configuration, measure_model, time_to_shutdown_event):
# def serve_forever(self):
# def start_new_session(self):
# def try_run_xmlrpc_server(self):
# def try_run_vty_client(self):
# def process_measure_worker(self):
# def process_measure(self, meas):
# def get_formated_welcome_message(self, **wargs):
# def get_formated_reply_message(self, **wargs):
# def get_last_measure(self, imsi):
# def save_measure_to_db(self, meas, extension):
# def __calculate_distance(self, ta):
# def process_unknown_adress_sms_worker(self):
# def start_tracking(self):
# def stop_tracking(self):
# def tracking_process(self):
# def prepare_ready_for_silent_sms(self):
# def vty_send_silent_sms(self, imsi):
# def send_sms(self, imsi, text):
# def send_sms_by_phone_number(self, extension, text):
. Output only the next line. | lac=0 |
Based on the snippet: <|code_start|>def usage(argv):
cmd = os.path.basename(argv[0])
print('usage: %s <config_uri>\n'
'(example: "%s development.ini")' % (cmd, cmd))
sys.exit(1)
def main(argv=sys.argv):
if len(argv) != 2:
usage(argv)
config_uri = argv[1]
setup_logging(config_uri)
settings = get_appsettings(config_uri)
engine = engine_from_config(settings, 'sqlalchemy.pf.')
DBSession.configure(bind=engine)
Base.metadata.create_all(engine)
hlr_engine = engine_from_config(settings, 'sqlalchemy.hlr.')
HLRDBSession.configure(bind=hlr_engine)
# initial settings
with transaction.manager:
DBSession.add_all([
Settings(name='imsiUpdate', value=3000),
Settings(name='smsUpdate', value=3000),
Settings(name='silentSms', value=3000),
Settings(
name='welcomeMessage',
value='You are connected to a mobile search and rescue team. ' + \
'Please SMS to {ph_phone_number} to communicate. ' + \
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import sys
import time
import datetime
import transaction
from sqlalchemy import engine_from_config
from pyramid.paster import (
get_appsettings,
setup_logging,
)
from model.hlr import (
HLRDBSession,
Subscriber
)
from model.models import (
DBSession,
Settings,
Base,
)
from com_interface.comms_interface_server import (
pf_subscriber_imsi,
pf_subscriber_extension,
pf_subscriber_name
)
and context (classes, functions, sometimes code) from other files:
# Path: model/hlr.py
# def bind_session(connection_string, echo=False):
# def user_data_decode(user_data, data_coding_scheme, ud_hdr_ind):
# def create_sms(src_addr, dest_addr, text, charset=None):
# class Subscriber(Base):
# class Sms(Base):
#
# Path: model/models.py
# def bind_session(connection_string, echo=False):
# class Measure(Base):
# class Settings(Base):
#
# Path: com_interface/comms_interface_server.py
# class RequestHandler(SimpleXMLRPCRequestHandler):
# class CommsInterfaceServer(object):
# def __init__(self, configuration, measure_model, time_to_shutdown_event):
# def serve_forever(self):
# def start_new_session(self):
# def try_run_xmlrpc_server(self):
# def try_run_vty_client(self):
# def process_measure_worker(self):
# def process_measure(self, meas):
# def get_formated_welcome_message(self, **wargs):
# def get_formated_reply_message(self, **wargs):
# def get_last_measure(self, imsi):
# def save_measure_to_db(self, meas, extension):
# def __calculate_distance(self, ta):
# def process_unknown_adress_sms_worker(self):
# def start_tracking(self):
# def stop_tracking(self):
# def tracking_process(self):
# def prepare_ready_for_silent_sms(self):
# def vty_send_silent_sms(self, imsi):
# def send_sms(self, imsi, text):
# def send_sms_by_phone_number(self, extension, text):
. Output only the next line. | 'Your temporary phone number is {ms_phone_number}' |
Given snippet: <|code_start|>
def usage(argv):
cmd = os.path.basename(argv[0])
print('usage: %s <config_uri>\n'
'(example: "%s development.ini")' % (cmd, cmd))
sys.exit(1)
def main(argv=sys.argv):
if len(argv) != 2:
usage(argv)
config_uri = argv[1]
setup_logging(config_uri)
settings = get_appsettings(config_uri)
engine = engine_from_config(settings, 'sqlalchemy.pf.')
DBSession.configure(bind=engine)
Base.metadata.create_all(engine)
hlr_engine = engine_from_config(settings, 'sqlalchemy.hlr.')
HLRDBSession.configure(bind=hlr_engine)
# initial settings
with transaction.manager:
DBSession.add_all([
Settings(name='imsiUpdate', value=3000),
Settings(name='smsUpdate', value=3000),
Settings(name='silentSms', value=3000),
Settings(
name='welcomeMessage',
value='You are connected to a mobile search and rescue team. ' + \
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import sys
import time
import datetime
import transaction
from sqlalchemy import engine_from_config
from pyramid.paster import (
get_appsettings,
setup_logging,
)
from model.hlr import (
HLRDBSession,
Subscriber
)
from model.models import (
DBSession,
Settings,
Base,
)
from com_interface.comms_interface_server import (
pf_subscriber_imsi,
pf_subscriber_extension,
pf_subscriber_name
)
and context:
# Path: model/hlr.py
# def bind_session(connection_string, echo=False):
# def user_data_decode(user_data, data_coding_scheme, ud_hdr_ind):
# def create_sms(src_addr, dest_addr, text, charset=None):
# class Subscriber(Base):
# class Sms(Base):
#
# Path: model/models.py
# def bind_session(connection_string, echo=False):
# class Measure(Base):
# class Settings(Base):
#
# Path: com_interface/comms_interface_server.py
# class RequestHandler(SimpleXMLRPCRequestHandler):
# class CommsInterfaceServer(object):
# def __init__(self, configuration, measure_model, time_to_shutdown_event):
# def serve_forever(self):
# def start_new_session(self):
# def try_run_xmlrpc_server(self):
# def try_run_vty_client(self):
# def process_measure_worker(self):
# def process_measure(self, meas):
# def get_formated_welcome_message(self, **wargs):
# def get_formated_reply_message(self, **wargs):
# def get_last_measure(self, imsi):
# def save_measure_to_db(self, meas, extension):
# def __calculate_distance(self, ta):
# def process_unknown_adress_sms_worker(self):
# def start_tracking(self):
# def stop_tracking(self):
# def tracking_process(self):
# def prepare_ready_for_silent_sms(self):
# def vty_send_silent_sms(self, imsi):
# def send_sms(self, imsi, text):
# def send_sms_by_phone_number(self, extension, text):
which might include code, classes, or functions. Output only the next line. | 'Please SMS to {ph_phone_number} to communicate. ' + \ |
Given the following code snippet before the placeholder: <|code_start|>
def usage(argv):
cmd = os.path.basename(argv[0])
print('usage: %s <config_uri>\n'
'(example: "%s development.ini")' % (cmd, cmd))
sys.exit(1)
def main(argv=sys.argv):
if len(argv) != 2:
usage(argv)
config_uri = argv[1]
setup_logging(config_uri)
settings = get_appsettings(config_uri)
engine = engine_from_config(settings, 'sqlalchemy.pf.')
DBSession.configure(bind=engine)
Base.metadata.create_all(engine)
hlr_engine = engine_from_config(settings, 'sqlalchemy.hlr.')
HLRDBSession.configure(bind=hlr_engine)
# initial settings
with transaction.manager:
DBSession.add_all([
Settings(name='imsiUpdate', value=3000),
Settings(name='smsUpdate', value=3000),
Settings(name='silentSms', value=3000),
Settings(
name='welcomeMessage',
value='You are connected to a mobile search and rescue team. ' + \
<|code_end|>
, predict the next line using imports from the current file:
import os
import sys
import time
import datetime
import transaction
from sqlalchemy import engine_from_config
from pyramid.paster import (
get_appsettings,
setup_logging,
)
from model.hlr import (
HLRDBSession,
Subscriber
)
from model.models import (
DBSession,
Settings,
Base,
)
from com_interface.comms_interface_server import (
pf_subscriber_imsi,
pf_subscriber_extension,
pf_subscriber_name
)
and context including class names, function names, and sometimes code from other files:
# Path: model/hlr.py
# def bind_session(connection_string, echo=False):
# def user_data_decode(user_data, data_coding_scheme, ud_hdr_ind):
# def create_sms(src_addr, dest_addr, text, charset=None):
# class Subscriber(Base):
# class Sms(Base):
#
# Path: model/models.py
# def bind_session(connection_string, echo=False):
# class Measure(Base):
# class Settings(Base):
#
# Path: com_interface/comms_interface_server.py
# class RequestHandler(SimpleXMLRPCRequestHandler):
# class CommsInterfaceServer(object):
# def __init__(self, configuration, measure_model, time_to_shutdown_event):
# def serve_forever(self):
# def start_new_session(self):
# def try_run_xmlrpc_server(self):
# def try_run_vty_client(self):
# def process_measure_worker(self):
# def process_measure(self, meas):
# def get_formated_welcome_message(self, **wargs):
# def get_formated_reply_message(self, **wargs):
# def get_last_measure(self, imsi):
# def save_measure_to_db(self, meas, extension):
# def __calculate_distance(self, ta):
# def process_unknown_adress_sms_worker(self):
# def start_tracking(self):
# def stop_tracking(self):
# def tracking_process(self):
# def prepare_ready_for_silent_sms(self):
# def vty_send_silent_sms(self, imsi):
# def send_sms(self, imsi, text):
# def send_sms_by_phone_number(self, extension, text):
. Output only the next line. | 'Please SMS to {ph_phone_number} to communicate. ' + \ |
Based on the snippet: <|code_start|>
def number_of_measurements_in_queue(self):
return len(self.queue)
def add_gps_meas(self, time, lat, lon):
self.__cc.add(time, lat, lon)
self.current_gps = (lat, lon)
def get_current_gps(self):
return self.current_gps
class CommsModelManager(BaseManager):
pass
CommsModelManager.register('CommsModel', CommsModel)
def start_comms_interface_server_process(configuration, comms_model):
logger = logging_utils.get_logger(multiprocessing.current_process().name)
try:
srv = CommsInterfaceServer(configuration, comms_model, multiprocessing.Event(), logger)
srv.serve_forever()
except ValueError as err:
logger.error("Cann't init comms interface server: {0}".format(err.message))
sys.exit(1)
def start_sms_server(configuration, comms_model):
logger = logging_utils.get_logger(multiprocessing.current_process().name)
try:
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import sys
import argparse
import ConfigParser
import time
import datetime
import multiprocessing
import transaction
import logging_utils
from multiprocessing.managers import BaseManager
from model.models import bind_session, DBSession, Measure, Settings
from model.hlr import bind_session as bind_hlr_session, HLRDBSession, Subscriber, Sms
from meas_json_client import MeasJsonListenerProcess
from gpsd_client import GPSDListenerProcess
from comms_interface_server import CommsInterfaceServer
from sms_server import SMSServer
and context (classes, functions, sometimes code) from other files:
# Path: model/models.py
# def bind_session(connection_string, echo=False):
# class Measure(Base):
# class Settings(Base):
#
# Path: model/hlr.py
# def bind_session(connection_string, echo=False):
# def user_data_decode(user_data, data_coding_scheme, ud_hdr_ind):
# def create_sms(src_addr, dest_addr, text, charset=None):
# class Subscriber(Base):
# class Sms(Base):
. Output only the next line. | srv = SMSServer(configuration, comms_model, logger)
|
Here is a snippet: <|code_start|> logger.info("Sms server STARTED with pid: {0}".format(
sms_server_process.pid))
meas_json_listener.start()
logger.info("meas_json listener STARTED with pid: {0}".format(
meas_json_listener.pid))
# Queue statistic ========================================================
try:
queue_measurement_size_prev = 0
while True:
if gpsd_listener.is_alive() is False:
gpsd_listener.terminate()
gpsd_listener.join()
gpsd_listener = GPSDListenerProcess(comms_model)
gpsd_listener.start()
logger.info("GPSD listener RESTARTED with pid: {0}".format(
gpsd_listener.pid))
queue_measurement_size = comms_model.number_of_measurements_in_queue()
if queue_measurement_size != queue_measurement_size_prev:
queue_measurement_size_prev = queue_measurement_size
logger.info(
"Number of measurements in queue change: {0}".format(
queue_measurement_size))
time.sleep(1)
except KeyboardInterrupt:
logger.info("KeyboardInterrupt")
<|code_end|>
. Write the next line using the current file imports:
import os
import sys
import argparse
import ConfigParser
import time
import datetime
import multiprocessing
import transaction
import logging_utils
from multiprocessing.managers import BaseManager
from model.models import bind_session, DBSession, Measure, Settings
from model.hlr import bind_session as bind_hlr_session, HLRDBSession, Subscriber, Sms
from meas_json_client import MeasJsonListenerProcess
from gpsd_client import GPSDListenerProcess
from comms_interface_server import CommsInterfaceServer
from sms_server import SMSServer
and context from other files:
# Path: model/models.py
# def bind_session(connection_string, echo=False):
# class Measure(Base):
# class Settings(Base):
#
# Path: model/hlr.py
# def bind_session(connection_string, echo=False):
# def user_data_decode(user_data, data_coding_scheme, ud_hdr_ind):
# def create_sms(src_addr, dest_addr, text, charset=None):
# class Subscriber(Base):
# class Sms(Base):
, which may include functions, classes, or code. Output only the next line. | comms_interface_server_process.terminate()
|
Given the following code snippet before the placeholder: <|code_start|> def add(self, time, lat, log):
if self.__count == self.__max_for_save:
self.__gps_times.pop(0)
self.__gps_coordinates.pop(0)
self.__count -= 1
self.__gps_times.append(time)
self.__gps_coordinates.append((lat, log))
self.__count += 1
def get_coordinates(self, time):
for index in xrange(0, self.__count):
if time <= self.__gps_times[index]:
return self.__gps_coordinates[index]
return self.__gps_coordinates[self.__count - 1]
class CommsModel(object):
def __init__(self):
self.queue = []
self.unknown_adresses_sms = []
self.__cc = GPSCoordinatesCollection()
self.current_gps = (None, None)
self.logger = logging_utils.get_logger("CommsModel")
<|code_end|>
, predict the next line using imports from the current file:
import os
import sys
import argparse
import ConfigParser
import time
import datetime
import multiprocessing
import transaction
import logging_utils
from multiprocessing.managers import BaseManager
from model.models import bind_session, DBSession, Measure, Settings
from model.hlr import bind_session as bind_hlr_session, HLRDBSession, Subscriber, Sms
from meas_json_client import MeasJsonListenerProcess
from gpsd_client import GPSDListenerProcess
from comms_interface_server import CommsInterfaceServer
from sms_server import SMSServer
and context including class names, function names, and sometimes code from other files:
# Path: model/models.py
# def bind_session(connection_string, echo=False):
# class Measure(Base):
# class Settings(Base):
#
# Path: model/hlr.py
# def bind_session(connection_string, echo=False):
# def user_data_decode(user_data, data_coding_scheme, ud_hdr_ind):
# def create_sms(src_addr, dest_addr, text, charset=None):
# class Subscriber(Base):
# class Sms(Base):
. Output only the next line. | def put_measurement(self, obj):
|
Predict the next line after this snippet: <|code_start|>if __name__ == "__main__":
parser = argparse.ArgumentParser(
description='People finder. Comm interface.')
parser.add_argument('-c', '--configuration', type=file, required=True)
parser.add_argument('-t', '--test_mode', action='store_true')
args = parser.parse_args()
configuration = ConfigParser.ConfigParser()
configuration.readfp(args.configuration)
logger = logging_utils.get_logger("main")
logger.info("Comm interface started! pid: {0}".format(os.getpid()))
# Init DB ================================================================
pf_db_conn_str = None
try:
pf_db_conn_str = configuration.get('app:main', 'sqlalchemy.pf.url')
except ConfigParser.Error as err:
logger.error("Identification People Finder DB fail: {0}".format(err.message))
sys.exit(1)
logger.info("PF db sqlite path: {0}".format(pf_db_conn_str))
try:
bind_session(pf_db_conn_str)
DBSession.query(Measure).count()
DBSession.query(Settings).count()
except:
logger.error("People finder DB connection err")
raise
<|code_end|>
using the current file's imports:
import os
import sys
import argparse
import ConfigParser
import time
import datetime
import multiprocessing
import transaction
import logging_utils
from multiprocessing.managers import BaseManager
from model.models import bind_session, DBSession, Measure, Settings
from model.hlr import bind_session as bind_hlr_session, HLRDBSession, Subscriber, Sms
from meas_json_client import MeasJsonListenerProcess
from gpsd_client import GPSDListenerProcess
from comms_interface_server import CommsInterfaceServer
from sms_server import SMSServer
and any relevant context from other files:
# Path: model/models.py
# def bind_session(connection_string, echo=False):
# class Measure(Base):
# class Settings(Base):
#
# Path: model/hlr.py
# def bind_session(connection_string, echo=False):
# def user_data_decode(user_data, data_coding_scheme, ud_hdr_ind):
# def create_sms(src_addr, dest_addr, text, charset=None):
# class Subscriber(Base):
# class Sms(Base):
. Output only the next line. | hlr_db_conn_str = None
|
Based on the snippet: <|code_start|> self.__gps_coordinates = []
self.__count = 0
self.__max_for_save = 100
self.logger = logging_utils.get_logger("GPSCoordinatesCollection")
self.add(time.time(), None, None)
def add(self, time, lat, log):
if self.__count == self.__max_for_save:
self.__gps_times.pop(0)
self.__gps_coordinates.pop(0)
self.__count -= 1
self.__gps_times.append(time)
self.__gps_coordinates.append((lat, log))
self.__count += 1
def get_coordinates(self, time):
for index in xrange(0, self.__count):
if time <= self.__gps_times[index]:
return self.__gps_coordinates[index]
return self.__gps_coordinates[self.__count - 1]
class CommsModel(object):
def __init__(self):
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import sys
import argparse
import ConfigParser
import time
import datetime
import multiprocessing
import transaction
import logging_utils
from multiprocessing.managers import BaseManager
from model.models import bind_session, DBSession, Measure, Settings
from model.hlr import bind_session as bind_hlr_session, HLRDBSession, Subscriber, Sms
from meas_json_client import MeasJsonListenerProcess
from gpsd_client import GPSDListenerProcess
from comms_interface_server import CommsInterfaceServer
from sms_server import SMSServer
and context (classes, functions, sometimes code) from other files:
# Path: model/models.py
# def bind_session(connection_string, echo=False):
# class Measure(Base):
# class Settings(Base):
#
# Path: model/hlr.py
# def bind_session(connection_string, echo=False):
# def user_data_decode(user_data, data_coding_scheme, ud_hdr_ind):
# def create_sms(src_addr, dest_addr, text, charset=None):
# class Subscriber(Base):
# class Sms(Base):
. Output only the next line. | self.queue = []
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.