Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Based on the snippet: <|code_start|>
class TestProfileCopier(BaseTestCase):
def setUp(self):
self.profile = Profile('test/vimrc')
self.settings = Settings(os.path.normpath('/home/foo'))
self.diskIo = Stubs.DiskIoStub()
# We use the real ProfileCache (with stubbed dependencies) because
# ProfileCache.getProfileLocation gets called by ProfileCopier
self.profileCache = ProfileCache(self.settings, self.diskIo)
self.profileDataIo = Stubs.ProfileDataIoStub()
self.profileCopier = ProfileCopier(self.settings, self.profileCache, self.profileDataIo)
# ProfileCopier.copyToHome(profile)
def test_copyToHome_deletesHomeData(self):
self.profileCopier.copyToHome(self.profile)
<|code_end|>
, predict the immediate next line with the help of imports:
from . import Stubs
from .BaseTestCase import BaseTestCase
from mock import MagicMock
from vimswitch.Profile import Profile
from vimswitch.ProfileCache import ProfileCache
from vimswitch.ProfileCopier import ProfileCopier
from vimswitch.Settings import Settings
import os
and context (classes, functions, sometimes code) from other files:
# Path: vimswitch/test/BaseTestCase.py
# class BaseTestCase(unittest.TestCase):
# def __init__(self, *args, **kwargs):
# unittest.TestCase.__init__(self, *args, **kwargs)
#
# # Python < 3.2 does not have assertNotRegex
# if not hasattr(self, 'assertNotRegex'):
# self.assertNotRegex = self.assertNotRegexpMatches
#
# def assertMultilineRegexpMatches(self, string, regexp):
# """
# Asserts that the entirety of `string` matches `regexp`. `regexp` can be
# a multiline string with indentation.
# """
# regexp = textwrap.dedent(regexp)
# regexp = regexp.strip()
# regexp = '^' + regexp + '$'
# regexp = re.compile(regexp, re.DOTALL)
#
# self.assertRegexpMatches(string, regexp)
#
# def assertStdout(self, stdout, regexp):
# "Asserts that the `stdout` io stream matches `regexp`"
# stdoutText = stdout.getvalue().strip()
# self.assertMultilineRegexpMatches(stdoutText, regexp)
#
# def resetStdout(self, stdout):
# stdout.seek(0)
# stdout.truncate(0)
#
# Path: vimswitch/Profile.py
# class Profile:
# def __init__(self, name):
# self.name = name
#
# def getName(self):
# return self.name
#
# def getDirName(self):
# return self.name.replace('/', '.')
#
# def __eq__(self, other):
# return isinstance(other, Profile) and self.name == other.name
#
# def __ne__(self, other):
# return not self.__eq__(other)
#
# def __repr__(self):
# return "Profile('%s')" % self.name
#
# Path: vimswitch/ProfileCache.py
# class ProfileCache:
# def __init__(self, settings, diskIo):
# self.settings = settings
# self.diskIo = diskIo
#
# def contains(self, profile):
# profileLocation = self.getProfileLocation(profile)
# return self.diskIo.dirExists(profileLocation)
#
# def delete(self, profile):
# profileDirPath = self.getProfileLocation(profile)
# self.diskIo.deleteDir(profileDirPath)
#
# def getProfileLocation(self, profile):
# """Returns the path where profile is located"""
# fullPath = os.path.join(self.settings.cachePath, profile.getDirName())
# return os.path.normpath(fullPath)
#
# def createEmptyProfile(self, profile):
# location = self.getProfileLocation(profile)
# self.diskIo.createDir(location)
#
# Path: vimswitch/ProfileCopier.py
# class ProfileCopier:
# def __init__(self, settings, profileCache, profileDataIo):
# self.settings = settings
# self.profileCache = profileCache
# self.profileDataIo = profileDataIo
#
# def copyToHome(self, profile):
# """
# Copies the cached profile to home, thus making it active
# """
# # TODO: If profileDataIo.copy fails, then we are left with an empty
# # profile at home. So we should use the 'operate on temp then rename'
# # pattern
# homePath = self.settings.homePath
# profilePath = self.profileCache.getProfileLocation(profile)
# self.profileDataIo.delete(homePath)
# self.profileDataIo.copy(profilePath, homePath)
#
# def copyFromHome(self, profile):
# """
# Copies the active profile data at home to a specified profile in cache.
# If the profile already exists in cache, it gets overwritten.
# """
# if not self.profileCache.contains(profile):
# self.profileCache.createEmptyProfile(profile)
# profilePath = self.profileCache.getProfileLocation(profile)
# homePath = self.settings.homePath
# self.profileDataIo.delete(profilePath)
# self.profileDataIo.copy(homePath, profilePath)
#
# Path: vimswitch/Settings.py
# class Settings:
#
# def __init__(self, homePath=''):
# """
# homePath is used as the prefix for all other paths. If homePath is not
# specified it gets set to the user's home directory.
# """
# self.homePath = homePath or os.path.expanduser('~')
# self.configPath = os.path.join(self.homePath, '.vimswitch')
# self.configFilePath = os.path.join(self.configPath, 'vimswitchrc')
# self.cachePath = os.path.join(self.configPath, 'profiles')
# self.downloadsPath = os.path.join(self.configPath, 'downloads')
# self.profileFiles = ['.vimrc', '_vimrc']
# self.profileDirs = ['.vim', '_vim']
# self.defaultProfile = Profile('default')
# self.currentProfile = None
#
# def __eq__(self, other):
# return self.__dict__ == other.__dict__
. Output only the next line. | homePath = os.path.normpath('/home/foo') |
Given the code snippet: <|code_start|>
class TestProfileCopier(BaseTestCase):
def setUp(self):
self.profile = Profile('test/vimrc')
self.settings = Settings(os.path.normpath('/home/foo'))
self.diskIo = Stubs.DiskIoStub()
# We use the real ProfileCache (with stubbed dependencies) because
# ProfileCache.getProfileLocation gets called by ProfileCopier
self.profileCache = ProfileCache(self.settings, self.diskIo)
self.profileDataIo = Stubs.ProfileDataIoStub()
self.profileCopier = ProfileCopier(self.settings, self.profileCache, self.profileDataIo)
# ProfileCopier.copyToHome(profile)
def test_copyToHome_deletesHomeData(self):
self.profileCopier.copyToHome(self.profile)
homePath = os.path.normpath('/home/foo')
self.profileDataIo.delete.assert_called_with(homePath)
def test_copyToHome_deletesHomeDir_fromSettings(self):
self.settings.homePath = 'testHomeDir'
self.profileCopier.copyToHome(self.profile)
self.profileDataIo.delete.assert_called_with(os.path.normpath('testHomeDir'))
<|code_end|>
, generate the next line using the imports in this file:
from . import Stubs
from .BaseTestCase import BaseTestCase
from mock import MagicMock
from vimswitch.Profile import Profile
from vimswitch.ProfileCache import ProfileCache
from vimswitch.ProfileCopier import ProfileCopier
from vimswitch.Settings import Settings
import os
and context (functions, classes, or occasionally code) from other files:
# Path: vimswitch/test/BaseTestCase.py
# class BaseTestCase(unittest.TestCase):
# def __init__(self, *args, **kwargs):
# unittest.TestCase.__init__(self, *args, **kwargs)
#
# # Python < 3.2 does not have assertNotRegex
# if not hasattr(self, 'assertNotRegex'):
# self.assertNotRegex = self.assertNotRegexpMatches
#
# def assertMultilineRegexpMatches(self, string, regexp):
# """
# Asserts that the entirety of `string` matches `regexp`. `regexp` can be
# a multiline string with indentation.
# """
# regexp = textwrap.dedent(regexp)
# regexp = regexp.strip()
# regexp = '^' + regexp + '$'
# regexp = re.compile(regexp, re.DOTALL)
#
# self.assertRegexpMatches(string, regexp)
#
# def assertStdout(self, stdout, regexp):
# "Asserts that the `stdout` io stream matches `regexp`"
# stdoutText = stdout.getvalue().strip()
# self.assertMultilineRegexpMatches(stdoutText, regexp)
#
# def resetStdout(self, stdout):
# stdout.seek(0)
# stdout.truncate(0)
#
# Path: vimswitch/Profile.py
# class Profile:
# def __init__(self, name):
# self.name = name
#
# def getName(self):
# return self.name
#
# def getDirName(self):
# return self.name.replace('/', '.')
#
# def __eq__(self, other):
# return isinstance(other, Profile) and self.name == other.name
#
# def __ne__(self, other):
# return not self.__eq__(other)
#
# def __repr__(self):
# return "Profile('%s')" % self.name
#
# Path: vimswitch/ProfileCache.py
# class ProfileCache:
# def __init__(self, settings, diskIo):
# self.settings = settings
# self.diskIo = diskIo
#
# def contains(self, profile):
# profileLocation = self.getProfileLocation(profile)
# return self.diskIo.dirExists(profileLocation)
#
# def delete(self, profile):
# profileDirPath = self.getProfileLocation(profile)
# self.diskIo.deleteDir(profileDirPath)
#
# def getProfileLocation(self, profile):
# """Returns the path where profile is located"""
# fullPath = os.path.join(self.settings.cachePath, profile.getDirName())
# return os.path.normpath(fullPath)
#
# def createEmptyProfile(self, profile):
# location = self.getProfileLocation(profile)
# self.diskIo.createDir(location)
#
# Path: vimswitch/ProfileCopier.py
# class ProfileCopier:
# def __init__(self, settings, profileCache, profileDataIo):
# self.settings = settings
# self.profileCache = profileCache
# self.profileDataIo = profileDataIo
#
# def copyToHome(self, profile):
# """
# Copies the cached profile to home, thus making it active
# """
# # TODO: If profileDataIo.copy fails, then we are left with an empty
# # profile at home. So we should use the 'operate on temp then rename'
# # pattern
# homePath = self.settings.homePath
# profilePath = self.profileCache.getProfileLocation(profile)
# self.profileDataIo.delete(homePath)
# self.profileDataIo.copy(profilePath, homePath)
#
# def copyFromHome(self, profile):
# """
# Copies the active profile data at home to a specified profile in cache.
# If the profile already exists in cache, it gets overwritten.
# """
# if not self.profileCache.contains(profile):
# self.profileCache.createEmptyProfile(profile)
# profilePath = self.profileCache.getProfileLocation(profile)
# homePath = self.settings.homePath
# self.profileDataIo.delete(profilePath)
# self.profileDataIo.copy(homePath, profilePath)
#
# Path: vimswitch/Settings.py
# class Settings:
#
# def __init__(self, homePath=''):
# """
# homePath is used as the prefix for all other paths. If homePath is not
# specified it gets set to the user's home directory.
# """
# self.homePath = homePath or os.path.expanduser('~')
# self.configPath = os.path.join(self.homePath, '.vimswitch')
# self.configFilePath = os.path.join(self.configPath, 'vimswitchrc')
# self.cachePath = os.path.join(self.configPath, 'profiles')
# self.downloadsPath = os.path.join(self.configPath, 'downloads')
# self.profileFiles = ['.vimrc', '_vimrc']
# self.profileDirs = ['.vim', '_vim']
# self.defaultProfile = Profile('default')
# self.currentProfile = None
#
# def __eq__(self, other):
# return self.__dict__ == other.__dict__
. Output only the next line. | def test_copyToHome_copiesFromProfileToHome(self): |
Predict the next line for this snippet: <|code_start|>
class VimSwitch:
def __init__(self, app=Application()):
self.app = app
self.raiseExceptions = False
<|code_end|>
with the help of current file imports:
from .ActionResolver import getActionResolver
from .Application import Application
from .ApplicationDirs import getApplicationDirs
from .CommandLineParser import getCommandLineParser
from .ConfigFile import getConfigFile
from .Settings import getSettings
and context from other files:
# Path: vimswitch/ActionResolver.py
# def getActionResolver(app):
# return app.get('actionResolver', createActionResolver(app))
#
# Path: vimswitch/Application.py
# class Application:
# """
# A container for components that are used application-wide.
#
# Examples of how this class can be used:
#
# - Set a component
# `app.foo = myFoo`
#
# - Get (or create) a component:
# `foo = app.get('foo', Foo())`
# This will try to return `app.foo`. If that does not exist, then it will
# set `app.foo = Foo()` and return that instead.
#
# - Get an already created component
# `foo = app.foo`
# Use this when you are sure that app.foo has already been set
# """
#
# def get(self, attr, default):
# """
# Returns self.attr. If attr does not exist, then make self.attr = default
# and then return default.
# """
# if hasattr(self, attr):
# return getattr(self, attr)
# else:
# setattr(self, attr, default)
# return default
#
# Path: vimswitch/ApplicationDirs.py
# def getApplicationDirs(app):
# return app.get('applicationDirs', createApplicationDirs(app))
#
# Path: vimswitch/CommandLineParser.py
# def getCommandLineParser(app):
# return app.get('commandLineParser', createCommandLineParser(app))
#
# Path: vimswitch/ConfigFile.py
# def getConfigFile(app):
# return app.get('configFile', createConfigFile(app))
#
# Path: vimswitch/Settings.py
# def getSettings(app):
# return app.get('settings', createSettings(app))
, which may contain function names, class names, or code. Output only the next line. | def main(self, argv): |
Here is a snippet: <|code_start|>
class VimSwitch:
def __init__(self, app=Application()):
self.app = app
<|code_end|>
. Write the next line using the current file imports:
from .ActionResolver import getActionResolver
from .Application import Application
from .ApplicationDirs import getApplicationDirs
from .CommandLineParser import getCommandLineParser
from .ConfigFile import getConfigFile
from .Settings import getSettings
and context from other files:
# Path: vimswitch/ActionResolver.py
# def getActionResolver(app):
# return app.get('actionResolver', createActionResolver(app))
#
# Path: vimswitch/Application.py
# class Application:
# """
# A container for components that are used application-wide.
#
# Examples of how this class can be used:
#
# - Set a component
# `app.foo = myFoo`
#
# - Get (or create) a component:
# `foo = app.get('foo', Foo())`
# This will try to return `app.foo`. If that does not exist, then it will
# set `app.foo = Foo()` and return that instead.
#
# - Get an already created component
# `foo = app.foo`
# Use this when you are sure that app.foo has already been set
# """
#
# def get(self, attr, default):
# """
# Returns self.attr. If attr does not exist, then make self.attr = default
# and then return default.
# """
# if hasattr(self, attr):
# return getattr(self, attr)
# else:
# setattr(self, attr, default)
# return default
#
# Path: vimswitch/ApplicationDirs.py
# def getApplicationDirs(app):
# return app.get('applicationDirs', createApplicationDirs(app))
#
# Path: vimswitch/CommandLineParser.py
# def getCommandLineParser(app):
# return app.get('commandLineParser', createCommandLineParser(app))
#
# Path: vimswitch/ConfigFile.py
# def getConfigFile(app):
# return app.get('configFile', createConfigFile(app))
#
# Path: vimswitch/Settings.py
# def getSettings(app):
# return app.get('settings', createSettings(app))
, which may include functions, classes, or code. Output only the next line. | self.raiseExceptions = False |
Continue the code snippet: <|code_start|>
class VimSwitch:
def __init__(self, app=Application()):
self.app = app
<|code_end|>
. Use current file imports:
from .ActionResolver import getActionResolver
from .Application import Application
from .ApplicationDirs import getApplicationDirs
from .CommandLineParser import getCommandLineParser
from .ConfigFile import getConfigFile
from .Settings import getSettings
and context (classes, functions, or code) from other files:
# Path: vimswitch/ActionResolver.py
# def getActionResolver(app):
# return app.get('actionResolver', createActionResolver(app))
#
# Path: vimswitch/Application.py
# class Application:
# """
# A container for components that are used application-wide.
#
# Examples of how this class can be used:
#
# - Set a component
# `app.foo = myFoo`
#
# - Get (or create) a component:
# `foo = app.get('foo', Foo())`
# This will try to return `app.foo`. If that does not exist, then it will
# set `app.foo = Foo()` and return that instead.
#
# - Get an already created component
# `foo = app.foo`
# Use this when you are sure that app.foo has already been set
# """
#
# def get(self, attr, default):
# """
# Returns self.attr. If attr does not exist, then make self.attr = default
# and then return default.
# """
# if hasattr(self, attr):
# return getattr(self, attr)
# else:
# setattr(self, attr, default)
# return default
#
# Path: vimswitch/ApplicationDirs.py
# def getApplicationDirs(app):
# return app.get('applicationDirs', createApplicationDirs(app))
#
# Path: vimswitch/CommandLineParser.py
# def getCommandLineParser(app):
# return app.get('commandLineParser', createCommandLineParser(app))
#
# Path: vimswitch/ConfigFile.py
# def getConfigFile(app):
# return app.get('configFile', createConfigFile(app))
#
# Path: vimswitch/Settings.py
# def getSettings(app):
# return app.get('settings', createSettings(app))
. Output only the next line. | self.raiseExceptions = False |
Predict the next line for this snippet: <|code_start|>
class TestProfileUrlResolver(BaseTestCase):
def test_getProfileUrl_convertsUserSlashRepo(self):
profile = Profile('testuser/testrepo')
url = getProfileUrl(profile)
expectedUrl = 'https://github.com/testuser/testrepo/archive/master.zip'
<|code_end|>
with the help of current file imports:
from .BaseTestCase import BaseTestCase
from vimswitch.Profile import Profile
from vimswitch.ProfileUrlResolver import getProfileUrl
and context from other files:
# Path: vimswitch/test/BaseTestCase.py
# class BaseTestCase(unittest.TestCase):
# def __init__(self, *args, **kwargs):
# unittest.TestCase.__init__(self, *args, **kwargs)
#
# # Python < 3.2 does not have assertNotRegex
# if not hasattr(self, 'assertNotRegex'):
# self.assertNotRegex = self.assertNotRegexpMatches
#
# def assertMultilineRegexpMatches(self, string, regexp):
# """
# Asserts that the entirety of `string` matches `regexp`. `regexp` can be
# a multiline string with indentation.
# """
# regexp = textwrap.dedent(regexp)
# regexp = regexp.strip()
# regexp = '^' + regexp + '$'
# regexp = re.compile(regexp, re.DOTALL)
#
# self.assertRegexpMatches(string, regexp)
#
# def assertStdout(self, stdout, regexp):
# "Asserts that the `stdout` io stream matches `regexp`"
# stdoutText = stdout.getvalue().strip()
# self.assertMultilineRegexpMatches(stdoutText, regexp)
#
# def resetStdout(self, stdout):
# stdout.seek(0)
# stdout.truncate(0)
#
# Path: vimswitch/Profile.py
# class Profile:
# def __init__(self, name):
# self.name = name
#
# def getName(self):
# return self.name
#
# def getDirName(self):
# return self.name.replace('/', '.')
#
# def __eq__(self, other):
# return isinstance(other, Profile) and self.name == other.name
#
# def __ne__(self, other):
# return not self.__eq__(other)
#
# def __repr__(self):
# return "Profile('%s')" % self.name
#
# Path: vimswitch/ProfileUrlResolver.py
# def getProfileUrl(profile):
# prefix = 'https://github.com/'
# suffix = '/archive/master.zip'
# url = prefix + profile.getName() + suffix
# return url
, which may contain function names, class names, or code. Output only the next line. | self.assertEqual(url, expectedUrl) |
Here is a snippet: <|code_start|>
class TestProfileUrlResolver(BaseTestCase):
def test_getProfileUrl_convertsUserSlashRepo(self):
profile = Profile('testuser/testrepo')
url = getProfileUrl(profile)
expectedUrl = 'https://github.com/testuser/testrepo/archive/master.zip'
<|code_end|>
. Write the next line using the current file imports:
from .BaseTestCase import BaseTestCase
from vimswitch.Profile import Profile
from vimswitch.ProfileUrlResolver import getProfileUrl
and context from other files:
# Path: vimswitch/test/BaseTestCase.py
# class BaseTestCase(unittest.TestCase):
# def __init__(self, *args, **kwargs):
# unittest.TestCase.__init__(self, *args, **kwargs)
#
# # Python < 3.2 does not have assertNotRegex
# if not hasattr(self, 'assertNotRegex'):
# self.assertNotRegex = self.assertNotRegexpMatches
#
# def assertMultilineRegexpMatches(self, string, regexp):
# """
# Asserts that the entirety of `string` matches `regexp`. `regexp` can be
# a multiline string with indentation.
# """
# regexp = textwrap.dedent(regexp)
# regexp = regexp.strip()
# regexp = '^' + regexp + '$'
# regexp = re.compile(regexp, re.DOTALL)
#
# self.assertRegexpMatches(string, regexp)
#
# def assertStdout(self, stdout, regexp):
# "Asserts that the `stdout` io stream matches `regexp`"
# stdoutText = stdout.getvalue().strip()
# self.assertMultilineRegexpMatches(stdoutText, regexp)
#
# def resetStdout(self, stdout):
# stdout.seek(0)
# stdout.truncate(0)
#
# Path: vimswitch/Profile.py
# class Profile:
# def __init__(self, name):
# self.name = name
#
# def getName(self):
# return self.name
#
# def getDirName(self):
# return self.name.replace('/', '.')
#
# def __eq__(self, other):
# return isinstance(other, Profile) and self.name == other.name
#
# def __ne__(self, other):
# return not self.__eq__(other)
#
# def __repr__(self):
# return "Profile('%s')" % self.name
#
# Path: vimswitch/ProfileUrlResolver.py
# def getProfileUrl(profile):
# prefix = 'https://github.com/'
# suffix = '/archive/master.zip'
# url = prefix + profile.getName() + suffix
# return url
, which may include functions, classes, or code. Output only the next line. | self.assertEqual(url, expectedUrl) |
Given the following code snippet before the placeholder: <|code_start|>
class TestProfileUrlResolver(BaseTestCase):
def test_getProfileUrl_convertsUserSlashRepo(self):
profile = Profile('testuser/testrepo')
url = getProfileUrl(profile)
<|code_end|>
, predict the next line using imports from the current file:
from .BaseTestCase import BaseTestCase
from vimswitch.Profile import Profile
from vimswitch.ProfileUrlResolver import getProfileUrl
and context including class names, function names, and sometimes code from other files:
# Path: vimswitch/test/BaseTestCase.py
# class BaseTestCase(unittest.TestCase):
# def __init__(self, *args, **kwargs):
# unittest.TestCase.__init__(self, *args, **kwargs)
#
# # Python < 3.2 does not have assertNotRegex
# if not hasattr(self, 'assertNotRegex'):
# self.assertNotRegex = self.assertNotRegexpMatches
#
# def assertMultilineRegexpMatches(self, string, regexp):
# """
# Asserts that the entirety of `string` matches `regexp`. `regexp` can be
# a multiline string with indentation.
# """
# regexp = textwrap.dedent(regexp)
# regexp = regexp.strip()
# regexp = '^' + regexp + '$'
# regexp = re.compile(regexp, re.DOTALL)
#
# self.assertRegexpMatches(string, regexp)
#
# def assertStdout(self, stdout, regexp):
# "Asserts that the `stdout` io stream matches `regexp`"
# stdoutText = stdout.getvalue().strip()
# self.assertMultilineRegexpMatches(stdoutText, regexp)
#
# def resetStdout(self, stdout):
# stdout.seek(0)
# stdout.truncate(0)
#
# Path: vimswitch/Profile.py
# class Profile:
# def __init__(self, name):
# self.name = name
#
# def getName(self):
# return self.name
#
# def getDirName(self):
# return self.name.replace('/', '.')
#
# def __eq__(self, other):
# return isinstance(other, Profile) and self.name == other.name
#
# def __ne__(self, other):
# return not self.__eq__(other)
#
# def __repr__(self):
# return "Profile('%s')" % self.name
#
# Path: vimswitch/ProfileUrlResolver.py
# def getProfileUrl(profile):
# prefix = 'https://github.com/'
# suffix = '/archive/master.zip'
# url = prefix + profile.getName() + suffix
# return url
. Output only the next line. | expectedUrl = 'https://github.com/testuser/testrepo/archive/master.zip' |
Here is a snippet: <|code_start|>
class FileDownloader:
def __init__(self, settings, diskIo):
self.settings = settings
self.diskIo = diskIo
<|code_end|>
. Write the next line using the current file imports:
import os
import re
import datetime
from .six.moves.urllib_parse import urlparse
from .six.moves.urllib_request import FancyURLopener
from .Settings import getSettings
from .DiskIo import getDiskIo
and context from other files:
# Path: vimswitch/Settings.py
# def getSettings(app):
# return app.get('settings', createSettings(app))
#
# Path: vimswitch/DiskIo.py
# def getDiskIo(app):
# return app.get('diskIo', createDiskIo(app))
, which may include functions, classes, or code. Output only the next line. | def download(self, url, path): |
Given snippet: <|code_start|>
# ProfileDataIo.delete#dirs
def test_delete_whenDirExists_deletesDir(self):
profilePath = os.path.normpath('/home/foo')
self.diskIo.dirExists.return_value = True
self.profileDataIo.delete(profilePath)
self.diskIo.deleteDir.assert_any_call(os.path.normpath('/home/foo/.vim'))
def test_delete_whenDirDoesNotExists_doesNotDeleteDir(self):
profilePath = os.path.normpath('/home/foo')
self.diskIo.dirExists.return_value = False
self.profileDataIo.delete(profilePath)
assertNoCall(self.diskIo.deleteDir, os.path.normpath('/home/foo/.vim'))
def test_delete_usesGetProfileDirs_fromSettings(self):
profilePath = os.path.normpath('/home/foo')
self.diskIo.dirExists.return_value = True
self.settings.profileDirs = ['testProfileDir']
self.profileDataIo.delete(profilePath)
self.diskIo.deleteDir.assert_any_call(os.path.normpath('/home/foo/testProfileDir'))
def test_delete_deletesMultipleDirs(self):
profilePath = os.path.normpath('/home/foo')
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from . import Stubs
from .BaseTestCase import BaseTestCase
from .TestHelpers import assertNoCall
from vimswitch.ProfileDataIo import ProfileDataIo
from vimswitch.Settings import Settings
import os
and context:
# Path: vimswitch/test/BaseTestCase.py
# class BaseTestCase(unittest.TestCase):
# def __init__(self, *args, **kwargs):
# unittest.TestCase.__init__(self, *args, **kwargs)
#
# # Python < 3.2 does not have assertNotRegex
# if not hasattr(self, 'assertNotRegex'):
# self.assertNotRegex = self.assertNotRegexpMatches
#
# def assertMultilineRegexpMatches(self, string, regexp):
# """
# Asserts that the entirety of `string` matches `regexp`. `regexp` can be
# a multiline string with indentation.
# """
# regexp = textwrap.dedent(regexp)
# regexp = regexp.strip()
# regexp = '^' + regexp + '$'
# regexp = re.compile(regexp, re.DOTALL)
#
# self.assertRegexpMatches(string, regexp)
#
# def assertStdout(self, stdout, regexp):
# "Asserts that the `stdout` io stream matches `regexp`"
# stdoutText = stdout.getvalue().strip()
# self.assertMultilineRegexpMatches(stdoutText, regexp)
#
# def resetStdout(self, stdout):
# stdout.seek(0)
# stdout.truncate(0)
#
# Path: vimswitch/test/TestHelpers.py
# def assertNoCall(mock, *args):
# calledWith = False
# try:
# mock.assert_any_call(*args)
# calledWith = True
# except AssertionError:
# pass
#
# if calledWith:
# raise AssertionError('Mock called with arguments', mock, args)
#
# Path: vimswitch/ProfileDataIo.py
# class ProfileDataIo:
# def __init__(self, settings, diskIo):
# self.settings = settings
# self.diskIo = diskIo
#
# def delete(self, path):
# """Deletes profile data found at path"""
# for file in self.settings.profileFiles:
# filePath = os.path.join(path, file)
# if self.diskIo.fileExists(filePath):
# self.diskIo.deleteFile(filePath)
#
# for dir in self.settings.profileDirs:
# dirPath = os.path.join(path, dir)
# if self.diskIo.dirExists(dirPath):
# self.diskIo.deleteDir(dirPath)
#
# def copy(self, srcPath, destPath):
# """
# Copies profile data from srcPath to destPath. Will replace existing
# files at destPath.
# """
# for file in self.settings.profileFiles:
# srcFilePath = os.path.join(srcPath, file)
# destFilePath = os.path.join(destPath, file)
# if self.diskIo.fileExists(srcFilePath):
# self.diskIo.copyFile(srcFilePath, destFilePath)
#
# for dir in self.settings.profileDirs:
# srcDirPath = os.path.join(srcPath, dir)
# destDirPath = os.path.join(destPath, dir)
# if self.diskIo.dirExists(srcDirPath):
# self.diskIo.copyDir(srcDirPath, destDirPath)
#
# Path: vimswitch/Settings.py
# class Settings:
#
# def __init__(self, homePath=''):
# """
# homePath is used as the prefix for all other paths. If homePath is not
# specified it gets set to the user's home directory.
# """
# self.homePath = homePath or os.path.expanduser('~')
# self.configPath = os.path.join(self.homePath, '.vimswitch')
# self.configFilePath = os.path.join(self.configPath, 'vimswitchrc')
# self.cachePath = os.path.join(self.configPath, 'profiles')
# self.downloadsPath = os.path.join(self.configPath, 'downloads')
# self.profileFiles = ['.vimrc', '_vimrc']
# self.profileDirs = ['.vim', '_vim']
# self.defaultProfile = Profile('default')
# self.currentProfile = None
#
# def __eq__(self, other):
# return self.__dict__ == other.__dict__
which might include code, classes, or functions. Output only the next line. | self.diskIo.dirExists.return_value = True |
Given the following code snippet before the placeholder: <|code_start|>
self.diskIo.deleteFile.assert_any_call(os.path.normpath('/home/foo/file1'))
self.diskIo.deleteFile.assert_any_call(os.path.normpath('/home/foo/file2'))
self.diskIo.deleteDir.assert_any_call(os.path.normpath('/home/foo/dir1'))
self.diskIo.deleteDir.assert_any_call(os.path.normpath('/home/foo/dir2'))
# ProfileDataIo.copy#files
def test_copy_whenFileExists_copiesFile(self):
srcPath = os.path.normpath('/home/foo/.vimswitch/profiles/test.vimrc')
destPath = os.path.normpath('/home/foo')
self.diskIo.fileExists.return_value = True
self.profileDataIo.copy(srcPath, destPath)
srcFile = os.path.normpath('/home/foo/.vimswitch/profiles/test.vimrc/.vimrc')
destFile = os.path.normpath('/home/foo/.vimrc')
self.diskIo.copyFile.assert_any_call(srcFile, destFile)
def test_copy_whenFileDoesNotExists_doesNotCopyFile(self):
srcPath = os.path.normpath('/home/foo/.vimswitch/profiles/test.vimrc')
destPath = os.path.normpath('/home/foo')
self.diskIo.fileExists.return_value = False
self.profileDataIo.copy(srcPath, destPath)
srcFile = os.path.normpath('/home/foo/.vimswitch/profiles/test.vimrc/.vimrc')
destFile = os.path.normpath('/home/foo/.vimrc')
assertNoCall(self.diskIo.copyFile, srcFile, destFile)
<|code_end|>
, predict the next line using imports from the current file:
from . import Stubs
from .BaseTestCase import BaseTestCase
from .TestHelpers import assertNoCall
from vimswitch.ProfileDataIo import ProfileDataIo
from vimswitch.Settings import Settings
import os
and context including class names, function names, and sometimes code from other files:
# Path: vimswitch/test/BaseTestCase.py
# class BaseTestCase(unittest.TestCase):
# def __init__(self, *args, **kwargs):
# unittest.TestCase.__init__(self, *args, **kwargs)
#
# # Python < 3.2 does not have assertNotRegex
# if not hasattr(self, 'assertNotRegex'):
# self.assertNotRegex = self.assertNotRegexpMatches
#
# def assertMultilineRegexpMatches(self, string, regexp):
# """
# Asserts that the entirety of `string` matches `regexp`. `regexp` can be
# a multiline string with indentation.
# """
# regexp = textwrap.dedent(regexp)
# regexp = regexp.strip()
# regexp = '^' + regexp + '$'
# regexp = re.compile(regexp, re.DOTALL)
#
# self.assertRegexpMatches(string, regexp)
#
# def assertStdout(self, stdout, regexp):
# "Asserts that the `stdout` io stream matches `regexp`"
# stdoutText = stdout.getvalue().strip()
# self.assertMultilineRegexpMatches(stdoutText, regexp)
#
# def resetStdout(self, stdout):
# stdout.seek(0)
# stdout.truncate(0)
#
# Path: vimswitch/test/TestHelpers.py
# def assertNoCall(mock, *args):
# calledWith = False
# try:
# mock.assert_any_call(*args)
# calledWith = True
# except AssertionError:
# pass
#
# if calledWith:
# raise AssertionError('Mock called with arguments', mock, args)
#
# Path: vimswitch/ProfileDataIo.py
# class ProfileDataIo:
# def __init__(self, settings, diskIo):
# self.settings = settings
# self.diskIo = diskIo
#
# def delete(self, path):
# """Deletes profile data found at path"""
# for file in self.settings.profileFiles:
# filePath = os.path.join(path, file)
# if self.diskIo.fileExists(filePath):
# self.diskIo.deleteFile(filePath)
#
# for dir in self.settings.profileDirs:
# dirPath = os.path.join(path, dir)
# if self.diskIo.dirExists(dirPath):
# self.diskIo.deleteDir(dirPath)
#
# def copy(self, srcPath, destPath):
# """
# Copies profile data from srcPath to destPath. Will replace existing
# files at destPath.
# """
# for file in self.settings.profileFiles:
# srcFilePath = os.path.join(srcPath, file)
# destFilePath = os.path.join(destPath, file)
# if self.diskIo.fileExists(srcFilePath):
# self.diskIo.copyFile(srcFilePath, destFilePath)
#
# for dir in self.settings.profileDirs:
# srcDirPath = os.path.join(srcPath, dir)
# destDirPath = os.path.join(destPath, dir)
# if self.diskIo.dirExists(srcDirPath):
# self.diskIo.copyDir(srcDirPath, destDirPath)
#
# Path: vimswitch/Settings.py
# class Settings:
#
# def __init__(self, homePath=''):
# """
# homePath is used as the prefix for all other paths. If homePath is not
# specified it gets set to the user's home directory.
# """
# self.homePath = homePath or os.path.expanduser('~')
# self.configPath = os.path.join(self.homePath, '.vimswitch')
# self.configFilePath = os.path.join(self.configPath, 'vimswitchrc')
# self.cachePath = os.path.join(self.configPath, 'profiles')
# self.downloadsPath = os.path.join(self.configPath, 'downloads')
# self.profileFiles = ['.vimrc', '_vimrc']
# self.profileDirs = ['.vim', '_vim']
# self.defaultProfile = Profile('default')
# self.currentProfile = None
#
# def __eq__(self, other):
# return self.__dict__ == other.__dict__
. Output only the next line. | def test_copy_usesGetProfileFiles_fromSettings(self): |
Using the snippet: <|code_start|>
class TestProfileDataIo(BaseTestCase):
def setUp(self):
self.diskIo = Stubs.DiskIoStub()
self.settings = Settings(os.path.normpath('/home/foo'))
self.profileDataIo = ProfileDataIo(self.settings, self.diskIo)
# ProfileDataIo.delete#files
def test_delete_whenFileExists_deletesFile(self):
profilePath = os.path.normpath('/home/foo')
self.diskIo.fileExists.return_value = True
self.profileDataIo.delete(profilePath)
<|code_end|>
, determine the next line of code. You have imports:
from . import Stubs
from .BaseTestCase import BaseTestCase
from .TestHelpers import assertNoCall
from vimswitch.ProfileDataIo import ProfileDataIo
from vimswitch.Settings import Settings
import os
and context (class names, function names, or code) available:
# Path: vimswitch/test/BaseTestCase.py
# class BaseTestCase(unittest.TestCase):
# def __init__(self, *args, **kwargs):
# unittest.TestCase.__init__(self, *args, **kwargs)
#
# # Python < 3.2 does not have assertNotRegex
# if not hasattr(self, 'assertNotRegex'):
# self.assertNotRegex = self.assertNotRegexpMatches
#
# def assertMultilineRegexpMatches(self, string, regexp):
# """
# Asserts that the entirety of `string` matches `regexp`. `regexp` can be
# a multiline string with indentation.
# """
# regexp = textwrap.dedent(regexp)
# regexp = regexp.strip()
# regexp = '^' + regexp + '$'
# regexp = re.compile(regexp, re.DOTALL)
#
# self.assertRegexpMatches(string, regexp)
#
# def assertStdout(self, stdout, regexp):
# "Asserts that the `stdout` io stream matches `regexp`"
# stdoutText = stdout.getvalue().strip()
# self.assertMultilineRegexpMatches(stdoutText, regexp)
#
# def resetStdout(self, stdout):
# stdout.seek(0)
# stdout.truncate(0)
#
# Path: vimswitch/test/TestHelpers.py
# def assertNoCall(mock, *args):
# calledWith = False
# try:
# mock.assert_any_call(*args)
# calledWith = True
# except AssertionError:
# pass
#
# if calledWith:
# raise AssertionError('Mock called with arguments', mock, args)
#
# Path: vimswitch/ProfileDataIo.py
# class ProfileDataIo:
# def __init__(self, settings, diskIo):
# self.settings = settings
# self.diskIo = diskIo
#
# def delete(self, path):
# """Deletes profile data found at path"""
# for file in self.settings.profileFiles:
# filePath = os.path.join(path, file)
# if self.diskIo.fileExists(filePath):
# self.diskIo.deleteFile(filePath)
#
# for dir in self.settings.profileDirs:
# dirPath = os.path.join(path, dir)
# if self.diskIo.dirExists(dirPath):
# self.diskIo.deleteDir(dirPath)
#
# def copy(self, srcPath, destPath):
# """
# Copies profile data from srcPath to destPath. Will replace existing
# files at destPath.
# """
# for file in self.settings.profileFiles:
# srcFilePath = os.path.join(srcPath, file)
# destFilePath = os.path.join(destPath, file)
# if self.diskIo.fileExists(srcFilePath):
# self.diskIo.copyFile(srcFilePath, destFilePath)
#
# for dir in self.settings.profileDirs:
# srcDirPath = os.path.join(srcPath, dir)
# destDirPath = os.path.join(destPath, dir)
# if self.diskIo.dirExists(srcDirPath):
# self.diskIo.copyDir(srcDirPath, destDirPath)
#
# Path: vimswitch/Settings.py
# class Settings:
#
# def __init__(self, homePath=''):
# """
# homePath is used as the prefix for all other paths. If homePath is not
# specified it gets set to the user's home directory.
# """
# self.homePath = homePath or os.path.expanduser('~')
# self.configPath = os.path.join(self.homePath, '.vimswitch')
# self.configFilePath = os.path.join(self.configPath, 'vimswitchrc')
# self.cachePath = os.path.join(self.configPath, 'profiles')
# self.downloadsPath = os.path.join(self.configPath, 'downloads')
# self.profileFiles = ['.vimrc', '_vimrc']
# self.profileDirs = ['.vim', '_vim']
# self.defaultProfile = Profile('default')
# self.currentProfile = None
#
# def __eq__(self, other):
# return self.__dict__ == other.__dict__
. Output only the next line. | self.diskIo.deleteFile.assert_any_call(os.path.normpath('/home/foo/.vimrc')) |
Predict the next line for this snippet: <|code_start|>
def test_copy_copiesMultipleDirs(self):
srcPath = os.path.normpath('/home/foo/.vimswitch/profiles/test.vimrc')
destPath = os.path.normpath('/home/foo')
self.diskIo.dirExists.return_value = True
self.settings.profileDirs = ['dir1', 'dir2']
self.profileDataIo.copy(srcPath, destPath)
srcDir1 = os.path.normpath('/home/foo/.vimswitch/profiles/test.vimrc/dir1')
destDir1 = os.path.normpath('/home/foo/dir1')
srcDir2 = os.path.normpath('/home/foo/.vimswitch/profiles/test.vimrc/dir2')
destDir2 = os.path.normpath('/home/foo/dir2')
self.diskIo.copyDir.assert_any_call(srcDir1, destDir1)
self.diskIo.copyDir.assert_any_call(srcDir2, destDir2)
def test_copy_copiesFilesAndDirs(self):
srcPath = os.path.normpath('/home/foo/.vimswitch/profiles/test.vimrc')
destPath = os.path.normpath('/home/foo')
self.diskIo.dirExists.return_value = True
self.settings.profileFiles = ['file1', 'file2']
self.settings.profileDirs = ['dir1', 'dir2']
self.profileDataIo.copy(srcPath, destPath)
srcFile1 = os.path.normpath('/home/foo/.vimswitch/profiles/test.vimrc/file1')
destFile1 = os.path.normpath('/home/foo/file1')
srcFile2 = os.path.normpath('/home/foo/.vimswitch/profiles/test.vimrc/file2')
destFile2 = os.path.normpath('/home/foo/file2')
srcDir1 = os.path.normpath('/home/foo/.vimswitch/profiles/test.vimrc/dir1')
<|code_end|>
with the help of current file imports:
from . import Stubs
from .BaseTestCase import BaseTestCase
from .TestHelpers import assertNoCall
from vimswitch.ProfileDataIo import ProfileDataIo
from vimswitch.Settings import Settings
import os
and context from other files:
# Path: vimswitch/test/BaseTestCase.py
# class BaseTestCase(unittest.TestCase):
# def __init__(self, *args, **kwargs):
# unittest.TestCase.__init__(self, *args, **kwargs)
#
# # Python < 3.2 does not have assertNotRegex
# if not hasattr(self, 'assertNotRegex'):
# self.assertNotRegex = self.assertNotRegexpMatches
#
# def assertMultilineRegexpMatches(self, string, regexp):
# """
# Asserts that the entirety of `string` matches `regexp`. `regexp` can be
# a multiline string with indentation.
# """
# regexp = textwrap.dedent(regexp)
# regexp = regexp.strip()
# regexp = '^' + regexp + '$'
# regexp = re.compile(regexp, re.DOTALL)
#
# self.assertRegexpMatches(string, regexp)
#
# def assertStdout(self, stdout, regexp):
# "Asserts that the `stdout` io stream matches `regexp`"
# stdoutText = stdout.getvalue().strip()
# self.assertMultilineRegexpMatches(stdoutText, regexp)
#
# def resetStdout(self, stdout):
# stdout.seek(0)
# stdout.truncate(0)
#
# Path: vimswitch/test/TestHelpers.py
# def assertNoCall(mock, *args):
# calledWith = False
# try:
# mock.assert_any_call(*args)
# calledWith = True
# except AssertionError:
# pass
#
# if calledWith:
# raise AssertionError('Mock called with arguments', mock, args)
#
# Path: vimswitch/ProfileDataIo.py
# class ProfileDataIo:
# def __init__(self, settings, diskIo):
# self.settings = settings
# self.diskIo = diskIo
#
# def delete(self, path):
# """Deletes profile data found at path"""
# for file in self.settings.profileFiles:
# filePath = os.path.join(path, file)
# if self.diskIo.fileExists(filePath):
# self.diskIo.deleteFile(filePath)
#
# for dir in self.settings.profileDirs:
# dirPath = os.path.join(path, dir)
# if self.diskIo.dirExists(dirPath):
# self.diskIo.deleteDir(dirPath)
#
# def copy(self, srcPath, destPath):
# """
# Copies profile data from srcPath to destPath. Will replace existing
# files at destPath.
# """
# for file in self.settings.profileFiles:
# srcFilePath = os.path.join(srcPath, file)
# destFilePath = os.path.join(destPath, file)
# if self.diskIo.fileExists(srcFilePath):
# self.diskIo.copyFile(srcFilePath, destFilePath)
#
# for dir in self.settings.profileDirs:
# srcDirPath = os.path.join(srcPath, dir)
# destDirPath = os.path.join(destPath, dir)
# if self.diskIo.dirExists(srcDirPath):
# self.diskIo.copyDir(srcDirPath, destDirPath)
#
# Path: vimswitch/Settings.py
# class Settings:
#
# def __init__(self, homePath=''):
# """
# homePath is used as the prefix for all other paths. If homePath is not
# specified it gets set to the user's home directory.
# """
# self.homePath = homePath or os.path.expanduser('~')
# self.configPath = os.path.join(self.homePath, '.vimswitch')
# self.configFilePath = os.path.join(self.configPath, 'vimswitchrc')
# self.cachePath = os.path.join(self.configPath, 'profiles')
# self.downloadsPath = os.path.join(self.configPath, 'downloads')
# self.profileFiles = ['.vimrc', '_vimrc']
# self.profileDirs = ['.vim', '_vim']
# self.defaultProfile = Profile('default')
# self.currentProfile = None
#
# def __eq__(self, other):
# return self.__dict__ == other.__dict__
, which may contain function names, class names, or code. Output only the next line. | destDir1 = os.path.normpath('/home/foo/dir1') |
Using the snippet: <|code_start|>
class TestUpdateProfileAction(BaseTestCase):
def setUp(self):
app = Application()
self.settings = getSettings(app)
self.switchProfileAction = MagicMock(SwitchProfileAction)
self.updateProfileAction = UpdateProfileAction(self.settings, self.switchProfileAction)
def test_execute_withProfile_updatesProfile(self):
self.updateProfileAction.profile = Profile('test/vimrc')
self.updateProfileAction.execute()
self.assertTrue(self.switchProfileAction.execute.called)
self.assertEqual(self.switchProfileAction.profile, Profile('test/vimrc'))
self.assertEqual(self.switchProfileAction.update, True)
def test_execute_withoutProfile_updatesCurrentProfile(self):
self.settings.currentProfile = Profile('test/currentProfile')
<|code_end|>
, determine the next line of code. You have imports:
from mock import MagicMock, patch
from vimswitch.Application import Application
from vimswitch.Profile import Profile
from vimswitch.Settings import getSettings
from vimswitch.SwitchProfileAction import SwitchProfileAction
from vimswitch.UpdateProfileAction import UpdateProfileAction
from vimswitch.six import StringIO
from .BaseTestCase import BaseTestCase
and context (class names, function names, or code) available:
# Path: vimswitch/Application.py
# class Application:
# """
# A container for components that are used application-wide.
#
# Examples of how this class can be used:
#
# - Set a component
# `app.foo = myFoo`
#
# - Get (or create) a component:
# `foo = app.get('foo', Foo())`
# This will try to return `app.foo`. If that does not exist, then it will
# set `app.foo = Foo()` and return that instead.
#
# - Get an already created component
# `foo = app.foo`
# Use this when you are sure that app.foo has already been set
# """
#
# def get(self, attr, default):
# """
# Returns self.attr. If attr does not exist, then make self.attr = default
# and then return default.
# """
# if hasattr(self, attr):
# return getattr(self, attr)
# else:
# setattr(self, attr, default)
# return default
#
# Path: vimswitch/Profile.py
# class Profile:
# def __init__(self, name):
# self.name = name
#
# def getName(self):
# return self.name
#
# def getDirName(self):
# return self.name.replace('/', '.')
#
# def __eq__(self, other):
# return isinstance(other, Profile) and self.name == other.name
#
# def __ne__(self, other):
# return not self.__eq__(other)
#
# def __repr__(self):
# return "Profile('%s')" % self.name
#
# Path: vimswitch/Settings.py
# def getSettings(app):
# return app.get('settings', createSettings(app))
#
# Path: vimswitch/SwitchProfileAction.py
# class SwitchProfileAction(Action):
#
# def __init__(self, settings, profileCache, profileCopier, profileRetriever):
# Action.__init__(self)
# self.settings = settings
# self.profileCache = profileCache
# self.profileCopier = profileCopier
# self.profileRetriever = profileRetriever
# self.update = False
# self.profile = None
#
# def execute(self):
# self._saveCurrentProfile()
# self._retrieveProfile(self.profile)
# self.profileCopier.copyToHome(self.profile)
# self.settings.currentProfile = self.profile
# print('Switched to profile: %s' % self.profile.name)
#
# def _saveCurrentProfile(self):
# currentProfile = self._getCurrentProfile()
# print('Saving profile: %s' % currentProfile.name)
# self.profileCopier.copyFromHome(currentProfile)
#
# def _retrieveProfile(self, profile):
# if not self.profileCache.contains(profile) or self.update:
# self.profileRetriever.retrieve(profile)
#
# def _getCurrentProfile(self):
# if self.settings.currentProfile is None:
# currentProfile = self.settings.defaultProfile
# else:
# currentProfile = self.settings.currentProfile
# return currentProfile
#
# Path: vimswitch/UpdateProfileAction.py
# class UpdateProfileAction(Action):
# def __init__(self, settings, switchProfileAction):
# Action.__init__(self)
# self.settings = settings
# self.switchProfileAction = switchProfileAction
# self.profile = None
#
# def execute(self):
# self.profile = self._getProfile()
#
# if self.profile == self.settings.defaultProfile:
# print('Cannot update default profile')
# self.exitCode = -1
# return
#
# self.switchProfileAction.update = True
# self.switchProfileAction.profile = self.profile
# self.switchProfileAction.execute()
#
# def _getProfile(self):
# if self.profile is None:
# if self.settings.currentProfile is None:
# return self.settings.defaultProfile
# else:
# return self.settings.currentProfile
# else:
# return self.profile
#
# Path: vimswitch/test/BaseTestCase.py
# class BaseTestCase(unittest.TestCase):
# def __init__(self, *args, **kwargs):
# unittest.TestCase.__init__(self, *args, **kwargs)
#
# # Python < 3.2 does not have assertNotRegex
# if not hasattr(self, 'assertNotRegex'):
# self.assertNotRegex = self.assertNotRegexpMatches
#
# def assertMultilineRegexpMatches(self, string, regexp):
# """
# Asserts that the entirety of `string` matches `regexp`. `regexp` can be
# a multiline string with indentation.
# """
# regexp = textwrap.dedent(regexp)
# regexp = regexp.strip()
# regexp = '^' + regexp + '$'
# regexp = re.compile(regexp, re.DOTALL)
#
# self.assertRegexpMatches(string, regexp)
#
# def assertStdout(self, stdout, regexp):
# "Asserts that the `stdout` io stream matches `regexp`"
# stdoutText = stdout.getvalue().strip()
# self.assertMultilineRegexpMatches(stdoutText, regexp)
#
# def resetStdout(self, stdout):
# stdout.seek(0)
# stdout.truncate(0)
. Output only the next line. | self.updateProfileAction.profile = None |
Given snippet: <|code_start|>
class TestUpdateProfileAction(BaseTestCase):
def setUp(self):
app = Application()
self.settings = getSettings(app)
self.switchProfileAction = MagicMock(SwitchProfileAction)
self.updateProfileAction = UpdateProfileAction(self.settings, self.switchProfileAction)
def test_execute_withProfile_updatesProfile(self):
self.updateProfileAction.profile = Profile('test/vimrc')
self.updateProfileAction.execute()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from mock import MagicMock, patch
from vimswitch.Application import Application
from vimswitch.Profile import Profile
from vimswitch.Settings import getSettings
from vimswitch.SwitchProfileAction import SwitchProfileAction
from vimswitch.UpdateProfileAction import UpdateProfileAction
from vimswitch.six import StringIO
from .BaseTestCase import BaseTestCase
and context:
# Path: vimswitch/Application.py
# class Application:
# """
# A container for components that are used application-wide.
#
# Examples of how this class can be used:
#
# - Set a component
# `app.foo = myFoo`
#
# - Get (or create) a component:
# `foo = app.get('foo', Foo())`
# This will try to return `app.foo`. If that does not exist, then it will
# set `app.foo = Foo()` and return that instead.
#
# - Get an already created component
# `foo = app.foo`
# Use this when you are sure that app.foo has already been set
# """
#
# def get(self, attr, default):
# """
# Returns self.attr. If attr does not exist, then make self.attr = default
# and then return default.
# """
# if hasattr(self, attr):
# return getattr(self, attr)
# else:
# setattr(self, attr, default)
# return default
#
# Path: vimswitch/Profile.py
# class Profile:
# def __init__(self, name):
# self.name = name
#
# def getName(self):
# return self.name
#
# def getDirName(self):
# return self.name.replace('/', '.')
#
# def __eq__(self, other):
# return isinstance(other, Profile) and self.name == other.name
#
# def __ne__(self, other):
# return not self.__eq__(other)
#
# def __repr__(self):
# return "Profile('%s')" % self.name
#
# Path: vimswitch/Settings.py
# def getSettings(app):
# return app.get('settings', createSettings(app))
#
# Path: vimswitch/SwitchProfileAction.py
# class SwitchProfileAction(Action):
#
# def __init__(self, settings, profileCache, profileCopier, profileRetriever):
# Action.__init__(self)
# self.settings = settings
# self.profileCache = profileCache
# self.profileCopier = profileCopier
# self.profileRetriever = profileRetriever
# self.update = False
# self.profile = None
#
# def execute(self):
# self._saveCurrentProfile()
# self._retrieveProfile(self.profile)
# self.profileCopier.copyToHome(self.profile)
# self.settings.currentProfile = self.profile
# print('Switched to profile: %s' % self.profile.name)
#
# def _saveCurrentProfile(self):
# currentProfile = self._getCurrentProfile()
# print('Saving profile: %s' % currentProfile.name)
# self.profileCopier.copyFromHome(currentProfile)
#
# def _retrieveProfile(self, profile):
# if not self.profileCache.contains(profile) or self.update:
# self.profileRetriever.retrieve(profile)
#
# def _getCurrentProfile(self):
# if self.settings.currentProfile is None:
# currentProfile = self.settings.defaultProfile
# else:
# currentProfile = self.settings.currentProfile
# return currentProfile
#
# Path: vimswitch/UpdateProfileAction.py
# class UpdateProfileAction(Action):
# def __init__(self, settings, switchProfileAction):
# Action.__init__(self)
# self.settings = settings
# self.switchProfileAction = switchProfileAction
# self.profile = None
#
# def execute(self):
# self.profile = self._getProfile()
#
# if self.profile == self.settings.defaultProfile:
# print('Cannot update default profile')
# self.exitCode = -1
# return
#
# self.switchProfileAction.update = True
# self.switchProfileAction.profile = self.profile
# self.switchProfileAction.execute()
#
# def _getProfile(self):
# if self.profile is None:
# if self.settings.currentProfile is None:
# return self.settings.defaultProfile
# else:
# return self.settings.currentProfile
# else:
# return self.profile
#
# Path: vimswitch/test/BaseTestCase.py
# class BaseTestCase(unittest.TestCase):
# def __init__(self, *args, **kwargs):
# unittest.TestCase.__init__(self, *args, **kwargs)
#
# # Python < 3.2 does not have assertNotRegex
# if not hasattr(self, 'assertNotRegex'):
# self.assertNotRegex = self.assertNotRegexpMatches
#
# def assertMultilineRegexpMatches(self, string, regexp):
# """
# Asserts that the entirety of `string` matches `regexp`. `regexp` can be
# a multiline string with indentation.
# """
# regexp = textwrap.dedent(regexp)
# regexp = regexp.strip()
# regexp = '^' + regexp + '$'
# regexp = re.compile(regexp, re.DOTALL)
#
# self.assertRegexpMatches(string, regexp)
#
# def assertStdout(self, stdout, regexp):
# "Asserts that the `stdout` io stream matches `regexp`"
# stdoutText = stdout.getvalue().strip()
# self.assertMultilineRegexpMatches(stdoutText, regexp)
#
# def resetStdout(self, stdout):
# stdout.seek(0)
# stdout.truncate(0)
which might include code, classes, or functions. Output only the next line. | self.assertTrue(self.switchProfileAction.execute.called) |
Using the snippet: <|code_start|>
class TestUpdateProfileAction(BaseTestCase):
def setUp(self):
app = Application()
self.settings = getSettings(app)
self.switchProfileAction = MagicMock(SwitchProfileAction)
self.updateProfileAction = UpdateProfileAction(self.settings, self.switchProfileAction)
def test_execute_withProfile_updatesProfile(self):
self.updateProfileAction.profile = Profile('test/vimrc')
self.updateProfileAction.execute()
self.assertTrue(self.switchProfileAction.execute.called)
self.assertEqual(self.switchProfileAction.profile, Profile('test/vimrc'))
<|code_end|>
, determine the next line of code. You have imports:
from mock import MagicMock, patch
from vimswitch.Application import Application
from vimswitch.Profile import Profile
from vimswitch.Settings import getSettings
from vimswitch.SwitchProfileAction import SwitchProfileAction
from vimswitch.UpdateProfileAction import UpdateProfileAction
from vimswitch.six import StringIO
from .BaseTestCase import BaseTestCase
and context (class names, function names, or code) available:
# Path: vimswitch/Application.py
# class Application:
# """
# A container for components that are used application-wide.
#
# Examples of how this class can be used:
#
# - Set a component
# `app.foo = myFoo`
#
# - Get (or create) a component:
# `foo = app.get('foo', Foo())`
# This will try to return `app.foo`. If that does not exist, then it will
# set `app.foo = Foo()` and return that instead.
#
# - Get an already created component
# `foo = app.foo`
# Use this when you are sure that app.foo has already been set
# """
#
# def get(self, attr, default):
# """
# Returns self.attr. If attr does not exist, then make self.attr = default
# and then return default.
# """
# if hasattr(self, attr):
# return getattr(self, attr)
# else:
# setattr(self, attr, default)
# return default
#
# Path: vimswitch/Profile.py
# class Profile:
# def __init__(self, name):
# self.name = name
#
# def getName(self):
# return self.name
#
# def getDirName(self):
# return self.name.replace('/', '.')
#
# def __eq__(self, other):
# return isinstance(other, Profile) and self.name == other.name
#
# def __ne__(self, other):
# return not self.__eq__(other)
#
# def __repr__(self):
# return "Profile('%s')" % self.name
#
# Path: vimswitch/Settings.py
# def getSettings(app):
# return app.get('settings', createSettings(app))
#
# Path: vimswitch/SwitchProfileAction.py
# class SwitchProfileAction(Action):
#
# def __init__(self, settings, profileCache, profileCopier, profileRetriever):
# Action.__init__(self)
# self.settings = settings
# self.profileCache = profileCache
# self.profileCopier = profileCopier
# self.profileRetriever = profileRetriever
# self.update = False
# self.profile = None
#
# def execute(self):
# self._saveCurrentProfile()
# self._retrieveProfile(self.profile)
# self.profileCopier.copyToHome(self.profile)
# self.settings.currentProfile = self.profile
# print('Switched to profile: %s' % self.profile.name)
#
# def _saveCurrentProfile(self):
# currentProfile = self._getCurrentProfile()
# print('Saving profile: %s' % currentProfile.name)
# self.profileCopier.copyFromHome(currentProfile)
#
# def _retrieveProfile(self, profile):
# if not self.profileCache.contains(profile) or self.update:
# self.profileRetriever.retrieve(profile)
#
# def _getCurrentProfile(self):
# if self.settings.currentProfile is None:
# currentProfile = self.settings.defaultProfile
# else:
# currentProfile = self.settings.currentProfile
# return currentProfile
#
# Path: vimswitch/UpdateProfileAction.py
# class UpdateProfileAction(Action):
# def __init__(self, settings, switchProfileAction):
# Action.__init__(self)
# self.settings = settings
# self.switchProfileAction = switchProfileAction
# self.profile = None
#
# def execute(self):
# self.profile = self._getProfile()
#
# if self.profile == self.settings.defaultProfile:
# print('Cannot update default profile')
# self.exitCode = -1
# return
#
# self.switchProfileAction.update = True
# self.switchProfileAction.profile = self.profile
# self.switchProfileAction.execute()
#
# def _getProfile(self):
# if self.profile is None:
# if self.settings.currentProfile is None:
# return self.settings.defaultProfile
# else:
# return self.settings.currentProfile
# else:
# return self.profile
#
# Path: vimswitch/test/BaseTestCase.py
# class BaseTestCase(unittest.TestCase):
# def __init__(self, *args, **kwargs):
# unittest.TestCase.__init__(self, *args, **kwargs)
#
# # Python < 3.2 does not have assertNotRegex
# if not hasattr(self, 'assertNotRegex'):
# self.assertNotRegex = self.assertNotRegexpMatches
#
# def assertMultilineRegexpMatches(self, string, regexp):
# """
# Asserts that the entirety of `string` matches `regexp`. `regexp` can be
# a multiline string with indentation.
# """
# regexp = textwrap.dedent(regexp)
# regexp = regexp.strip()
# regexp = '^' + regexp + '$'
# regexp = re.compile(regexp, re.DOTALL)
#
# self.assertRegexpMatches(string, regexp)
#
# def assertStdout(self, stdout, regexp):
# "Asserts that the `stdout` io stream matches `regexp`"
# stdoutText = stdout.getvalue().strip()
# self.assertMultilineRegexpMatches(stdoutText, regexp)
#
# def resetStdout(self, stdout):
# stdout.seek(0)
# stdout.truncate(0)
. Output only the next line. | self.assertEqual(self.switchProfileAction.update, True) |
Using the snippet: <|code_start|>
class ActionResolver:
def __init__(self, app, commandLineParser):
self.app = app
<|code_end|>
, determine the next line of code. You have imports:
from .CommandLineParser import getCommandLineParser
from .InvalidArgsAction import createInvalidArgsAction
from .ShowCurrentProfileAction import createShowCurrentProfileAction
from .ShowVersionAction import createShowVersionAction
from .SwitchProfileAction import createSwitchProfileAction
from .UpdateProfileAction import createUpdateProfileAction
and context (class names, function names, or code) available:
# Path: vimswitch/CommandLineParser.py
# def getCommandLineParser(app):
# return app.get('commandLineParser', createCommandLineParser(app))
#
# Path: vimswitch/InvalidArgsAction.py
# def createInvalidArgsAction(app):
# return InvalidArgsAction()
#
# Path: vimswitch/ShowCurrentProfileAction.py
# def createShowCurrentProfileAction(app):
# settings = getSettings(app)
# showCurrentProfileAction = ShowCurrentProfileAction(settings)
# return showCurrentProfileAction
#
# Path: vimswitch/ShowVersionAction.py
# def createShowVersionAction(app):
# return ShowVersionAction()
#
# Path: vimswitch/SwitchProfileAction.py
# def createSwitchProfileAction(app):
# settings = getSettings(app)
# profileCache = getProfileCache(app)
# profileCopier = getProfileCopier(app)
# profileRetriever = getProfileRetriever(app)
# switchProfileAction = SwitchProfileAction(settings, profileCache, profileCopier, profileRetriever)
# return switchProfileAction
#
# Path: vimswitch/UpdateProfileAction.py
# def createUpdateProfileAction(app):
# settings = getSettings(app)
# switchProfileAction = createSwitchProfileAction(app)
# updateProfileAction = UpdateProfileAction(settings, switchProfileAction)
# return updateProfileAction
. Output only the next line. | self.commandLineParser = commandLineParser |
Predict the next line after this snippet: <|code_start|>
class ActionResolver:
def __init__(self, app, commandLineParser):
self.app = app
self.commandLineParser = commandLineParser
self.exitCode = 0
def doActions(self):
actionString = self.commandLineParser.action
if actionString == 'switchProfile':
action = createSwitchProfileAction(self.app)
action.profile = self.commandLineParser.profile
elif actionString == 'updateProfile':
action = createUpdateProfileAction(self.app)
action.profile = self.commandLineParser.profile
elif actionString == 'showCurrentProfile':
action = createShowCurrentProfileAction(self.app)
elif actionString == 'showVersion':
action = createShowVersionAction(self.app)
<|code_end|>
using the current file's imports:
from .CommandLineParser import getCommandLineParser
from .InvalidArgsAction import createInvalidArgsAction
from .ShowCurrentProfileAction import createShowCurrentProfileAction
from .ShowVersionAction import createShowVersionAction
from .SwitchProfileAction import createSwitchProfileAction
from .UpdateProfileAction import createUpdateProfileAction
and any relevant context from other files:
# Path: vimswitch/CommandLineParser.py
# def getCommandLineParser(app):
# return app.get('commandLineParser', createCommandLineParser(app))
#
# Path: vimswitch/InvalidArgsAction.py
# def createInvalidArgsAction(app):
# return InvalidArgsAction()
#
# Path: vimswitch/ShowCurrentProfileAction.py
# def createShowCurrentProfileAction(app):
# settings = getSettings(app)
# showCurrentProfileAction = ShowCurrentProfileAction(settings)
# return showCurrentProfileAction
#
# Path: vimswitch/ShowVersionAction.py
# def createShowVersionAction(app):
# return ShowVersionAction()
#
# Path: vimswitch/SwitchProfileAction.py
# def createSwitchProfileAction(app):
# settings = getSettings(app)
# profileCache = getProfileCache(app)
# profileCopier = getProfileCopier(app)
# profileRetriever = getProfileRetriever(app)
# switchProfileAction = SwitchProfileAction(settings, profileCache, profileCopier, profileRetriever)
# return switchProfileAction
#
# Path: vimswitch/UpdateProfileAction.py
# def createUpdateProfileAction(app):
# settings = getSettings(app)
# switchProfileAction = createSwitchProfileAction(app)
# updateProfileAction = UpdateProfileAction(settings, switchProfileAction)
# return updateProfileAction
. Output only the next line. | else: |
Using the snippet: <|code_start|>
class ActionResolver:
def __init__(self, app, commandLineParser):
self.app = app
self.commandLineParser = commandLineParser
<|code_end|>
, determine the next line of code. You have imports:
from .CommandLineParser import getCommandLineParser
from .InvalidArgsAction import createInvalidArgsAction
from .ShowCurrentProfileAction import createShowCurrentProfileAction
from .ShowVersionAction import createShowVersionAction
from .SwitchProfileAction import createSwitchProfileAction
from .UpdateProfileAction import createUpdateProfileAction
and context (class names, function names, or code) available:
# Path: vimswitch/CommandLineParser.py
# def getCommandLineParser(app):
# return app.get('commandLineParser', createCommandLineParser(app))
#
# Path: vimswitch/InvalidArgsAction.py
# def createInvalidArgsAction(app):
# return InvalidArgsAction()
#
# Path: vimswitch/ShowCurrentProfileAction.py
# def createShowCurrentProfileAction(app):
# settings = getSettings(app)
# showCurrentProfileAction = ShowCurrentProfileAction(settings)
# return showCurrentProfileAction
#
# Path: vimswitch/ShowVersionAction.py
# def createShowVersionAction(app):
# return ShowVersionAction()
#
# Path: vimswitch/SwitchProfileAction.py
# def createSwitchProfileAction(app):
# settings = getSettings(app)
# profileCache = getProfileCache(app)
# profileCopier = getProfileCopier(app)
# profileRetriever = getProfileRetriever(app)
# switchProfileAction = SwitchProfileAction(settings, profileCache, profileCopier, profileRetriever)
# return switchProfileAction
#
# Path: vimswitch/UpdateProfileAction.py
# def createUpdateProfileAction(app):
# settings = getSettings(app)
# switchProfileAction = createSwitchProfileAction(app)
# updateProfileAction = UpdateProfileAction(settings, switchProfileAction)
# return updateProfileAction
. Output only the next line. | self.exitCode = 0 |
Next line prediction: <|code_start|>
class ActionResolver:
def __init__(self, app, commandLineParser):
self.app = app
self.commandLineParser = commandLineParser
self.exitCode = 0
def doActions(self):
actionString = self.commandLineParser.action
if actionString == 'switchProfile':
action = createSwitchProfileAction(self.app)
action.profile = self.commandLineParser.profile
elif actionString == 'updateProfile':
action = createUpdateProfileAction(self.app)
<|code_end|>
. Use current file imports:
(from .CommandLineParser import getCommandLineParser
from .InvalidArgsAction import createInvalidArgsAction
from .ShowCurrentProfileAction import createShowCurrentProfileAction
from .ShowVersionAction import createShowVersionAction
from .SwitchProfileAction import createSwitchProfileAction
from .UpdateProfileAction import createUpdateProfileAction)
and context including class names, function names, or small code snippets from other files:
# Path: vimswitch/CommandLineParser.py
# def getCommandLineParser(app):
# return app.get('commandLineParser', createCommandLineParser(app))
#
# Path: vimswitch/InvalidArgsAction.py
# def createInvalidArgsAction(app):
# return InvalidArgsAction()
#
# Path: vimswitch/ShowCurrentProfileAction.py
# def createShowCurrentProfileAction(app):
# settings = getSettings(app)
# showCurrentProfileAction = ShowCurrentProfileAction(settings)
# return showCurrentProfileAction
#
# Path: vimswitch/ShowVersionAction.py
# def createShowVersionAction(app):
# return ShowVersionAction()
#
# Path: vimswitch/SwitchProfileAction.py
# def createSwitchProfileAction(app):
# settings = getSettings(app)
# profileCache = getProfileCache(app)
# profileCopier = getProfileCopier(app)
# profileRetriever = getProfileRetriever(app)
# switchProfileAction = SwitchProfileAction(settings, profileCache, profileCopier, profileRetriever)
# return switchProfileAction
#
# Path: vimswitch/UpdateProfileAction.py
# def createUpdateProfileAction(app):
# settings = getSettings(app)
# switchProfileAction = createSwitchProfileAction(app)
# updateProfileAction = UpdateProfileAction(settings, switchProfileAction)
# return updateProfileAction
. Output only the next line. | action.profile = self.commandLineParser.profile |
Based on the snippet: <|code_start|>
class ActionResolver:
def __init__(self, app, commandLineParser):
self.app = app
self.commandLineParser = commandLineParser
self.exitCode = 0
def doActions(self):
actionString = self.commandLineParser.action
if actionString == 'switchProfile':
action = createSwitchProfileAction(self.app)
action.profile = self.commandLineParser.profile
elif actionString == 'updateProfile':
action = createUpdateProfileAction(self.app)
action.profile = self.commandLineParser.profile
elif actionString == 'showCurrentProfile':
action = createShowCurrentProfileAction(self.app)
elif actionString == 'showVersion':
action = createShowVersionAction(self.app)
<|code_end|>
, predict the immediate next line with the help of imports:
from .CommandLineParser import getCommandLineParser
from .InvalidArgsAction import createInvalidArgsAction
from .ShowCurrentProfileAction import createShowCurrentProfileAction
from .ShowVersionAction import createShowVersionAction
from .SwitchProfileAction import createSwitchProfileAction
from .UpdateProfileAction import createUpdateProfileAction
and context (classes, functions, sometimes code) from other files:
# Path: vimswitch/CommandLineParser.py
# def getCommandLineParser(app):
# return app.get('commandLineParser', createCommandLineParser(app))
#
# Path: vimswitch/InvalidArgsAction.py
# def createInvalidArgsAction(app):
# return InvalidArgsAction()
#
# Path: vimswitch/ShowCurrentProfileAction.py
# def createShowCurrentProfileAction(app):
# settings = getSettings(app)
# showCurrentProfileAction = ShowCurrentProfileAction(settings)
# return showCurrentProfileAction
#
# Path: vimswitch/ShowVersionAction.py
# def createShowVersionAction(app):
# return ShowVersionAction()
#
# Path: vimswitch/SwitchProfileAction.py
# def createSwitchProfileAction(app):
# settings = getSettings(app)
# profileCache = getProfileCache(app)
# profileCopier = getProfileCopier(app)
# profileRetriever = getProfileRetriever(app)
# switchProfileAction = SwitchProfileAction(settings, profileCache, profileCopier, profileRetriever)
# return switchProfileAction
#
# Path: vimswitch/UpdateProfileAction.py
# def createUpdateProfileAction(app):
# settings = getSettings(app)
# switchProfileAction = createSwitchProfileAction(app)
# updateProfileAction = UpdateProfileAction(settings, switchProfileAction)
# return updateProfileAction
. Output only the next line. | else: |
Predict the next line for this snippet: <|code_start|>
class ActionResolver:
def __init__(self, app, commandLineParser):
self.app = app
self.commandLineParser = commandLineParser
self.exitCode = 0
def doActions(self):
actionString = self.commandLineParser.action
if actionString == 'switchProfile':
action = createSwitchProfileAction(self.app)
action.profile = self.commandLineParser.profile
elif actionString == 'updateProfile':
action = createUpdateProfileAction(self.app)
action.profile = self.commandLineParser.profile
elif actionString == 'showCurrentProfile':
action = createShowCurrentProfileAction(self.app)
elif actionString == 'showVersion':
action = createShowVersionAction(self.app)
<|code_end|>
with the help of current file imports:
from .CommandLineParser import getCommandLineParser
from .InvalidArgsAction import createInvalidArgsAction
from .ShowCurrentProfileAction import createShowCurrentProfileAction
from .ShowVersionAction import createShowVersionAction
from .SwitchProfileAction import createSwitchProfileAction
from .UpdateProfileAction import createUpdateProfileAction
and context from other files:
# Path: vimswitch/CommandLineParser.py
# def getCommandLineParser(app):
# return app.get('commandLineParser', createCommandLineParser(app))
#
# Path: vimswitch/InvalidArgsAction.py
# def createInvalidArgsAction(app):
# return InvalidArgsAction()
#
# Path: vimswitch/ShowCurrentProfileAction.py
# def createShowCurrentProfileAction(app):
# settings = getSettings(app)
# showCurrentProfileAction = ShowCurrentProfileAction(settings)
# return showCurrentProfileAction
#
# Path: vimswitch/ShowVersionAction.py
# def createShowVersionAction(app):
# return ShowVersionAction()
#
# Path: vimswitch/SwitchProfileAction.py
# def createSwitchProfileAction(app):
# settings = getSettings(app)
# profileCache = getProfileCache(app)
# profileCopier = getProfileCopier(app)
# profileRetriever = getProfileRetriever(app)
# switchProfileAction = SwitchProfileAction(settings, profileCache, profileCopier, profileRetriever)
# return switchProfileAction
#
# Path: vimswitch/UpdateProfileAction.py
# def createUpdateProfileAction(app):
# settings = getSettings(app)
# switchProfileAction = createSwitchProfileAction(app)
# updateProfileAction = UpdateProfileAction(settings, switchProfileAction)
# return updateProfileAction
, which may contain function names, class names, or code. Output only the next line. | else: |
Next line prediction: <|code_start|> model = Jury
fields = '__all__'
def get_object(self):
return Jury.objects.get(event__slug=self.kwargs.get('slug'))
class InviteEvent(BaseEventView, UpdateView):
template_name = 'event/jury_invite.html'
form_class = InviteForm
def form_valid(self, form):
try:
form.add_to_jury()
except ValidationError as e:
messages.warning(self.request, e.message)
else:
user = User.objects.get(email=form.cleaned_data.get('email'))
messages.success(
self.request,
_(u'The "@%s" are successfully joined to the Jury.') % user)
return HttpResponseRedirect(
reverse('jury_event', kwargs={'slug': self.get_object().slug}),
)
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(InviteEvent, self).dispatch(*args, **kwargs)
<|code_end|>
. Use current file imports:
(from django.http import HttpResponseRedirect
from django.core.exceptions import ValidationError
from django.core.urlresolvers import reverse
from django.contrib import messages
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.utils.translation import ugettext as _
from vanilla import UpdateView
from deck.views import BaseEventView
from deck.models import Event
from .forms import InviteForm
from .models import Jury)
and context including class names, function names, or small code snippets from other files:
# Path: deck/views.py
# class BaseEventView(object):
# model = Event
# form_class = EventForm
# lookup_field = 'slug'
#
# Path: deck/models.py
# class Event(DeckBaseModel):
# allow_public_voting = models.BooleanField(_('Allow Public Voting'),
# default=True)
# closing_date = models.DateTimeField(null=False, blank=False)
# slots = models.SmallIntegerField(_('Slots'), default=10)
#
# # relations
# jury = models.OneToOneField(to='jury.Jury', related_name='event',
# null=True, blank=True)
# anonymous_voting = models.BooleanField(
# _('Anonymous Voting?'), default=False)
#
# class Meta:
# ordering = ['-closing_date', '-created_at']
# verbose_name = _('Event')
# verbose_name_plural = _('Events')
#
# @property
# def closing_date_is_passed(self):
# return timezone.now() > self.closing_date
#
# @property
# def closing_date_is_close(self):
# if self.closing_date_is_passed:
# return False
# return timezone.now() > self.closing_date - timezone.timedelta(days=7)
#
# def get_absolute_url(self):
# return reverse('view_event', kwargs={'slug': self.slug})
#
# def user_can_see_proposals(self, user):
# can_see_proposals = False
# if user.is_superuser or self.author == user:
# can_see_proposals = True
# elif self.allow_public_voting:
# can_see_proposals = True
# elif (not user.is_anonymous() and
# self.jury.users.filter(pk=user.pk).exists()):
# can_see_proposals = True
# return can_see_proposals
#
# def get_proposers_count(self):
# return self.proposals.values_list(
# 'author', flat=True).distinct().count()
#
# def get_votes_count(self):
# return self.proposals.values_list('votes', flat=True).count()
#
# def get_votes_to_export(self):
# return self.proposals.values(
# 'id', 'title', 'author__username', 'author__email'
# ).annotate(
# Sum('votes__rate')
# ).annotate(Count('votes'))
#
# def get_schedule(self):
# schedule = Activity.objects.filter(track__event=self)\
# .cached_authors()\
# .annotate(Sum('proposal__votes__rate'))\
# .extra(select=dict(track_isnull='track_id IS NULL'))\
# .order_by('track_isnull', 'track_order',
# '-proposal__votes__rate__sum')
# return schedule
#
# def get_not_approved_schedule(self):
# return self.proposals\
# .cached_authors()\
# .filter(
# models.Q(is_approved=False) |
# models.Q(track__isnull=True))
#
# def get_main_track(self):
# return self.tracks.first()
#
# def filter_not_scheduled_by_slots(self):
# return self.get_not_approved_schedule()[:self.slots]
#
# def user_in_jury(self, user):
# return self.jury.users.filter(pk=user.pk).exists()
. Output only the next line. | def remove_user_from_event_jury(request, slug, user_pk): |
Here is a snippet: <|code_start|>
class JuryView(UpdateView):
template_name = 'jury/jury_detail.html'
lookup_field = 'slug'
model = Jury
fields = '__all__'
def get_object(self):
return Jury.objects.get(event__slug=self.kwargs.get('slug'))
class InviteEvent(BaseEventView, UpdateView):
template_name = 'event/jury_invite.html'
form_class = InviteForm
def form_valid(self, form):
try:
<|code_end|>
. Write the next line using the current file imports:
from django.http import HttpResponseRedirect
from django.core.exceptions import ValidationError
from django.core.urlresolvers import reverse
from django.contrib import messages
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.utils.translation import ugettext as _
from vanilla import UpdateView
from deck.views import BaseEventView
from deck.models import Event
from .forms import InviteForm
from .models import Jury
and context from other files:
# Path: deck/views.py
# class BaseEventView(object):
# model = Event
# form_class = EventForm
# lookup_field = 'slug'
#
# Path: deck/models.py
# class Event(DeckBaseModel):
# allow_public_voting = models.BooleanField(_('Allow Public Voting'),
# default=True)
# closing_date = models.DateTimeField(null=False, blank=False)
# slots = models.SmallIntegerField(_('Slots'), default=10)
#
# # relations
# jury = models.OneToOneField(to='jury.Jury', related_name='event',
# null=True, blank=True)
# anonymous_voting = models.BooleanField(
# _('Anonymous Voting?'), default=False)
#
# class Meta:
# ordering = ['-closing_date', '-created_at']
# verbose_name = _('Event')
# verbose_name_plural = _('Events')
#
# @property
# def closing_date_is_passed(self):
# return timezone.now() > self.closing_date
#
# @property
# def closing_date_is_close(self):
# if self.closing_date_is_passed:
# return False
# return timezone.now() > self.closing_date - timezone.timedelta(days=7)
#
# def get_absolute_url(self):
# return reverse('view_event', kwargs={'slug': self.slug})
#
# def user_can_see_proposals(self, user):
# can_see_proposals = False
# if user.is_superuser or self.author == user:
# can_see_proposals = True
# elif self.allow_public_voting:
# can_see_proposals = True
# elif (not user.is_anonymous() and
# self.jury.users.filter(pk=user.pk).exists()):
# can_see_proposals = True
# return can_see_proposals
#
# def get_proposers_count(self):
# return self.proposals.values_list(
# 'author', flat=True).distinct().count()
#
# def get_votes_count(self):
# return self.proposals.values_list('votes', flat=True).count()
#
# def get_votes_to_export(self):
# return self.proposals.values(
# 'id', 'title', 'author__username', 'author__email'
# ).annotate(
# Sum('votes__rate')
# ).annotate(Count('votes'))
#
# def get_schedule(self):
# schedule = Activity.objects.filter(track__event=self)\
# .cached_authors()\
# .annotate(Sum('proposal__votes__rate'))\
# .extra(select=dict(track_isnull='track_id IS NULL'))\
# .order_by('track_isnull', 'track_order',
# '-proposal__votes__rate__sum')
# return schedule
#
# def get_not_approved_schedule(self):
# return self.proposals\
# .cached_authors()\
# .filter(
# models.Q(is_approved=False) |
# models.Q(track__isnull=True))
#
# def get_main_track(self):
# return self.tracks.first()
#
# def filter_not_scheduled_by_slots(self):
# return self.get_not_approved_schedule()[:self.slots]
#
# def user_in_jury(self, user):
# return self.jury.users.filter(pk=user.pk).exists()
, which may include functions, classes, or code. Output only the next line. | form.add_to_jury() |
Based on the snippet: <|code_start|>@register.filter
def already_voted(user, proposal):
return proposal.user_already_voted(user)
@register.filter
def allowed_to_vote(user, proposal):
return proposal.user_can_vote(user)
@register.filter
def get_rate_display(user, proposal):
if user.is_authenticated():
vote = proposal.votes.filter(user=user)
if vote:
return vote.first().get_rate_display()
@register.filter
def get_rate_title(rate):
return Vote.VOTE_TITLES.get(rate)
@register.filter
def get_user_photo(user, size=40):
social = user.socialaccount_set.first()
if user.profile.image:
return user.profile.image.url
<|code_end|>
, predict the immediate next line with the help of imports:
import hashlib
from django.contrib.auth.models import AnonymousUser
from django import template
from deck.models import Vote, Event
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
and context (classes, functions, sometimes code) from other files:
# Path: deck/models.py
# class Vote(models.Model):
# ANGRY, SLEEPY, SAD, HAPPY, LAUGHING = range(-1, 4)
# VOTE_TITLES = dict(
# angry=_('Angry'), sad=_('Sad'),
# sleepy=_('Sleepy'), happy=_('Happy'),
# laughing=_('Laughing')
# )
# VOTE_RATES = ((ANGRY, 'angry'),
# (SAD, 'sad'),
# (SLEEPY, 'sleepy'),
# (HAPPY, 'happy'),
# (LAUGHING, 'laughing'))
# rate = models.SmallIntegerField(_('Rate Index'), null=True, blank=True,
# choices=VOTE_RATES)
#
# # relations
# proposal = models.ForeignKey(to='deck.Proposal', related_name='votes')
# user = models.ForeignKey(to=settings.AUTH_USER_MODEL, related_name='votes')
#
# class Meta:
# verbose_name = _('Vote')
# verbose_name_plural = _('Votes')
# unique_together = (('proposal', 'user'),)
#
# def __str__(self):
# return six.text_type("{0.user}: {0.rate} in {0.proposal}".format(self))
#
# def save(self, *args, **kwargs):
# validation_message = None
#
# user_is_in_jury = self.proposal.event.jury.users.filter(
# pk=self.user.pk).exists()
# if (self.user.is_superuser or user_is_in_jury):
# pass
# elif self.user == self.proposal.author:
# validation_message = _(u'You cannot Rate your own proposals.')
# elif not self.proposal.event.allow_public_voting:
# validation_message = _(u"Proposal doesn't accept Public Voting.")
#
# if validation_message:
# raise ValidationError(_(validation_message))
#
# return super(Vote, self).save(*args, **kwargs)
#
# class Event(DeckBaseModel):
# allow_public_voting = models.BooleanField(_('Allow Public Voting'),
# default=True)
# closing_date = models.DateTimeField(null=False, blank=False)
# slots = models.SmallIntegerField(_('Slots'), default=10)
#
# # relations
# jury = models.OneToOneField(to='jury.Jury', related_name='event',
# null=True, blank=True)
# anonymous_voting = models.BooleanField(
# _('Anonymous Voting?'), default=False)
#
# class Meta:
# ordering = ['-closing_date', '-created_at']
# verbose_name = _('Event')
# verbose_name_plural = _('Events')
#
# @property
# def closing_date_is_passed(self):
# return timezone.now() > self.closing_date
#
# @property
# def closing_date_is_close(self):
# if self.closing_date_is_passed:
# return False
# return timezone.now() > self.closing_date - timezone.timedelta(days=7)
#
# def get_absolute_url(self):
# return reverse('view_event', kwargs={'slug': self.slug})
#
# def user_can_see_proposals(self, user):
# can_see_proposals = False
# if user.is_superuser or self.author == user:
# can_see_proposals = True
# elif self.allow_public_voting:
# can_see_proposals = True
# elif (not user.is_anonymous() and
# self.jury.users.filter(pk=user.pk).exists()):
# can_see_proposals = True
# return can_see_proposals
#
# def get_proposers_count(self):
# return self.proposals.values_list(
# 'author', flat=True).distinct().count()
#
# def get_votes_count(self):
# return self.proposals.values_list('votes', flat=True).count()
#
# def get_votes_to_export(self):
# return self.proposals.values(
# 'id', 'title', 'author__username', 'author__email'
# ).annotate(
# Sum('votes__rate')
# ).annotate(Count('votes'))
#
# def get_schedule(self):
# schedule = Activity.objects.filter(track__event=self)\
# .cached_authors()\
# .annotate(Sum('proposal__votes__rate'))\
# .extra(select=dict(track_isnull='track_id IS NULL'))\
# .order_by('track_isnull', 'track_order',
# '-proposal__votes__rate__sum')
# return schedule
#
# def get_not_approved_schedule(self):
# return self.proposals\
# .cached_authors()\
# .filter(
# models.Q(is_approved=False) |
# models.Q(track__isnull=True))
#
# def get_main_track(self):
# return self.tracks.first()
#
# def filter_not_scheduled_by_slots(self):
# return self.get_not_approved_schedule()[:self.slots]
#
# def user_in_jury(self, user):
# return self.jury.users.filter(pk=user.pk).exists()
. Output only the next line. | if social: |
Here is a snippet: <|code_start|># coding: utf-8
class AboutViewTest(TestCase):
def setUp(self):
self.resp = self.client.get('/about/')
def test_get(self):
'GET /about/ must return status code 200'
self.assertEqual(200, self.resp.status_code)
def test_template(self):
'About page must use about.html'
<|code_end|>
. Write the next line using the current file imports:
from django.contrib.auth import get_user_model
from django.test import TestCase, Client
from django.core.urlresolvers import reverse
from django.utils import timezone
from django.utils.translation import get_language
from model_mommy import mommy
from core.models import Profile
and context from other files:
# Path: core/models.py
# class Profile(models.Model):
# language = models.CharField(
# _('Language'), choices=settings.LANGUAGES,
# max_length=50, null=True, blank=False)
# about_me = models.TextField(
# _('About me'), max_length=500, null=True, blank=True)
# github = models.CharField(
# _('Github username'), max_length=50, null=True, blank=True)
# facebook = models.CharField(
# _('Facebook username'), max_length=50, null=True, blank=True)
# twitter = models.CharField(
# _('Twitter username'), max_length=50, null=True, blank=True)
# site = models.URLField(
# _('Site url'), max_length=200, null=True, blank=True)
# image = models.ImageField(null=True, blank=True)
#
# # relations
# user = models.OneToOneField(to=settings.AUTH_USER_MODEL)
#
# class Meta:
# verbose_name = _('Profile')
#
# def __str__(self):
# return self.user.get_full_name()
#
# def get_absolute_url(self):
# return reverse_lazy(
# 'user_profile', kwargs={'user__username': self.user.username})
#
# def get_github_url(self):
# if self.github:
# return 'https://github.com/{}'.format(self.github)
#
# def get_facebook_url(self):
# if self.facebook:
# return 'https://facebook.com/{}'.format(self.facebook)
#
# def get_twitter_url(self):
# if self.twitter:
# return 'https://twitter.com/{}'.format(self.twitter)
#
# def get_site_url(self):
# return self.site
#
# def get_profile_events(self):
# return self.user.events.filter(is_published=True)
#
# def get_profile_proposals(self):
# return Proposal.objects.filter(
# author=self.user,
# event__is_published=True,
# event__anonymous_voting=False,
# is_published=True,
# )
, which may include functions, classes, or code. Output only the next line. | self.assertTemplateUsed(self.resp, 'about.html') |
Next line prediction: <|code_start|> self.assertQuerysetEqual(event.proposals.all(),
["<Proposal: Python For Zombies>"])
python_for_zombies = event.proposals.get()
self.assertEquals('Python For Zombies', python_for_zombies.title)
self.assertEquals('Brain...', python_for_zombies.description)
def test_notify_event_jury_and_proposal_author_on_new_proposal(self):
if not settings.SEND_NOTIFICATIONS:
return
event = Event.objects.create(**self.event_data)
self.client.post(
reverse('create_event_proposal', kwargs={'slug': event.slug}),
self.proposal_data, follow=True
)
proposal = event.proposals.get()
self.assertEqual(2, len(mail.outbox))
jury_email = mail.outbox[0]
for jury in event.jury.users.all():
self.assertIn(jury.email, jury_email.recipients())
self.assertIn(settings.NO_REPLY_EMAIL, jury_email.from_email)
author_email = mail.outbox[0]
self.assertIn(proposal.author.email, author_email.recipients())
self.assertIn(settings.NO_REPLY_EMAIL, author_email.from_email)
def test_anonymous_user_create_event_proposal(self):
event = Event.objects.create(**self.event_data)
<|code_end|>
. Use current file imports:
(from collections import namedtuple
from django.conf import settings
from django.contrib.auth.models import User
from django.core import mail
from django.utils import six
from django.core.urlresolvers import reverse
from django.test import TestCase, Client
from django.utils.timezone import now, timedelta
from django.utils.translation import ugettext as _
from deck.models import (Event, Proposal, Vote, Jury,
send_proposal_deleted_mail, send_welcome_mail)
from deck.tests.test_unit import (
EVENT_DATA, PROPOSAL_DATA, ANOTHER_PROPOSAL_DATA)
import datetime
import json)
and context including class names, function names, or small code snippets from other files:
# Path: deck/models.py
# class DeckBaseManager(models.QuerySet):
# class DeckBaseModel(models.Model):
# class Meta:
# class Vote(models.Model):
# class Meta:
# class Activity(DeckBaseModel):
# class Meta:
# class Proposal(Activity):
# class Meta:
# class Track(models.Model):
# class Meta:
# class Event(DeckBaseModel):
# class Meta:
# def cached_authors(self):
# def published_ones(self):
# def upcoming(self, published_only=True):
# def order_by_never_voted(self, user_id):
# def __str__(self):
# def __str__(self):
# def save(self, *args, **kwargs):
# def get_activities_by_parameters_order(ids):
# def timetable(self):
# def is_proposal(self):
# def get_full_slides_url(self):
# def save(self, *args, **kwargs):
# def get_rate(self):
# def rate(self, user, rate):
# def user_already_voted(self, user):
# def user_can_vote(self, user):
# def user_can_approve(self, user):
# def get_absolute_url(self):
# def approve(self):
# def disapprove(self):
# def __str__(self):
# def proposals(self):
# def has_activities(self):
# def add_proposal_to_slot(self, proposal, slot_index):
# def add_activity_to_slot(self, activity, slot_index):
# def refresh_track(self):
# def closing_date_is_passed(self):
# def closing_date_is_close(self):
# def get_absolute_url(self):
# def user_can_see_proposals(self, user):
# def get_proposers_count(self):
# def get_votes_count(self):
# def get_votes_to_export(self):
# def get_schedule(self):
# def get_not_approved_schedule(self):
# def get_main_track(self):
# def filter_not_scheduled_by_slots(self):
# def user_in_jury(self, user):
# def send_welcome_mail(request, user, **kwargs):
# def create_initial_jury(sender, instance, signal, created, **kwargs):
# def create_initial_track(sender, instance, signal, created, **kwargs):
# def send_proposal_deleted_mail(sender, instance, **kwargs):
# ANGRY, SLEEPY, SAD, HAPPY, LAUGHING = range(-1, 4)
# VOTE_TITLES = dict(
# angry=_('Angry'), sad=_('Sad'),
# sleepy=_('Sleepy'), happy=_('Happy'),
# laughing=_('Laughing')
# )
# VOTE_RATES = ((ANGRY, 'angry'),
# (SAD, 'sad'),
# (SLEEPY, 'sleepy'),
# (HAPPY, 'happy'),
# (LAUGHING, 'laughing'))
# PROPOSAL = 'proposal'
# WORKSHOP = 'workshop'
# OPENNING = 'openning'
# COFFEEBREAK = 'coffee-break'
# LUNCH = 'lunch'
# LIGHTNINGTALKS = 'lightning-talks'
# ENDING = 'ending'
# ACTIVITY_TYPES = (
# (PROPOSAL, _('Proposal')),
# (WORKSHOP, _('Workshop')),
# (OPENNING, _('Openning')),
# (COFFEEBREAK, _('Coffee Break')),
# (LUNCH, _('Lunch')),
# (LIGHTNINGTALKS, _('Lightning Talks')),
# (ENDING, _('Ending')),
# )
#
# Path: deck/tests/test_unit.py
# EVENT_DATA = {
# 'title': 'RuPy',
# 'slug': 'rupy',
# 'description': 'A really good event.',
# 'author_id': 1,
# 'is_published': False,
# 'slots': 30,
# 'closing_date': now() + timedelta(days=7),
# }
#
# PROPOSAL_DATA = {
# 'title': 'Python For Zombies',
# 'slug': 'python-for-zombies',
# 'description': 'Brain...',
# 'author_id': 1,
# 'slides_url': 'jane_doe/talk'
# }
#
# ANOTHER_PROPOSAL_DATA = {
# 'title': 'A Python 3 Metaprogramming Tutorial',
# 'slug': 'python-3-metaprogramming',
# 'description': 'An advanced tutorial on Python 3 and Metaprogramming',
# 'author_id': 1
# }
. Output only the next line. | self.client.logout() |
Next line prediction: <|code_start|>
python_for_zombies = event.proposals.get()
self.assertEquals('Python For Zombies', python_for_zombies.title)
self.assertEquals('Brain...', python_for_zombies.description)
def test_notify_event_jury_and_proposal_author_on_new_proposal(self):
if not settings.SEND_NOTIFICATIONS:
return
event = Event.objects.create(**self.event_data)
self.client.post(
reverse('create_event_proposal', kwargs={'slug': event.slug}),
self.proposal_data, follow=True
)
proposal = event.proposals.get()
self.assertEqual(2, len(mail.outbox))
jury_email = mail.outbox[0]
for jury in event.jury.users.all():
self.assertIn(jury.email, jury_email.recipients())
self.assertIn(settings.NO_REPLY_EMAIL, jury_email.from_email)
author_email = mail.outbox[0]
self.assertIn(proposal.author.email, author_email.recipients())
self.assertIn(settings.NO_REPLY_EMAIL, author_email.from_email)
def test_anonymous_user_create_event_proposal(self):
event = Event.objects.create(**self.event_data)
self.client.logout()
event_create_proposal_url = reverse(
<|code_end|>
. Use current file imports:
(from collections import namedtuple
from django.conf import settings
from django.contrib.auth.models import User
from django.core import mail
from django.utils import six
from django.core.urlresolvers import reverse
from django.test import TestCase, Client
from django.utils.timezone import now, timedelta
from django.utils.translation import ugettext as _
from deck.models import (Event, Proposal, Vote, Jury,
send_proposal_deleted_mail, send_welcome_mail)
from deck.tests.test_unit import (
EVENT_DATA, PROPOSAL_DATA, ANOTHER_PROPOSAL_DATA)
import datetime
import json)
and context including class names, function names, or small code snippets from other files:
# Path: deck/models.py
# class DeckBaseManager(models.QuerySet):
# class DeckBaseModel(models.Model):
# class Meta:
# class Vote(models.Model):
# class Meta:
# class Activity(DeckBaseModel):
# class Meta:
# class Proposal(Activity):
# class Meta:
# class Track(models.Model):
# class Meta:
# class Event(DeckBaseModel):
# class Meta:
# def cached_authors(self):
# def published_ones(self):
# def upcoming(self, published_only=True):
# def order_by_never_voted(self, user_id):
# def __str__(self):
# def __str__(self):
# def save(self, *args, **kwargs):
# def get_activities_by_parameters_order(ids):
# def timetable(self):
# def is_proposal(self):
# def get_full_slides_url(self):
# def save(self, *args, **kwargs):
# def get_rate(self):
# def rate(self, user, rate):
# def user_already_voted(self, user):
# def user_can_vote(self, user):
# def user_can_approve(self, user):
# def get_absolute_url(self):
# def approve(self):
# def disapprove(self):
# def __str__(self):
# def proposals(self):
# def has_activities(self):
# def add_proposal_to_slot(self, proposal, slot_index):
# def add_activity_to_slot(self, activity, slot_index):
# def refresh_track(self):
# def closing_date_is_passed(self):
# def closing_date_is_close(self):
# def get_absolute_url(self):
# def user_can_see_proposals(self, user):
# def get_proposers_count(self):
# def get_votes_count(self):
# def get_votes_to_export(self):
# def get_schedule(self):
# def get_not_approved_schedule(self):
# def get_main_track(self):
# def filter_not_scheduled_by_slots(self):
# def user_in_jury(self, user):
# def send_welcome_mail(request, user, **kwargs):
# def create_initial_jury(sender, instance, signal, created, **kwargs):
# def create_initial_track(sender, instance, signal, created, **kwargs):
# def send_proposal_deleted_mail(sender, instance, **kwargs):
# ANGRY, SLEEPY, SAD, HAPPY, LAUGHING = range(-1, 4)
# VOTE_TITLES = dict(
# angry=_('Angry'), sad=_('Sad'),
# sleepy=_('Sleepy'), happy=_('Happy'),
# laughing=_('Laughing')
# )
# VOTE_RATES = ((ANGRY, 'angry'),
# (SAD, 'sad'),
# (SLEEPY, 'sleepy'),
# (HAPPY, 'happy'),
# (LAUGHING, 'laughing'))
# PROPOSAL = 'proposal'
# WORKSHOP = 'workshop'
# OPENNING = 'openning'
# COFFEEBREAK = 'coffee-break'
# LUNCH = 'lunch'
# LIGHTNINGTALKS = 'lightning-talks'
# ENDING = 'ending'
# ACTIVITY_TYPES = (
# (PROPOSAL, _('Proposal')),
# (WORKSHOP, _('Workshop')),
# (OPENNING, _('Openning')),
# (COFFEEBREAK, _('Coffee Break')),
# (LUNCH, _('Lunch')),
# (LIGHTNINGTALKS, _('Lightning Talks')),
# (ENDING, _('Ending')),
# )
#
# Path: deck/tests/test_unit.py
# EVENT_DATA = {
# 'title': 'RuPy',
# 'slug': 'rupy',
# 'description': 'A really good event.',
# 'author_id': 1,
# 'is_published': False,
# 'slots': 30,
# 'closing_date': now() + timedelta(days=7),
# }
#
# PROPOSAL_DATA = {
# 'title': 'Python For Zombies',
# 'slug': 'python-for-zombies',
# 'description': 'Brain...',
# 'author_id': 1,
# 'slides_url': 'jane_doe/talk'
# }
#
# ANOTHER_PROPOSAL_DATA = {
# 'title': 'A Python 3 Metaprogramming Tutorial',
# 'slug': 'python-3-metaprogramming',
# 'description': 'An advanced tutorial on Python 3 and Metaprogramming',
# 'author_id': 1
# }
. Output only the next line. | 'create_event_proposal', kwargs={'slug': event.slug}) |
Continue the code snippet: <|code_start|> self.proposal = Proposal.objects.first()
self.assertEquals(200, response.status_code)
self.assertEquals(False, self.proposal.is_approved)
def test_disapprove_proposal_with_the_jury_user(self):
self.event.jury.users.add(User.objects.get(username='another'))
self.client.logout()
self.client.login(username='another', password='another')
self.proposal.is_approved = True
self.proposal.save()
disapprove_proposal_data = {
'event_slug': self.proposal.event.slug,
'slug': self.proposal.slug
}
response = self.client.post(
reverse('disapprove_proposal', kwargs=disapprove_proposal_data),
follow=True
)
self.proposal = Proposal.objects.first()
self.assertEquals(200, response.status_code)
self.assertIn('message', json.loads(response.content.decode("utf-8")))
self.assertEquals(False, self.proposal.is_approved)
def test_disapprove_proposal_with_the_jury_user_by_get(self):
self.event.jury.users.add(User.objects.get(username='another'))
self.client.logout()
self.client.login(username='another', password='another')
self.proposal.is_approved = True
<|code_end|>
. Use current file imports:
from collections import namedtuple
from django.conf import settings
from django.contrib.auth.models import User
from django.core import mail
from django.utils import six
from django.core.urlresolvers import reverse
from django.test import TestCase, Client
from django.utils.timezone import now, timedelta
from django.utils.translation import ugettext as _
from deck.models import (Event, Proposal, Vote, Jury,
send_proposal_deleted_mail, send_welcome_mail)
from deck.tests.test_unit import (
EVENT_DATA, PROPOSAL_DATA, ANOTHER_PROPOSAL_DATA)
import datetime
import json
and context (classes, functions, or code) from other files:
# Path: deck/models.py
# class DeckBaseManager(models.QuerySet):
# class DeckBaseModel(models.Model):
# class Meta:
# class Vote(models.Model):
# class Meta:
# class Activity(DeckBaseModel):
# class Meta:
# class Proposal(Activity):
# class Meta:
# class Track(models.Model):
# class Meta:
# class Event(DeckBaseModel):
# class Meta:
# def cached_authors(self):
# def published_ones(self):
# def upcoming(self, published_only=True):
# def order_by_never_voted(self, user_id):
# def __str__(self):
# def __str__(self):
# def save(self, *args, **kwargs):
# def get_activities_by_parameters_order(ids):
# def timetable(self):
# def is_proposal(self):
# def get_full_slides_url(self):
# def save(self, *args, **kwargs):
# def get_rate(self):
# def rate(self, user, rate):
# def user_already_voted(self, user):
# def user_can_vote(self, user):
# def user_can_approve(self, user):
# def get_absolute_url(self):
# def approve(self):
# def disapprove(self):
# def __str__(self):
# def proposals(self):
# def has_activities(self):
# def add_proposal_to_slot(self, proposal, slot_index):
# def add_activity_to_slot(self, activity, slot_index):
# def refresh_track(self):
# def closing_date_is_passed(self):
# def closing_date_is_close(self):
# def get_absolute_url(self):
# def user_can_see_proposals(self, user):
# def get_proposers_count(self):
# def get_votes_count(self):
# def get_votes_to_export(self):
# def get_schedule(self):
# def get_not_approved_schedule(self):
# def get_main_track(self):
# def filter_not_scheduled_by_slots(self):
# def user_in_jury(self, user):
# def send_welcome_mail(request, user, **kwargs):
# def create_initial_jury(sender, instance, signal, created, **kwargs):
# def create_initial_track(sender, instance, signal, created, **kwargs):
# def send_proposal_deleted_mail(sender, instance, **kwargs):
# ANGRY, SLEEPY, SAD, HAPPY, LAUGHING = range(-1, 4)
# VOTE_TITLES = dict(
# angry=_('Angry'), sad=_('Sad'),
# sleepy=_('Sleepy'), happy=_('Happy'),
# laughing=_('Laughing')
# )
# VOTE_RATES = ((ANGRY, 'angry'),
# (SAD, 'sad'),
# (SLEEPY, 'sleepy'),
# (HAPPY, 'happy'),
# (LAUGHING, 'laughing'))
# PROPOSAL = 'proposal'
# WORKSHOP = 'workshop'
# OPENNING = 'openning'
# COFFEEBREAK = 'coffee-break'
# LUNCH = 'lunch'
# LIGHTNINGTALKS = 'lightning-talks'
# ENDING = 'ending'
# ACTIVITY_TYPES = (
# (PROPOSAL, _('Proposal')),
# (WORKSHOP, _('Workshop')),
# (OPENNING, _('Openning')),
# (COFFEEBREAK, _('Coffee Break')),
# (LUNCH, _('Lunch')),
# (LIGHTNINGTALKS, _('Lightning Talks')),
# (ENDING, _('Ending')),
# )
#
# Path: deck/tests/test_unit.py
# EVENT_DATA = {
# 'title': 'RuPy',
# 'slug': 'rupy',
# 'description': 'A really good event.',
# 'author_id': 1,
# 'is_published': False,
# 'slots': 30,
# 'closing_date': now() + timedelta(days=7),
# }
#
# PROPOSAL_DATA = {
# 'title': 'Python For Zombies',
# 'slug': 'python-for-zombies',
# 'description': 'Brain...',
# 'author_id': 1,
# 'slides_url': 'jane_doe/talk'
# }
#
# ANOTHER_PROPOSAL_DATA = {
# 'title': 'A Python 3 Metaprogramming Tutorial',
# 'slug': 'python-3-metaprogramming',
# 'description': 'An advanced tutorial on Python 3 and Metaprogramming',
# 'author_id': 1
# }
. Output only the next line. | self.proposal.save() |
Given snippet: <|code_start|> follow=True
)
self.assertEquals(200, response.status_code)
self.assertQuerysetEqual(response.context['event_proposals'], [])
def test_list_proposal_with_public_voting(self):
self.client.logout()
self.client.login(username='another', password='another')
self.event.allow_public_voting = True
self.event.save()
self.proposal.is_published = True
self.proposal.save()
response = self.client.get(
reverse('view_event', kwargs={'slug': self.event.slug}),
follow=True
)
self.assertEquals(200, response.status_code)
self.assertQuerysetEqual(response.context['event_proposals'],
["<Proposal: Python For Zombies>"])
def test_list_proposal_ordering_when_user_is_logged(self):
another_proposal_data = ANOTHER_PROPOSAL_DATA.copy()
another_proposal_data.update(event=self.event)
another_proposal = Proposal.objects.create(**another_proposal_data)
response = self.client.get(
reverse('view_event', kwargs={'slug': self.event.slug}),
follow=True
)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from collections import namedtuple
from django.conf import settings
from django.contrib.auth.models import User
from django.core import mail
from django.utils import six
from django.core.urlresolvers import reverse
from django.test import TestCase, Client
from django.utils.timezone import now, timedelta
from django.utils.translation import ugettext as _
from deck.models import (Event, Proposal, Vote, Jury,
send_proposal_deleted_mail, send_welcome_mail)
from deck.tests.test_unit import (
EVENT_DATA, PROPOSAL_DATA, ANOTHER_PROPOSAL_DATA)
import datetime
import json
and context:
# Path: deck/models.py
# class DeckBaseManager(models.QuerySet):
# class DeckBaseModel(models.Model):
# class Meta:
# class Vote(models.Model):
# class Meta:
# class Activity(DeckBaseModel):
# class Meta:
# class Proposal(Activity):
# class Meta:
# class Track(models.Model):
# class Meta:
# class Event(DeckBaseModel):
# class Meta:
# def cached_authors(self):
# def published_ones(self):
# def upcoming(self, published_only=True):
# def order_by_never_voted(self, user_id):
# def __str__(self):
# def __str__(self):
# def save(self, *args, **kwargs):
# def get_activities_by_parameters_order(ids):
# def timetable(self):
# def is_proposal(self):
# def get_full_slides_url(self):
# def save(self, *args, **kwargs):
# def get_rate(self):
# def rate(self, user, rate):
# def user_already_voted(self, user):
# def user_can_vote(self, user):
# def user_can_approve(self, user):
# def get_absolute_url(self):
# def approve(self):
# def disapprove(self):
# def __str__(self):
# def proposals(self):
# def has_activities(self):
# def add_proposal_to_slot(self, proposal, slot_index):
# def add_activity_to_slot(self, activity, slot_index):
# def refresh_track(self):
# def closing_date_is_passed(self):
# def closing_date_is_close(self):
# def get_absolute_url(self):
# def user_can_see_proposals(self, user):
# def get_proposers_count(self):
# def get_votes_count(self):
# def get_votes_to_export(self):
# def get_schedule(self):
# def get_not_approved_schedule(self):
# def get_main_track(self):
# def filter_not_scheduled_by_slots(self):
# def user_in_jury(self, user):
# def send_welcome_mail(request, user, **kwargs):
# def create_initial_jury(sender, instance, signal, created, **kwargs):
# def create_initial_track(sender, instance, signal, created, **kwargs):
# def send_proposal_deleted_mail(sender, instance, **kwargs):
# ANGRY, SLEEPY, SAD, HAPPY, LAUGHING = range(-1, 4)
# VOTE_TITLES = dict(
# angry=_('Angry'), sad=_('Sad'),
# sleepy=_('Sleepy'), happy=_('Happy'),
# laughing=_('Laughing')
# )
# VOTE_RATES = ((ANGRY, 'angry'),
# (SAD, 'sad'),
# (SLEEPY, 'sleepy'),
# (HAPPY, 'happy'),
# (LAUGHING, 'laughing'))
# PROPOSAL = 'proposal'
# WORKSHOP = 'workshop'
# OPENNING = 'openning'
# COFFEEBREAK = 'coffee-break'
# LUNCH = 'lunch'
# LIGHTNINGTALKS = 'lightning-talks'
# ENDING = 'ending'
# ACTIVITY_TYPES = (
# (PROPOSAL, _('Proposal')),
# (WORKSHOP, _('Workshop')),
# (OPENNING, _('Openning')),
# (COFFEEBREAK, _('Coffee Break')),
# (LUNCH, _('Lunch')),
# (LIGHTNINGTALKS, _('Lightning Talks')),
# (ENDING, _('Ending')),
# )
#
# Path: deck/tests/test_unit.py
# EVENT_DATA = {
# 'title': 'RuPy',
# 'slug': 'rupy',
# 'description': 'A really good event.',
# 'author_id': 1,
# 'is_published': False,
# 'slots': 30,
# 'closing_date': now() + timedelta(days=7),
# }
#
# PROPOSAL_DATA = {
# 'title': 'Python For Zombies',
# 'slug': 'python-for-zombies',
# 'description': 'Brain...',
# 'author_id': 1,
# 'slides_url': 'jane_doe/talk'
# }
#
# ANOTHER_PROPOSAL_DATA = {
# 'title': 'A Python 3 Metaprogramming Tutorial',
# 'slug': 'python-3-metaprogramming',
# 'description': 'An advanced tutorial on Python 3 and Metaprogramming',
# 'author_id': 1
# }
which might include code, classes, or functions. Output only the next line. | self.assertEquals(200, response.status_code) |
Predict the next line for this snippet: <|code_start|> response = self.client.get(
reverse('view_event', kwargs={'slug': self.event.slug}),
follow=True
)
self.assertEquals(200, response.status_code)
self.assertQuerysetEqual(response.context['event_proposals'],
["<Proposal: Python For Zombies>"])
def test_list_proposal_without_public_voting_as_author(self):
self.client.logout()
self.client.login(username='another', password='another')
self.event.author = User.objects.get(username='another')
self.event.allow_public_voting = False
self.event.save()
response = self.client.get(
reverse('view_event', kwargs={'slug': self.event.slug}),
follow=True
)
self.assertEquals(200, response.status_code)
self.assertQuerysetEqual(response.context['event_proposals'],
["<Proposal: Python For Zombies>"])
def test_list_proposal_without_published_and_as_author(self):
self.client.logout()
self.client.login(username='another', password='another')
self.event.author = User.objects.get(username='another')
self.event.save()
self.proposal.is_published = False
self.proposal.save()
response = self.client.get(
<|code_end|>
with the help of current file imports:
from collections import namedtuple
from django.conf import settings
from django.contrib.auth.models import User
from django.core import mail
from django.utils import six
from django.core.urlresolvers import reverse
from django.test import TestCase, Client
from django.utils.timezone import now, timedelta
from django.utils.translation import ugettext as _
from deck.models import (Event, Proposal, Vote, Jury,
send_proposal_deleted_mail, send_welcome_mail)
from deck.tests.test_unit import (
EVENT_DATA, PROPOSAL_DATA, ANOTHER_PROPOSAL_DATA)
import datetime
import json
and context from other files:
# Path: deck/models.py
# class DeckBaseManager(models.QuerySet):
# class DeckBaseModel(models.Model):
# class Meta:
# class Vote(models.Model):
# class Meta:
# class Activity(DeckBaseModel):
# class Meta:
# class Proposal(Activity):
# class Meta:
# class Track(models.Model):
# class Meta:
# class Event(DeckBaseModel):
# class Meta:
# def cached_authors(self):
# def published_ones(self):
# def upcoming(self, published_only=True):
# def order_by_never_voted(self, user_id):
# def __str__(self):
# def __str__(self):
# def save(self, *args, **kwargs):
# def get_activities_by_parameters_order(ids):
# def timetable(self):
# def is_proposal(self):
# def get_full_slides_url(self):
# def save(self, *args, **kwargs):
# def get_rate(self):
# def rate(self, user, rate):
# def user_already_voted(self, user):
# def user_can_vote(self, user):
# def user_can_approve(self, user):
# def get_absolute_url(self):
# def approve(self):
# def disapprove(self):
# def __str__(self):
# def proposals(self):
# def has_activities(self):
# def add_proposal_to_slot(self, proposal, slot_index):
# def add_activity_to_slot(self, activity, slot_index):
# def refresh_track(self):
# def closing_date_is_passed(self):
# def closing_date_is_close(self):
# def get_absolute_url(self):
# def user_can_see_proposals(self, user):
# def get_proposers_count(self):
# def get_votes_count(self):
# def get_votes_to_export(self):
# def get_schedule(self):
# def get_not_approved_schedule(self):
# def get_main_track(self):
# def filter_not_scheduled_by_slots(self):
# def user_in_jury(self, user):
# def send_welcome_mail(request, user, **kwargs):
# def create_initial_jury(sender, instance, signal, created, **kwargs):
# def create_initial_track(sender, instance, signal, created, **kwargs):
# def send_proposal_deleted_mail(sender, instance, **kwargs):
# ANGRY, SLEEPY, SAD, HAPPY, LAUGHING = range(-1, 4)
# VOTE_TITLES = dict(
# angry=_('Angry'), sad=_('Sad'),
# sleepy=_('Sleepy'), happy=_('Happy'),
# laughing=_('Laughing')
# )
# VOTE_RATES = ((ANGRY, 'angry'),
# (SAD, 'sad'),
# (SLEEPY, 'sleepy'),
# (HAPPY, 'happy'),
# (LAUGHING, 'laughing'))
# PROPOSAL = 'proposal'
# WORKSHOP = 'workshop'
# OPENNING = 'openning'
# COFFEEBREAK = 'coffee-break'
# LUNCH = 'lunch'
# LIGHTNINGTALKS = 'lightning-talks'
# ENDING = 'ending'
# ACTIVITY_TYPES = (
# (PROPOSAL, _('Proposal')),
# (WORKSHOP, _('Workshop')),
# (OPENNING, _('Openning')),
# (COFFEEBREAK, _('Coffee Break')),
# (LUNCH, _('Lunch')),
# (LIGHTNINGTALKS, _('Lightning Talks')),
# (ENDING, _('Ending')),
# )
#
# Path: deck/tests/test_unit.py
# EVENT_DATA = {
# 'title': 'RuPy',
# 'slug': 'rupy',
# 'description': 'A really good event.',
# 'author_id': 1,
# 'is_published': False,
# 'slots': 30,
# 'closing_date': now() + timedelta(days=7),
# }
#
# PROPOSAL_DATA = {
# 'title': 'Python For Zombies',
# 'slug': 'python-for-zombies',
# 'description': 'Brain...',
# 'author_id': 1,
# 'slides_url': 'jane_doe/talk'
# }
#
# ANOTHER_PROPOSAL_DATA = {
# 'title': 'A Python 3 Metaprogramming Tutorial',
# 'slug': 'python-3-metaprogramming',
# 'description': 'An advanced tutorial on Python 3 and Metaprogramming',
# 'author_id': 1
# }
, which may contain function names, class names, or code. Output only the next line. | reverse('view_event', kwargs={'slug': self.event.slug}), |
Predict the next line after this snippet: <|code_start|> self.event.jury.users.add(User.objects.get(username='another'))
self.client.logout()
self.client.login(username='another', password='another')
rate_proposal_data = {
'event_slug': self.proposal.event.slug,
'slug': self.proposal.slug,
'rate': 'sad'
}
response = self.client.post(
reverse('rate_proposal', kwargs=rate_proposal_data),
follow=True
)
self.assertEquals(200, response.status_code)
self.assertEquals(1, self.proposal.get_rate)
self.assertEquals(1, self.proposal.votes.count())
self.assertEquals(1, Vote.objects.count())
def test_rate_proposal_with_the_jury_user_by_get(self):
self.event.jury.users.add(User.objects.get(username='another'))
self.client.logout()
self.client.login(username='another', password='another')
rate_proposal_data = {
'event_slug': self.proposal.event.slug,
'slug': self.proposal.slug,
'rate': 'sad'
}
response = self.client.get(
<|code_end|>
using the current file's imports:
from collections import namedtuple
from django.conf import settings
from django.contrib.auth.models import User
from django.core import mail
from django.utils import six
from django.core.urlresolvers import reverse
from django.test import TestCase, Client
from django.utils.timezone import now, timedelta
from django.utils.translation import ugettext as _
from deck.models import (Event, Proposal, Vote, Jury,
send_proposal_deleted_mail, send_welcome_mail)
from deck.tests.test_unit import (
EVENT_DATA, PROPOSAL_DATA, ANOTHER_PROPOSAL_DATA)
import datetime
import json
and any relevant context from other files:
# Path: deck/models.py
# class DeckBaseManager(models.QuerySet):
# class DeckBaseModel(models.Model):
# class Meta:
# class Vote(models.Model):
# class Meta:
# class Activity(DeckBaseModel):
# class Meta:
# class Proposal(Activity):
# class Meta:
# class Track(models.Model):
# class Meta:
# class Event(DeckBaseModel):
# class Meta:
# def cached_authors(self):
# def published_ones(self):
# def upcoming(self, published_only=True):
# def order_by_never_voted(self, user_id):
# def __str__(self):
# def __str__(self):
# def save(self, *args, **kwargs):
# def get_activities_by_parameters_order(ids):
# def timetable(self):
# def is_proposal(self):
# def get_full_slides_url(self):
# def save(self, *args, **kwargs):
# def get_rate(self):
# def rate(self, user, rate):
# def user_already_voted(self, user):
# def user_can_vote(self, user):
# def user_can_approve(self, user):
# def get_absolute_url(self):
# def approve(self):
# def disapprove(self):
# def __str__(self):
# def proposals(self):
# def has_activities(self):
# def add_proposal_to_slot(self, proposal, slot_index):
# def add_activity_to_slot(self, activity, slot_index):
# def refresh_track(self):
# def closing_date_is_passed(self):
# def closing_date_is_close(self):
# def get_absolute_url(self):
# def user_can_see_proposals(self, user):
# def get_proposers_count(self):
# def get_votes_count(self):
# def get_votes_to_export(self):
# def get_schedule(self):
# def get_not_approved_schedule(self):
# def get_main_track(self):
# def filter_not_scheduled_by_slots(self):
# def user_in_jury(self, user):
# def send_welcome_mail(request, user, **kwargs):
# def create_initial_jury(sender, instance, signal, created, **kwargs):
# def create_initial_track(sender, instance, signal, created, **kwargs):
# def send_proposal_deleted_mail(sender, instance, **kwargs):
# ANGRY, SLEEPY, SAD, HAPPY, LAUGHING = range(-1, 4)
# VOTE_TITLES = dict(
# angry=_('Angry'), sad=_('Sad'),
# sleepy=_('Sleepy'), happy=_('Happy'),
# laughing=_('Laughing')
# )
# VOTE_RATES = ((ANGRY, 'angry'),
# (SAD, 'sad'),
# (SLEEPY, 'sleepy'),
# (HAPPY, 'happy'),
# (LAUGHING, 'laughing'))
# PROPOSAL = 'proposal'
# WORKSHOP = 'workshop'
# OPENNING = 'openning'
# COFFEEBREAK = 'coffee-break'
# LUNCH = 'lunch'
# LIGHTNINGTALKS = 'lightning-talks'
# ENDING = 'ending'
# ACTIVITY_TYPES = (
# (PROPOSAL, _('Proposal')),
# (WORKSHOP, _('Workshop')),
# (OPENNING, _('Openning')),
# (COFFEEBREAK, _('Coffee Break')),
# (LUNCH, _('Lunch')),
# (LIGHTNINGTALKS, _('Lightning Talks')),
# (ENDING, _('Ending')),
# )
#
# Path: deck/tests/test_unit.py
# EVENT_DATA = {
# 'title': 'RuPy',
# 'slug': 'rupy',
# 'description': 'A really good event.',
# 'author_id': 1,
# 'is_published': False,
# 'slots': 30,
# 'closing_date': now() + timedelta(days=7),
# }
#
# PROPOSAL_DATA = {
# 'title': 'Python For Zombies',
# 'slug': 'python-for-zombies',
# 'description': 'Brain...',
# 'author_id': 1,
# 'slides_url': 'jane_doe/talk'
# }
#
# ANOTHER_PROPOSAL_DATA = {
# 'title': 'A Python 3 Metaprogramming Tutorial',
# 'slug': 'python-3-metaprogramming',
# 'description': 'An advanced tutorial on Python 3 and Metaprogramming',
# 'author_id': 1
# }
. Output only the next line. | reverse('rate_proposal', kwargs=rate_proposal_data), |
Next line prediction: <|code_start|> new_proposal_data = self.proposal_data.copy()
new_proposal_data['description'] = 'A really really good proposal.'
new_proposal_data['slides_url'] = 'john_doe/talk'
proposal_update_url = reverse(
'update_proposal',
kwargs={'event_slug': self.event.slug,
'slug': self.proposal.slug}
)
response = self.client.post(
proposal_update_url,
new_proposal_data, follow=True
)
self.assertEquals(200, response.status_code)
self.assertEquals(proposal_update_url,
response.context_data.get('redirect_field_value'))
self.assertEquals('Brain...', self.proposal.description)
def test_delete_proposal(self):
new_proposal_data = self.proposal_data.copy()
new_proposal_data['author_id'] = User.objects.get(username='user').id
new_proposal_data['description'] = 'A good candidate to be deleted.'
proposal = Proposal.objects.create(**new_proposal_data)
self.assertEqual(
Proposal.objects.filter(slug=proposal.slug).count(), 1)
response = self.client.post(
<|code_end|>
. Use current file imports:
(from collections import namedtuple
from django.conf import settings
from django.contrib.auth.models import User
from django.core import mail
from django.utils import six
from django.core.urlresolvers import reverse
from django.test import TestCase, Client
from django.utils.timezone import now, timedelta
from django.utils.translation import ugettext as _
from deck.models import (Event, Proposal, Vote, Jury,
send_proposal_deleted_mail, send_welcome_mail)
from deck.tests.test_unit import (
EVENT_DATA, PROPOSAL_DATA, ANOTHER_PROPOSAL_DATA)
import datetime
import json)
and context including class names, function names, or small code snippets from other files:
# Path: deck/models.py
# class DeckBaseManager(models.QuerySet):
# class DeckBaseModel(models.Model):
# class Meta:
# class Vote(models.Model):
# class Meta:
# class Activity(DeckBaseModel):
# class Meta:
# class Proposal(Activity):
# class Meta:
# class Track(models.Model):
# class Meta:
# class Event(DeckBaseModel):
# class Meta:
# def cached_authors(self):
# def published_ones(self):
# def upcoming(self, published_only=True):
# def order_by_never_voted(self, user_id):
# def __str__(self):
# def __str__(self):
# def save(self, *args, **kwargs):
# def get_activities_by_parameters_order(ids):
# def timetable(self):
# def is_proposal(self):
# def get_full_slides_url(self):
# def save(self, *args, **kwargs):
# def get_rate(self):
# def rate(self, user, rate):
# def user_already_voted(self, user):
# def user_can_vote(self, user):
# def user_can_approve(self, user):
# def get_absolute_url(self):
# def approve(self):
# def disapprove(self):
# def __str__(self):
# def proposals(self):
# def has_activities(self):
# def add_proposal_to_slot(self, proposal, slot_index):
# def add_activity_to_slot(self, activity, slot_index):
# def refresh_track(self):
# def closing_date_is_passed(self):
# def closing_date_is_close(self):
# def get_absolute_url(self):
# def user_can_see_proposals(self, user):
# def get_proposers_count(self):
# def get_votes_count(self):
# def get_votes_to_export(self):
# def get_schedule(self):
# def get_not_approved_schedule(self):
# def get_main_track(self):
# def filter_not_scheduled_by_slots(self):
# def user_in_jury(self, user):
# def send_welcome_mail(request, user, **kwargs):
# def create_initial_jury(sender, instance, signal, created, **kwargs):
# def create_initial_track(sender, instance, signal, created, **kwargs):
# def send_proposal_deleted_mail(sender, instance, **kwargs):
# ANGRY, SLEEPY, SAD, HAPPY, LAUGHING = range(-1, 4)
# VOTE_TITLES = dict(
# angry=_('Angry'), sad=_('Sad'),
# sleepy=_('Sleepy'), happy=_('Happy'),
# laughing=_('Laughing')
# )
# VOTE_RATES = ((ANGRY, 'angry'),
# (SAD, 'sad'),
# (SLEEPY, 'sleepy'),
# (HAPPY, 'happy'),
# (LAUGHING, 'laughing'))
# PROPOSAL = 'proposal'
# WORKSHOP = 'workshop'
# OPENNING = 'openning'
# COFFEEBREAK = 'coffee-break'
# LUNCH = 'lunch'
# LIGHTNINGTALKS = 'lightning-talks'
# ENDING = 'ending'
# ACTIVITY_TYPES = (
# (PROPOSAL, _('Proposal')),
# (WORKSHOP, _('Workshop')),
# (OPENNING, _('Openning')),
# (COFFEEBREAK, _('Coffee Break')),
# (LUNCH, _('Lunch')),
# (LIGHTNINGTALKS, _('Lightning Talks')),
# (ENDING, _('Ending')),
# )
#
# Path: deck/tests/test_unit.py
# EVENT_DATA = {
# 'title': 'RuPy',
# 'slug': 'rupy',
# 'description': 'A really good event.',
# 'author_id': 1,
# 'is_published': False,
# 'slots': 30,
# 'closing_date': now() + timedelta(days=7),
# }
#
# PROPOSAL_DATA = {
# 'title': 'Python For Zombies',
# 'slug': 'python-for-zombies',
# 'description': 'Brain...',
# 'author_id': 1,
# 'slides_url': 'jane_doe/talk'
# }
#
# ANOTHER_PROPOSAL_DATA = {
# 'title': 'A Python 3 Metaprogramming Tutorial',
# 'slug': 'python-3-metaprogramming',
# 'description': 'An advanced tutorial on Python 3 and Metaprogramming',
# 'author_id': 1
# }
. Output only the next line. | reverse('delete_proposal', |
Continue the code snippet: <|code_start|> closing_date=now() - timedelta(days=7)
)
Event.objects.create(**past_event_data)
response = self.client.get(reverse('list_events'), follow=True)
self.assertEquals(200, response.status_code)
self.assertQuerysetEqual(response.context['event_list'],
["<Event: RuPy>"])
def test_search_event(self):
event_data = self.event_data.copy()
event_data.update(is_published=True)
Event.objects.create(**event_data)
past_event_data = self.event_data.copy()
past_event_data.update(
title='Python Nordeste',
is_published=True,
closing_date=now() - timedelta(days=7)
)
Event.objects.create(**past_event_data)
response = self.client.get(reverse('list_events'),
data={'search': 'RuPy'}, follow=True)
self.assertEquals(200, response.status_code)
self.assertQuerysetEqual(response.context['event_list'],
["<Event: RuPy>"])
def test_empty_search(self):
event_data = self.event_data.copy()
<|code_end|>
. Use current file imports:
from collections import namedtuple
from django.conf import settings
from django.contrib.auth.models import User
from django.core import mail
from django.utils import six
from django.core.urlresolvers import reverse
from django.test import TestCase, Client
from django.utils.timezone import now, timedelta
from django.utils.translation import ugettext as _
from deck.models import (Event, Proposal, Vote, Jury,
send_proposal_deleted_mail, send_welcome_mail)
from deck.tests.test_unit import (
EVENT_DATA, PROPOSAL_DATA, ANOTHER_PROPOSAL_DATA)
import datetime
import json
and context (classes, functions, or code) from other files:
# Path: deck/models.py
# class DeckBaseManager(models.QuerySet):
# class DeckBaseModel(models.Model):
# class Meta:
# class Vote(models.Model):
# class Meta:
# class Activity(DeckBaseModel):
# class Meta:
# class Proposal(Activity):
# class Meta:
# class Track(models.Model):
# class Meta:
# class Event(DeckBaseModel):
# class Meta:
# def cached_authors(self):
# def published_ones(self):
# def upcoming(self, published_only=True):
# def order_by_never_voted(self, user_id):
# def __str__(self):
# def __str__(self):
# def save(self, *args, **kwargs):
# def get_activities_by_parameters_order(ids):
# def timetable(self):
# def is_proposal(self):
# def get_full_slides_url(self):
# def save(self, *args, **kwargs):
# def get_rate(self):
# def rate(self, user, rate):
# def user_already_voted(self, user):
# def user_can_vote(self, user):
# def user_can_approve(self, user):
# def get_absolute_url(self):
# def approve(self):
# def disapprove(self):
# def __str__(self):
# def proposals(self):
# def has_activities(self):
# def add_proposal_to_slot(self, proposal, slot_index):
# def add_activity_to_slot(self, activity, slot_index):
# def refresh_track(self):
# def closing_date_is_passed(self):
# def closing_date_is_close(self):
# def get_absolute_url(self):
# def user_can_see_proposals(self, user):
# def get_proposers_count(self):
# def get_votes_count(self):
# def get_votes_to_export(self):
# def get_schedule(self):
# def get_not_approved_schedule(self):
# def get_main_track(self):
# def filter_not_scheduled_by_slots(self):
# def user_in_jury(self, user):
# def send_welcome_mail(request, user, **kwargs):
# def create_initial_jury(sender, instance, signal, created, **kwargs):
# def create_initial_track(sender, instance, signal, created, **kwargs):
# def send_proposal_deleted_mail(sender, instance, **kwargs):
# ANGRY, SLEEPY, SAD, HAPPY, LAUGHING = range(-1, 4)
# VOTE_TITLES = dict(
# angry=_('Angry'), sad=_('Sad'),
# sleepy=_('Sleepy'), happy=_('Happy'),
# laughing=_('Laughing')
# )
# VOTE_RATES = ((ANGRY, 'angry'),
# (SAD, 'sad'),
# (SLEEPY, 'sleepy'),
# (HAPPY, 'happy'),
# (LAUGHING, 'laughing'))
# PROPOSAL = 'proposal'
# WORKSHOP = 'workshop'
# OPENNING = 'openning'
# COFFEEBREAK = 'coffee-break'
# LUNCH = 'lunch'
# LIGHTNINGTALKS = 'lightning-talks'
# ENDING = 'ending'
# ACTIVITY_TYPES = (
# (PROPOSAL, _('Proposal')),
# (WORKSHOP, _('Workshop')),
# (OPENNING, _('Openning')),
# (COFFEEBREAK, _('Coffee Break')),
# (LUNCH, _('Lunch')),
# (LIGHTNINGTALKS, _('Lightning Talks')),
# (ENDING, _('Ending')),
# )
#
# Path: deck/tests/test_unit.py
# EVENT_DATA = {
# 'title': 'RuPy',
# 'slug': 'rupy',
# 'description': 'A really good event.',
# 'author_id': 1,
# 'is_published': False,
# 'slots': 30,
# 'closing_date': now() + timedelta(days=7),
# }
#
# PROPOSAL_DATA = {
# 'title': 'Python For Zombies',
# 'slug': 'python-for-zombies',
# 'description': 'Brain...',
# 'author_id': 1,
# 'slides_url': 'jane_doe/talk'
# }
#
# ANOTHER_PROPOSAL_DATA = {
# 'title': 'A Python 3 Metaprogramming Tutorial',
# 'slug': 'python-3-metaprogramming',
# 'description': 'An advanced tutorial on Python 3 and Metaprogramming',
# 'author_id': 1
# }
. Output only the next line. | event_data.update(is_published=True) |
Continue the code snippet: <|code_start|> }
self.client.post(
reverse('rate_proposal', kwargs=rate_proposal_data),
follow=True
)
self.assertEquals(3, self.proposal.get_rate)
rate_proposal_data.update({'rate': 'happy'})
response = self.client.post(
reverse('rate_proposal', kwargs=rate_proposal_data),
follow=True
)
self.assertEquals(200, response.status_code)
self.assertEquals(1, Vote.objects.count())
self.assertEquals(1, self.proposal.votes.count())
self.assertEquals(2, self.proposal.get_rate)
def test_rate_proposal_change_vote_by_get(self):
rate_proposal_data = {
'event_slug': self.proposal.event.slug,
'slug': self.proposal.slug,
'rate': 'laughing'
}
self.client.get(
reverse('rate_proposal', kwargs=rate_proposal_data),
follow=True
)
self.assertEquals(3, self.proposal.get_rate)
rate_proposal_data.update({'rate': 'happy'})
<|code_end|>
. Use current file imports:
from collections import namedtuple
from django.conf import settings
from django.contrib.auth.models import User
from django.core import mail
from django.utils import six
from django.core.urlresolvers import reverse
from django.test import TestCase, Client
from django.utils.timezone import now, timedelta
from django.utils.translation import ugettext as _
from deck.models import (Event, Proposal, Vote, Jury,
send_proposal_deleted_mail, send_welcome_mail)
from deck.tests.test_unit import (
EVENT_DATA, PROPOSAL_DATA, ANOTHER_PROPOSAL_DATA)
import datetime
import json
and context (classes, functions, or code) from other files:
# Path: deck/models.py
# class DeckBaseManager(models.QuerySet):
# class DeckBaseModel(models.Model):
# class Meta:
# class Vote(models.Model):
# class Meta:
# class Activity(DeckBaseModel):
# class Meta:
# class Proposal(Activity):
# class Meta:
# class Track(models.Model):
# class Meta:
# class Event(DeckBaseModel):
# class Meta:
# def cached_authors(self):
# def published_ones(self):
# def upcoming(self, published_only=True):
# def order_by_never_voted(self, user_id):
# def __str__(self):
# def __str__(self):
# def save(self, *args, **kwargs):
# def get_activities_by_parameters_order(ids):
# def timetable(self):
# def is_proposal(self):
# def get_full_slides_url(self):
# def save(self, *args, **kwargs):
# def get_rate(self):
# def rate(self, user, rate):
# def user_already_voted(self, user):
# def user_can_vote(self, user):
# def user_can_approve(self, user):
# def get_absolute_url(self):
# def approve(self):
# def disapprove(self):
# def __str__(self):
# def proposals(self):
# def has_activities(self):
# def add_proposal_to_slot(self, proposal, slot_index):
# def add_activity_to_slot(self, activity, slot_index):
# def refresh_track(self):
# def closing_date_is_passed(self):
# def closing_date_is_close(self):
# def get_absolute_url(self):
# def user_can_see_proposals(self, user):
# def get_proposers_count(self):
# def get_votes_count(self):
# def get_votes_to_export(self):
# def get_schedule(self):
# def get_not_approved_schedule(self):
# def get_main_track(self):
# def filter_not_scheduled_by_slots(self):
# def user_in_jury(self, user):
# def send_welcome_mail(request, user, **kwargs):
# def create_initial_jury(sender, instance, signal, created, **kwargs):
# def create_initial_track(sender, instance, signal, created, **kwargs):
# def send_proposal_deleted_mail(sender, instance, **kwargs):
# ANGRY, SLEEPY, SAD, HAPPY, LAUGHING = range(-1, 4)
# VOTE_TITLES = dict(
# angry=_('Angry'), sad=_('Sad'),
# sleepy=_('Sleepy'), happy=_('Happy'),
# laughing=_('Laughing')
# )
# VOTE_RATES = ((ANGRY, 'angry'),
# (SAD, 'sad'),
# (SLEEPY, 'sleepy'),
# (HAPPY, 'happy'),
# (LAUGHING, 'laughing'))
# PROPOSAL = 'proposal'
# WORKSHOP = 'workshop'
# OPENNING = 'openning'
# COFFEEBREAK = 'coffee-break'
# LUNCH = 'lunch'
# LIGHTNINGTALKS = 'lightning-talks'
# ENDING = 'ending'
# ACTIVITY_TYPES = (
# (PROPOSAL, _('Proposal')),
# (WORKSHOP, _('Workshop')),
# (OPENNING, _('Openning')),
# (COFFEEBREAK, _('Coffee Break')),
# (LUNCH, _('Lunch')),
# (LIGHTNINGTALKS, _('Lightning Talks')),
# (ENDING, _('Ending')),
# )
#
# Path: deck/tests/test_unit.py
# EVENT_DATA = {
# 'title': 'RuPy',
# 'slug': 'rupy',
# 'description': 'A really good event.',
# 'author_id': 1,
# 'is_published': False,
# 'slots': 30,
# 'closing_date': now() + timedelta(days=7),
# }
#
# PROPOSAL_DATA = {
# 'title': 'Python For Zombies',
# 'slug': 'python-for-zombies',
# 'description': 'Brain...',
# 'author_id': 1,
# 'slides_url': 'jane_doe/talk'
# }
#
# ANOTHER_PROPOSAL_DATA = {
# 'title': 'A Python 3 Metaprogramming Tutorial',
# 'slug': 'python-3-metaprogramming',
# 'description': 'An advanced tutorial on Python 3 and Metaprogramming',
# 'author_id': 1
# }
. Output only the next line. | response = self.client.get( |
Given snippet: <|code_start|> _('Twitter username'), max_length=50, null=True, blank=True)
site = models.URLField(
_('Site url'), max_length=200, null=True, blank=True)
image = models.ImageField(null=True, blank=True)
# relations
user = models.OneToOneField(to=settings.AUTH_USER_MODEL)
class Meta:
verbose_name = _('Profile')
def __str__(self):
return self.user.get_full_name()
def get_absolute_url(self):
return reverse_lazy(
'user_profile', kwargs={'user__username': self.user.username})
def get_github_url(self):
if self.github:
return 'https://github.com/{}'.format(self.github)
def get_facebook_url(self):
if self.facebook:
return 'https://facebook.com/{}'.format(self.facebook)
def get_twitter_url(self):
if self.twitter:
return 'https://twitter.com/{}'.format(self.twitter)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.core.exceptions import AppRegistryNotReady
from django.core.urlresolvers import reverse_lazy
from django.conf import settings
from django.db import models
from django.db.models.signals import post_save, pre_save
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext as _
from deck.models import Proposal
from django.contrib.auth import get_user_model
from django.contrib.auth.models import User
and context:
# Path: deck/models.py
# class Proposal(Activity):
# is_approved = models.BooleanField(_('Is approved'), default=False)
# more_information = models.TextField(
# _('More information'), max_length=10000, null=True, blank=True)
# slides_url = models.CharField(
# _('speakerdeck.com/'), max_length=250, null=True, blank=True)
#
# def get_full_slides_url(self):
# if self.slides_url:
# return 'http://www.speakerdeck.com/{0}'.format(self.slides_url)
#
# # relations
# event = models.ForeignKey(to='deck.Event', related_name='proposals')
#
# class Meta:
# ordering = ['title']
# verbose_name = _('Proposal')
# verbose_name_plural = _('Proposals')
#
# def save(self, *args, **kwargs):
# if not self.pk and self.event.closing_date_is_passed:
# raise ValidationError(
# _("This Event doesn't accept Proposals anymore."))
# return super(Proposal, self).save(*args, **kwargs)
#
# @property
# def get_rate(self):
# rate = None
# try:
# rate = self.votes__rate__sum
# except AttributeError:
# rate = self.votes.aggregate(Sum('rate'))['rate__sum']
# finally:
# return rate or 0
#
# def rate(self, user, rate):
# rate_int = [r[0] for r in Vote.VOTE_RATES if rate in r][0]
# with transaction.atomic():
# self.votes.update_or_create(user=user, defaults={'rate': rate_int})
#
# def user_already_voted(self, user):
# if isinstance(user, AnonymousUser):
# return False
# return self.votes.filter(user=user).exists()
#
# def user_can_vote(self, user):
# can_vote = False
# if self.author == user and not self.event.author == user:
# pass
# elif self.event.allow_public_voting:
# can_vote = True
# elif user.is_superuser:
# can_vote = True
# elif self.event.jury.users.filter(pk=user.pk).exists():
# can_vote = True
# return can_vote
#
# def user_can_approve(self, user):
# can_approve = False
# if user.is_superuser:
# can_approve = True
# elif self.event.jury.users.filter(pk=user.pk).exists():
# can_approve = True
# return can_approve
#
# def get_absolute_url(self):
# return reverse('view_event', kwargs={'slug': self.event.slug}) + \
# '#' + self.slug
#
# def approve(self):
# if self.is_approved:
# raise ValidationError(_("This Proposal was already approved."))
# self.is_approved = True
# self.save()
#
# def disapprove(self):
# if not self.is_approved:
# raise ValidationError(_("This Proposal was already disapproved."))
# self.is_approved = False
# self.save()
which might include code, classes, or functions. Output only the next line. | def get_site_url(self): |
Here is a snippet: <|code_start|>
class PermissionsTestCase(TestCase):
def setUp(self):
self.user = mommy.make(settings.AUTH_USER_MODEL)
self.event = mommy.make(Event)
def test_super_user_is_always_allowed(self):
<|code_end|>
. Write the next line using the current file imports:
from django.test import TestCase
from django.conf import settings
from mock import patch, Mock
from model_mommy import mommy
from deck.permissions import has_manage_schedule_permission
from deck.models import Event
and context from other files:
# Path: deck/permissions.py
# def has_manage_schedule_permission(user, event):
# return user.is_superuser or event.user_in_jury(user)
#
# Path: deck/models.py
# class Event(DeckBaseModel):
# allow_public_voting = models.BooleanField(_('Allow Public Voting'),
# default=True)
# closing_date = models.DateTimeField(null=False, blank=False)
# slots = models.SmallIntegerField(_('Slots'), default=10)
#
# # relations
# jury = models.OneToOneField(to='jury.Jury', related_name='event',
# null=True, blank=True)
# anonymous_voting = models.BooleanField(
# _('Anonymous Voting?'), default=False)
#
# class Meta:
# ordering = ['-closing_date', '-created_at']
# verbose_name = _('Event')
# verbose_name_plural = _('Events')
#
# @property
# def closing_date_is_passed(self):
# return timezone.now() > self.closing_date
#
# @property
# def closing_date_is_close(self):
# if self.closing_date_is_passed:
# return False
# return timezone.now() > self.closing_date - timezone.timedelta(days=7)
#
# def get_absolute_url(self):
# return reverse('view_event', kwargs={'slug': self.slug})
#
# def user_can_see_proposals(self, user):
# can_see_proposals = False
# if user.is_superuser or self.author == user:
# can_see_proposals = True
# elif self.allow_public_voting:
# can_see_proposals = True
# elif (not user.is_anonymous() and
# self.jury.users.filter(pk=user.pk).exists()):
# can_see_proposals = True
# return can_see_proposals
#
# def get_proposers_count(self):
# return self.proposals.values_list(
# 'author', flat=True).distinct().count()
#
# def get_votes_count(self):
# return self.proposals.values_list('votes', flat=True).count()
#
# def get_votes_to_export(self):
# return self.proposals.values(
# 'id', 'title', 'author__username', 'author__email'
# ).annotate(
# Sum('votes__rate')
# ).annotate(Count('votes'))
#
# def get_schedule(self):
# schedule = Activity.objects.filter(track__event=self)\
# .cached_authors()\
# .annotate(Sum('proposal__votes__rate'))\
# .extra(select=dict(track_isnull='track_id IS NULL'))\
# .order_by('track_isnull', 'track_order',
# '-proposal__votes__rate__sum')
# return schedule
#
# def get_not_approved_schedule(self):
# return self.proposals\
# .cached_authors()\
# .filter(
# models.Q(is_approved=False) |
# models.Q(track__isnull=True))
#
# def get_main_track(self):
# return self.tracks.first()
#
# def filter_not_scheduled_by_slots(self):
# return self.get_not_approved_schedule()[:self.slots]
#
# def user_in_jury(self, user):
# return self.jury.users.filter(pk=user.pk).exists()
, which may include functions, classes, or code. Output only the next line. | self.user.is_superuser = True |
Predict the next line for this snippet: <|code_start|> raise ValidationError(message)
return username
def save(self, *args, **kwargs):
self.save_user_data()
return super(ProfileForm, self).save(*args, **kwargs)
def save_user_data(self):
data = self.cleaned_data
if data.get('name') != self.instance.user.get_full_name():
first_name = data.get('name').split()[0]
last_name = ' '.join(data.get('name').split()[1:])
self.instance.user.first_name = first_name
self.instance.user.last_name = last_name
if data.get('email') != self.instance.user.email:
self.instance.user.email = data.get('email')
if data.get('username') != self.instance.user.username:
self.instance.user.username = data.get('username')
self.instance.user.save()
class ProfilePictureForm(forms.ModelForm):
class Meta:
model = Profile
<|code_end|>
with the help of current file imports:
from django.utils.translation import ugettext as _
from django.contrib.auth.models import User
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from django import forms
from core.models import Profile
and context from other files:
# Path: core/models.py
# class Profile(models.Model):
# language = models.CharField(
# _('Language'), choices=settings.LANGUAGES,
# max_length=50, null=True, blank=False)
# about_me = models.TextField(
# _('About me'), max_length=500, null=True, blank=True)
# github = models.CharField(
# _('Github username'), max_length=50, null=True, blank=True)
# facebook = models.CharField(
# _('Facebook username'), max_length=50, null=True, blank=True)
# twitter = models.CharField(
# _('Twitter username'), max_length=50, null=True, blank=True)
# site = models.URLField(
# _('Site url'), max_length=200, null=True, blank=True)
# image = models.ImageField(null=True, blank=True)
#
# # relations
# user = models.OneToOneField(to=settings.AUTH_USER_MODEL)
#
# class Meta:
# verbose_name = _('Profile')
#
# def __str__(self):
# return self.user.get_full_name()
#
# def get_absolute_url(self):
# return reverse_lazy(
# 'user_profile', kwargs={'user__username': self.user.username})
#
# def get_github_url(self):
# if self.github:
# return 'https://github.com/{}'.format(self.github)
#
# def get_facebook_url(self):
# if self.facebook:
# return 'https://facebook.com/{}'.format(self.facebook)
#
# def get_twitter_url(self):
# if self.twitter:
# return 'https://twitter.com/{}'.format(self.twitter)
#
# def get_site_url(self):
# return self.site
#
# def get_profile_events(self):
# return self.user.events.filter(is_published=True)
#
# def get_profile_proposals(self):
# return Proposal.objects.filter(
# author=self.user,
# event__is_published=True,
# event__anonymous_voting=False,
# is_published=True,
# )
, which may contain function names, class names, or code. Output only the next line. | fields = ('image',) |
Next line prediction: <|code_start|>
def setUp(self):
User = get_user_model()
self.user = User.objects.get(username='user')
self.client = Client()
self.client.login(username='user', password='user')
def test_create_organization(self):
url = reverse('create_organization')
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
data = {'name': 'Speakerfight Corp', 'about': 'Cool company'}
url = reverse('create_organization')
response = self.client.post(url, data)
self.assertEqual(response.status_code, 302)
self.assertRedirects(
response,
reverse('update_organization', kwargs={'slug': 'speakerfight-corp'})
)
self.assertEqual(Organization.objects.count(), 1)
organization = Organization.objects.get(slug='speakerfight-corp')
self.assertEqual(organization.name, 'Speakerfight Corp')
self.assertEqual(organization.about, 'Cool company')
self.assertEqual(organization.created_by, self.user)
def test_update_organization(self):
organization = Organization.objects.create(
name='Speakerfight Corp',
about='Cool company',
<|code_end|>
. Use current file imports:
(from django.core.urlresolvers import reverse
from django.test import Client, TestCase
from django.contrib.auth import get_user_model
from organization.models import Organization)
and context including class names, function names, or small code snippets from other files:
# Path: organization/models.py
# class Organization(models.Model):
# name = models.CharField(_('Name'), max_length=100)
# slug = AutoSlugField(populate_from='name', overwrite=True,
# max_length=200, unique=True, db_index=True)
# about = models.TextField(
# _('About'), max_length=10000, blank=True)
#
# # relations
# created_by = models.ForeignKey(
# to=settings.AUTH_USER_MODEL, related_name='organizations'
# )
#
# def __str__(self):
# return six.text_type(self.name)
. Output only the next line. | created_by=self.user, |
Given snippet: <|code_start|>#
# Jasy - Web Tooling Framework
# Copyright 2010-2012 Zynga Inc.
#
class BlockPacker():
def __init__(self, w = 0, h = 0):
self.nodes = []
self.autogrow = False
if w > 0 and h > 0:
self.root = BlockNode(self, 0, 0, w, h)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from jasy.asset.sprite.BlockNode import BlockNode
and context:
# Path: jasy/asset/sprite/BlockNode.py
# class BlockNode():
#
# def __init__(self, parent, x, y, w, h):
#
# parent.nodes.append(self)
# self.x = x
# self.y = y
# self.w = w
# self.h = h
# self.down = None
# self.right = None
# self.used = False
which might include code, classes, or functions. Output only the next line. | else: |
Continue the code snippet: <|code_start|> result = type
elif type in self.__prefixes:
if getattr(node, "postfix", False):
result = self.compress(node[0]) + self.__prefixes[node.type]
else:
result = self.__prefixes[node.type] + self.compress(node[0])
elif type in self.__dividers:
first = self.compress(node[0])
second = self.compress(node[1])
divider = self.__dividers[node.type]
# Fast path
if node.type not in ("plus", "minus"):
result = "%s%s%s" % (first, divider, second)
# Special code for dealing with situations like x + ++y and y-- - x
else:
result = first
if first.endswith(divider):
result += " "
result += divider
if second.startswith(divider):
result += " "
result += second
else:
<|code_end|>
. Use current file imports:
import re, sys, json
from jasy.js.tokenize.Lang import keywords
from jasy.js.parse.Lang import expressions, futureReserved
and context (classes, functions, or code) from other files:
# Path: jasy/js/tokenize/Lang.py
#
# Path: jasy/js/parse/Lang.py
# def __createOrder():
. Output only the next line. | try: |
Continue the code snippet: <|code_start|> "lt" : '<',
"ursh" : '>>>',
"rsh" : '>>',
"ge" : '>=',
"gt" : '>',
"bitwise_or" : '|',
"bitwise_xor" : '^',
"bitwise_and" : '&'
}
__prefixes = {
"increment" : "++",
"decrement" : "--",
"bitwise_not" : '~',
"not" : "!",
"unary_plus" : "+",
"unary_minus" : "-",
"delete" : "delete ",
"new" : "new ",
"typeof" : "typeof ",
"void" : "void "
}
#
# Script Scope
#
def type_script(self, node):
<|code_end|>
. Use current file imports:
import re, sys, json
from jasy.js.tokenize.Lang import keywords
from jasy.js.parse.Lang import expressions, futureReserved
and context (classes, functions, or code) from other files:
# Path: jasy/js/tokenize/Lang.py
#
# Path: jasy/js/parse/Lang.py
# def __createOrder():
. Output only the next line. | return self.__statements(node) |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python3
# Extend PYTHONPATH with local 'lib' folder
if __name__ == "__main__":
jasyroot = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]), os.pardir, os.pardir, os.pardir, os.pardir))
sys.path.insert(0, jasyroot)
print("Running from %s..." % jasyroot)
class Tests(unittest.TestCase):
def process(self, code):
tree = Parser.parse(code)
meta = MetaData(tree)
return meta
def test_other(self):
meta = self.process('''
<|code_end|>
using the current file's imports:
import sys, os, unittest, logging
import jasy.js.parse.Parser as Parser
from jasy.js.MetaData import MetaData
and any relevant context from other files:
# Path: jasy/js/MetaData.py
# class MetaData:
# """
# Data structure to hold all meta information.
#
# A instance of this class is typically created by processing all
# meta data relevant tags of all doc comments in the given node structure.
#
# Hint: Must be a clean data class without links to other
# systems for optiomal cachability using Pickle
# """
#
# __slots__ = ["name", "requires", "optionals", "breaks", "assets"]
#
# def __init__(self, tree):
# self.name = None
#
# self.requires = set()
# self.optionals = set()
# self.breaks = set()
# self.assets = set()
#
# self.__inspect(tree)
#
#
# def __inspect(self, node):
# """ The internal inspection routine """
#
# # Parse comments
# comments = getattr(node, "comments", None)
# if comments:
# for comment in comments:
# commentTags = comment.getTags()
# if commentTags:
#
# if "name" in commentTags:
# self.name = list(commentTags["name"])[0]
# if "require" in commentTags:
# self.requires.update(commentTags["require"])
# if "load" in commentTags:
# # load is a special combination shorthand for requires + breaks
# # This means load it but don't require it being loaded first
# self.requires.update(commentTags["load"])
# self.breaks.update(commentTags["load"])
# if "optional" in commentTags:
# self.optionals.update(commentTags["optional"])
# if "break" in commentTags:
# self.breaks.update(commentTags["break"])
# if "asset" in commentTags:
# self.assets.update(commentTags["asset"])
#
# # Process children
# for child in node:
# if child is not None:
# self.__inspect(child)
. Output only the next line. | /** |
Using the snippet: <|code_start|>extensions = {
".png" : "image",
".jpeg" : "image",
".jpg" : "image",
".gif" : "image",
".mp3" : "audio",
".ogg" : "audio",
".m4a" : "audio",
".aac" : "audio",
".wav" : "audio",
".avi" : "video",
".mpeg" : "video",
".mpg" : "video",
".m4v" : "video",
".mkv" : "video",
".eot" : "font",
".woff" : "font",
".ttf" : "font",
".otf" : "font",
".pfa" : "font",
".pfb" : "font",
".afm" : "font",
".json" : "text",
".svg" : "text",
".txt" : "text",
".csv" : "text",
<|code_end|>
, determine the next line of code. You have imports:
import os.path
import jasy.asset.ImageInfo
import jasy.item.Abstract
import jasy.core.Console as Console
from jasy.core.Util import getKey
from jasy.core.Config import loadConfig
and context (class names, function names, or code) available:
# Path: jasy/core/Util.py
# def getKey(data, key, default=None):
# """
# Returns the key from the data if available or the given default
#
# :param data: Data structure to inspect
# :type data: dict
# :param key: Key to lookup in dictionary
# :type key: str
# :param default: Default value to return when key is not set
# :type default: any
# """
#
# if key in data:
# return data[key]
# else:
# return default
#
# Path: jasy/core/Config.py
# def loadConfig(fileName, encoding="utf-8"):
# """
# Loads the given configuration file (filename without extension) and
# returns the parsed object structure
# """
#
# configName = findConfig(fileName)
# if configName is None:
# raise UserError("Unsupported config file: %s" % fileName)
#
# fileHandle = open(configName, mode="r", encoding=encoding)
#
# fileExt = os.path.splitext(configName)[1]
# if fileExt == ".json":
# result = json.load(fileHandle)
#
# elif fileExt == ".yaml":
# result = yaml.load(fileHandle)
#
# fileHandle.close()
# return result
. Output only the next line. | ".html" : "text", |
Predict the next line for this snippet: <|code_start|> ".css" : "text",
".htc" : "text",
".xml" : "text",
".tmpl" : "text",
".fla" : "binary",
".swf" : "binary",
".psd" : "binary",
".pdf" : "binary"
}
class AssetItem(jasy.item.Abstract.AbstractItem):
kind = "asset"
__imageSpriteData = []
__imageAnimationData = []
__imageDimensionData = []
def __init__(self, project, id=None):
# Call Item's init method first
super().__init__(project, id)
self.extension = os.path.splitext(self.id.lower())[1]
self.type = getKey(extensions, self.extension, "other")
self.shortType = self.type[0]
def isImageSpriteConfig(self):
<|code_end|>
with the help of current file imports:
import os.path
import jasy.asset.ImageInfo
import jasy.item.Abstract
import jasy.core.Console as Console
from jasy.core.Util import getKey
from jasy.core.Config import loadConfig
and context from other files:
# Path: jasy/core/Util.py
# def getKey(data, key, default=None):
# """
# Returns the key from the data if available or the given default
#
# :param data: Data structure to inspect
# :type data: dict
# :param key: Key to lookup in dictionary
# :type key: str
# :param default: Default value to return when key is not set
# :type default: any
# """
#
# if key in data:
# return data[key]
# else:
# return default
#
# Path: jasy/core/Config.py
# def loadConfig(fileName, encoding="utf-8"):
# """
# Loads the given configuration file (filename without extension) and
# returns the parsed object structure
# """
#
# configName = findConfig(fileName)
# if configName is None:
# raise UserError("Unsupported config file: %s" % fileName)
#
# fileHandle = open(configName, mode="r", encoding=encoding)
#
# fileExt = os.path.splitext(configName)[1]
# if fileExt == ".json":
# result = json.load(fileHandle)
#
# elif fileExt == ".yaml":
# result = yaml.load(fileHandle)
#
# fileHandle.close()
# return result
, which may contain function names, class names, or code. Output only the next line. | return self.isText() and (os.path.basename(self.id) == "jasysprite.yaml" or os.path.basename(self.id) == "jasysprite.json") |
Using the snippet: <|code_start|>
def get_default_parameters():
aggregated_data = pd.read_csv(join(utils_data.FOLDER_SIMULATOR_INPUT, 'aggregated_data.csv'), index_col=0)
params = {
# seed for random number generator of current simulation
'seed': 666,
# start and end date of simulation
'start_date': datetime(2016, 1, 1).replace(tzinfo=timezone('US/Pacific')),
'end_date': datetime(2016, 12, 31).replace(tzinfo=timezone('US/Pacific')),
# how much noise we use in the simulation (use more for fraudulent than genuine customers)
'noise_level': 0.1,
# number of customers and fraudsters at beginning of simulation
# (note that this doesn't really influence the total amount of transactions;
# for that change the probability of making transactions)
'num_customers': 3333,
'num_fraudsters': 55,
# the initial satisfaction of customers
'init_satisfaction': 1.,
# number of fraud cards also used in genuine cards
'fraud_cards_in_genuine': float(aggregated_data.loc['fraud cards in genuine', 'fraud']),
# number of merchants at the beginning of simulation
<|code_end|>
, determine the next line of code. You have imports:
from datetime import datetime
from pytz import timezone
from os.path import join
from data import utils_data
import numpy as np
import pandas as pd
and context (class names, function names, or code) available:
# Path: data/utils_data.py
# FOLDER_REAL_DATA = join(dirname(__file__), 'real_data')
# FOLDER_SIMULATOR_INPUT = join(dirname(__file__), 'simulator_input')
# FOLDER_REAL_DATA_ANALYSIS = join(FOLDER_REAL_DATA, 'analysis')
# FOLDER_SIMULATOR_LOG = join(pardir, 'experiments/results')
# FILE_ANONYMIZED_DATASET = join(FOLDER_REAL_DATA, 'anonymized_dataset.csv')
# FILE_REAL_LOG = join(FOLDER_REAL_DATA, 'transaction_log.csv')
# FILE_SIMULATOR_LOG = join(FOLDER_SIMULATOR_LOG, 'transaction_log.csv')
# def get_dataset(file):
# def get_real_dataset():
# def get_simulated_dataset(result_idx):
# def get_real_data_stats():
# def get_simulated_data_stats(result_idx):
# def get_data_stats(datasets):
# def get_grouped_prob(group_by, col_name):
# def get_transaction_dist(col_name):
# def plot_hist_num_transactions(trans_frac, col_name):
# def plot_bar_trans_prob(trans_frac, col_name, file_name=None):
. Output only the next line. | 'num_merchants': int(aggregated_data.loc['num merchants', 'all']), |
Using the snippet: <|code_start|>
FOLDER_RESULTS = join(dirname(__file__), 'results')
FILE_RESULTS_IDX = join(FOLDER_RESULTS, 'curr_idx.txt')
def get_result_idx():
for line in open(FILE_RESULTS_IDX):
if line.strip(): # line contains eol character(s)
return int(line)
def update_result_idx(old_result_idx):
# increase result counter by one
<|code_end|>
, determine the next line of code. You have imports:
from os.path import isdir, join, dirname, exists
from os import mkdir
from simulator import parameters
import pickle
import numpy as np
import datetime
import pandas as pd
and context (class names, function names, or code) available:
# Path: simulator/parameters.py
# def get_default_parameters():
. Output only the next line. | f = open(FILE_RESULTS_IDX, 'w+') |
Here is a snippet: <|code_start|> def authorise_transaction(self, customer):
if customer.fraudster:
customer.give_authentication()
class NeverSecondAuthenticator(AbstractAuthenticator):
def authorise_transaction(self, customer):
pass
class AlwaysSecondAuthenticator(AbstractAuthenticator):
def authorise_transaction(self, customer):
customer.give_authentication()
class HeuristicAuthenticator(AbstractAuthenticator):
def __init__(self, thresh=50):
super().__init__()
self.thresh = thresh
def authorise_transaction(self, customer):
if customer.curr_amount > self.thresh:
customer.give_authentication()
def take_action(self, customer):
if customer.curr_amount > self.thresh:
return 1
class RandomAuthenticator(AbstractAuthenticator):
<|code_end|>
. Write the next line using the current file imports:
from authenticators.abstract_authenticator import AbstractAuthenticator
and context from other files:
# Path: authenticators/abstract_authenticator.py
# class AbstractAuthenticator(metaclass=ABCMeta):
# def __init__(self):
# """
# Every authenticator has to have a name
# :param name:
# """
# super().__init__()
#
# @abstractmethod
# def authorise_transaction(self, customer):
# """
# Decide whether to authorise transaction.
# Note that all relevant information can be obtained from the customer.
# :param customer: the customer making a transaction
# :return: boolean, whether or not to authorise the transaction
# """
, which may include functions, classes, or code. Output only the next line. | def authorise_transaction(self, customer): |
Given snippet: <|code_start|>
def test_word_count():
with open("WordCount/birds.txt", "r") as f:
data = f.read()
num_words = word_count.count_words(data)
assert(num_words == 34)
def test_line_count():
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from WordCount.word_count import count_words
from WordCount import word_count
and context:
# Path: WordCount/word_count.py
# def count_words(data):
# words = data.split(" ")
# num_words = len(words)
# return num_words
#
# Path: WordCount/word_count.py
# def count_words(data):
# def count_lines(data):
which might include code, classes, or functions. Output only the next line. | with open("WordCount/birds.txt", "r") as f: |
Given the code snippet: <|code_start|>
def test_word_count():
with open("WordCount/birds.txt", "r") as f:
data = f.read()
num_words = word_count.count_words(data)
assert(num_words == 34)
<|code_end|>
, generate the next line using the imports in this file:
from WordCount.word_count import count_words
from WordCount import word_count
and context (functions, classes, or occasionally code) from other files:
# Path: WordCount/word_count.py
# def count_words(data):
# words = data.split(" ")
# num_words = len(words)
# return num_words
#
# Path: WordCount/word_count.py
# def count_words(data):
# def count_lines(data):
. Output only the next line. | def test_line_count(): |
Next line prediction: <|code_start|>
def test_create_wave():
try:
for f in glob.glob("test.wav"):
os.remove(f)
except:
pass
create_wave.create_wav()
assert(os.path.exists("test.wav"))
def test_get_freq():
assert(1000 == get_freq.get_freq(True))
<|code_end|>
. Use current file imports:
(from audio import get_freq,create_wave,noisy
import os)
and context including class names, function names, or small code snippets from other files:
# Path: audio/get_freq.py
# def get_freq(nogui = False):
# frame_rate = 48000.0
# infile = "test.wav"
# num_samples = 48000
#
# wav_file = wave.open(infile, 'r')
# data = wav_file.readframes(num_samples)
# wav_file.close()
#
# data = struct.unpack('{n}h'.format(n=num_samples), data)
# data = np.array(data)
#
# data_fft = np.fft.fft(data)
#
# # This will give us the frequency we want
# frequencies = np.abs(data_fft)
# print("The frequency is {} Hz".format(np.argmax(frequencies)))
#
# if nogui:
# return np.argmax(frequencies)
# else:
# plt.subplot(2,1,1)
# plt.plot(data[:300])
# plt.title("Original audio wave")
# plt.subplot(2,1,2)
# plt.plot(frequencies)
# plt.title("Frequencies found")
#
# plt.xlim(0,1200)
# plt.savefig('wave.png')
#
# plt.show()
#
# Path: audio/create_wave.py
# def create_wav():
#
# Path: audio/noisy.py
# def noisy(nogui = False):
# # frequency is the number of times a wave repeats a second
# frequency = 1000
# noisy_freq = 50
# num_samples = 48000
#
# # The sampling rate of the analog to digital convert
# sampling_rate = 48000.0
#
# #Create the sine wave and noise
# sine_wave = [np.sin(2 * np.pi * frequency * x1 / sampling_rate) for x1 in range(num_samples)]
#
# sine_noise = [np.sin(2 * np.pi * noisy_freq * x1/ sampling_rate) for x1 in range(num_samples)]
#
#
# #Convert them to numpy arrays
# sine_wave = np.array(sine_wave)
# sine_noise = np.array(sine_noise)
#
# # Add them to create a noisy signal
# combined_signal = sine_wave + sine_noise
# if not nogui:
#
# plt.subplot(3,1,1)
# plt.title("Original sine wave")
#
# # Need to add empty space, else everything looks scrunched up!
# plt.subplots_adjust(hspace=.5)
# plt.plot(sine_wave[:500])
#
# plt.subplot(3,1,2)
# plt.title("Noisy wave")
# plt.plot(sine_noise[:4000])
#
# plt.subplot(3,1,3)
# plt.title("Original + Noise")
# plt.plot(combined_signal[:3000])
#
# plt.show()
#
#
# data_fft = np.fft.fft(combined_signal)
#
# freq = (np.abs(data_fft[:len(data_fft)]))
#
# if not nogui:
# plt.plot(freq)
# plt.title("Before filtering: Will have main signal (1000Hz) + noise frequency (50Hz)")
# plt.xlim(0,1200)
# plt.show()
#
# filtered_freq = []
# index = 0
# result = 0,0
# for f in freq:
# # Filter between lower and upper limits
# # Choosing 950, as closest to 1000. In real world, won't get exact numbers like these
# if index > 950 and index < 1050:
# # Has a real value. I'm choosing >1, as many values are like 0.000000001 etc
# if f > 1:
# filtered_freq.append(f)
# result = f,index
#
# else:
# filtered_freq.append(0)
# else:
# filtered_freq.append(0)
# index += 1
#
# if not nogui:
# plt.plot(filtered_freq)
# plt.title("After filtering: Main signal only (1000Hz)")
# plt.xlim(0,1200)
# plt.show()
# plt.close()
#
# recovered_signal = np.fft.ifft(filtered_freq)
#
# if not nogui:
#
# plt.subplot(3,1,1)
# plt.title("Original sine wave")
# # Need to add empty space, else everything looks scrunched up!
# plt.subplots_adjust(hspace=.5)
#
# plt.plot(sine_wave[:500])
#
# plt.subplot(3,1,2)
# plt.title("Noisy wave")
# plt.plot(combined_signal[:4000])
#
# plt.subplot(3,1,3)
# plt.title("Sine wave after clean up")
# plt.plot((recovered_signal[:500]))
# else:
# return result
. Output only the next line. | def test_noisy(): |
Here is a snippet: <|code_start|>
def test_edge():
try:
for f in glob.glob("test*.png"):
os.remove(f)
except:
pass
image = "Image_Video/ship.jpg"
edge_detect.edge_detect(image, True)
assert(os.path.exists("test_edge.png"))
def test_count_cards():
try:
for f in glob.glob("test*.png"):
os.remove(f)
except:
pass
image = "Image_Video/cards.jpg"
cards = count_cards.count_cards(image, True)
assert(cards == 5)
assert(os.path.exists("test_count_cards.png"))
for f in glob.glob("test*.png"):
os.remove(f)
def test_face_detect():
try:
for f in glob.glob("test*.png"):
os.remove(f)
<|code_end|>
. Write the next line using the current file imports:
from pdb import Pdb
from Image_Video import display,blur,edge_detect,count_cards,face_detect,webcam_face_detect
import os
import glob
and context from other files:
# Path: Image_Video/display.py
# def display(infile, nogui=False):
# image = cv2.imread(infile)
# if nogui:
# cv2.imwrite('test_display2.png', image)
# else:
# cv2.imshow("Image", image)
# cv2.waitKey(0)
#
# Path: Image_Video/blur.py
# def blur_display(infile, nogui=False):
#
# Path: Image_Video/edge_detect.py
# def edge_detect(infile, nogui=False):
# # The first argument is the image
# image = cv2.imread(infile)
#
# #conver to grayscale
# gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
#
# #blur it
# blurred_image = cv2.GaussianBlur(gray_image, (7,7), 0)
# # Use low thresholds
# canny = cv2.Canny(blurred_image, 10, 30)
# # Use high thresholds
# canny2 = cv2.Canny(blurred_image, 50, 150)
#
# if nogui:
# cv2.imwrite('test_edge.png', canny2)
# else:
# cv2.imshow("Orignal Image", image)
# cv2.imshow("Canny with low thresholds", canny)
# cv2.imshow("Canny with high thresholds", canny2)
# cv2.waitKey(0)
#
# Path: Image_Video/count_cards.py
# def count_cards(infile="cards.jpg", nogui=False):
# # Read the image
# image = cv2.imread(infile)
#
# #convert to grayscale
# gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
#
# #blur it
# blurred_image = cv2.GaussianBlur(gray_image, (7,7), 0)
#
# # Run the Canny edge detector
# canny = cv2.Canny(blurred_image, 30, 100)
# contours, hierarchy= cv2.findContours(canny, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# image2 = image
# cv2.drawContours(image2, contours, -1, (0,255,0), 2)
#
# print("Number of objects found = ", len(contours))
#
# if nogui:
# cv2.imwrite('test_count_cards.png', image2)
# return len(contours)
# else:
# # Show both our images
# cv2.imshow("Original image", image)
# cv2.imshow("Blurred image", blurred_image)
# cv2.imshow("Canny", canny)
# cv2.imshow("objects Found", image2)
# cv2.waitKey(0)
#
# Path: Image_Video/face_detect.py
# def face_detect(imgpath, nogui = False, cascasdepath = "haarcascade_frontalface_default.xml"):
#
# image = cv2.imread(imgpath)
# gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
#
# face_cascade = cv2.CascadeClassifier(cascasdepath)
#
# faces = face_cascade.detectMultiScale(
# gray,
# scaleFactor = 1.2,
# minNeighbors = 5,
# minSize = (30,30)
#
# )
#
# print("The number of faces found = ", len(faces))
#
# for (x,y,w,h) in faces:
# cv2.rectangle(image, (x,y), (x+h, y+h), (0, 255, 0), 2)
#
# if nogui:
# cv2.imwrite('test_face.png', image)
# return len(faces)
# else:
# cv2.imshow("Faces found", image)
# cv2.waitKey(0)
#
# Path: Image_Video/webcam_face_detect.py
# def webcam_face_detect(video_mode, nogui = False, cascasdepath = "haarcascade_frontalface_default.xml"):
#
# face_cascade = cv2.CascadeClassifier(cascasdepath)
#
# video_capture = cv2.VideoCapture(video_mode)
# num_faces = 0
#
#
# while True:
# ret, image = video_capture.read()
#
# if not ret:
# break
#
# gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
#
# faces = face_cascade.detectMultiScale(
# gray,
# scaleFactor = 1.2,
# minNeighbors = 5,
# minSize = (30,30)
#
# )
#
# print("The number of faces found = ", len(faces))
# num_faces = len(faces)
#
# if not nogui:
# for (x,y,w,h) in faces:
# cv2.rectangle(image, (x,y), (x+h, y+h), (0, 255, 0), 2)
#
# cv2.imshow("Faces found", image)
# if cv2.waitKey(1) & 0xFF == ord('q'):
# break
#
# video_capture.release()
# cv2.destroyAllWindows()
# return num_faces
, which may include functions, classes, or code. Output only the next line. | except: |
Given snippet: <|code_start|>
def test_blur():
try:
for f in glob.glob("test*.png"):
os.remove(f)
except:
pass
image = "Image_Video/ship.jpg"
blur.blur_display(image, True)
assert(os.path.exists("test_blurred.png"))
def test_edge():
try:
for f in glob.glob("test*.png"):
os.remove(f)
except:
pass
image = "Image_Video/ship.jpg"
edge_detect.edge_detect(image, True)
assert(os.path.exists("test_edge.png"))
def test_count_cards():
try:
for f in glob.glob("test*.png"):
os.remove(f)
except:
pass
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from pdb import Pdb
from Image_Video import display,blur,edge_detect,count_cards,face_detect,webcam_face_detect
import os
import glob
and context:
# Path: Image_Video/display.py
# def display(infile, nogui=False):
# image = cv2.imread(infile)
# if nogui:
# cv2.imwrite('test_display2.png', image)
# else:
# cv2.imshow("Image", image)
# cv2.waitKey(0)
#
# Path: Image_Video/blur.py
# def blur_display(infile, nogui=False):
#
# Path: Image_Video/edge_detect.py
# def edge_detect(infile, nogui=False):
# # The first argument is the image
# image = cv2.imread(infile)
#
# #conver to grayscale
# gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
#
# #blur it
# blurred_image = cv2.GaussianBlur(gray_image, (7,7), 0)
# # Use low thresholds
# canny = cv2.Canny(blurred_image, 10, 30)
# # Use high thresholds
# canny2 = cv2.Canny(blurred_image, 50, 150)
#
# if nogui:
# cv2.imwrite('test_edge.png', canny2)
# else:
# cv2.imshow("Orignal Image", image)
# cv2.imshow("Canny with low thresholds", canny)
# cv2.imshow("Canny with high thresholds", canny2)
# cv2.waitKey(0)
#
# Path: Image_Video/count_cards.py
# def count_cards(infile="cards.jpg", nogui=False):
# # Read the image
# image = cv2.imread(infile)
#
# #convert to grayscale
# gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
#
# #blur it
# blurred_image = cv2.GaussianBlur(gray_image, (7,7), 0)
#
# # Run the Canny edge detector
# canny = cv2.Canny(blurred_image, 30, 100)
# contours, hierarchy= cv2.findContours(canny, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# image2 = image
# cv2.drawContours(image2, contours, -1, (0,255,0), 2)
#
# print("Number of objects found = ", len(contours))
#
# if nogui:
# cv2.imwrite('test_count_cards.png', image2)
# return len(contours)
# else:
# # Show both our images
# cv2.imshow("Original image", image)
# cv2.imshow("Blurred image", blurred_image)
# cv2.imshow("Canny", canny)
# cv2.imshow("objects Found", image2)
# cv2.waitKey(0)
#
# Path: Image_Video/face_detect.py
# def face_detect(imgpath, nogui = False, cascasdepath = "haarcascade_frontalface_default.xml"):
#
# image = cv2.imread(imgpath)
# gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
#
# face_cascade = cv2.CascadeClassifier(cascasdepath)
#
# faces = face_cascade.detectMultiScale(
# gray,
# scaleFactor = 1.2,
# minNeighbors = 5,
# minSize = (30,30)
#
# )
#
# print("The number of faces found = ", len(faces))
#
# for (x,y,w,h) in faces:
# cv2.rectangle(image, (x,y), (x+h, y+h), (0, 255, 0), 2)
#
# if nogui:
# cv2.imwrite('test_face.png', image)
# return len(faces)
# else:
# cv2.imshow("Faces found", image)
# cv2.waitKey(0)
#
# Path: Image_Video/webcam_face_detect.py
# def webcam_face_detect(video_mode, nogui = False, cascasdepath = "haarcascade_frontalface_default.xml"):
#
# face_cascade = cv2.CascadeClassifier(cascasdepath)
#
# video_capture = cv2.VideoCapture(video_mode)
# num_faces = 0
#
#
# while True:
# ret, image = video_capture.read()
#
# if not ret:
# break
#
# gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
#
# faces = face_cascade.detectMultiScale(
# gray,
# scaleFactor = 1.2,
# minNeighbors = 5,
# minSize = (30,30)
#
# )
#
# print("The number of faces found = ", len(faces))
# num_faces = len(faces)
#
# if not nogui:
# for (x,y,w,h) in faces:
# cv2.rectangle(image, (x,y), (x+h, y+h), (0, 255, 0), 2)
#
# cv2.imshow("Faces found", image)
# if cv2.waitKey(1) & 0xFF == ord('q'):
# break
#
# video_capture.release()
# cv2.destroyAllWindows()
# return num_faces
which might include code, classes, or functions. Output only the next line. | image = "Image_Video/cards.jpg" |
Predict the next line after this snippet: <|code_start|> os.remove(f)
except:
pass
image = "Image_Video/ship.jpg"
blur.blur_display(image, True)
assert(os.path.exists("test_blurred.png"))
def test_edge():
try:
for f in glob.glob("test*.png"):
os.remove(f)
except:
pass
image = "Image_Video/ship.jpg"
edge_detect.edge_detect(image, True)
assert(os.path.exists("test_edge.png"))
def test_count_cards():
try:
for f in glob.glob("test*.png"):
os.remove(f)
except:
pass
image = "Image_Video/cards.jpg"
cards = count_cards.count_cards(image, True)
assert(cards == 5)
assert(os.path.exists("test_count_cards.png"))
for f in glob.glob("test*.png"):
<|code_end|>
using the current file's imports:
from pdb import Pdb
from Image_Video import display,blur,edge_detect,count_cards,face_detect,webcam_face_detect
import os
import glob
and any relevant context from other files:
# Path: Image_Video/display.py
# def display(infile, nogui=False):
# image = cv2.imread(infile)
# if nogui:
# cv2.imwrite('test_display2.png', image)
# else:
# cv2.imshow("Image", image)
# cv2.waitKey(0)
#
# Path: Image_Video/blur.py
# def blur_display(infile, nogui=False):
#
# Path: Image_Video/edge_detect.py
# def edge_detect(infile, nogui=False):
# # The first argument is the image
# image = cv2.imread(infile)
#
# #conver to grayscale
# gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
#
# #blur it
# blurred_image = cv2.GaussianBlur(gray_image, (7,7), 0)
# # Use low thresholds
# canny = cv2.Canny(blurred_image, 10, 30)
# # Use high thresholds
# canny2 = cv2.Canny(blurred_image, 50, 150)
#
# if nogui:
# cv2.imwrite('test_edge.png', canny2)
# else:
# cv2.imshow("Orignal Image", image)
# cv2.imshow("Canny with low thresholds", canny)
# cv2.imshow("Canny with high thresholds", canny2)
# cv2.waitKey(0)
#
# Path: Image_Video/count_cards.py
# def count_cards(infile="cards.jpg", nogui=False):
# # Read the image
# image = cv2.imread(infile)
#
# #convert to grayscale
# gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
#
# #blur it
# blurred_image = cv2.GaussianBlur(gray_image, (7,7), 0)
#
# # Run the Canny edge detector
# canny = cv2.Canny(blurred_image, 30, 100)
# contours, hierarchy= cv2.findContours(canny, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# image2 = image
# cv2.drawContours(image2, contours, -1, (0,255,0), 2)
#
# print("Number of objects found = ", len(contours))
#
# if nogui:
# cv2.imwrite('test_count_cards.png', image2)
# return len(contours)
# else:
# # Show both our images
# cv2.imshow("Original image", image)
# cv2.imshow("Blurred image", blurred_image)
# cv2.imshow("Canny", canny)
# cv2.imshow("objects Found", image2)
# cv2.waitKey(0)
#
# Path: Image_Video/face_detect.py
# def face_detect(imgpath, nogui = False, cascasdepath = "haarcascade_frontalface_default.xml"):
#
# image = cv2.imread(imgpath)
# gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
#
# face_cascade = cv2.CascadeClassifier(cascasdepath)
#
# faces = face_cascade.detectMultiScale(
# gray,
# scaleFactor = 1.2,
# minNeighbors = 5,
# minSize = (30,30)
#
# )
#
# print("The number of faces found = ", len(faces))
#
# for (x,y,w,h) in faces:
# cv2.rectangle(image, (x,y), (x+h, y+h), (0, 255, 0), 2)
#
# if nogui:
# cv2.imwrite('test_face.png', image)
# return len(faces)
# else:
# cv2.imshow("Faces found", image)
# cv2.waitKey(0)
#
# Path: Image_Video/webcam_face_detect.py
# def webcam_face_detect(video_mode, nogui = False, cascasdepath = "haarcascade_frontalface_default.xml"):
#
# face_cascade = cv2.CascadeClassifier(cascasdepath)
#
# video_capture = cv2.VideoCapture(video_mode)
# num_faces = 0
#
#
# while True:
# ret, image = video_capture.read()
#
# if not ret:
# break
#
# gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
#
# faces = face_cascade.detectMultiScale(
# gray,
# scaleFactor = 1.2,
# minNeighbors = 5,
# minSize = (30,30)
#
# )
#
# print("The number of faces found = ", len(faces))
# num_faces = len(faces)
#
# if not nogui:
# for (x,y,w,h) in faces:
# cv2.rectangle(image, (x,y), (x+h, y+h), (0, 255, 0), 2)
#
# cv2.imshow("Faces found", image)
# if cv2.waitKey(1) & 0xFF == ord('q'):
# break
#
# video_capture.release()
# cv2.destroyAllWindows()
# return num_faces
. Output only the next line. | os.remove(f) |
Here is a snippet: <|code_start|>def test_count_cards():
try:
for f in glob.glob("test*.png"):
os.remove(f)
except:
pass
image = "Image_Video/cards.jpg"
cards = count_cards.count_cards(image, True)
assert(cards == 5)
assert(os.path.exists("test_count_cards.png"))
for f in glob.glob("test*.png"):
os.remove(f)
def test_face_detect():
try:
for f in glob.glob("test*.png"):
os.remove(f)
except:
pass
image = "Image_Video/abba.png"
faces = face_detect.face_detect(image, True, "Image_Video/haarcascade_frontalface_default.xml")
assert(faces == 4)
assert(os.path.exists("test_face.png"))
for f in glob.glob("test*.png"):
os.remove(f)
def test_webcam_face_detect():
try:
for f in glob.glob("test*.png"):
<|code_end|>
. Write the next line using the current file imports:
from pdb import Pdb
from Image_Video import display,blur,edge_detect,count_cards,face_detect,webcam_face_detect
import os
import glob
and context from other files:
# Path: Image_Video/display.py
# def display(infile, nogui=False):
# image = cv2.imread(infile)
# if nogui:
# cv2.imwrite('test_display2.png', image)
# else:
# cv2.imshow("Image", image)
# cv2.waitKey(0)
#
# Path: Image_Video/blur.py
# def blur_display(infile, nogui=False):
#
# Path: Image_Video/edge_detect.py
# def edge_detect(infile, nogui=False):
# # The first argument is the image
# image = cv2.imread(infile)
#
# #conver to grayscale
# gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
#
# #blur it
# blurred_image = cv2.GaussianBlur(gray_image, (7,7), 0)
# # Use low thresholds
# canny = cv2.Canny(blurred_image, 10, 30)
# # Use high thresholds
# canny2 = cv2.Canny(blurred_image, 50, 150)
#
# if nogui:
# cv2.imwrite('test_edge.png', canny2)
# else:
# cv2.imshow("Orignal Image", image)
# cv2.imshow("Canny with low thresholds", canny)
# cv2.imshow("Canny with high thresholds", canny2)
# cv2.waitKey(0)
#
# Path: Image_Video/count_cards.py
# def count_cards(infile="cards.jpg", nogui=False):
# # Read the image
# image = cv2.imread(infile)
#
# #convert to grayscale
# gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
#
# #blur it
# blurred_image = cv2.GaussianBlur(gray_image, (7,7), 0)
#
# # Run the Canny edge detector
# canny = cv2.Canny(blurred_image, 30, 100)
# contours, hierarchy= cv2.findContours(canny, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# image2 = image
# cv2.drawContours(image2, contours, -1, (0,255,0), 2)
#
# print("Number of objects found = ", len(contours))
#
# if nogui:
# cv2.imwrite('test_count_cards.png', image2)
# return len(contours)
# else:
# # Show both our images
# cv2.imshow("Original image", image)
# cv2.imshow("Blurred image", blurred_image)
# cv2.imshow("Canny", canny)
# cv2.imshow("objects Found", image2)
# cv2.waitKey(0)
#
# Path: Image_Video/face_detect.py
# def face_detect(imgpath, nogui = False, cascasdepath = "haarcascade_frontalface_default.xml"):
#
# image = cv2.imread(imgpath)
# gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
#
# face_cascade = cv2.CascadeClassifier(cascasdepath)
#
# faces = face_cascade.detectMultiScale(
# gray,
# scaleFactor = 1.2,
# minNeighbors = 5,
# minSize = (30,30)
#
# )
#
# print("The number of faces found = ", len(faces))
#
# for (x,y,w,h) in faces:
# cv2.rectangle(image, (x,y), (x+h, y+h), (0, 255, 0), 2)
#
# if nogui:
# cv2.imwrite('test_face.png', image)
# return len(faces)
# else:
# cv2.imshow("Faces found", image)
# cv2.waitKey(0)
#
# Path: Image_Video/webcam_face_detect.py
# def webcam_face_detect(video_mode, nogui = False, cascasdepath = "haarcascade_frontalface_default.xml"):
#
# face_cascade = cv2.CascadeClassifier(cascasdepath)
#
# video_capture = cv2.VideoCapture(video_mode)
# num_faces = 0
#
#
# while True:
# ret, image = video_capture.read()
#
# if not ret:
# break
#
# gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
#
# faces = face_cascade.detectMultiScale(
# gray,
# scaleFactor = 1.2,
# minNeighbors = 5,
# minSize = (30,30)
#
# )
#
# print("The number of faces found = ", len(faces))
# num_faces = len(faces)
#
# if not nogui:
# for (x,y,w,h) in faces:
# cv2.rectangle(image, (x,y), (x+h, y+h), (0, 255, 0), 2)
#
# cv2.imshow("Faces found", image)
# if cv2.waitKey(1) & 0xFF == ord('q'):
# break
#
# video_capture.release()
# cv2.destroyAllWindows()
# return num_faces
, which may include functions, classes, or code. Output only the next line. | os.remove(f) |
Using the snippet: <|code_start|> image = "Image_Video/ship.jpg"
display.display(image, True)
assert(os.path.exists("test_display2.png"))
def test_blur():
try:
for f in glob.glob("test*.png"):
os.remove(f)
except:
pass
image = "Image_Video/ship.jpg"
blur.blur_display(image, True)
assert(os.path.exists("test_blurred.png"))
def test_edge():
try:
for f in glob.glob("test*.png"):
os.remove(f)
except:
pass
image = "Image_Video/ship.jpg"
edge_detect.edge_detect(image, True)
assert(os.path.exists("test_edge.png"))
def test_count_cards():
try:
for f in glob.glob("test*.png"):
<|code_end|>
, determine the next line of code. You have imports:
from pdb import Pdb
from Image_Video import display,blur,edge_detect,count_cards,face_detect,webcam_face_detect
import os
import glob
and context (class names, function names, or code) available:
# Path: Image_Video/display.py
# def display(infile, nogui=False):
# image = cv2.imread(infile)
# if nogui:
# cv2.imwrite('test_display2.png', image)
# else:
# cv2.imshow("Image", image)
# cv2.waitKey(0)
#
# Path: Image_Video/blur.py
# def blur_display(infile, nogui=False):
#
# Path: Image_Video/edge_detect.py
# def edge_detect(infile, nogui=False):
# # The first argument is the image
# image = cv2.imread(infile)
#
# #conver to grayscale
# gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
#
# #blur it
# blurred_image = cv2.GaussianBlur(gray_image, (7,7), 0)
# # Use low thresholds
# canny = cv2.Canny(blurred_image, 10, 30)
# # Use high thresholds
# canny2 = cv2.Canny(blurred_image, 50, 150)
#
# if nogui:
# cv2.imwrite('test_edge.png', canny2)
# else:
# cv2.imshow("Orignal Image", image)
# cv2.imshow("Canny with low thresholds", canny)
# cv2.imshow("Canny with high thresholds", canny2)
# cv2.waitKey(0)
#
# Path: Image_Video/count_cards.py
# def count_cards(infile="cards.jpg", nogui=False):
# # Read the image
# image = cv2.imread(infile)
#
# #convert to grayscale
# gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
#
# #blur it
# blurred_image = cv2.GaussianBlur(gray_image, (7,7), 0)
#
# # Run the Canny edge detector
# canny = cv2.Canny(blurred_image, 30, 100)
# contours, hierarchy= cv2.findContours(canny, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# image2 = image
# cv2.drawContours(image2, contours, -1, (0,255,0), 2)
#
# print("Number of objects found = ", len(contours))
#
# if nogui:
# cv2.imwrite('test_count_cards.png', image2)
# return len(contours)
# else:
# # Show both our images
# cv2.imshow("Original image", image)
# cv2.imshow("Blurred image", blurred_image)
# cv2.imshow("Canny", canny)
# cv2.imshow("objects Found", image2)
# cv2.waitKey(0)
#
# Path: Image_Video/face_detect.py
# def face_detect(imgpath, nogui = False, cascasdepath = "haarcascade_frontalface_default.xml"):
#
# image = cv2.imread(imgpath)
# gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
#
# face_cascade = cv2.CascadeClassifier(cascasdepath)
#
# faces = face_cascade.detectMultiScale(
# gray,
# scaleFactor = 1.2,
# minNeighbors = 5,
# minSize = (30,30)
#
# )
#
# print("The number of faces found = ", len(faces))
#
# for (x,y,w,h) in faces:
# cv2.rectangle(image, (x,y), (x+h, y+h), (0, 255, 0), 2)
#
# if nogui:
# cv2.imwrite('test_face.png', image)
# return len(faces)
# else:
# cv2.imshow("Faces found", image)
# cv2.waitKey(0)
#
# Path: Image_Video/webcam_face_detect.py
# def webcam_face_detect(video_mode, nogui = False, cascasdepath = "haarcascade_frontalface_default.xml"):
#
# face_cascade = cv2.CascadeClassifier(cascasdepath)
#
# video_capture = cv2.VideoCapture(video_mode)
# num_faces = 0
#
#
# while True:
# ret, image = video_capture.read()
#
# if not ret:
# break
#
# gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
#
# faces = face_cascade.detectMultiScale(
# gray,
# scaleFactor = 1.2,
# minNeighbors = 5,
# minSize = (30,30)
#
# )
#
# print("The number of faces found = ", len(faces))
# num_faces = len(faces)
#
# if not nogui:
# for (x,y,w,h) in faces:
# cv2.rectangle(image, (x,y), (x+h, y+h), (0, 255, 0), 2)
#
# cv2.imshow("Faces found", image)
# if cv2.waitKey(1) & 0xFF == ord('q'):
# break
#
# video_capture.release()
# cv2.destroyAllWindows()
# return num_faces
. Output only the next line. | os.remove(f) |
Continue the code snippet: <|code_start|>
class Command(BaseCommand):
help = 'Delete all DedupEvents for a particular task'
def add_arguments(self, parser):
parser.add_argument('task_pair_id', nargs='+', type=int)
parser.add_argument('--no-op', action='store_true', help="dry run")
def handle(self, *args, **options):
for task_pair_id in options['task_pair_id']:
qs = DedupEvent.objects.filter(task_pair_id=task_pair_id)
<|code_end|>
. Use current file imports:
from django.core.management.base import BaseCommand, CommandError
from helper.models import DedupEvent
and context (classes, functions, or code) from other files:
# Path: helper/models.py
# class DedupEvent(models.Model):
# """
# A simpler event type for when you just need to suppress duplicate
# events by a simple unique key. For example, any facbeook event might be
# stored for deduplication by it's FBID
# """
# task_pair = models.ForeignKey(TaskPair)
# key = models.TextField()
# created = models.DateTimeField(auto_now=True)
#
# class Meta:
# unique_together = ('task_pair', 'key')
#
# def __str__(self):
# return '{0.task_pair}::{0.key}'.format(self)
. Output only the next line. | count = qs.count() |
Given the code snippet: <|code_start|>
@shared_task
@format_options_from_event
def send_file_to_dropbox(data, task_pair_id, access_token,
filename, path, url):
client = DropboxClient(access_token)
file_path = posixpath.join(path, filename)
file_path = file_path.replace('\\', '|')
file_path = file_path.encode('ascii', errors='replace').decode()
resp = requests.get(url)
resp.raise_for_status()
<|code_end|>
, generate the next line using the imports in this file:
import posixpath
import requests
from celery import shared_task
from django import forms
from dropbox.client import DropboxClient
from helper.utils.decorators import format_options_from_event
and context (functions, classes, or occasionally code) from other files:
# Path: helper/utils/decorators.py
# def format_options_from_event(func):
# """
# MUST(ok.. should) be the first decorator used since it actually wraps the
# function and all others just add stuff (at least HELPeR decorators)
#
# Applies formatting to all keys if task_pair_id isn't present, else looks up
# the effect task's options and only formats those.
# """
# @wraps(func)
# def wrapper(data, **kwargs):
# from helper.models import TaskPair # Avoid circular import
# try:
# options = TaskPair.objects.get(
# pk=kwargs['task_pair_id']).effect.options
# except (TaskPair.DoesNotExist, KeyError):
# options = kwargs.keys()
# for option in options:
# kwargs[option] = kwargs[option].format(**data)
# return func(data, **kwargs)
# return wrapper
. Output only the next line. | client.put_file(file_path, resp.content, overwrite=True) |
Using the snippet: <|code_start|>
class Command(BaseCommand):
help = 'Popoulate DedupEvents for a particular task'
def add_arguments(self, parser):
parser.add_argument('task_pair_id', nargs='+', type=int)
def handle(self, *args, **options):
<|code_end|>
, determine the next line of code. You have imports:
from django.core.management.base import BaseCommand, CommandError
from helper.models import TaskPair
and context (class names, function names, or code) available:
# Path: helper/models.py
# class TaskPair(models.Model):
# name = models.CharField(max_length=255, null=True, blank=True)
# enabled = models.BooleanField(default=True)
# cause_agent = models.ForeignKey(AgentConfig,
# related_name='cause_task_pairs')
# cause_task = models.CharField(max_length=255)
# cause_options = HStoreField(null=True, blank=True)
# effect_agent = models.ForeignKey(AgentConfig,
# related_name='effect_task_pairs')
# effect_task = models.CharField(max_length=255)
# effect_options = HStoreField(null=True, blank=True)
#
# def __str__(self):
# if self.name:
# return self.name
# return '{}:{} -> {}:{}'.format(
# self.cause_agent, self.cause_task,
# self.effect_agent, self.effect_task,
# )
#
# def get_absolute_url(self):
# return reverse('task_pair_detail', kwargs={'pk': self.id})
#
# def clean(self):
# try:
# self.cause
# except AttributeError:
# raise ValidationError('module "{}" has no task "{}"'.format(
# self.cause_agent.name + '.task', self.cause_task
# ))
# except ImportError:
# raise ValidationError('module "{}" does not exist'.format(
# self.cause_agent.name + '.task'
# ))
# try:
# self.effect
# except AttributeError:
# raise ValidationError('module "{}" has no task "{}"'.format(
# self.effect_agent.name + '.task', self.effect_task
# ))
# except ImportError:
# raise ValidationError('module "{}" does not exist'.format(
# self.effect_agent.name + '.task'
# ))
#
# @property
# def cause(self):
# cause = self.cause_agent.agent.cause_tasks[self.cause_task]
# cause.do_not_call_in_templates = True
# return cause
#
# @property
# def effect(self):
# effect = self.effect_agent.agent.effect_tasks[self.effect_task]
# effect.do_not_call_in_templates = True
# return effect
#
# @property
# def cause_view(self):
# return getattr(import_module(self.cause_agent.name + '.views'),
# self.cause_task)
#
# @property
# def effect_view(self):
# return getattr(import_module(self.effect_agent.name + '.views'),
# self.effect_task)
#
# @property
# def cause_name(self):
# return getattr(self.cause, 'label',
# self.cause_task.replace('_', ' ').capitalize())
#
# @property
# def effect_name(self):
# return getattr(self.effect, 'label',
# self.effect_task.replace('_', ' ').capitalize())
#
# @property
# def schedule(self):
# try:
# return self.cause.every
# except (AttributeError, ImportError):
# pass
#
# def run(self):
# cause_options = self.cause_agent.options or {}
# cause_options.update({k: v for k, v in self.cause_options.items()
# if not k.startswith('_')})
# cause_options['task_pair_id'] = self.id
# effect_options = self.effect_agent.options or {}
# effect_options.update({k: v for k, v in self.effect_options.items()
# if not k.startswith('_')})
# effect_options['task_pair_id'] = self.id
#
# cause = self.cause.s(**cause_options)
#
# if getattr(self.cause, 'dedup_key', None) is not None:
# effect = dedup_effect_wrapper.s(
# dedup_key=self.cause.dedup_key,
# task_pair_id=self.id,
# effect=self.effect.s(**effect_options),
# )
# else:
# effect = self.effect.s(**effect_options)
#
# return chain(cause, dmap.s(effect))()
#
# def populate_dedup_events(self):
# if getattr(self.cause, 'dedup_key', None) is not None:
# cause_options = self.cause_agent.options or {}
# cause_options.update({k: v for k, v in self.cause_options.items()
# if not k.startswith('_')})
# cause_options['task_pair_id'] = self.id
#
# cause = self.cause.s(**cause_options)
# effect = create_dedup_event.s(task_pair_id=self.id,
# dedup_key=self.cause.dedup_key)
# return chain(cause, dmap.s(effect))()
. Output only the next line. | for task_pair_id in options['task_pair_id']: |
Based on the snippet: <|code_start|>
class Command(BaseCommand):
help = 'Runs the specified task'
def add_arguments(self, parser):
<|code_end|>
, predict the immediate next line with the help of imports:
from django.core.management.base import BaseCommand, CommandError
from helper.models import TaskPair
and context (classes, functions, sometimes code) from other files:
# Path: helper/models.py
# class TaskPair(models.Model):
# name = models.CharField(max_length=255, null=True, blank=True)
# enabled = models.BooleanField(default=True)
# cause_agent = models.ForeignKey(AgentConfig,
# related_name='cause_task_pairs')
# cause_task = models.CharField(max_length=255)
# cause_options = HStoreField(null=True, blank=True)
# effect_agent = models.ForeignKey(AgentConfig,
# related_name='effect_task_pairs')
# effect_task = models.CharField(max_length=255)
# effect_options = HStoreField(null=True, blank=True)
#
# def __str__(self):
# if self.name:
# return self.name
# return '{}:{} -> {}:{}'.format(
# self.cause_agent, self.cause_task,
# self.effect_agent, self.effect_task,
# )
#
# def get_absolute_url(self):
# return reverse('task_pair_detail', kwargs={'pk': self.id})
#
# def clean(self):
# try:
# self.cause
# except AttributeError:
# raise ValidationError('module "{}" has no task "{}"'.format(
# self.cause_agent.name + '.task', self.cause_task
# ))
# except ImportError:
# raise ValidationError('module "{}" does not exist'.format(
# self.cause_agent.name + '.task'
# ))
# try:
# self.effect
# except AttributeError:
# raise ValidationError('module "{}" has no task "{}"'.format(
# self.effect_agent.name + '.task', self.effect_task
# ))
# except ImportError:
# raise ValidationError('module "{}" does not exist'.format(
# self.effect_agent.name + '.task'
# ))
#
# @property
# def cause(self):
# cause = self.cause_agent.agent.cause_tasks[self.cause_task]
# cause.do_not_call_in_templates = True
# return cause
#
# @property
# def effect(self):
# effect = self.effect_agent.agent.effect_tasks[self.effect_task]
# effect.do_not_call_in_templates = True
# return effect
#
# @property
# def cause_view(self):
# return getattr(import_module(self.cause_agent.name + '.views'),
# self.cause_task)
#
# @property
# def effect_view(self):
# return getattr(import_module(self.effect_agent.name + '.views'),
# self.effect_task)
#
# @property
# def cause_name(self):
# return getattr(self.cause, 'label',
# self.cause_task.replace('_', ' ').capitalize())
#
# @property
# def effect_name(self):
# return getattr(self.effect, 'label',
# self.effect_task.replace('_', ' ').capitalize())
#
# @property
# def schedule(self):
# try:
# return self.cause.every
# except (AttributeError, ImportError):
# pass
#
# def run(self):
# cause_options = self.cause_agent.options or {}
# cause_options.update({k: v for k, v in self.cause_options.items()
# if not k.startswith('_')})
# cause_options['task_pair_id'] = self.id
# effect_options = self.effect_agent.options or {}
# effect_options.update({k: v for k, v in self.effect_options.items()
# if not k.startswith('_')})
# effect_options['task_pair_id'] = self.id
#
# cause = self.cause.s(**cause_options)
#
# if getattr(self.cause, 'dedup_key', None) is not None:
# effect = dedup_effect_wrapper.s(
# dedup_key=self.cause.dedup_key,
# task_pair_id=self.id,
# effect=self.effect.s(**effect_options),
# )
# else:
# effect = self.effect.s(**effect_options)
#
# return chain(cause, dmap.s(effect))()
#
# def populate_dedup_events(self):
# if getattr(self.cause, 'dedup_key', None) is not None:
# cause_options = self.cause_agent.options or {}
# cause_options.update({k: v for k, v in self.cause_options.items()
# if not k.startswith('_')})
# cause_options['task_pair_id'] = self.id
#
# cause = self.cause.s(**cause_options)
# effect = create_dedup_event.s(task_pair_id=self.id,
# dedup_key=self.cause.dedup_key)
# return chain(cause, dmap.s(effect))()
. Output only the next line. | parser.add_argument('task_id', nargs='+', type=int) |
Predict the next line for this snippet: <|code_start|> url(r'^agent/?$',
AgentConfigListView.as_view(),
name='agent_config_list'),
url(r'^agent/add/?$',
AgentConfigCreateView.as_view(),
name='agent_config_create'),
url(r'^agent/(?P<pk>[a-zA-Z.]+)/?$',
AgentConfigDetailView.as_view(),
name='agent_config_detail'),
url(r'^agent/(?P<pk>[a-zA-Z.]+)/delete/?$',
AgentConfigDeleteView.as_view(),
name='agent_config_delete'),
# agentconfig custom view
url(r'^agent/(?P<agent_config_id>[a-zA-Z.]+)/(?P<view_name>\w+)',
'helper.views.dispatch_agent_config_url',
name='dispatch_agent_config_url'),
# taskpair generics
url(r'^task/?$',
TaskPairListView.as_view(),
name='task_pair_list'),
url(r'^task/add/?$',
TaskPairWizard.as_view(),
name='task_pair_create'),
url(r'^task/add/advanced/?$',
TaskPairCreateView.as_view(),
name='task_pair_create_advanced'),
url(r'^task/(?P<pk>\d+)/?$',
TaskPairDetailView.as_view(),
name='task_pair_detail'),
<|code_end|>
with the help of current file imports:
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.views.generic import RedirectView
from .views import (AgentConfigDetailView, AgentConfigListView,
AgentConfigDeleteView, AgentConfigCreateView,
TaskPairDetailView, TaskPairListView,
TaskPairDeleteView, TaskPairWizard,
TaskPairAdvancedDetailView, TaskPairCreateView)
and context from other files:
# Path: helper/views.py
# class AgentConfigDetailView(UpdateView):
# model = AgentConfig
# template_name_suffix = '_detail'
# form_class = AgentConfigUpdateForm
#
# def get_success_url(self):
# return self.object.get_absolute_url()
#
# class AgentConfigListView(ListView):
# model = AgentConfig
#
# class AgentConfigDeleteView(DeleteView):
# model = AgentConfig
# success_url = reverse_lazy('agent_config_list')
#
# def get_context_data(self, **kwargs):
# context = super(AgentConfigDeleteView, self).get_context_data(**kwargs)
# context['cascade_task_pairs'] = TaskPair.objects.filter(
# Q(cause_agent=self.object) | Q(effect_agent=self.object)
# ).distinct()
# return context
#
# class AgentConfigCreateView(CreateView):
# model = AgentConfig
# form_class = AgentConfigCreateForm
#
# class TaskPairDetailView(UpdateView):
# model = TaskPair
# template_name_suffix = '_detail'
# form_class = TaskPairUpdateForm
#
# def get_success_url(object):
# return reverse('task_pair_list')
#
# class TaskPairListView(ListView):
# model = TaskPair
#
# class TaskPairDeleteView(DeleteView):
# model = TaskPair
# success_url = reverse_lazy('task_pair_list')
#
# class TaskPairWizard(SessionWizardView):
# form_list = [TaskPairChooseCauseAgentForm, TaskPairChooseCauseTaskForm,
# TaskPairCauseOptionsForm,
# TaskPairChooseEffectAgentForm, TaskPairChooseEffectTaskForm,
# TaskPairEffectOptionsForm,
# ]
# template_name = 'helper/taskpair_wizard.html'
#
#
# def render_done(self, form, **kwargs):
# """
# Dont' want all the revalidation storage stuff... The form is fine :)
# """
# task_pair = TaskPair.objects.create(**form.cleaned_data)
# task_pair.populate_dedup_events()
# return redirect(task_pair)
#
# def process_step(self, form):
# """
# user cleaned_data as next forms initial data
# """
# if self.steps.next:
# self.initial_dict.setdefault(self.steps.next, {}).update({
# k: v.pk if hasattr(v, 'pk') else v
# for k, v in form.cleaned_data.items()})
#
# class TaskPairAdvancedDetailView(UpdateView):
# model = TaskPair
# template_name_suffix = '_detail'
# form_class = TaskPairAdvancedForm
#
# def get_success_url(object):
# return reverse('task_pair_list')
#
# class TaskPairCreateView(CreateView):
# model = TaskPair
# form_class = TaskPairAdvancedForm
# template_name = 'helper/taskpair_detail.html'
, which may contain function names, class names, or code. Output only the next line. | url(r'^task/(?P<pk>\d+)/advanced/?$', |
Given snippet: <|code_start|> url(r'^task/add/?$',
TaskPairWizard.as_view(),
name='task_pair_create'),
url(r'^task/add/advanced/?$',
TaskPairCreateView.as_view(),
name='task_pair_create_advanced'),
url(r'^task/(?P<pk>\d+)/?$',
TaskPairDetailView.as_view(),
name='task_pair_detail'),
url(r'^task/(?P<pk>\d+)/advanced/?$',
TaskPairAdvancedDetailView.as_view(),
name='task_pair_detail_advanced'),
url(r'^task/(?P<pk>\d+)/delete/?$',
TaskPairDeleteView.as_view(),
name='task_pair_delete'),
# taskpair custom url
url(r'^task/(?P<task_pair_id>\d+)/(?P<secret>\w+)',
'helper.views.dispatch_task_pair_url',
name='dispatch_task_pair_url'),
# auth endpoints
url(r'^accounts/login/$', 'django.contrib.auth.views.login',
{'template_name': 'login.html'}, name="login"),
url(r'^accounts/logout/$', 'django.contrib.auth.views.logout',
{'next_page': '/'}, name="logout"),
]
if 'django.contrib.admin' in settings.INSTALLED_APPS:
urlpatterns += [
url(r'^admin/', include(admin.site.urls)),
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.views.generic import RedirectView
from .views import (AgentConfigDetailView, AgentConfigListView,
AgentConfigDeleteView, AgentConfigCreateView,
TaskPairDetailView, TaskPairListView,
TaskPairDeleteView, TaskPairWizard,
TaskPairAdvancedDetailView, TaskPairCreateView)
and context:
# Path: helper/views.py
# class AgentConfigDetailView(UpdateView):
# model = AgentConfig
# template_name_suffix = '_detail'
# form_class = AgentConfigUpdateForm
#
# def get_success_url(self):
# return self.object.get_absolute_url()
#
# class AgentConfigListView(ListView):
# model = AgentConfig
#
# class AgentConfigDeleteView(DeleteView):
# model = AgentConfig
# success_url = reverse_lazy('agent_config_list')
#
# def get_context_data(self, **kwargs):
# context = super(AgentConfigDeleteView, self).get_context_data(**kwargs)
# context['cascade_task_pairs'] = TaskPair.objects.filter(
# Q(cause_agent=self.object) | Q(effect_agent=self.object)
# ).distinct()
# return context
#
# class AgentConfigCreateView(CreateView):
# model = AgentConfig
# form_class = AgentConfigCreateForm
#
# class TaskPairDetailView(UpdateView):
# model = TaskPair
# template_name_suffix = '_detail'
# form_class = TaskPairUpdateForm
#
# def get_success_url(object):
# return reverse('task_pair_list')
#
# class TaskPairListView(ListView):
# model = TaskPair
#
# class TaskPairDeleteView(DeleteView):
# model = TaskPair
# success_url = reverse_lazy('task_pair_list')
#
# class TaskPairWizard(SessionWizardView):
# form_list = [TaskPairChooseCauseAgentForm, TaskPairChooseCauseTaskForm,
# TaskPairCauseOptionsForm,
# TaskPairChooseEffectAgentForm, TaskPairChooseEffectTaskForm,
# TaskPairEffectOptionsForm,
# ]
# template_name = 'helper/taskpair_wizard.html'
#
#
# def render_done(self, form, **kwargs):
# """
# Dont' want all the revalidation storage stuff... The form is fine :)
# """
# task_pair = TaskPair.objects.create(**form.cleaned_data)
# task_pair.populate_dedup_events()
# return redirect(task_pair)
#
# def process_step(self, form):
# """
# user cleaned_data as next forms initial data
# """
# if self.steps.next:
# self.initial_dict.setdefault(self.steps.next, {}).update({
# k: v.pk if hasattr(v, 'pk') else v
# for k, v in form.cleaned_data.items()})
#
# class TaskPairAdvancedDetailView(UpdateView):
# model = TaskPair
# template_name_suffix = '_detail'
# form_class = TaskPairAdvancedForm
#
# def get_success_url(object):
# return reverse('task_pair_list')
#
# class TaskPairCreateView(CreateView):
# model = TaskPair
# form_class = TaskPairAdvancedForm
# template_name = 'helper/taskpair_detail.html'
which might include code, classes, or functions. Output only the next line. | ] |
Given the following code snippet before the placeholder: <|code_start|> name='agent_config_create'),
url(r'^agent/(?P<pk>[a-zA-Z.]+)/?$',
AgentConfigDetailView.as_view(),
name='agent_config_detail'),
url(r'^agent/(?P<pk>[a-zA-Z.]+)/delete/?$',
AgentConfigDeleteView.as_view(),
name='agent_config_delete'),
# agentconfig custom view
url(r'^agent/(?P<agent_config_id>[a-zA-Z.]+)/(?P<view_name>\w+)',
'helper.views.dispatch_agent_config_url',
name='dispatch_agent_config_url'),
# taskpair generics
url(r'^task/?$',
TaskPairListView.as_view(),
name='task_pair_list'),
url(r'^task/add/?$',
TaskPairWizard.as_view(),
name='task_pair_create'),
url(r'^task/add/advanced/?$',
TaskPairCreateView.as_view(),
name='task_pair_create_advanced'),
url(r'^task/(?P<pk>\d+)/?$',
TaskPairDetailView.as_view(),
name='task_pair_detail'),
url(r'^task/(?P<pk>\d+)/advanced/?$',
TaskPairAdvancedDetailView.as_view(),
name='task_pair_detail_advanced'),
url(r'^task/(?P<pk>\d+)/delete/?$',
TaskPairDeleteView.as_view(),
<|code_end|>
, predict the next line using imports from the current file:
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.views.generic import RedirectView
from .views import (AgentConfigDetailView, AgentConfigListView,
AgentConfigDeleteView, AgentConfigCreateView,
TaskPairDetailView, TaskPairListView,
TaskPairDeleteView, TaskPairWizard,
TaskPairAdvancedDetailView, TaskPairCreateView)
and context including class names, function names, and sometimes code from other files:
# Path: helper/views.py
# class AgentConfigDetailView(UpdateView):
# model = AgentConfig
# template_name_suffix = '_detail'
# form_class = AgentConfigUpdateForm
#
# def get_success_url(self):
# return self.object.get_absolute_url()
#
# class AgentConfigListView(ListView):
# model = AgentConfig
#
# class AgentConfigDeleteView(DeleteView):
# model = AgentConfig
# success_url = reverse_lazy('agent_config_list')
#
# def get_context_data(self, **kwargs):
# context = super(AgentConfigDeleteView, self).get_context_data(**kwargs)
# context['cascade_task_pairs'] = TaskPair.objects.filter(
# Q(cause_agent=self.object) | Q(effect_agent=self.object)
# ).distinct()
# return context
#
# class AgentConfigCreateView(CreateView):
# model = AgentConfig
# form_class = AgentConfigCreateForm
#
# class TaskPairDetailView(UpdateView):
# model = TaskPair
# template_name_suffix = '_detail'
# form_class = TaskPairUpdateForm
#
# def get_success_url(object):
# return reverse('task_pair_list')
#
# class TaskPairListView(ListView):
# model = TaskPair
#
# class TaskPairDeleteView(DeleteView):
# model = TaskPair
# success_url = reverse_lazy('task_pair_list')
#
# class TaskPairWizard(SessionWizardView):
# form_list = [TaskPairChooseCauseAgentForm, TaskPairChooseCauseTaskForm,
# TaskPairCauseOptionsForm,
# TaskPairChooseEffectAgentForm, TaskPairChooseEffectTaskForm,
# TaskPairEffectOptionsForm,
# ]
# template_name = 'helper/taskpair_wizard.html'
#
#
# def render_done(self, form, **kwargs):
# """
# Dont' want all the revalidation storage stuff... The form is fine :)
# """
# task_pair = TaskPair.objects.create(**form.cleaned_data)
# task_pair.populate_dedup_events()
# return redirect(task_pair)
#
# def process_step(self, form):
# """
# user cleaned_data as next forms initial data
# """
# if self.steps.next:
# self.initial_dict.setdefault(self.steps.next, {}).update({
# k: v.pk if hasattr(v, 'pk') else v
# for k, v in form.cleaned_data.items()})
#
# class TaskPairAdvancedDetailView(UpdateView):
# model = TaskPair
# template_name_suffix = '_detail'
# form_class = TaskPairAdvancedForm
#
# def get_success_url(object):
# return reverse('task_pair_list')
#
# class TaskPairCreateView(CreateView):
# model = TaskPair
# form_class = TaskPairAdvancedForm
# template_name = 'helper/taskpair_detail.html'
. Output only the next line. | name='task_pair_delete'), |
Based on the snippet: <|code_start|>
urlpatterns = [
# redirect to tasks for now
url(r'^$', RedirectView.as_view(pattern_name='task_pair_list',
permanent=False), name='home'),
# agentconfig generics
url(r'^agent/?$',
AgentConfigListView.as_view(),
name='agent_config_list'),
url(r'^agent/add/?$',
AgentConfigCreateView.as_view(),
name='agent_config_create'),
url(r'^agent/(?P<pk>[a-zA-Z.]+)/?$',
AgentConfigDetailView.as_view(),
name='agent_config_detail'),
url(r'^agent/(?P<pk>[a-zA-Z.]+)/delete/?$',
AgentConfigDeleteView.as_view(),
name='agent_config_delete'),
# agentconfig custom view
url(r'^agent/(?P<agent_config_id>[a-zA-Z.]+)/(?P<view_name>\w+)',
<|code_end|>
, predict the immediate next line with the help of imports:
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.views.generic import RedirectView
from .views import (AgentConfigDetailView, AgentConfigListView,
AgentConfigDeleteView, AgentConfigCreateView,
TaskPairDetailView, TaskPairListView,
TaskPairDeleteView, TaskPairWizard,
TaskPairAdvancedDetailView, TaskPairCreateView)
and context (classes, functions, sometimes code) from other files:
# Path: helper/views.py
# class AgentConfigDetailView(UpdateView):
# model = AgentConfig
# template_name_suffix = '_detail'
# form_class = AgentConfigUpdateForm
#
# def get_success_url(self):
# return self.object.get_absolute_url()
#
# class AgentConfigListView(ListView):
# model = AgentConfig
#
# class AgentConfigDeleteView(DeleteView):
# model = AgentConfig
# success_url = reverse_lazy('agent_config_list')
#
# def get_context_data(self, **kwargs):
# context = super(AgentConfigDeleteView, self).get_context_data(**kwargs)
# context['cascade_task_pairs'] = TaskPair.objects.filter(
# Q(cause_agent=self.object) | Q(effect_agent=self.object)
# ).distinct()
# return context
#
# class AgentConfigCreateView(CreateView):
# model = AgentConfig
# form_class = AgentConfigCreateForm
#
# class TaskPairDetailView(UpdateView):
# model = TaskPair
# template_name_suffix = '_detail'
# form_class = TaskPairUpdateForm
#
# def get_success_url(object):
# return reverse('task_pair_list')
#
# class TaskPairListView(ListView):
# model = TaskPair
#
# class TaskPairDeleteView(DeleteView):
# model = TaskPair
# success_url = reverse_lazy('task_pair_list')
#
# class TaskPairWizard(SessionWizardView):
# form_list = [TaskPairChooseCauseAgentForm, TaskPairChooseCauseTaskForm,
# TaskPairCauseOptionsForm,
# TaskPairChooseEffectAgentForm, TaskPairChooseEffectTaskForm,
# TaskPairEffectOptionsForm,
# ]
# template_name = 'helper/taskpair_wizard.html'
#
#
# def render_done(self, form, **kwargs):
# """
# Dont' want all the revalidation storage stuff... The form is fine :)
# """
# task_pair = TaskPair.objects.create(**form.cleaned_data)
# task_pair.populate_dedup_events()
# return redirect(task_pair)
#
# def process_step(self, form):
# """
# user cleaned_data as next forms initial data
# """
# if self.steps.next:
# self.initial_dict.setdefault(self.steps.next, {}).update({
# k: v.pk if hasattr(v, 'pk') else v
# for k, v in form.cleaned_data.items()})
#
# class TaskPairAdvancedDetailView(UpdateView):
# model = TaskPair
# template_name_suffix = '_detail'
# form_class = TaskPairAdvancedForm
#
# def get_success_url(object):
# return reverse('task_pair_list')
#
# class TaskPairCreateView(CreateView):
# model = TaskPair
# form_class = TaskPairAdvancedForm
# template_name = 'helper/taskpair_detail.html'
. Output only the next line. | 'helper.views.dispatch_agent_config_url', |
Given snippet: <|code_start|> name='agent_config_create'),
url(r'^agent/(?P<pk>[a-zA-Z.]+)/?$',
AgentConfigDetailView.as_view(),
name='agent_config_detail'),
url(r'^agent/(?P<pk>[a-zA-Z.]+)/delete/?$',
AgentConfigDeleteView.as_view(),
name='agent_config_delete'),
# agentconfig custom view
url(r'^agent/(?P<agent_config_id>[a-zA-Z.]+)/(?P<view_name>\w+)',
'helper.views.dispatch_agent_config_url',
name='dispatch_agent_config_url'),
# taskpair generics
url(r'^task/?$',
TaskPairListView.as_view(),
name='task_pair_list'),
url(r'^task/add/?$',
TaskPairWizard.as_view(),
name='task_pair_create'),
url(r'^task/add/advanced/?$',
TaskPairCreateView.as_view(),
name='task_pair_create_advanced'),
url(r'^task/(?P<pk>\d+)/?$',
TaskPairDetailView.as_view(),
name='task_pair_detail'),
url(r'^task/(?P<pk>\d+)/advanced/?$',
TaskPairAdvancedDetailView.as_view(),
name='task_pair_detail_advanced'),
url(r'^task/(?P<pk>\d+)/delete/?$',
TaskPairDeleteView.as_view(),
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.views.generic import RedirectView
from .views import (AgentConfigDetailView, AgentConfigListView,
AgentConfigDeleteView, AgentConfigCreateView,
TaskPairDetailView, TaskPairListView,
TaskPairDeleteView, TaskPairWizard,
TaskPairAdvancedDetailView, TaskPairCreateView)
and context:
# Path: helper/views.py
# class AgentConfigDetailView(UpdateView):
# model = AgentConfig
# template_name_suffix = '_detail'
# form_class = AgentConfigUpdateForm
#
# def get_success_url(self):
# return self.object.get_absolute_url()
#
# class AgentConfigListView(ListView):
# model = AgentConfig
#
# class AgentConfigDeleteView(DeleteView):
# model = AgentConfig
# success_url = reverse_lazy('agent_config_list')
#
# def get_context_data(self, **kwargs):
# context = super(AgentConfigDeleteView, self).get_context_data(**kwargs)
# context['cascade_task_pairs'] = TaskPair.objects.filter(
# Q(cause_agent=self.object) | Q(effect_agent=self.object)
# ).distinct()
# return context
#
# class AgentConfigCreateView(CreateView):
# model = AgentConfig
# form_class = AgentConfigCreateForm
#
# class TaskPairDetailView(UpdateView):
# model = TaskPair
# template_name_suffix = '_detail'
# form_class = TaskPairUpdateForm
#
# def get_success_url(object):
# return reverse('task_pair_list')
#
# class TaskPairListView(ListView):
# model = TaskPair
#
# class TaskPairDeleteView(DeleteView):
# model = TaskPair
# success_url = reverse_lazy('task_pair_list')
#
# class TaskPairWizard(SessionWizardView):
# form_list = [TaskPairChooseCauseAgentForm, TaskPairChooseCauseTaskForm,
# TaskPairCauseOptionsForm,
# TaskPairChooseEffectAgentForm, TaskPairChooseEffectTaskForm,
# TaskPairEffectOptionsForm,
# ]
# template_name = 'helper/taskpair_wizard.html'
#
#
# def render_done(self, form, **kwargs):
# """
# Dont' want all the revalidation storage stuff... The form is fine :)
# """
# task_pair = TaskPair.objects.create(**form.cleaned_data)
# task_pair.populate_dedup_events()
# return redirect(task_pair)
#
# def process_step(self, form):
# """
# user cleaned_data as next forms initial data
# """
# if self.steps.next:
# self.initial_dict.setdefault(self.steps.next, {}).update({
# k: v.pk if hasattr(v, 'pk') else v
# for k, v in form.cleaned_data.items()})
#
# class TaskPairAdvancedDetailView(UpdateView):
# model = TaskPair
# template_name_suffix = '_detail'
# form_class = TaskPairAdvancedForm
#
# def get_success_url(object):
# return reverse('task_pair_list')
#
# class TaskPairCreateView(CreateView):
# model = TaskPair
# form_class = TaskPairAdvancedForm
# template_name = 'helper/taskpair_detail.html'
which might include code, classes, or functions. Output only the next line. | name='task_pair_delete'), |
Here is a snippet: <|code_start|> url(r'^agent/add/?$',
AgentConfigCreateView.as_view(),
name='agent_config_create'),
url(r'^agent/(?P<pk>[a-zA-Z.]+)/?$',
AgentConfigDetailView.as_view(),
name='agent_config_detail'),
url(r'^agent/(?P<pk>[a-zA-Z.]+)/delete/?$',
AgentConfigDeleteView.as_view(),
name='agent_config_delete'),
# agentconfig custom view
url(r'^agent/(?P<agent_config_id>[a-zA-Z.]+)/(?P<view_name>\w+)',
'helper.views.dispatch_agent_config_url',
name='dispatch_agent_config_url'),
# taskpair generics
url(r'^task/?$',
TaskPairListView.as_view(),
name='task_pair_list'),
url(r'^task/add/?$',
TaskPairWizard.as_view(),
name='task_pair_create'),
url(r'^task/add/advanced/?$',
TaskPairCreateView.as_view(),
name='task_pair_create_advanced'),
url(r'^task/(?P<pk>\d+)/?$',
TaskPairDetailView.as_view(),
name='task_pair_detail'),
url(r'^task/(?P<pk>\d+)/advanced/?$',
TaskPairAdvancedDetailView.as_view(),
name='task_pair_detail_advanced'),
<|code_end|>
. Write the next line using the current file imports:
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.views.generic import RedirectView
from .views import (AgentConfigDetailView, AgentConfigListView,
AgentConfigDeleteView, AgentConfigCreateView,
TaskPairDetailView, TaskPairListView,
TaskPairDeleteView, TaskPairWizard,
TaskPairAdvancedDetailView, TaskPairCreateView)
and context from other files:
# Path: helper/views.py
# class AgentConfigDetailView(UpdateView):
# model = AgentConfig
# template_name_suffix = '_detail'
# form_class = AgentConfigUpdateForm
#
# def get_success_url(self):
# return self.object.get_absolute_url()
#
# class AgentConfigListView(ListView):
# model = AgentConfig
#
# class AgentConfigDeleteView(DeleteView):
# model = AgentConfig
# success_url = reverse_lazy('agent_config_list')
#
# def get_context_data(self, **kwargs):
# context = super(AgentConfigDeleteView, self).get_context_data(**kwargs)
# context['cascade_task_pairs'] = TaskPair.objects.filter(
# Q(cause_agent=self.object) | Q(effect_agent=self.object)
# ).distinct()
# return context
#
# class AgentConfigCreateView(CreateView):
# model = AgentConfig
# form_class = AgentConfigCreateForm
#
# class TaskPairDetailView(UpdateView):
# model = TaskPair
# template_name_suffix = '_detail'
# form_class = TaskPairUpdateForm
#
# def get_success_url(object):
# return reverse('task_pair_list')
#
# class TaskPairListView(ListView):
# model = TaskPair
#
# class TaskPairDeleteView(DeleteView):
# model = TaskPair
# success_url = reverse_lazy('task_pair_list')
#
# class TaskPairWizard(SessionWizardView):
# form_list = [TaskPairChooseCauseAgentForm, TaskPairChooseCauseTaskForm,
# TaskPairCauseOptionsForm,
# TaskPairChooseEffectAgentForm, TaskPairChooseEffectTaskForm,
# TaskPairEffectOptionsForm,
# ]
# template_name = 'helper/taskpair_wizard.html'
#
#
# def render_done(self, form, **kwargs):
# """
# Dont' want all the revalidation storage stuff... The form is fine :)
# """
# task_pair = TaskPair.objects.create(**form.cleaned_data)
# task_pair.populate_dedup_events()
# return redirect(task_pair)
#
# def process_step(self, form):
# """
# user cleaned_data as next forms initial data
# """
# if self.steps.next:
# self.initial_dict.setdefault(self.steps.next, {}).update({
# k: v.pk if hasattr(v, 'pk') else v
# for k, v in form.cleaned_data.items()})
#
# class TaskPairAdvancedDetailView(UpdateView):
# model = TaskPair
# template_name_suffix = '_detail'
# form_class = TaskPairAdvancedForm
#
# def get_success_url(object):
# return reverse('task_pair_list')
#
# class TaskPairCreateView(CreateView):
# model = TaskPair
# form_class = TaskPairAdvancedForm
# template_name = 'helper/taskpair_detail.html'
, which may include functions, classes, or code. Output only the next line. | url(r'^task/(?P<pk>\d+)/delete/?$', |
Predict the next line for this snippet: <|code_start|> name='agent_config_detail'),
url(r'^agent/(?P<pk>[a-zA-Z.]+)/delete/?$',
AgentConfigDeleteView.as_view(),
name='agent_config_delete'),
# agentconfig custom view
url(r'^agent/(?P<agent_config_id>[a-zA-Z.]+)/(?P<view_name>\w+)',
'helper.views.dispatch_agent_config_url',
name='dispatch_agent_config_url'),
# taskpair generics
url(r'^task/?$',
TaskPairListView.as_view(),
name='task_pair_list'),
url(r'^task/add/?$',
TaskPairWizard.as_view(),
name='task_pair_create'),
url(r'^task/add/advanced/?$',
TaskPairCreateView.as_view(),
name='task_pair_create_advanced'),
url(r'^task/(?P<pk>\d+)/?$',
TaskPairDetailView.as_view(),
name='task_pair_detail'),
url(r'^task/(?P<pk>\d+)/advanced/?$',
TaskPairAdvancedDetailView.as_view(),
name='task_pair_detail_advanced'),
url(r'^task/(?P<pk>\d+)/delete/?$',
TaskPairDeleteView.as_view(),
name='task_pair_delete'),
# taskpair custom url
url(r'^task/(?P<task_pair_id>\d+)/(?P<secret>\w+)',
<|code_end|>
with the help of current file imports:
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.views.generic import RedirectView
from .views import (AgentConfigDetailView, AgentConfigListView,
AgentConfigDeleteView, AgentConfigCreateView,
TaskPairDetailView, TaskPairListView,
TaskPairDeleteView, TaskPairWizard,
TaskPairAdvancedDetailView, TaskPairCreateView)
and context from other files:
# Path: helper/views.py
# class AgentConfigDetailView(UpdateView):
# model = AgentConfig
# template_name_suffix = '_detail'
# form_class = AgentConfigUpdateForm
#
# def get_success_url(self):
# return self.object.get_absolute_url()
#
# class AgentConfigListView(ListView):
# model = AgentConfig
#
# class AgentConfigDeleteView(DeleteView):
# model = AgentConfig
# success_url = reverse_lazy('agent_config_list')
#
# def get_context_data(self, **kwargs):
# context = super(AgentConfigDeleteView, self).get_context_data(**kwargs)
# context['cascade_task_pairs'] = TaskPair.objects.filter(
# Q(cause_agent=self.object) | Q(effect_agent=self.object)
# ).distinct()
# return context
#
# class AgentConfigCreateView(CreateView):
# model = AgentConfig
# form_class = AgentConfigCreateForm
#
# class TaskPairDetailView(UpdateView):
# model = TaskPair
# template_name_suffix = '_detail'
# form_class = TaskPairUpdateForm
#
# def get_success_url(object):
# return reverse('task_pair_list')
#
# class TaskPairListView(ListView):
# model = TaskPair
#
# class TaskPairDeleteView(DeleteView):
# model = TaskPair
# success_url = reverse_lazy('task_pair_list')
#
# class TaskPairWizard(SessionWizardView):
# form_list = [TaskPairChooseCauseAgentForm, TaskPairChooseCauseTaskForm,
# TaskPairCauseOptionsForm,
# TaskPairChooseEffectAgentForm, TaskPairChooseEffectTaskForm,
# TaskPairEffectOptionsForm,
# ]
# template_name = 'helper/taskpair_wizard.html'
#
#
# def render_done(self, form, **kwargs):
# """
# Dont' want all the revalidation storage stuff... The form is fine :)
# """
# task_pair = TaskPair.objects.create(**form.cleaned_data)
# task_pair.populate_dedup_events()
# return redirect(task_pair)
#
# def process_step(self, form):
# """
# user cleaned_data as next forms initial data
# """
# if self.steps.next:
# self.initial_dict.setdefault(self.steps.next, {}).update({
# k: v.pk if hasattr(v, 'pk') else v
# for k, v in form.cleaned_data.items()})
#
# class TaskPairAdvancedDetailView(UpdateView):
# model = TaskPair
# template_name_suffix = '_detail'
# form_class = TaskPairAdvancedForm
#
# def get_success_url(object):
# return reverse('task_pair_list')
#
# class TaskPairCreateView(CreateView):
# model = TaskPair
# form_class = TaskPairAdvancedForm
# template_name = 'helper/taskpair_detail.html'
, which may contain function names, class names, or code. Output only the next line. | 'helper.views.dispatch_task_pair_url', |
Given the code snippet: <|code_start|> permanent=False), name='home'),
# agentconfig generics
url(r'^agent/?$',
AgentConfigListView.as_view(),
name='agent_config_list'),
url(r'^agent/add/?$',
AgentConfigCreateView.as_view(),
name='agent_config_create'),
url(r'^agent/(?P<pk>[a-zA-Z.]+)/?$',
AgentConfigDetailView.as_view(),
name='agent_config_detail'),
url(r'^agent/(?P<pk>[a-zA-Z.]+)/delete/?$',
AgentConfigDeleteView.as_view(),
name='agent_config_delete'),
# agentconfig custom view
url(r'^agent/(?P<agent_config_id>[a-zA-Z.]+)/(?P<view_name>\w+)',
'helper.views.dispatch_agent_config_url',
name='dispatch_agent_config_url'),
# taskpair generics
url(r'^task/?$',
TaskPairListView.as_view(),
name='task_pair_list'),
url(r'^task/add/?$',
TaskPairWizard.as_view(),
name='task_pair_create'),
url(r'^task/add/advanced/?$',
TaskPairCreateView.as_view(),
name='task_pair_create_advanced'),
<|code_end|>
, generate the next line using the imports in this file:
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.views.generic import RedirectView
from .views import (AgentConfigDetailView, AgentConfigListView,
AgentConfigDeleteView, AgentConfigCreateView,
TaskPairDetailView, TaskPairListView,
TaskPairDeleteView, TaskPairWizard,
TaskPairAdvancedDetailView, TaskPairCreateView)
and context (functions, classes, or occasionally code) from other files:
# Path: helper/views.py
# class AgentConfigDetailView(UpdateView):
# model = AgentConfig
# template_name_suffix = '_detail'
# form_class = AgentConfigUpdateForm
#
# def get_success_url(self):
# return self.object.get_absolute_url()
#
# class AgentConfigListView(ListView):
# model = AgentConfig
#
# class AgentConfigDeleteView(DeleteView):
# model = AgentConfig
# success_url = reverse_lazy('agent_config_list')
#
# def get_context_data(self, **kwargs):
# context = super(AgentConfigDeleteView, self).get_context_data(**kwargs)
# context['cascade_task_pairs'] = TaskPair.objects.filter(
# Q(cause_agent=self.object) | Q(effect_agent=self.object)
# ).distinct()
# return context
#
# class AgentConfigCreateView(CreateView):
# model = AgentConfig
# form_class = AgentConfigCreateForm
#
# class TaskPairDetailView(UpdateView):
# model = TaskPair
# template_name_suffix = '_detail'
# form_class = TaskPairUpdateForm
#
# def get_success_url(object):
# return reverse('task_pair_list')
#
# class TaskPairListView(ListView):
# model = TaskPair
#
# class TaskPairDeleteView(DeleteView):
# model = TaskPair
# success_url = reverse_lazy('task_pair_list')
#
# class TaskPairWizard(SessionWizardView):
# form_list = [TaskPairChooseCauseAgentForm, TaskPairChooseCauseTaskForm,
# TaskPairCauseOptionsForm,
# TaskPairChooseEffectAgentForm, TaskPairChooseEffectTaskForm,
# TaskPairEffectOptionsForm,
# ]
# template_name = 'helper/taskpair_wizard.html'
#
#
# def render_done(self, form, **kwargs):
# """
# Dont' want all the revalidation storage stuff... The form is fine :)
# """
# task_pair = TaskPair.objects.create(**form.cleaned_data)
# task_pair.populate_dedup_events()
# return redirect(task_pair)
#
# def process_step(self, form):
# """
# user cleaned_data as next forms initial data
# """
# if self.steps.next:
# self.initial_dict.setdefault(self.steps.next, {}).update({
# k: v.pk if hasattr(v, 'pk') else v
# for k, v in form.cleaned_data.items()})
#
# class TaskPairAdvancedDetailView(UpdateView):
# model = TaskPair
# template_name_suffix = '_detail'
# form_class = TaskPairAdvancedForm
#
# def get_success_url(object):
# return reverse('task_pair_list')
#
# class TaskPairCreateView(CreateView):
# model = TaskPair
# form_class = TaskPairAdvancedForm
# template_name = 'helper/taskpair_detail.html'
. Output only the next line. | url(r'^task/(?P<pk>\d+)/?$', |
Here is a snippet: <|code_start|>
urlpatterns = [
# redirect to tasks for now
url(r'^$', RedirectView.as_view(pattern_name='task_pair_list',
permanent=False), name='home'),
# agentconfig generics
url(r'^agent/?$',
AgentConfigListView.as_view(),
name='agent_config_list'),
url(r'^agent/add/?$',
AgentConfigCreateView.as_view(),
name='agent_config_create'),
url(r'^agent/(?P<pk>[a-zA-Z.]+)/?$',
AgentConfigDetailView.as_view(),
name='agent_config_detail'),
url(r'^agent/(?P<pk>[a-zA-Z.]+)/delete/?$',
AgentConfigDeleteView.as_view(),
name='agent_config_delete'),
# agentconfig custom view
url(r'^agent/(?P<agent_config_id>[a-zA-Z.]+)/(?P<view_name>\w+)',
'helper.views.dispatch_agent_config_url',
name='dispatch_agent_config_url'),
# taskpair generics
<|code_end|>
. Write the next line using the current file imports:
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.views.generic import RedirectView
from .views import (AgentConfigDetailView, AgentConfigListView,
AgentConfigDeleteView, AgentConfigCreateView,
TaskPairDetailView, TaskPairListView,
TaskPairDeleteView, TaskPairWizard,
TaskPairAdvancedDetailView, TaskPairCreateView)
and context from other files:
# Path: helper/views.py
# class AgentConfigDetailView(UpdateView):
# model = AgentConfig
# template_name_suffix = '_detail'
# form_class = AgentConfigUpdateForm
#
# def get_success_url(self):
# return self.object.get_absolute_url()
#
# class AgentConfigListView(ListView):
# model = AgentConfig
#
# class AgentConfigDeleteView(DeleteView):
# model = AgentConfig
# success_url = reverse_lazy('agent_config_list')
#
# def get_context_data(self, **kwargs):
# context = super(AgentConfigDeleteView, self).get_context_data(**kwargs)
# context['cascade_task_pairs'] = TaskPair.objects.filter(
# Q(cause_agent=self.object) | Q(effect_agent=self.object)
# ).distinct()
# return context
#
# class AgentConfigCreateView(CreateView):
# model = AgentConfig
# form_class = AgentConfigCreateForm
#
# class TaskPairDetailView(UpdateView):
# model = TaskPair
# template_name_suffix = '_detail'
# form_class = TaskPairUpdateForm
#
# def get_success_url(object):
# return reverse('task_pair_list')
#
# class TaskPairListView(ListView):
# model = TaskPair
#
# class TaskPairDeleteView(DeleteView):
# model = TaskPair
# success_url = reverse_lazy('task_pair_list')
#
# class TaskPairWizard(SessionWizardView):
# form_list = [TaskPairChooseCauseAgentForm, TaskPairChooseCauseTaskForm,
# TaskPairCauseOptionsForm,
# TaskPairChooseEffectAgentForm, TaskPairChooseEffectTaskForm,
# TaskPairEffectOptionsForm,
# ]
# template_name = 'helper/taskpair_wizard.html'
#
#
# def render_done(self, form, **kwargs):
# """
# Dont' want all the revalidation storage stuff... The form is fine :)
# """
# task_pair = TaskPair.objects.create(**form.cleaned_data)
# task_pair.populate_dedup_events()
# return redirect(task_pair)
#
# def process_step(self, form):
# """
# user cleaned_data as next forms initial data
# """
# if self.steps.next:
# self.initial_dict.setdefault(self.steps.next, {}).update({
# k: v.pk if hasattr(v, 'pk') else v
# for k, v in form.cleaned_data.items()})
#
# class TaskPairAdvancedDetailView(UpdateView):
# model = TaskPair
# template_name_suffix = '_detail'
# form_class = TaskPairAdvancedForm
#
# def get_success_url(object):
# return reverse('task_pair_list')
#
# class TaskPairCreateView(CreateView):
# model = TaskPair
# form_class = TaskPairAdvancedForm
# template_name = 'helper/taskpair_detail.html'
, which may include functions, classes, or code. Output only the next line. | url(r'^task/?$', |
Here is a snippet: <|code_start|>
def _check_photos(access_token, paginate=False, extra_params=None,
taskname=None, task_pair_id=None):
params = {'access_token': access_token}
if extra_params is not None:
params.update(extra_params)
while True:
resp = requests.get('https://graph.facebook.com/me/photos',
params=params)
resp.raise_for_status()
for image in resp.json()['data']:
yield {
'user': image['from']['name'],
'name': ''.join(c for c in image.get('name', '(nocaption)')
if c not in '?#'+os.path.sep)[:75],
'image': image['images'][0]['source'],
'date': image['created_time'],
'fbid': image['id'],
}
if 'next' in resp.json()['paging'] and paginate:
params['after'] = resp.json()['paging']['cursors']['after']
else:
break
@dedup('fbid')
@schedule(5)
<|code_end|>
. Write the next line using the current file imports:
import os
import requests
from celery import shared_task
from helper.scheduler import schedule
from helper.utils.dedup.decorators import dedup
and context from other files:
# Path: helper/scheduler.py
# def schedule(every):
# def decorator(task):
# task.every = every
# return task
# return decorator
#
# Path: helper/utils/dedup/decorators.py
# def dedup(key):
# def decorator(task):
# task.dedup_key = key
# return task
# return decorator
, which may include functions, classes, or code. Output only the next line. | @shared_task |
Predict the next line for this snippet: <|code_start|>
def get_from_event_store(task_pair_id, task_type):
return [{k: json.loads(v) for k, v in event.items()}
for event in Event.objects.filter(
<|code_end|>
with the help of current file imports:
import json
from ..models import Event
and context from other files:
# Path: helper/models.py
# class Event(models.Model):
# TASK_TYPE_CHOICES = [('cause',)*2, ('effect',)*2]
# task_pair = models.ForeignKey('TaskPair')
# task_type = models.CharField(max_length=255, choices=TASK_TYPE_CHOICES)
# data = HStoreField()
# created = models.DateTimeField(auto_now=True)
#
# def __str__(self):
# return '{0.task_pair}::{0.task_type}'.format(self)
, which may contain function names, class names, or code. Output only the next line. | task_pair__id=task_pair_id, task_type=task_type)\ |
Given the code snippet: <|code_start|>@shared_task
def rail_incident(api_key, line, task_pair_id, commute_only='always'):
now = datetime.now()
if not any([l <= now.hour < u and dl <= now.weekday() < du
for l, u, dl, du in time_ranges[commute_only]]):
return []
resp = requests.get('https://api.wmata.com/Incidents.svc/json/Incidents',
headers={'api_key': api_key})
resp.raise_for_status()
events = []
for incident in resp.json().get('Incidents', []):
lines = [l.strip() for l in incident['LinesAffected'].split(';') if l.strip()]
if line not in lines:
continue
events.append({
'id': incident['IncidentID'],
'lines': ','.join(lines),
'description': incident['Description'],
'date_updated': incident['DateUpdated'],
})
return events
rail_incident.event_keys = ['id', 'lines', 'description', 'date_updated']
rail_incident.options = {
'line': forms.ChoiceField(label='Line', choices=[
('RD', 'Red'),
('GR', 'Green'),
('OR', 'Orange'),
('YL', 'Yellow'),
<|code_end|>
, generate the next line using the imports in this file:
from datetime import datetime
from celery import shared_task
from django import forms
from helper.scheduler import schedule
from helper.utils.dedup.decorators import dedup
import requests
and context (functions, classes, or occasionally code) from other files:
# Path: helper/scheduler.py
# def schedule(every):
# def decorator(task):
# task.every = every
# return task
# return decorator
#
# Path: helper/utils/dedup/decorators.py
# def dedup(key):
# def decorator(task):
# task.dedup_key = key
# return task
# return decorator
. Output only the next line. | ('BL', 'Blue'), |
Continue the code snippet: <|code_start|>
time_ranges = {
'both': [(7, 10, 0, 5), (16, 19, 0, 5)],
'morning': [(7, 10, 0, 5)],
'evening': [(16, 19, 0, 5)],
'always': [(0, 24, 0, 8)],
}
@dedup('id')
@schedule(1)
@shared_task
def rail_incident(api_key, line, task_pair_id, commute_only='always'):
now = datetime.now()
if not any([l <= now.hour < u and dl <= now.weekday() < du
for l, u, dl, du in time_ranges[commute_only]]):
return []
resp = requests.get('https://api.wmata.com/Incidents.svc/json/Incidents',
headers={'api_key': api_key})
resp.raise_for_status()
events = []
for incident in resp.json().get('Incidents', []):
lines = [l.strip() for l in incident['LinesAffected'].split(';') if l.strip()]
if line not in lines:
continue
events.append({
'id': incident['IncidentID'],
'lines': ','.join(lines),
<|code_end|>
. Use current file imports:
from datetime import datetime
from celery import shared_task
from django import forms
from helper.scheduler import schedule
from helper.utils.dedup.decorators import dedup
import requests
and context (classes, functions, or code) from other files:
# Path: helper/scheduler.py
# def schedule(every):
# def decorator(task):
# task.every = every
# return task
# return decorator
#
# Path: helper/utils/dedup/decorators.py
# def dedup(key):
# def decorator(task):
# task.dedup_key = key
# return task
# return decorator
. Output only the next line. | 'description': incident['Description'], |
Here is a snippet: <|code_start|> )
else:
effect = self.effect.s(**effect_options)
return chain(cause, dmap.s(effect))()
def populate_dedup_events(self):
if getattr(self.cause, 'dedup_key', None) is not None:
cause_options = self.cause_agent.options or {}
cause_options.update({k: v for k, v in self.cause_options.items()
if not k.startswith('_')})
cause_options['task_pair_id'] = self.id
cause = self.cause.s(**cause_options)
effect = create_dedup_event.s(task_pair_id=self.id,
dedup_key=self.cause.dedup_key)
return chain(cause, dmap.s(effect))()
class Event(models.Model):
TASK_TYPE_CHOICES = [('cause',)*2, ('effect',)*2]
task_pair = models.ForeignKey('TaskPair')
task_type = models.CharField(max_length=255, choices=TASK_TYPE_CHOICES)
data = HStoreField()
created = models.DateTimeField(auto_now=True)
def __str__(self):
return '{0.task_pair}::{0.task_type}'.format(self)
<|code_end|>
. Write the next line using the current file imports:
from collections import OrderedDict
from importlib import import_module
from django.db import models
from django.core.urlresolvers import reverse
from django.core.exceptions import ValidationError
from django.contrib.postgres.fields import HStoreField
from celery import chain
from helper.utils.tasks import dmap
from helper.utils.dedup.tasks import dedup_effect_wrapper, create_dedup_event
and context from other files:
# Path: helper/utils/tasks.py
# @shared_task
# def dmap(iter, callback):
# # Map a callback over an iterator and return as a group
# callback = subtask(callback)
# return group(callback.clone([arg,]) for arg in iter)()
#
# Path: helper/utils/dedup/tasks.py
# @shared_task
# def dedup_effect_wrapper(data, dedup_key, task_pair_id, effect):
# from helper.models import DedupEvent # avoid recursive import.
# if DedupEvent.objects.get_or_create(task_pair_id=task_pair_id,
# key=data[dedup_key])[1]:
# effect.apply_async(
# (data,), link_error=remove_from_dedup_cache_on_error.s(
# dedup_key, task_pair_id, data))
# return data
#
# @shared_task
# def create_dedup_event(data, dedup_key, task_pair_id):
# from helper.models import DedupEvent # avoid recursive import.
# return DedupEvent.objects.get_or_create(
# task_pair_id=task_pair_id, key=data[dedup_key])[1]
, which may include functions, classes, or code. Output only the next line. | class DedupEvent(models.Model): |
Given the following code snippet before the placeholder: <|code_start|>
@property
def effect_view(self):
return getattr(import_module(self.effect_agent.name + '.views'),
self.effect_task)
@property
def cause_name(self):
return getattr(self.cause, 'label',
self.cause_task.replace('_', ' ').capitalize())
@property
def effect_name(self):
return getattr(self.effect, 'label',
self.effect_task.replace('_', ' ').capitalize())
@property
def schedule(self):
try:
return self.cause.every
except (AttributeError, ImportError):
pass
def run(self):
cause_options = self.cause_agent.options or {}
cause_options.update({k: v for k, v in self.cause_options.items()
if not k.startswith('_')})
cause_options['task_pair_id'] = self.id
effect_options = self.effect_agent.options or {}
effect_options.update({k: v for k, v in self.effect_options.items()
<|code_end|>
, predict the next line using imports from the current file:
from collections import OrderedDict
from importlib import import_module
from django.db import models
from django.core.urlresolvers import reverse
from django.core.exceptions import ValidationError
from django.contrib.postgres.fields import HStoreField
from celery import chain
from helper.utils.tasks import dmap
from helper.utils.dedup.tasks import dedup_effect_wrapper, create_dedup_event
and context including class names, function names, and sometimes code from other files:
# Path: helper/utils/tasks.py
# @shared_task
# def dmap(iter, callback):
# # Map a callback over an iterator and return as a group
# callback = subtask(callback)
# return group(callback.clone([arg,]) for arg in iter)()
#
# Path: helper/utils/dedup/tasks.py
# @shared_task
# def dedup_effect_wrapper(data, dedup_key, task_pair_id, effect):
# from helper.models import DedupEvent # avoid recursive import.
# if DedupEvent.objects.get_or_create(task_pair_id=task_pair_id,
# key=data[dedup_key])[1]:
# effect.apply_async(
# (data,), link_error=remove_from_dedup_cache_on_error.s(
# dedup_key, task_pair_id, data))
# return data
#
# @shared_task
# def create_dedup_event(data, dedup_key, task_pair_id):
# from helper.models import DedupEvent # avoid recursive import.
# return DedupEvent.objects.get_or_create(
# task_pair_id=task_pair_id, key=data[dedup_key])[1]
. Output only the next line. | if not k.startswith('_')}) |
Continue the code snippet: <|code_start|> return getattr(import_module(self.effect_agent.name + '.views'),
self.effect_task)
@property
def cause_name(self):
return getattr(self.cause, 'label',
self.cause_task.replace('_', ' ').capitalize())
@property
def effect_name(self):
return getattr(self.effect, 'label',
self.effect_task.replace('_', ' ').capitalize())
@property
def schedule(self):
try:
return self.cause.every
except (AttributeError, ImportError):
pass
def run(self):
cause_options = self.cause_agent.options or {}
cause_options.update({k: v for k, v in self.cause_options.items()
if not k.startswith('_')})
cause_options['task_pair_id'] = self.id
effect_options = self.effect_agent.options or {}
effect_options.update({k: v for k, v in self.effect_options.items()
if not k.startswith('_')})
effect_options['task_pair_id'] = self.id
<|code_end|>
. Use current file imports:
from collections import OrderedDict
from importlib import import_module
from django.db import models
from django.core.urlresolvers import reverse
from django.core.exceptions import ValidationError
from django.contrib.postgres.fields import HStoreField
from celery import chain
from helper.utils.tasks import dmap
from helper.utils.dedup.tasks import dedup_effect_wrapper, create_dedup_event
and context (classes, functions, or code) from other files:
# Path: helper/utils/tasks.py
# @shared_task
# def dmap(iter, callback):
# # Map a callback over an iterator and return as a group
# callback = subtask(callback)
# return group(callback.clone([arg,]) for arg in iter)()
#
# Path: helper/utils/dedup/tasks.py
# @shared_task
# def dedup_effect_wrapper(data, dedup_key, task_pair_id, effect):
# from helper.models import DedupEvent # avoid recursive import.
# if DedupEvent.objects.get_or_create(task_pair_id=task_pair_id,
# key=data[dedup_key])[1]:
# effect.apply_async(
# (data,), link_error=remove_from_dedup_cache_on_error.s(
# dedup_key, task_pair_id, data))
# return data
#
# @shared_task
# def create_dedup_event(data, dedup_key, task_pair_id):
# from helper.models import DedupEvent # avoid recursive import.
# return DedupEvent.objects.get_or_create(
# task_pair_id=task_pair_id, key=data[dedup_key])[1]
. Output only the next line. | cause = self.cause.s(**cause_options) |
Based on the snippet: <|code_start|>
@shared_task
@format_options_from_event
def send_push(data, token, user, message, title, device, url, url_title,
priority, html, task_pair_id=None):
resp = requests.post('https://api.pushover.net/1/messages.json', data={
'title': title,
'message': message,
'token': token,
'user': user,
'html': html,
'url': url,
'url_title': url_title,
'priority': priority,
})
<|code_end|>
, predict the immediate next line with the help of imports:
from collections import OrderedDict
from celery import shared_task
from django import forms
from helper.utils.decorators import format_options_from_event
import requests
and context (classes, functions, sometimes code) from other files:
# Path: helper/utils/decorators.py
# def format_options_from_event(func):
# """
# MUST(ok.. should) be the first decorator used since it actually wraps the
# function and all others just add stuff (at least HELPeR decorators)
#
# Applies formatting to all keys if task_pair_id isn't present, else looks up
# the effect task's options and only formats those.
# """
# @wraps(func)
# def wrapper(data, **kwargs):
# from helper.models import TaskPair # Avoid circular import
# try:
# options = TaskPair.objects.get(
# pk=kwargs['task_pair_id']).effect.options
# except (TaskPair.DoesNotExist, KeyError):
# options = kwargs.keys()
# for option in options:
# kwargs[option] = kwargs[option].format(**data)
# return func(data, **kwargs)
# return wrapper
. Output only the next line. | resp.raise_for_status() |
Given snippet: <|code_start|>
def struct2isoformat(struct):
if struct is None:
return ''
return datetime.datetime.fromtimestamp(time.mktime(struct)).isoformat()
@schedule(1)
@dedup('id')
@shared_task
def get_rss_feed(url, task_pair_id, secret):
resp = feedparser.parse(url)
assert 'bozo_exception' not in resp
return [{
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import time
import datetime
import feedparser
from celery import shared_task
from django import forms
from helper.scheduler import schedule
from helper.utils.decorators import dedup, format_options_from_event
from helper.agents.utils import send_to_event_store
and context:
# Path: helper/scheduler.py
# def schedule(every):
# def decorator(task):
# task.every = every
# return task
# return decorator
#
# Path: helper/utils/decorators.py
# def format_options_from_event(func):
# def wrapper(data, **kwargs):
#
# Path: helper/agents/utils.py
# def send_to_event_store(data, task_pair_id, task_type):
# Event.objects.create(data={k: json.dumps(v) for k, v in data.items()},
# task_pair_id=task_pair_id, task_type=task_type)
which might include code, classes, or functions. Output only the next line. | 'title': entry.title, |
Here is a snippet: <|code_start|>def get_rss_feed(url, task_pair_id, secret):
resp = feedparser.parse(url)
assert 'bozo_exception' not in resp
return [{
'title': entry.title,
'link': entry.link,
'description': entry.description,
'published': ('' if 'published_parsed' not in entry
else struct2isoformat(entry.published_parsed)),
'updated': ('' if 'updated_parsed' not in entry
else struct2isoformat(entry.updated_parsed)),
'id': entry.id,
} for entry in resp.entries]
get_rss_feed.options = {'url': forms.URLField(label='URL')}
get_rss_feed.event_keys = ['title', 'link', 'description', 'published', 'id']
get_rss_feed.label = 'Get feed'
@shared_task
@format_options_from_event
def generate_rss_feed(data, task_pair_id, **kwargs):
send_to_event_store(kwargs, task_pair_id, 'effect')
generate_rss_feed.options = {
'feed_title': forms.CharField(label='Feed title'),
'feed_link': forms.CharField(label='Feed link'),
'feed_description': forms.CharField(label='Feed description'),
'item_title': forms.CharField(label='Item title'),
'item_link': forms.CharField(label='Item link'),
'item_description': forms.CharField(label='Item description'),
'item_guid': forms.CharField(label='Item GUID'),
<|code_end|>
. Write the next line using the current file imports:
import time
import datetime
import feedparser
from celery import shared_task
from django import forms
from helper.scheduler import schedule
from helper.utils.decorators import dedup, format_options_from_event
from helper.agents.utils import send_to_event_store
and context from other files:
# Path: helper/scheduler.py
# def schedule(every):
# def decorator(task):
# task.every = every
# return task
# return decorator
#
# Path: helper/utils/decorators.py
# def format_options_from_event(func):
# def wrapper(data, **kwargs):
#
# Path: helper/agents/utils.py
# def send_to_event_store(data, task_pair_id, task_type):
# Event.objects.create(data={k: json.dumps(v) for k, v in data.items()},
# task_pair_id=task_pair_id, task_type=task_type)
, which may include functions, classes, or code. Output only the next line. | 'item_pubdate': forms.CharField(label='Item publication date'), |
Here is a snippet: <|code_start|>
def struct2isoformat(struct):
if struct is None:
return ''
return datetime.datetime.fromtimestamp(time.mktime(struct)).isoformat()
@schedule(1)
@dedup('id')
@shared_task
def get_rss_feed(url, task_pair_id, secret):
resp = feedparser.parse(url)
assert 'bozo_exception' not in resp
return [{
'title': entry.title,
'link': entry.link,
'description': entry.description,
'published': ('' if 'published_parsed' not in entry
else struct2isoformat(entry.published_parsed)),
'updated': ('' if 'updated_parsed' not in entry
else struct2isoformat(entry.updated_parsed)),
'id': entry.id,
} for entry in resp.entries]
<|code_end|>
. Write the next line using the current file imports:
import time
import datetime
import feedparser
from celery import shared_task
from django import forms
from helper.scheduler import schedule
from helper.utils.decorators import dedup, format_options_from_event
from helper.agents.utils import send_to_event_store
and context from other files:
# Path: helper/scheduler.py
# def schedule(every):
# def decorator(task):
# task.every = every
# return task
# return decorator
#
# Path: helper/utils/decorators.py
# def format_options_from_event(func):
# def wrapper(data, **kwargs):
#
# Path: helper/agents/utils.py
# def send_to_event_store(data, task_pair_id, task_type):
# Event.objects.create(data={k: json.dumps(v) for k, v in data.items()},
# task_pair_id=task_pair_id, task_type=task_type)
, which may include functions, classes, or code. Output only the next line. | get_rss_feed.options = {'url': forms.URLField(label='URL')} |
Given the following code snippet before the placeholder: <|code_start|>
@shared_task
@format_options_from_event
def send_email(data, access_token, from_, to, subject, body, task_pair_id,
**kwargs):
message = MIMEText(body)
<|code_end|>
, predict the next line using imports from the current file:
import base64
import requests
from collections import OrderedDict
from email.mime.text import MIMEText
from django import forms
from celery import shared_task
from helper.utils.decorators import format_options_from_event
and context including class names, function names, and sometimes code from other files:
# Path: helper/utils/decorators.py
# def format_options_from_event(func):
# """
# MUST(ok.. should) be the first decorator used since it actually wraps the
# function and all others just add stuff (at least HELPeR decorators)
#
# Applies formatting to all keys if task_pair_id isn't present, else looks up
# the effect task's options and only formats those.
# """
# @wraps(func)
# def wrapper(data, **kwargs):
# from helper.models import TaskPair # Avoid circular import
# try:
# options = TaskPair.objects.get(
# pk=kwargs['task_pair_id']).effect.options
# except (TaskPair.DoesNotExist, KeyError):
# options = kwargs.keys()
# for option in options:
# kwargs[option] = kwargs[option].format(**data)
# return func(data, **kwargs)
# return wrapper
. Output only the next line. | message['to'] = to |
Continue the code snippet: <|code_start|>
def _check_photos(access_token, paginate=False, extra_params=None,
url=None, taskname=None, task_pair_id=None):
params = {'access_token': access_token}
if extra_params is not None:
params.update(extra_params)
while True:
resp = requests.get(url, params=params)
resp.raise_for_status()
for image in resp.json()['data']:
yield {
'name': ''.join(c for c in ('' if not image['caption']
else image['caption']['text'])
if c not in '?#' + os.path.sep)[:75],
'image': image['images']['standard_resolution']['url'],
'date': image['created_time'],
'id': image['id'],
}
if 'next_max_id' in resp.json()['pagination'] and paginate:
params['max_id'] = resp.json()['pagination']['next_max_id']
<|code_end|>
. Use current file imports:
import os
import requests
from celery import shared_task
from helper.scheduler import schedule
from helper.utils.dedup.decorators import dedup
and context (classes, functions, or code) from other files:
# Path: helper/scheduler.py
# def schedule(every):
# def decorator(task):
# task.every = every
# return task
# return decorator
#
# Path: helper/utils/dedup/decorators.py
# def dedup(key):
# def decorator(task):
# task.dedup_key = key
# return task
# return decorator
. Output only the next line. | else: |
Given the following code snippet before the placeholder: <|code_start|>
def _check_photos(access_token, paginate=False, extra_params=None,
url=None, taskname=None, task_pair_id=None):
params = {'access_token': access_token}
if extra_params is not None:
params.update(extra_params)
while True:
resp = requests.get(url, params=params)
resp.raise_for_status()
for image in resp.json()['data']:
yield {
'name': ''.join(c for c in ('' if not image['caption']
else image['caption']['text'])
if c not in '?#' + os.path.sep)[:75],
'image': image['images']['standard_resolution']['url'],
'date': image['created_time'],
'id': image['id'],
}
if 'next_max_id' in resp.json()['pagination'] and paginate:
params['max_id'] = resp.json()['pagination']['next_max_id']
else:
break
@dedup('id')
@schedule(5)
<|code_end|>
, predict the next line using imports from the current file:
import os
import requests
from celery import shared_task
from helper.scheduler import schedule
from helper.utils.dedup.decorators import dedup
and context including class names, function names, and sometimes code from other files:
# Path: helper/scheduler.py
# def schedule(every):
# def decorator(task):
# task.every = every
# return task
# return decorator
#
# Path: helper/utils/dedup/decorators.py
# def dedup(key):
# def decorator(task):
# task.dedup_key = key
# return task
# return decorator
. Output only the next line. | @shared_task |
Next line prediction: <|code_start|> kwargs = {}
if user or pass_:
kwargs['auth'] = (user, pass_)
if json:
kwargs['json'] = json
if data_:
kwargs['data'] = data_
if verify == 'false':
kwargs['verify'] = False
resp = requests.request(method, url, **kwargs)
resp.raise_for_status()
http_request.options = OrderedDict([
('method', forms.ChoiceField(label='Method', choices=[
('GET',)*2,
('POST',)*2,
('PUT',)*2,
('PATCH',)*2,
('DELETE',)*2,
('HEAD',)*2,
])),
('url', forms.CharField(label='URL')),
('user', forms.CharField(label='User', required=False)),
('pass_', forms.CharField(label='Password', required=False,
widget=forms.PasswordInput())),
('data_', forms.CharField(label='Data', required=False,
widget=forms.Textarea())),
('json', forms.CharField(label='JSON', required=False,
<|code_end|>
. Use current file imports:
(from collections import OrderedDict
from django import forms
from celery import shared_task
from helper.utils.decorators import format_options_from_event
import requests)
and context including class names, function names, or small code snippets from other files:
# Path: helper/utils/decorators.py
# def format_options_from_event(func):
# """
# MUST(ok.. should) be the first decorator used since it actually wraps the
# function and all others just add stuff (at least HELPeR decorators)
#
# Applies formatting to all keys if task_pair_id isn't present, else looks up
# the effect task's options and only formats those.
# """
# @wraps(func)
# def wrapper(data, **kwargs):
# from helper.models import TaskPair # Avoid circular import
# try:
# options = TaskPair.objects.get(
# pk=kwargs['task_pair_id']).effect.options
# except (TaskPair.DoesNotExist, KeyError):
# options = kwargs.keys()
# for option in options:
# kwargs[option] = kwargs[option].format(**data)
# return func(data, **kwargs)
# return wrapper
. Output only the next line. | widget=forms.Textarea())), |
Predict the next line after this snippet: <|code_start|>
def generate_rss_feed(request, task_pair):
rss = PyRSS2Gen.RSS2(
title=task_pair.effect_options['feed_title'],
link=task_pair.effect_options['feed_link'],
description=task_pair.effect_options['feed_description'],
lastBuildDate=datetime.datetime.now(),
<|code_end|>
using the current file's imports:
import datetime
import PyRSS2Gen
from io import StringIO
from django.http import HttpResponse
from helper.agents.utils import get_from_event_store
and any relevant context from other files:
# Path: helper/agents/utils.py
# def get_from_event_store(task_pair_id, task_type):
# return [{k: json.loads(v) for k, v in event.items()}
# for event in Event.objects.filter(
# task_pair__id=task_pair_id, task_type=task_type)\
# .values_list('data', flat=True)]
. Output only the next line. | items=[PyRSS2Gen.RSSItem( |
Predict the next line after this snippet: <|code_start|>
class Command(BaseCommand):
help = 'Delete all Events for a particular task'
def add_arguments(self, parser):
parser.add_argument('task_pair_id', nargs='+', type=int)
parser.add_argument('--no-op', action='store_true', help="dry run")
<|code_end|>
using the current file's imports:
from django.core.management.base import BaseCommand, CommandError
from helper.models import Event
and any relevant context from other files:
# Path: helper/models.py
# class Event(models.Model):
# TASK_TYPE_CHOICES = [('cause',)*2, ('effect',)*2]
# task_pair = models.ForeignKey('TaskPair')
# task_type = models.CharField(max_length=255, choices=TASK_TYPE_CHOICES)
# data = HStoreField()
# created = models.DateTimeField(auto_now=True)
#
# def __str__(self):
# return '{0.task_pair}::{0.task_type}'.format(self)
. Output only the next line. | def handle(self, *args, **options): |
Predict the next line after this snippet: <|code_start|>
def get_api(consumer_key, consumer_secret,
access_token, access_token_secret):
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
return tweepy.API(auth)
@shared_task
@format_options_from_event
def send_tweet(data, status, task_pair_id,
consumer_key, consumer_secret,
access_token, access_token_secret):
api = get_api(consumer_key, consumer_secret,
access_token, access_token_secret)
api.update_status(status=status)
send_tweet.options = {
'status': forms.CharField(label='Status', widget=forms.Textarea())
}
@dedup('id')
@schedule(5)
@shared_task
def sent_tweet(user, task_pair_id,
consumer_key, consumer_secret,
access_token, access_token_secret):
api = get_api(consumer_key, consumer_secret,
access_token, access_token_secret)
<|code_end|>
using the current file's imports:
import json
import tweepy
from django import forms
from celery import shared_task
from helper.scheduler import schedule
from helper.utils.decorators import format_options_from_event, dedup
and any relevant context from other files:
# Path: helper/scheduler.py
# def schedule(every):
# def decorator(task):
# task.every = every
# return task
# return decorator
#
# Path: helper/utils/decorators.py
# def format_options_from_event(func):
# def wrapper(data, **kwargs):
. Output only the next line. | return [{ |
Given the following code snippet before the placeholder: <|code_start|> auth.set_access_token(access_token, access_token_secret)
return tweepy.API(auth)
@shared_task
@format_options_from_event
def send_tweet(data, status, task_pair_id,
consumer_key, consumer_secret,
access_token, access_token_secret):
api = get_api(consumer_key, consumer_secret,
access_token, access_token_secret)
api.update_status(status=status)
send_tweet.options = {
'status': forms.CharField(label='Status', widget=forms.Textarea())
}
@dedup('id')
@schedule(5)
@shared_task
def sent_tweet(user, task_pair_id,
consumer_key, consumer_secret,
access_token, access_token_secret):
api = get_api(consumer_key, consumer_secret,
access_token, access_token_secret)
return [{
'id': str(t.id),
'status': t.text,
'date': t.created_at.isoformat(),
<|code_end|>
, predict the next line using imports from the current file:
import json
import tweepy
from django import forms
from celery import shared_task
from helper.scheduler import schedule
from helper.utils.decorators import format_options_from_event, dedup
and context including class names, function names, and sometimes code from other files:
# Path: helper/scheduler.py
# def schedule(every):
# def decorator(task):
# task.every = every
# return task
# return decorator
#
# Path: helper/utils/decorators.py
# def format_options_from_event(func):
# def wrapper(data, **kwargs):
. Output only the next line. | 'raw': json.dumps(t._json), |
Given the code snippet: <|code_start|>
def get_api(consumer_key, consumer_secret,
access_token, access_token_secret):
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
return tweepy.API(auth)
@shared_task
@format_options_from_event
def send_tweet(data, status, task_pair_id,
consumer_key, consumer_secret,
access_token, access_token_secret):
api = get_api(consumer_key, consumer_secret,
access_token, access_token_secret)
api.update_status(status=status)
send_tweet.options = {
'status': forms.CharField(label='Status', widget=forms.Textarea())
}
@dedup('id')
@schedule(5)
@shared_task
def sent_tweet(user, task_pair_id,
consumer_key, consumer_secret,
access_token, access_token_secret):
api = get_api(consumer_key, consumer_secret,
access_token, access_token_secret)
<|code_end|>
, generate the next line using the imports in this file:
import json
import tweepy
from django import forms
from celery import shared_task
from helper.scheduler import schedule
from helper.utils.decorators import format_options_from_event, dedup
and context (functions, classes, or occasionally code) from other files:
# Path: helper/scheduler.py
# def schedule(every):
# def decorator(task):
# task.every = every
# return task
# return decorator
#
# Path: helper/utils/decorators.py
# def format_options_from_event(func):
# def wrapper(data, **kwargs):
. Output only the next line. | return [{ |
Predict the next line for this snippet: <|code_start|>
@dedup('id')
@schedule(1)
@shared_task
def get_notifications(access_token, user, task_pair_id):
resp = requests.get('https://api.github.com/notifications',
auth=(user, access_token))
resp.raise_for_status()
events = []
for notification in resp.json():
events.append({
<|code_end|>
with the help of current file imports:
import requests
from celery import shared_task
from helper.scheduler import schedule
from helper.utils.dedup.decorators import dedup
and context from other files:
# Path: helper/scheduler.py
# def schedule(every):
# def decorator(task):
# task.every = every
# return task
# return decorator
#
# Path: helper/utils/dedup/decorators.py
# def dedup(key):
# def decorator(task):
# task.dedup_key = key
# return task
# return decorator
, which may contain function names, class names, or code. Output only the next line. | 'title': notification['subject']['title'], |
Given snippet: <|code_start|>
@dedup('id')
@schedule(1)
@shared_task
def get_notifications(access_token, user, task_pair_id):
resp = requests.get('https://api.github.com/notifications',
auth=(user, access_token))
resp.raise_for_status()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import requests
from celery import shared_task
from helper.scheduler import schedule
from helper.utils.dedup.decorators import dedup
and context:
# Path: helper/scheduler.py
# def schedule(every):
# def decorator(task):
# task.every = every
# return task
# return decorator
#
# Path: helper/utils/dedup/decorators.py
# def dedup(key):
# def decorator(task):
# task.dedup_key = key
# return task
# return decorator
which might include code, classes, or functions. Output only the next line. | events = [] |
Given the code snippet: <|code_start|># Copyright (C) 2008-2011 Dejan Muhamedagic <dmuhamedagic@suse.de>
# See COPYING for license information.
logger = log.setup_logger(__name__)
logger_utils = log.LoggerUtils(logger)
class TerminateSubCommand(Exception):
"""
This is an exception to jump out of subcommand when meeting errors while staying interactive shell
"""
def to_ascii(input_str):
"""Convert the bytes string to a ASCII string
Usefull to remove accent (diacritics)"""
if input_str is None:
return input_str
if isinstance(input_str, str):
return input_str
try:
return str(input_str, 'utf-8')
except UnicodeDecodeError:
if config.core.debug or options.regression_tests:
traceback.print_exc()
return input_str.decode('utf-8', errors='ignore')
<|code_end|>
, generate the next line using the imports in this file:
import os
import sys
import subprocess
import re
import glob
import time
import datetime
import shutil
import shlex
import bz2
import fnmatch
import gc
import ipaddress
import argparse
import random
import string
import traceback
import pwd
import grp
import tempfile
import traceback
import inspect
import curses
import dateutil
import dateutil.tz
import configparser
import configparser
import socket
import parallax
import parallax
import parallax
import parallax
import hashlib
import parallax
import urllib2 as urllib
import urllib.request as urllib
import socket
from tempfile import mkstemp
from pathlib import Path
from contextlib import contextmanager, closing
from stat import S_ISBLK
from lxml import etree
from . import config
from . import userdir
from . import constants
from . import options
from . import term
from . import parallax
from distutils.version import LooseVersion
from .constants import SSH_OPTION
from . import log
from pwd import getpwnam
from os.path import join, basename
from math import ceil
from dateutil import parser, tz
from dateutil import parser, tz
from . import xmlutil
from . import tmpfiles
from . import corosync
from . import corosync
from . import bootstrap
from . import sbd
from .cibconfig import cib_factory
from . import xmlutil
from . import xmlutil
from .cibconfig import cib_factory
and context (functions, classes, or occasionally code) from other files:
# Path: crmsh/constants.py
# SSH_OPTION = "-o StrictHostKeyChecking=no"
. Output only the next line. | def filter_keys(key_list, args, sign="="): |
Predict the next line after this snippet: <|code_start|># Copyright (C) 2008-2011 Dejan Muhamedagic <dmuhamedagic@suse.de>
# See COPYING for license information.
logger = log.setup_logger(__name__)
def get_tag_by_id(node, tag, ident):
"Find a doc node which matches tag and id."
<|code_end|>
using the current file's imports:
import os
from tempfile import mkstemp
from lxml import etree
from . import tmpfiles
from . import xmlutil
from . import utils
from . import config
from .utils import ext_cmd, show_dot_graph, page_string
from . import log
and any relevant context from other files:
# Path: crmsh/utils.py
# def ext_cmd(cmd, shell=True):
# cmd = add_sudo(cmd)
# if options.regression_tests:
# print(".EXT", cmd)
# logger.debug("invoke: %s", cmd)
# return subprocess.call(cmd, shell=shell)
#
# def show_dot_graph(dotfile, keep_file=False, desc="transition graph"):
# cmd = "%s %s" % (config.core.dotty, dotfile)
# if not keep_file:
# cmd = "(%s; rm -f %s)" % (cmd, dotfile)
# if options.regression_tests:
# print(".EXT", cmd)
# subprocess.Popen(cmd, shell=True, bufsize=0,
# stdin=None, stdout=None, stderr=None, close_fds=True)
# logger.info("starting %s to show %s", config.core.dotty, desc)
#
# def page_string(s):
# 'Page string rendered for TERM.'
# if not s:
# return
# constants.need_reset = True
# w, h = get_winsize()
# if not need_pager(s, w, h):
# print(term_render(s))
# elif not config.core.pager or not can_ask() or options.batch:
# print(term_render(s))
# else:
# pipe_string(get_pager_cmd(), term_render(s).encode('utf-8'))
# constants.need_reset = False
. Output only the next line. | for n in node.xpath(".//%s" % tag): |
Using the snippet: <|code_start|># Copyright (C) 2008-2011 Dejan Muhamedagic <dmuhamedagic@suse.de>
# See COPYING for license information.
logger = log.setup_logger(__name__)
def get_tag_by_id(node, tag, ident):
"Find a doc node which matches tag and id."
<|code_end|>
, determine the next line of code. You have imports:
import os
from tempfile import mkstemp
from lxml import etree
from . import tmpfiles
from . import xmlutil
from . import utils
from . import config
from .utils import ext_cmd, show_dot_graph, page_string
from . import log
and context (class names, function names, or code) available:
# Path: crmsh/utils.py
# def ext_cmd(cmd, shell=True):
# cmd = add_sudo(cmd)
# if options.regression_tests:
# print(".EXT", cmd)
# logger.debug("invoke: %s", cmd)
# return subprocess.call(cmd, shell=shell)
#
# def show_dot_graph(dotfile, keep_file=False, desc="transition graph"):
# cmd = "%s %s" % (config.core.dotty, dotfile)
# if not keep_file:
# cmd = "(%s; rm -f %s)" % (cmd, dotfile)
# if options.regression_tests:
# print(".EXT", cmd)
# subprocess.Popen(cmd, shell=True, bufsize=0,
# stdin=None, stdout=None, stderr=None, close_fds=True)
# logger.info("starting %s to show %s", config.core.dotty, desc)
#
# def page_string(s):
# 'Page string rendered for TERM.'
# if not s:
# return
# constants.need_reset = True
# w, h = get_winsize()
# if not need_pager(s, w, h):
# print(term_render(s))
# elif not config.core.pager or not can_ask() or options.batch:
# print(term_render(s))
# else:
# pipe_string(get_pager_cmd(), term_render(s).encode('utf-8'))
# constants.need_reset = False
. Output only the next line. | for n in node.xpath(".//%s" % tag): |
Using the snippet: <|code_start|># Copyright (C) 2008-2011 Dejan Muhamedagic <dmuhamedagic@suse.de>
# See COPYING for license information.
logger = log.setup_logger(__name__)
def get_tag_by_id(node, tag, ident):
"Find a doc node which matches tag and id."
for n in node.xpath(".//%s" % tag):
if n.get("id") == ident:
return n
return None
def get_status_node_id(n):
try:
n = n.getparent()
except:
return None
if n.tag != "node_state":
return get_status_node_id(n)
return n.get("id")
def get_status_node(status_node, node):
for n in status_node.iterchildren("node_state"):
<|code_end|>
, determine the next line of code. You have imports:
import os
from tempfile import mkstemp
from lxml import etree
from . import tmpfiles
from . import xmlutil
from . import utils
from . import config
from .utils import ext_cmd, show_dot_graph, page_string
from . import log
and context (class names, function names, or code) available:
# Path: crmsh/utils.py
# def ext_cmd(cmd, shell=True):
# cmd = add_sudo(cmd)
# if options.regression_tests:
# print(".EXT", cmd)
# logger.debug("invoke: %s", cmd)
# return subprocess.call(cmd, shell=shell)
#
# def show_dot_graph(dotfile, keep_file=False, desc="transition graph"):
# cmd = "%s %s" % (config.core.dotty, dotfile)
# if not keep_file:
# cmd = "(%s; rm -f %s)" % (cmd, dotfile)
# if options.regression_tests:
# print(".EXT", cmd)
# subprocess.Popen(cmd, shell=True, bufsize=0,
# stdin=None, stdout=None, stderr=None, close_fds=True)
# logger.info("starting %s to show %s", config.core.dotty, desc)
#
# def page_string(s):
# 'Page string rendered for TERM.'
# if not s:
# return
# constants.need_reset = True
# w, h = get_winsize()
# if not need_pager(s, w, h):
# print(term_render(s))
# elif not config.core.pager or not can_ask() or options.batch:
# print(term_render(s))
# else:
# pipe_string(get_pager_cmd(), term_render(s).encode('utf-8'))
# constants.need_reset = False
. Output only the next line. | if n.get("id") == node: |
Given snippet: <|code_start|> if msg.startswith("ERROR: "):
logger.error(msg[7:])
elif msg.startswith("WARNING: "):
logger.warning(msg[9:])
elif msg.startswith("INFO: "):
logger.info(msg[6:])
elif msg.startswith("DEBUG: "):
logger.debug(msg[7:])
else:
logger.info(msg)
return p.returncode, out
DLM_RA_SCRIPTS = """
primitive {id} ocf:pacemaker:controld \
op start timeout=90 \
op stop timeout=100 \
op monitor interval=60 timeout=60"""
FILE_SYSTEM_RA_SCRIPTS = """
primitive {id} ocf:heartbeat:Filesystem \
params directory="{mnt_point}" fstype="{fs_type}" device="{device}" \
op monitor interval=20 timeout=40 \
op start timeout=60 \
op stop timeout=60"""
LVMLOCKD_RA_SCRIPTS = """
primitive {id} ocf:heartbeat:lvmlockd \
op start timeout=90 \
op stop timeout=100 \
op monitor interval=30 timeout=90"""
LVMACTIVATE_RA_SCRIPTS = """
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import subprocess
import copy
import re
import glob
from lxml import etree
from . import cache
from . import constants
from . import config
from . import options
from . import userdir
from . import utils
from .utils import stdout2list, is_program, is_process, to_ascii
from .utils import os_types_list, get_stdout
from .utils import crm_msec, crm_time_cmp
from . import log
from distutils import version
and context:
# Path: crmsh/utils.py
# def stdout2list(cmd, stderr_on=True, shell=True):
# '''
# Run a cmd, fetch output, return it as a list of lines.
# stderr_on controls whether to show output which comes on stderr.
# '''
# rc, s = get_stdout(add_sudo(cmd), stderr_on=stderr_on, shell=shell)
# if not s:
# return rc, []
# return rc, s.split('\n')
#
# def is_program(prog):
# """Is this program available?"""
# def isexec(filename):
# return os.path.isfile(filename) and os.access(filename, os.X_OK)
# for p in os.getenv("PATH").split(os.pathsep):
# f = os.path.join(p, prog)
# if isexec(f):
# return f
# return None
#
# def is_process(s):
# """
# Returns true if argument is the name of a running process.
#
# s: process name
# returns Boolean
# """
# from os.path import join, basename
# # find pids of running processes
# pids = [pid for pid in os.listdir('/proc') if pid.isdigit()]
# for pid in pids:
# try:
# cmdline = open(join('/proc', pid, 'cmdline'), 'rb').read()
# procname = basename(to_ascii(cmdline).replace('\x00', ' ').split(' ')[0])
# if procname == s:
# return True
# except EnvironmentError:
# # a process may have died since we got the list of pids
# pass
# return False
#
# def to_ascii(input_str):
# """Convert the bytes string to a ASCII string
# Usefull to remove accent (diacritics)"""
# if input_str is None:
# return input_str
# if isinstance(input_str, str):
# return input_str
# try:
# return str(input_str, 'utf-8')
# except UnicodeDecodeError:
# if config.core.debug or options.regression_tests:
# import traceback
# traceback.print_exc()
# return input_str.decode('utf-8', errors='ignore')
#
# Path: crmsh/utils.py
# def os_types_list(path):
# l = []
# for f in glob.glob(path):
# if os.access(f, os.X_OK) and os.path.isfile(f):
# a = f.split("/")
# l.append(a[-1])
# return l
#
# def get_stdout(cmd, input_s=None, stderr_on=True, shell=True, raw=False):
# '''
# Run a cmd, return stdout output.
# Optional input string "input_s".
# stderr_on controls whether to show output which comes on stderr.
# '''
# if stderr_on:
# stderr = None
# else:
# stderr = subprocess.PIPE
# if options.regression_tests:
# print(".EXT", cmd)
# proc = subprocess.Popen(cmd,
# shell=shell,
# stdin=subprocess.PIPE,
# stdout=subprocess.PIPE,
# stderr=stderr)
# stdout_data, stderr_data = proc.communicate(input_s)
# if raw:
# return proc.returncode, stdout_data
# return proc.returncode, to_ascii(stdout_data).strip()
#
# Path: crmsh/utils.py
# def crm_msec(t):
# '''
# See lib/common/utils.c:crm_get_msec().
# '''
# convtab = {
# 'ms': (1, 1),
# 'msec': (1, 1),
# 'us': (1, 1000),
# 'usec': (1, 1000),
# '': (1000, 1),
# 's': (1000, 1),
# 'sec': (1000, 1),
# 'm': (60*1000, 1),
# 'min': (60*1000, 1),
# 'h': (60*60*1000, 1),
# 'hr': (60*60*1000, 1),
# }
# if not t:
# return -1
# r = re.match(r"\s*(\d+)\s*([a-zA-Z]+)?", t)
# if not r:
# return -1
# if not r.group(2):
# q = ''
# else:
# q = r.group(2).lower()
# try:
# mult, div = convtab[q]
# except KeyError:
# return -1
# return (int(r.group(1))*mult) // div
#
# def crm_time_cmp(a, b):
# return crm_msec(a) - crm_msec(b)
which might include code, classes, or functions. Output only the next line. | primitive {id} ocf:heartbeat:LVM-activate \ |
Based on the snippet: <|code_start|>
DLM_RA_SCRIPTS = """
primitive {id} ocf:pacemaker:controld \
op start timeout=90 \
op stop timeout=100 \
op monitor interval=60 timeout=60"""
FILE_SYSTEM_RA_SCRIPTS = """
primitive {id} ocf:heartbeat:Filesystem \
params directory="{mnt_point}" fstype="{fs_type}" device="{device}" \
op monitor interval=20 timeout=40 \
op start timeout=60 \
op stop timeout=60"""
LVMLOCKD_RA_SCRIPTS = """
primitive {id} ocf:heartbeat:lvmlockd \
op start timeout=90 \
op stop timeout=100 \
op monitor interval=30 timeout=90"""
LVMACTIVATE_RA_SCRIPTS = """
primitive {id} ocf:heartbeat:LVM-activate \
params vgname={vgname} vg_access_mode=lvmlockd activation_mode=shared \
op start timeout=90s \
op stop timeout=90s \
op monitor interval=30s timeout=90s"""
GROUP_SCRIPTS = """
group {id} {ra_string}"""
CLONE_SCRIPTS = """
clone {id} {group_id} meta interleave=true"""
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import subprocess
import copy
import re
import glob
from lxml import etree
from . import cache
from . import constants
from . import config
from . import options
from . import userdir
from . import utils
from .utils import stdout2list, is_program, is_process, to_ascii
from .utils import os_types_list, get_stdout
from .utils import crm_msec, crm_time_cmp
from . import log
from distutils import version
and context (classes, functions, sometimes code) from other files:
# Path: crmsh/utils.py
# def stdout2list(cmd, stderr_on=True, shell=True):
# '''
# Run a cmd, fetch output, return it as a list of lines.
# stderr_on controls whether to show output which comes on stderr.
# '''
# rc, s = get_stdout(add_sudo(cmd), stderr_on=stderr_on, shell=shell)
# if not s:
# return rc, []
# return rc, s.split('\n')
#
# def is_program(prog):
# """Is this program available?"""
# def isexec(filename):
# return os.path.isfile(filename) and os.access(filename, os.X_OK)
# for p in os.getenv("PATH").split(os.pathsep):
# f = os.path.join(p, prog)
# if isexec(f):
# return f
# return None
#
# def is_process(s):
# """
# Returns true if argument is the name of a running process.
#
# s: process name
# returns Boolean
# """
# from os.path import join, basename
# # find pids of running processes
# pids = [pid for pid in os.listdir('/proc') if pid.isdigit()]
# for pid in pids:
# try:
# cmdline = open(join('/proc', pid, 'cmdline'), 'rb').read()
# procname = basename(to_ascii(cmdline).replace('\x00', ' ').split(' ')[0])
# if procname == s:
# return True
# except EnvironmentError:
# # a process may have died since we got the list of pids
# pass
# return False
#
# def to_ascii(input_str):
# """Convert the bytes string to a ASCII string
# Usefull to remove accent (diacritics)"""
# if input_str is None:
# return input_str
# if isinstance(input_str, str):
# return input_str
# try:
# return str(input_str, 'utf-8')
# except UnicodeDecodeError:
# if config.core.debug or options.regression_tests:
# import traceback
# traceback.print_exc()
# return input_str.decode('utf-8', errors='ignore')
#
# Path: crmsh/utils.py
# def os_types_list(path):
# l = []
# for f in glob.glob(path):
# if os.access(f, os.X_OK) and os.path.isfile(f):
# a = f.split("/")
# l.append(a[-1])
# return l
#
# def get_stdout(cmd, input_s=None, stderr_on=True, shell=True, raw=False):
# '''
# Run a cmd, return stdout output.
# Optional input string "input_s".
# stderr_on controls whether to show output which comes on stderr.
# '''
# if stderr_on:
# stderr = None
# else:
# stderr = subprocess.PIPE
# if options.regression_tests:
# print(".EXT", cmd)
# proc = subprocess.Popen(cmd,
# shell=shell,
# stdin=subprocess.PIPE,
# stdout=subprocess.PIPE,
# stderr=stderr)
# stdout_data, stderr_data = proc.communicate(input_s)
# if raw:
# return proc.returncode, stdout_data
# return proc.returncode, to_ascii(stdout_data).strip()
#
# Path: crmsh/utils.py
# def crm_msec(t):
# '''
# See lib/common/utils.c:crm_get_msec().
# '''
# convtab = {
# 'ms': (1, 1),
# 'msec': (1, 1),
# 'us': (1, 1000),
# 'usec': (1, 1000),
# '': (1000, 1),
# 's': (1000, 1),
# 'sec': (1000, 1),
# 'm': (60*1000, 1),
# 'min': (60*1000, 1),
# 'h': (60*60*1000, 1),
# 'hr': (60*60*1000, 1),
# }
# if not t:
# return -1
# r = re.match(r"\s*(\d+)\s*([a-zA-Z]+)?", t)
# if not r:
# return -1
# if not r.group(2):
# q = ''
# else:
# q = r.group(2).lower()
# try:
# mult, div = convtab[q]
# except KeyError:
# return -1
# return (int(r.group(1))*mult) // div
#
# def crm_time_cmp(a, b):
# return crm_msec(a) - crm_msec(b)
. Output only the next line. | CONFIGURE_RA_TEMPLATE_DICT = { |
Predict the next line for this snippet: <|code_start|> my_env["OCF_RESKEY_" + k] = v
cmd = [os.path.join(config.path.ocf_root, "resource.d", agent.ra_provider, agent.ra_type), "validate-all"]
if options.regression_tests:
print(".EXT", " ".join(cmd))
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=my_env)
_out, _ = p.communicate()
out = to_ascii(_out)
p.wait()
if log is True:
for msg in out.splitlines():
if msg.startswith("ERROR: "):
logger.error(msg[7:])
elif msg.startswith("WARNING: "):
logger.warning(msg[9:])
elif msg.startswith("INFO: "):
logger.info(msg[6:])
elif msg.startswith("DEBUG: "):
logger.debug(msg[7:])
else:
logger.info(msg)
return p.returncode, out
DLM_RA_SCRIPTS = """
primitive {id} ocf:pacemaker:controld \
op start timeout=90 \
op stop timeout=100 \
op monitor interval=60 timeout=60"""
FILE_SYSTEM_RA_SCRIPTS = """
<|code_end|>
with the help of current file imports:
import os
import subprocess
import copy
import re
import glob
from lxml import etree
from . import cache
from . import constants
from . import config
from . import options
from . import userdir
from . import utils
from .utils import stdout2list, is_program, is_process, to_ascii
from .utils import os_types_list, get_stdout
from .utils import crm_msec, crm_time_cmp
from . import log
from distutils import version
and context from other files:
# Path: crmsh/utils.py
# def stdout2list(cmd, stderr_on=True, shell=True):
# '''
# Run a cmd, fetch output, return it as a list of lines.
# stderr_on controls whether to show output which comes on stderr.
# '''
# rc, s = get_stdout(add_sudo(cmd), stderr_on=stderr_on, shell=shell)
# if not s:
# return rc, []
# return rc, s.split('\n')
#
# def is_program(prog):
# """Is this program available?"""
# def isexec(filename):
# return os.path.isfile(filename) and os.access(filename, os.X_OK)
# for p in os.getenv("PATH").split(os.pathsep):
# f = os.path.join(p, prog)
# if isexec(f):
# return f
# return None
#
# def is_process(s):
# """
# Returns true if argument is the name of a running process.
#
# s: process name
# returns Boolean
# """
# from os.path import join, basename
# # find pids of running processes
# pids = [pid for pid in os.listdir('/proc') if pid.isdigit()]
# for pid in pids:
# try:
# cmdline = open(join('/proc', pid, 'cmdline'), 'rb').read()
# procname = basename(to_ascii(cmdline).replace('\x00', ' ').split(' ')[0])
# if procname == s:
# return True
# except EnvironmentError:
# # a process may have died since we got the list of pids
# pass
# return False
#
# def to_ascii(input_str):
# """Convert the bytes string to a ASCII string
# Usefull to remove accent (diacritics)"""
# if input_str is None:
# return input_str
# if isinstance(input_str, str):
# return input_str
# try:
# return str(input_str, 'utf-8')
# except UnicodeDecodeError:
# if config.core.debug or options.regression_tests:
# import traceback
# traceback.print_exc()
# return input_str.decode('utf-8', errors='ignore')
#
# Path: crmsh/utils.py
# def os_types_list(path):
# l = []
# for f in glob.glob(path):
# if os.access(f, os.X_OK) and os.path.isfile(f):
# a = f.split("/")
# l.append(a[-1])
# return l
#
# def get_stdout(cmd, input_s=None, stderr_on=True, shell=True, raw=False):
# '''
# Run a cmd, return stdout output.
# Optional input string "input_s".
# stderr_on controls whether to show output which comes on stderr.
# '''
# if stderr_on:
# stderr = None
# else:
# stderr = subprocess.PIPE
# if options.regression_tests:
# print(".EXT", cmd)
# proc = subprocess.Popen(cmd,
# shell=shell,
# stdin=subprocess.PIPE,
# stdout=subprocess.PIPE,
# stderr=stderr)
# stdout_data, stderr_data = proc.communicate(input_s)
# if raw:
# return proc.returncode, stdout_data
# return proc.returncode, to_ascii(stdout_data).strip()
#
# Path: crmsh/utils.py
# def crm_msec(t):
# '''
# See lib/common/utils.c:crm_get_msec().
# '''
# convtab = {
# 'ms': (1, 1),
# 'msec': (1, 1),
# 'us': (1, 1000),
# 'usec': (1, 1000),
# '': (1000, 1),
# 's': (1000, 1),
# 'sec': (1000, 1),
# 'm': (60*1000, 1),
# 'min': (60*1000, 1),
# 'h': (60*60*1000, 1),
# 'hr': (60*60*1000, 1),
# }
# if not t:
# return -1
# r = re.match(r"\s*(\d+)\s*([a-zA-Z]+)?", t)
# if not r:
# return -1
# if not r.group(2):
# q = ''
# else:
# q = r.group(2).lower()
# try:
# mult, div = convtab[q]
# except KeyError:
# return -1
# return (int(r.group(1))*mult) // div
#
# def crm_time_cmp(a, b):
# return crm_msec(a) - crm_msec(b)
, which may contain function names, class names, or code. Output only the next line. | primitive {id} ocf:heartbeat:Filesystem \ |
Here is a snippet: <|code_start|>op stop timeout=100 \
op monitor interval=60 timeout=60"""
FILE_SYSTEM_RA_SCRIPTS = """
primitive {id} ocf:heartbeat:Filesystem \
params directory="{mnt_point}" fstype="{fs_type}" device="{device}" \
op monitor interval=20 timeout=40 \
op start timeout=60 \
op stop timeout=60"""
LVMLOCKD_RA_SCRIPTS = """
primitive {id} ocf:heartbeat:lvmlockd \
op start timeout=90 \
op stop timeout=100 \
op monitor interval=30 timeout=90"""
LVMACTIVATE_RA_SCRIPTS = """
primitive {id} ocf:heartbeat:LVM-activate \
params vgname={vgname} vg_access_mode=lvmlockd activation_mode=shared \
op start timeout=90s \
op stop timeout=90s \
op monitor interval=30s timeout=90s"""
GROUP_SCRIPTS = """
group {id} {ra_string}"""
CLONE_SCRIPTS = """
clone {id} {group_id} meta interleave=true"""
CONFIGURE_RA_TEMPLATE_DICT = {
"DLM": DLM_RA_SCRIPTS,
"Filesystem": FILE_SYSTEM_RA_SCRIPTS,
"LVMLockd": LVMLOCKD_RA_SCRIPTS,
"LVMActivate": LVMACTIVATE_RA_SCRIPTS,
<|code_end|>
. Write the next line using the current file imports:
import os
import subprocess
import copy
import re
import glob
from lxml import etree
from . import cache
from . import constants
from . import config
from . import options
from . import userdir
from . import utils
from .utils import stdout2list, is_program, is_process, to_ascii
from .utils import os_types_list, get_stdout
from .utils import crm_msec, crm_time_cmp
from . import log
from distutils import version
and context from other files:
# Path: crmsh/utils.py
# def stdout2list(cmd, stderr_on=True, shell=True):
# '''
# Run a cmd, fetch output, return it as a list of lines.
# stderr_on controls whether to show output which comes on stderr.
# '''
# rc, s = get_stdout(add_sudo(cmd), stderr_on=stderr_on, shell=shell)
# if not s:
# return rc, []
# return rc, s.split('\n')
#
# def is_program(prog):
# """Is this program available?"""
# def isexec(filename):
# return os.path.isfile(filename) and os.access(filename, os.X_OK)
# for p in os.getenv("PATH").split(os.pathsep):
# f = os.path.join(p, prog)
# if isexec(f):
# return f
# return None
#
# def is_process(s):
# """
# Returns true if argument is the name of a running process.
#
# s: process name
# returns Boolean
# """
# from os.path import join, basename
# # find pids of running processes
# pids = [pid for pid in os.listdir('/proc') if pid.isdigit()]
# for pid in pids:
# try:
# cmdline = open(join('/proc', pid, 'cmdline'), 'rb').read()
# procname = basename(to_ascii(cmdline).replace('\x00', ' ').split(' ')[0])
# if procname == s:
# return True
# except EnvironmentError:
# # a process may have died since we got the list of pids
# pass
# return False
#
# def to_ascii(input_str):
# """Convert the bytes string to a ASCII string
# Usefull to remove accent (diacritics)"""
# if input_str is None:
# return input_str
# if isinstance(input_str, str):
# return input_str
# try:
# return str(input_str, 'utf-8')
# except UnicodeDecodeError:
# if config.core.debug or options.regression_tests:
# import traceback
# traceback.print_exc()
# return input_str.decode('utf-8', errors='ignore')
#
# Path: crmsh/utils.py
# def os_types_list(path):
# l = []
# for f in glob.glob(path):
# if os.access(f, os.X_OK) and os.path.isfile(f):
# a = f.split("/")
# l.append(a[-1])
# return l
#
# def get_stdout(cmd, input_s=None, stderr_on=True, shell=True, raw=False):
# '''
# Run a cmd, return stdout output.
# Optional input string "input_s".
# stderr_on controls whether to show output which comes on stderr.
# '''
# if stderr_on:
# stderr = None
# else:
# stderr = subprocess.PIPE
# if options.regression_tests:
# print(".EXT", cmd)
# proc = subprocess.Popen(cmd,
# shell=shell,
# stdin=subprocess.PIPE,
# stdout=subprocess.PIPE,
# stderr=stderr)
# stdout_data, stderr_data = proc.communicate(input_s)
# if raw:
# return proc.returncode, stdout_data
# return proc.returncode, to_ascii(stdout_data).strip()
#
# Path: crmsh/utils.py
# def crm_msec(t):
# '''
# See lib/common/utils.c:crm_get_msec().
# '''
# convtab = {
# 'ms': (1, 1),
# 'msec': (1, 1),
# 'us': (1, 1000),
# 'usec': (1, 1000),
# '': (1000, 1),
# 's': (1000, 1),
# 'sec': (1000, 1),
# 'm': (60*1000, 1),
# 'min': (60*1000, 1),
# 'h': (60*60*1000, 1),
# 'hr': (60*60*1000, 1),
# }
# if not t:
# return -1
# r = re.match(r"\s*(\d+)\s*([a-zA-Z]+)?", t)
# if not r:
# return -1
# if not r.group(2):
# q = ''
# else:
# q = r.group(2).lower()
# try:
# mult, div = convtab[q]
# except KeyError:
# return -1
# return (int(r.group(1))*mult) // div
#
# def crm_time_cmp(a, b):
# return crm_msec(a) - crm_msec(b)
, which may include functions, classes, or code. Output only the next line. | "GROUP": GROUP_SCRIPTS, |
Using the snippet: <|code_start|> if log is True:
for msg in out.splitlines():
if msg.startswith("ERROR: "):
logger.error(msg[7:])
elif msg.startswith("WARNING: "):
logger.warning(msg[9:])
elif msg.startswith("INFO: "):
logger.info(msg[6:])
elif msg.startswith("DEBUG: "):
logger.debug(msg[7:])
else:
logger.info(msg)
return p.returncode, out
DLM_RA_SCRIPTS = """
primitive {id} ocf:pacemaker:controld \
op start timeout=90 \
op stop timeout=100 \
op monitor interval=60 timeout=60"""
FILE_SYSTEM_RA_SCRIPTS = """
primitive {id} ocf:heartbeat:Filesystem \
params directory="{mnt_point}" fstype="{fs_type}" device="{device}" \
op monitor interval=20 timeout=40 \
op start timeout=60 \
op stop timeout=60"""
LVMLOCKD_RA_SCRIPTS = """
primitive {id} ocf:heartbeat:lvmlockd \
op start timeout=90 \
op stop timeout=100 \
<|code_end|>
, determine the next line of code. You have imports:
import os
import subprocess
import copy
import re
import glob
from lxml import etree
from . import cache
from . import constants
from . import config
from . import options
from . import userdir
from . import utils
from .utils import stdout2list, is_program, is_process, to_ascii
from .utils import os_types_list, get_stdout
from .utils import crm_msec, crm_time_cmp
from . import log
from distutils import version
and context (class names, function names, or code) available:
# Path: crmsh/utils.py
# def stdout2list(cmd, stderr_on=True, shell=True):
# '''
# Run a cmd, fetch output, return it as a list of lines.
# stderr_on controls whether to show output which comes on stderr.
# '''
# rc, s = get_stdout(add_sudo(cmd), stderr_on=stderr_on, shell=shell)
# if not s:
# return rc, []
# return rc, s.split('\n')
#
# def is_program(prog):
# """Is this program available?"""
# def isexec(filename):
# return os.path.isfile(filename) and os.access(filename, os.X_OK)
# for p in os.getenv("PATH").split(os.pathsep):
# f = os.path.join(p, prog)
# if isexec(f):
# return f
# return None
#
# def is_process(s):
# """
# Returns true if argument is the name of a running process.
#
# s: process name
# returns Boolean
# """
# from os.path import join, basename
# # find pids of running processes
# pids = [pid for pid in os.listdir('/proc') if pid.isdigit()]
# for pid in pids:
# try:
# cmdline = open(join('/proc', pid, 'cmdline'), 'rb').read()
# procname = basename(to_ascii(cmdline).replace('\x00', ' ').split(' ')[0])
# if procname == s:
# return True
# except EnvironmentError:
# # a process may have died since we got the list of pids
# pass
# return False
#
# def to_ascii(input_str):
# """Convert the bytes string to a ASCII string
# Usefull to remove accent (diacritics)"""
# if input_str is None:
# return input_str
# if isinstance(input_str, str):
# return input_str
# try:
# return str(input_str, 'utf-8')
# except UnicodeDecodeError:
# if config.core.debug or options.regression_tests:
# import traceback
# traceback.print_exc()
# return input_str.decode('utf-8', errors='ignore')
#
# Path: crmsh/utils.py
# def os_types_list(path):
# l = []
# for f in glob.glob(path):
# if os.access(f, os.X_OK) and os.path.isfile(f):
# a = f.split("/")
# l.append(a[-1])
# return l
#
# def get_stdout(cmd, input_s=None, stderr_on=True, shell=True, raw=False):
# '''
# Run a cmd, return stdout output.
# Optional input string "input_s".
# stderr_on controls whether to show output which comes on stderr.
# '''
# if stderr_on:
# stderr = None
# else:
# stderr = subprocess.PIPE
# if options.regression_tests:
# print(".EXT", cmd)
# proc = subprocess.Popen(cmd,
# shell=shell,
# stdin=subprocess.PIPE,
# stdout=subprocess.PIPE,
# stderr=stderr)
# stdout_data, stderr_data = proc.communicate(input_s)
# if raw:
# return proc.returncode, stdout_data
# return proc.returncode, to_ascii(stdout_data).strip()
#
# Path: crmsh/utils.py
# def crm_msec(t):
# '''
# See lib/common/utils.c:crm_get_msec().
# '''
# convtab = {
# 'ms': (1, 1),
# 'msec': (1, 1),
# 'us': (1, 1000),
# 'usec': (1, 1000),
# '': (1000, 1),
# 's': (1000, 1),
# 'sec': (1000, 1),
# 'm': (60*1000, 1),
# 'min': (60*1000, 1),
# 'h': (60*60*1000, 1),
# 'hr': (60*60*1000, 1),
# }
# if not t:
# return -1
# r = re.match(r"\s*(\d+)\s*([a-zA-Z]+)?", t)
# if not r:
# return -1
# if not r.group(2):
# q = ''
# else:
# q = r.group(2).lower()
# try:
# mult, div = convtab[q]
# except KeyError:
# return -1
# return (int(r.group(1))*mult) // div
#
# def crm_time_cmp(a, b):
# return crm_msec(a) - crm_msec(b)
. Output only the next line. | op monitor interval=30 timeout=90""" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.