Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Predict the next line after this snippet: <|code_start|>"""
py2app/py2exe build script for Electrum Litecoin
Usage (Mac OS X):
python setup.py py2app
Usage (Windows):
python setup.py py2exe
"""
name = "Electrum-Doge"
mainscript = 'electrum-doge'
if sys.version_info[:3] < (2, 6, 0):
<|code_end|>
using the current file's imports:
from setuptools import setup
from lib.util import print_error
from lib.version import ELECTRUM_VERSION as version
from plistlib import Plist
from distutils import dir_util
import os
import re
import shutil
import sys
and any relevant context from other files:
# Path: lib/util.py
# def print_error(*args):
# if not is_verbose: return
# print_stderr(*args)
#
# Path: lib/version.py
# ELECTRUM_VERSION = '2.2.1' # version of the client package
. Output only the next line. | print_error("Error: " + name + " requires Python version >= 2.6.0...") |
Here is a snippet: <|code_start|>"""
py2app/py2exe build script for Electrum Litecoin
Usage (Mac OS X):
python setup.py py2app
Usage (Windows):
python setup.py py2exe
"""
<|code_end|>
. Write the next line using the current file imports:
from setuptools import setup
from lib.util import print_error
from lib.version import ELECTRUM_VERSION as version
from plistlib import Plist
from distutils import dir_util
import os
import re
import shutil
import sys
and context from other files:
# Path: lib/util.py
# def print_error(*args):
# if not is_verbose: return
# print_stderr(*args)
#
# Path: lib/version.py
# ELECTRUM_VERSION = '2.2.1' # version of the client package
, which may include functions, classes, or code. Output only the next line. | from lib.version import ELECTRUM_VERSION as version |
Using the snippet: <|code_start|> default=-1,
)
def run(self, options, args):
self.get_repo(options)
opts, args = self.parser.parse_args(args)
if opts.help:
self.help()
return self.print_issues(opts)
# Formatting and printing
def format_short_issue(self, issue):
extra = []
if issue.milestone:
extra.append(issue.milestone.title)
if issue.assignee:
extra.append(issue.assignee.login)
if extra:
extra = ' (' + ' -- '.join(extra) + ')'
else:
extra = ''
issue.title = fix_encoding(issue.title)
<|code_end|>
, determine the next line of code. You have imports:
from gh.base import Command
from gh.util import tc
from gh.compat import fix_encoding
and context (class names, function names, or code) available:
# Path: gh/base.py
# class Command(object):
# __metaclass__ = ABCMeta
# name = None
# usage = None
# repository = ()
# user = ''
# subcommands = {}
# SUCCESS = 0
# FAILURE = 1
# COMMAND_UNKNOWN = 127
#
# def __init__(self):
# super(Command, self).__init__()
# assert self.name
# commands[self.name] = self
# self.gh = GitHub()
# self.gh.set_user_agent('github-cli/{0} (http://git.io/MEmEmw)'.format(
# __version__
# ))
# self.parser = CustomOptionParser(usage=self.usage)
#
# @abstractmethod
# def run(self, options, args):
# return self.FAILURE
#
# def get_repo(self, options):
# self.repo = None
# if self.repository:
# self.repo = self.gh.repository(*self.repository)
#
# if not (self.repo or options.loc_aware):
# self.parser.error('A repository is required.')
#
# def get_user(self):
# if not self.user:
# self.login()
# self.user = self.gh.user()
#
# def login(self):
# # Get the full path to the configuration file
# config = github_config()
# parser = ConfigParser()
#
# # Check to make sure the file exists and we are allowed to read it
# if os.path.isfile(config) and os.access(config, os.R_OK | os.W_OK):
# parser.readfp(open(config))
# self.gh.login(token=parser.get('github', 'token'))
# else:
# # Either the file didn't exist or we didn't have the correct
# # permissions
# user = ''
# while not user:
# # We will not stop until we are given a username
# user = input('Username: ')
#
# self.user = user
#
# pw = ''
# while not pw:
# # Nor will we stop until we're given a password
# pw = getpass('Password: ')
#
# # Get an authorization for this
# auth = self.gh.authorize(
# user, pw, ['user', 'repo', 'gist'], 'github-cli',
# 'http://git.io/MEmEmw'
# )
# parser.add_section('github')
# parser.set('github', 'token', auth.token)
# self.gh.login(token=auth.token)
# # Create the file if it doesn't exist. Otherwise completely blank
# # out what was there before. Kind of dangerous and destructive but
# # somewhat necessary
# parser.write(open(config, 'w+'))
#
# def help(self):
# self.parser.print_help()
# if self.subcommands:
# print('\nSubcommands:')
# for command in sorted(self.subcommands.keys()):
# print(' {0}:\n\t{1}'.format(
# command, self.subcommands[command]
# ))
# sys.exit(0)
#
# Path: gh/util.py
# def get_repository_tuple():
# def find_git_config():
# def github_config():
# def trim_numbers(number):
# def read_stdin():
# def mktmpfile(prefix='gh-'):
# def rmtmpfile(name):
# def wrap(text):
# def get_issue_number(args, parser, error):
#
# Path: gh/compat.py
# def fix_encoding(content):
# if sys.version_info < (3, 0):
# return content.encode('ascii', 'replace')
# return content
. Output only the next line. | return (self.fs.format(issue, bold=tc['bold'], default=tc['default']) |
Predict the next line for this snippet: <|code_start|> type='int',
nargs=1,
default=-1,
)
def run(self, options, args):
self.get_repo(options)
opts, args = self.parser.parse_args(args)
if opts.help:
self.help()
return self.print_issues(opts)
# Formatting and printing
def format_short_issue(self, issue):
extra = []
if issue.milestone:
extra.append(issue.milestone.title)
if issue.assignee:
extra.append(issue.assignee.login)
if extra:
extra = ' (' + ' -- '.join(extra) + ')'
else:
extra = ''
<|code_end|>
with the help of current file imports:
from gh.base import Command
from gh.util import tc
from gh.compat import fix_encoding
and context from other files:
# Path: gh/base.py
# class Command(object):
# __metaclass__ = ABCMeta
# name = None
# usage = None
# repository = ()
# user = ''
# subcommands = {}
# SUCCESS = 0
# FAILURE = 1
# COMMAND_UNKNOWN = 127
#
# def __init__(self):
# super(Command, self).__init__()
# assert self.name
# commands[self.name] = self
# self.gh = GitHub()
# self.gh.set_user_agent('github-cli/{0} (http://git.io/MEmEmw)'.format(
# __version__
# ))
# self.parser = CustomOptionParser(usage=self.usage)
#
# @abstractmethod
# def run(self, options, args):
# return self.FAILURE
#
# def get_repo(self, options):
# self.repo = None
# if self.repository:
# self.repo = self.gh.repository(*self.repository)
#
# if not (self.repo or options.loc_aware):
# self.parser.error('A repository is required.')
#
# def get_user(self):
# if not self.user:
# self.login()
# self.user = self.gh.user()
#
# def login(self):
# # Get the full path to the configuration file
# config = github_config()
# parser = ConfigParser()
#
# # Check to make sure the file exists and we are allowed to read it
# if os.path.isfile(config) and os.access(config, os.R_OK | os.W_OK):
# parser.readfp(open(config))
# self.gh.login(token=parser.get('github', 'token'))
# else:
# # Either the file didn't exist or we didn't have the correct
# # permissions
# user = ''
# while not user:
# # We will not stop until we are given a username
# user = input('Username: ')
#
# self.user = user
#
# pw = ''
# while not pw:
# # Nor will we stop until we're given a password
# pw = getpass('Password: ')
#
# # Get an authorization for this
# auth = self.gh.authorize(
# user, pw, ['user', 'repo', 'gist'], 'github-cli',
# 'http://git.io/MEmEmw'
# )
# parser.add_section('github')
# parser.set('github', 'token', auth.token)
# self.gh.login(token=auth.token)
# # Create the file if it doesn't exist. Otherwise completely blank
# # out what was there before. Kind of dangerous and destructive but
# # somewhat necessary
# parser.write(open(config, 'w+'))
#
# def help(self):
# self.parser.print_help()
# if self.subcommands:
# print('\nSubcommands:')
# for command in sorted(self.subcommands.keys()):
# print(' {0}:\n\t{1}'.format(
# command, self.subcommands[command]
# ))
# sys.exit(0)
#
# Path: gh/util.py
# def get_repository_tuple():
# def find_git_config():
# def github_config():
# def trim_numbers(number):
# def read_stdin():
# def mktmpfile(prefix='gh-'):
# def rmtmpfile(name):
# def wrap(text):
# def get_issue_number(args, parser, error):
#
# Path: gh/compat.py
# def fix_encoding(content):
# if sys.version_info < (3, 0):
# return content.encode('ascii', 'replace')
# return content
, which may contain function names, class names, or code. Output only the next line. | issue.title = fix_encoding(issue.title) |
Here is a snippet: <|code_start|> summary = 'Create a new repository'
subcommands = {}
def __init__(self):
super(CreateRepoCommand, self).__init__()
add = self.parser.add_option
add('-o', '--organization',
dest='organization',
help='Organization to create this repository under',
type='str',
default='',
nargs=1,
)
def run(self, options, args):
opts, args = self.parser.parse_args(args)
if not args:
self.parser.error('You must provide a name for your repository')
return self.FAILURE
name = args.pop(0)
self.login()
org = None
if opts.organization:
org = self.gh.organization(opts.organization)
conf = {}
<|code_end|>
. Write the next line using the current file imports:
from gh.base import Command
from gh.compat import input
and context from other files:
# Path: gh/base.py
# class Command(object):
# __metaclass__ = ABCMeta
# name = None
# usage = None
# repository = ()
# user = ''
# subcommands = {}
# SUCCESS = 0
# FAILURE = 1
# COMMAND_UNKNOWN = 127
#
# def __init__(self):
# super(Command, self).__init__()
# assert self.name
# commands[self.name] = self
# self.gh = GitHub()
# self.gh.set_user_agent('github-cli/{0} (http://git.io/MEmEmw)'.format(
# __version__
# ))
# self.parser = CustomOptionParser(usage=self.usage)
#
# @abstractmethod
# def run(self, options, args):
# return self.FAILURE
#
# def get_repo(self, options):
# self.repo = None
# if self.repository:
# self.repo = self.gh.repository(*self.repository)
#
# if not (self.repo or options.loc_aware):
# self.parser.error('A repository is required.')
#
# def get_user(self):
# if not self.user:
# self.login()
# self.user = self.gh.user()
#
# def login(self):
# # Get the full path to the configuration file
# config = github_config()
# parser = ConfigParser()
#
# # Check to make sure the file exists and we are allowed to read it
# if os.path.isfile(config) and os.access(config, os.R_OK | os.W_OK):
# parser.readfp(open(config))
# self.gh.login(token=parser.get('github', 'token'))
# else:
# # Either the file didn't exist or we didn't have the correct
# # permissions
# user = ''
# while not user:
# # We will not stop until we are given a username
# user = input('Username: ')
#
# self.user = user
#
# pw = ''
# while not pw:
# # Nor will we stop until we're given a password
# pw = getpass('Password: ')
#
# # Get an authorization for this
# auth = self.gh.authorize(
# user, pw, ['user', 'repo', 'gist'], 'github-cli',
# 'http://git.io/MEmEmw'
# )
# parser.add_section('github')
# parser.set('github', 'token', auth.token)
# self.gh.login(token=auth.token)
# # Create the file if it doesn't exist. Otherwise completely blank
# # out what was there before. Kind of dangerous and destructive but
# # somewhat necessary
# parser.write(open(config, 'w+'))
#
# def help(self):
# self.parser.print_help()
# if self.subcommands:
# print('\nSubcommands:')
# for command in sorted(self.subcommands.keys()):
# print(' {0}:\n\t{1}'.format(
# command, self.subcommands[command]
# ))
# sys.exit(0)
#
# Path: gh/compat.py
# def fix_encoding(content):
, which may include functions, classes, or code. Output only the next line. | conf['description'] = input('Description: ') |
Here is a snippet: <|code_start|>
def main():
opts, args = main_parser.parse_args()
if opts.help and not args:
args = ['help']
if not args:
main_parser.error('You must give a command. '
'(Use `gh help` to see a list of commands)')
repository = ()
if opts.repository and '/' in opts.repository:
repository = opts.repository.split('/', 1)
if opts.loc_aware and not repository:
repository = get_repository_tuple()
command = args[0].lower()
<|code_end|>
. Write the next line using the current file imports:
from gh.base import main_parser, load_command, commands
from gh.util import get_repository_tuple
import sys
and context from other files:
# Path: gh/base.py
# class Command(object):
# class CustomOptionParser(OptionParser):
# SUCCESS = 0
# FAILURE = 1
# COMMAND_UNKNOWN = 127
# def __init__(self):
# def run(self, options, args):
# def get_repo(self, options):
# def get_user(self):
# def login(self):
# def help(self):
# def __init__(self, *args, **kwargs):
# def load_command(name):
#
# Path: gh/util.py
# def get_repository_tuple():
# """Parse the git config file for this repository if it exists.
#
# :returns: namedtuple with attributes, owner and repo
# """
# # If there are multiple remotes, this could choose the wrong one
# reg = compile(
# '(?:https://|git@)github\.com(?::|/)([^\./-]*)/(.*)'
# )
# config = find_git_config()
# r = ()
# if config:
# fd = open(config)
# for line in fd:
# match = reg.search(line)
# if match and match.groups():
# r = match.groups()
# break
#
# fd.close()
#
# if r and r[1].endswith('.git'):
# r = (r[0], r[1][:-4])
# return r
, which may include functions, classes, or code. Output only the next line. | load_command(command) |
Given the code snippet: <|code_start|>
def main():
opts, args = main_parser.parse_args()
if opts.help and not args:
args = ['help']
if not args:
main_parser.error('You must give a command. '
'(Use `gh help` to see a list of commands)')
repository = ()
if opts.repository and '/' in opts.repository:
repository = opts.repository.split('/', 1)
if opts.loc_aware and not repository:
repository = get_repository_tuple()
command = args[0].lower()
load_command(command)
status = 1
<|code_end|>
, generate the next line using the imports in this file:
from gh.base import main_parser, load_command, commands
from gh.util import get_repository_tuple
import sys
and context (functions, classes, or occasionally code) from other files:
# Path: gh/base.py
# class Command(object):
# class CustomOptionParser(OptionParser):
# SUCCESS = 0
# FAILURE = 1
# COMMAND_UNKNOWN = 127
# def __init__(self):
# def run(self, options, args):
# def get_repo(self, options):
# def get_user(self):
# def login(self):
# def help(self):
# def __init__(self, *args, **kwargs):
# def load_command(name):
#
# Path: gh/util.py
# def get_repository_tuple():
# """Parse the git config file for this repository if it exists.
#
# :returns: namedtuple with attributes, owner and repo
# """
# # If there are multiple remotes, this could choose the wrong one
# reg = compile(
# '(?:https://|git@)github\.com(?::|/)([^\./-]*)/(.*)'
# )
# config = find_git_config()
# r = ()
# if config:
# fd = open(config)
# for line in fd:
# match = reg.search(line)
# if match and match.groups():
# r = match.groups()
# break
#
# fd.close()
#
# if r and r[1].endswith('.git'):
# r = (r[0], r[1][:-4])
# return r
. Output only the next line. | if command in commands: |
Continue the code snippet: <|code_start|>
def main():
opts, args = main_parser.parse_args()
if opts.help and not args:
args = ['help']
if not args:
main_parser.error('You must give a command. '
'(Use `gh help` to see a list of commands)')
repository = ()
if opts.repository and '/' in opts.repository:
repository = opts.repository.split('/', 1)
if opts.loc_aware and not repository:
<|code_end|>
. Use current file imports:
from gh.base import main_parser, load_command, commands
from gh.util import get_repository_tuple
import sys
and context (classes, functions, or code) from other files:
# Path: gh/base.py
# class Command(object):
# class CustomOptionParser(OptionParser):
# SUCCESS = 0
# FAILURE = 1
# COMMAND_UNKNOWN = 127
# def __init__(self):
# def run(self, options, args):
# def get_repo(self, options):
# def get_user(self):
# def login(self):
# def help(self):
# def __init__(self, *args, **kwargs):
# def load_command(name):
#
# Path: gh/util.py
# def get_repository_tuple():
# """Parse the git config file for this repository if it exists.
#
# :returns: namedtuple with attributes, owner and repo
# """
# # If there are multiple remotes, this could choose the wrong one
# reg = compile(
# '(?:https://|git@)github\.com(?::|/)([^\./-]*)/(.*)'
# )
# config = find_git_config()
# r = ()
# if config:
# fd = open(config)
# for line in fd:
# match = reg.search(line)
# if match and match.groups():
# r = match.groups()
# break
#
# fd.close()
#
# if r and r[1].endswith('.git'):
# r = (r[0], r[1][:-4])
# return r
. Output only the next line. | repository = get_repository_tuple() |
Given the following code snippet before the placeholder: <|code_start|>
class TestCompat(TestCase):
def test_input(self):
if sys.version_info < (3, 0):
<|code_end|>
, predict the next line using imports from the current file:
from unittest import TestCase
from gh.compat import input, ConfigParser
import sys
and context including class names, function names, and sometimes code from other files:
# Path: gh/compat.py
# def fix_encoding(content):
. Output only the next line. | assert input == raw_input |
Here is a snippet: <|code_start|>
class TestCompat(TestCase):
def test_input(self):
if sys.version_info < (3, 0):
assert input == raw_input
else:
assert input == input
def test_ConfigParser(self):
if sys.version_info < (3, 0):
<|code_end|>
. Write the next line using the current file imports:
from unittest import TestCase
from gh.compat import input, ConfigParser
import sys
and context from other files:
# Path: gh/compat.py
# def fix_encoding(content):
, which may include functions, classes, or code. Output only the next line. | assert 'ConfigParser' == ConfigParser.__module__ |
Continue the code snippet: <|code_start|> )
def run(self, options, args):
opts, args = self.parser.parse_args(args)
if opts.help:
self.help()
if opts.sort == 'name':
opts.sort = 'full_name'
if args:
user = args.pop(0)
else:
user = self.get_user()
kwargs = {
'type': opts.type,
'sort': opts.sort,
'direction': opts.direction,
'number': opts.number
}
if isinstance(user, User):
repos = self.gh.iter_repos(**kwargs)
else:
repos = self.gh.iter_repos(self.user, **kwargs)
for repo in repos:
fs = self.fs if repo.description else self.fs2
<|code_end|>
. Use current file imports:
from gh.base import Command
from gh.util import tc
from github3.users import User
and context (classes, functions, or code) from other files:
# Path: gh/base.py
# class Command(object):
# __metaclass__ = ABCMeta
# name = None
# usage = None
# repository = ()
# user = ''
# subcommands = {}
# SUCCESS = 0
# FAILURE = 1
# COMMAND_UNKNOWN = 127
#
# def __init__(self):
# super(Command, self).__init__()
# assert self.name
# commands[self.name] = self
# self.gh = GitHub()
# self.gh.set_user_agent('github-cli/{0} (http://git.io/MEmEmw)'.format(
# __version__
# ))
# self.parser = CustomOptionParser(usage=self.usage)
#
# @abstractmethod
# def run(self, options, args):
# return self.FAILURE
#
# def get_repo(self, options):
# self.repo = None
# if self.repository:
# self.repo = self.gh.repository(*self.repository)
#
# if not (self.repo or options.loc_aware):
# self.parser.error('A repository is required.')
#
# def get_user(self):
# if not self.user:
# self.login()
# self.user = self.gh.user()
#
# def login(self):
# # Get the full path to the configuration file
# config = github_config()
# parser = ConfigParser()
#
# # Check to make sure the file exists and we are allowed to read it
# if os.path.isfile(config) and os.access(config, os.R_OK | os.W_OK):
# parser.readfp(open(config))
# self.gh.login(token=parser.get('github', 'token'))
# else:
# # Either the file didn't exist or we didn't have the correct
# # permissions
# user = ''
# while not user:
# # We will not stop until we are given a username
# user = input('Username: ')
#
# self.user = user
#
# pw = ''
# while not pw:
# # Nor will we stop until we're given a password
# pw = getpass('Password: ')
#
# # Get an authorization for this
# auth = self.gh.authorize(
# user, pw, ['user', 'repo', 'gist'], 'github-cli',
# 'http://git.io/MEmEmw'
# )
# parser.add_section('github')
# parser.set('github', 'token', auth.token)
# self.gh.login(token=auth.token)
# # Create the file if it doesn't exist. Otherwise completely blank
# # out what was there before. Kind of dangerous and destructive but
# # somewhat necessary
# parser.write(open(config, 'w+'))
#
# def help(self):
# self.parser.print_help()
# if self.subcommands:
# print('\nSubcommands:')
# for command in sorted(self.subcommands.keys()):
# print(' {0}:\n\t{1}'.format(
# command, self.subcommands[command]
# ))
# sys.exit(0)
#
# Path: gh/util.py
# def get_repository_tuple():
# def find_git_config():
# def github_config():
# def trim_numbers(number):
# def read_stdin():
# def mktmpfile(prefix='gh-'):
# def rmtmpfile(name):
# def wrap(text):
# def get_issue_number(args, parser, error):
. Output only the next line. | print(fs.format(repo, repo.description.encode('utf-8'), d=tc)) |
Here is a snippet: <|code_start|> add('-a', '--anonymous',
dest='anonymous',
help='Create anonymously',
default=False,
action='store_true',
)
self.parser.epilog = ('create.gist will accept stdin if you use `-`'
' to indicate that is your intention')
def run(self, options, args):
opts, args = self.parser.parse_args(args)
if opts.help:
self.help()
if not opts.anonymous:
self.login()
else:
opts.private = False
status = self.COMMAND_UNKNOWN
if not args:
self.parser.print_help()
return self.FAILURE
status = self.FAILURE
files = {}
if '-' == args[0]:
<|code_end|>
. Write the next line using the current file imports:
import os
from gh.base import Command
from gh.util import read_stdin
and context from other files:
# Path: gh/base.py
# class Command(object):
# __metaclass__ = ABCMeta
# name = None
# usage = None
# repository = ()
# user = ''
# subcommands = {}
# SUCCESS = 0
# FAILURE = 1
# COMMAND_UNKNOWN = 127
#
# def __init__(self):
# super(Command, self).__init__()
# assert self.name
# commands[self.name] = self
# self.gh = GitHub()
# self.gh.set_user_agent('github-cli/{0} (http://git.io/MEmEmw)'.format(
# __version__
# ))
# self.parser = CustomOptionParser(usage=self.usage)
#
# @abstractmethod
# def run(self, options, args):
# return self.FAILURE
#
# def get_repo(self, options):
# self.repo = None
# if self.repository:
# self.repo = self.gh.repository(*self.repository)
#
# if not (self.repo or options.loc_aware):
# self.parser.error('A repository is required.')
#
# def get_user(self):
# if not self.user:
# self.login()
# self.user = self.gh.user()
#
# def login(self):
# # Get the full path to the configuration file
# config = github_config()
# parser = ConfigParser()
#
# # Check to make sure the file exists and we are allowed to read it
# if os.path.isfile(config) and os.access(config, os.R_OK | os.W_OK):
# parser.readfp(open(config))
# self.gh.login(token=parser.get('github', 'token'))
# else:
# # Either the file didn't exist or we didn't have the correct
# # permissions
# user = ''
# while not user:
# # We will not stop until we are given a username
# user = input('Username: ')
#
# self.user = user
#
# pw = ''
# while not pw:
# # Nor will we stop until we're given a password
# pw = getpass('Password: ')
#
# # Get an authorization for this
# auth = self.gh.authorize(
# user, pw, ['user', 'repo', 'gist'], 'github-cli',
# 'http://git.io/MEmEmw'
# )
# parser.add_section('github')
# parser.set('github', 'token', auth.token)
# self.gh.login(token=auth.token)
# # Create the file if it doesn't exist. Otherwise completely blank
# # out what was there before. Kind of dangerous and destructive but
# # somewhat necessary
# parser.write(open(config, 'w+'))
#
# def help(self):
# self.parser.print_help()
# if self.subcommands:
# print('\nSubcommands:')
# for command in sorted(self.subcommands.keys()):
# print(' {0}:\n\t{1}'.format(
# command, self.subcommands[command]
# ))
# sys.exit(0)
#
# Path: gh/util.py
# def read_stdin():
# return sys.stdin.read()
, which may include functions, classes, or code. Output only the next line. | files['stdin'] = read_stdin() |
Predict the next line for this snippet: <|code_start|> add = self.parser.add_option
add('-t', '--title',
dest='title',
help='Title for a new issue',
type='str',
default='',
nargs=1,
)
def run(self, options, args):
self.get_repo(options)
opts, args = self.parser.parse_args(args)
if opts.help:
parser.print_help()
return self.SUCCESS
if not opts.title:
print('issue.create requires a title')
self.parser.print_help()
return self.FAILURE
self.login()
# I need to handle this on Windows too somehow
if not os.path.expandvars('$EDITOR'):
print("$EDITOR not set")
return self.FAILURE
status = self.SUCCESS
<|code_end|>
with the help of current file imports:
import os
from gh.base import Command
from gh.util import mktmpfile, rmtmpfile
and context from other files:
# Path: gh/base.py
# class Command(object):
# __metaclass__ = ABCMeta
# name = None
# usage = None
# repository = ()
# user = ''
# subcommands = {}
# SUCCESS = 0
# FAILURE = 1
# COMMAND_UNKNOWN = 127
#
# def __init__(self):
# super(Command, self).__init__()
# assert self.name
# commands[self.name] = self
# self.gh = GitHub()
# self.gh.set_user_agent('github-cli/{0} (http://git.io/MEmEmw)'.format(
# __version__
# ))
# self.parser = CustomOptionParser(usage=self.usage)
#
# @abstractmethod
# def run(self, options, args):
# return self.FAILURE
#
# def get_repo(self, options):
# self.repo = None
# if self.repository:
# self.repo = self.gh.repository(*self.repository)
#
# if not (self.repo or options.loc_aware):
# self.parser.error('A repository is required.')
#
# def get_user(self):
# if not self.user:
# self.login()
# self.user = self.gh.user()
#
# def login(self):
# # Get the full path to the configuration file
# config = github_config()
# parser = ConfigParser()
#
# # Check to make sure the file exists and we are allowed to read it
# if os.path.isfile(config) and os.access(config, os.R_OK | os.W_OK):
# parser.readfp(open(config))
# self.gh.login(token=parser.get('github', 'token'))
# else:
# # Either the file didn't exist or we didn't have the correct
# # permissions
# user = ''
# while not user:
# # We will not stop until we are given a username
# user = input('Username: ')
#
# self.user = user
#
# pw = ''
# while not pw:
# # Nor will we stop until we're given a password
# pw = getpass('Password: ')
#
# # Get an authorization for this
# auth = self.gh.authorize(
# user, pw, ['user', 'repo', 'gist'], 'github-cli',
# 'http://git.io/MEmEmw'
# )
# parser.add_section('github')
# parser.set('github', 'token', auth.token)
# self.gh.login(token=auth.token)
# # Create the file if it doesn't exist. Otherwise completely blank
# # out what was there before. Kind of dangerous and destructive but
# # somewhat necessary
# parser.write(open(config, 'w+'))
#
# def help(self):
# self.parser.print_help()
# if self.subcommands:
# print('\nSubcommands:')
# for command in sorted(self.subcommands.keys()):
# print(' {0}:\n\t{1}'.format(
# command, self.subcommands[command]
# ))
# sys.exit(0)
#
# Path: gh/util.py
# def mktmpfile(prefix='gh-'):
# return NamedTemporaryFile(prefix=prefix, delete=False)
#
# def rmtmpfile(name):
# if name:
# os.remove(name)
, which may contain function names, class names, or code. Output only the next line. | with mktmpfile('gh-newissue-') as fd: |
Here is a snippet: <|code_start|> opts, args = self.parser.parse_args(args)
if opts.help:
parser.print_help()
return self.SUCCESS
if not opts.title:
print('issue.create requires a title')
self.parser.print_help()
return self.FAILURE
self.login()
# I need to handle this on Windows too somehow
if not os.path.expandvars('$EDITOR'):
print("$EDITOR not set")
return self.FAILURE
status = self.SUCCESS
with mktmpfile('gh-newissue-') as fd:
name = fd.name
os.system('$EDITOR {0}'.format(fd.name))
issue = self.repo.create_issue(opts.title, open(name).read())
if not issue:
status = self.FAILURE
print("Issue file is at saved at {0}".format(name))
else:
print("#{0.number} {0.html_url}".format(issue))
<|code_end|>
. Write the next line using the current file imports:
import os
from gh.base import Command
from gh.util import mktmpfile, rmtmpfile
and context from other files:
# Path: gh/base.py
# class Command(object):
# __metaclass__ = ABCMeta
# name = None
# usage = None
# repository = ()
# user = ''
# subcommands = {}
# SUCCESS = 0
# FAILURE = 1
# COMMAND_UNKNOWN = 127
#
# def __init__(self):
# super(Command, self).__init__()
# assert self.name
# commands[self.name] = self
# self.gh = GitHub()
# self.gh.set_user_agent('github-cli/{0} (http://git.io/MEmEmw)'.format(
# __version__
# ))
# self.parser = CustomOptionParser(usage=self.usage)
#
# @abstractmethod
# def run(self, options, args):
# return self.FAILURE
#
# def get_repo(self, options):
# self.repo = None
# if self.repository:
# self.repo = self.gh.repository(*self.repository)
#
# if not (self.repo or options.loc_aware):
# self.parser.error('A repository is required.')
#
# def get_user(self):
# if not self.user:
# self.login()
# self.user = self.gh.user()
#
# def login(self):
# # Get the full path to the configuration file
# config = github_config()
# parser = ConfigParser()
#
# # Check to make sure the file exists and we are allowed to read it
# if os.path.isfile(config) and os.access(config, os.R_OK | os.W_OK):
# parser.readfp(open(config))
# self.gh.login(token=parser.get('github', 'token'))
# else:
# # Either the file didn't exist or we didn't have the correct
# # permissions
# user = ''
# while not user:
# # We will not stop until we are given a username
# user = input('Username: ')
#
# self.user = user
#
# pw = ''
# while not pw:
# # Nor will we stop until we're given a password
# pw = getpass('Password: ')
#
# # Get an authorization for this
# auth = self.gh.authorize(
# user, pw, ['user', 'repo', 'gist'], 'github-cli',
# 'http://git.io/MEmEmw'
# )
# parser.add_section('github')
# parser.set('github', 'token', auth.token)
# self.gh.login(token=auth.token)
# # Create the file if it doesn't exist. Otherwise completely blank
# # out what was there before. Kind of dangerous and destructive but
# # somewhat necessary
# parser.write(open(config, 'w+'))
#
# def help(self):
# self.parser.print_help()
# if self.subcommands:
# print('\nSubcommands:')
# for command in sorted(self.subcommands.keys()):
# print(' {0}:\n\t{1}'.format(
# command, self.subcommands[command]
# ))
# sys.exit(0)
#
# Path: gh/util.py
# def mktmpfile(prefix='gh-'):
# return NamedTemporaryFile(prefix=prefix, delete=False)
#
# def rmtmpfile(name):
# if name:
# os.remove(name)
, which may include functions, classes, or code. Output only the next line. | rmtmpfile(name) |
Continue the code snippet: <|code_start|>
class IssueReopenCommand(Command):
name = 'issue.reopen'
usage = '%prog [options] issue.reopen [#]number'
summary = 'Reopen an issue'
subcommands = {}
def run(self, options, args):
self.get_repo(options)
opts, args = self.parser.parse_args(args)
if opts.help:
self.help()
<|code_end|>
. Use current file imports:
from gh.base import Command
from gh.util import get_issue_number
and context (classes, functions, or code) from other files:
# Path: gh/base.py
# class Command(object):
# __metaclass__ = ABCMeta
# name = None
# usage = None
# repository = ()
# user = ''
# subcommands = {}
# SUCCESS = 0
# FAILURE = 1
# COMMAND_UNKNOWN = 127
#
# def __init__(self):
# super(Command, self).__init__()
# assert self.name
# commands[self.name] = self
# self.gh = GitHub()
# self.gh.set_user_agent('github-cli/{0} (http://git.io/MEmEmw)'.format(
# __version__
# ))
# self.parser = CustomOptionParser(usage=self.usage)
#
# @abstractmethod
# def run(self, options, args):
# return self.FAILURE
#
# def get_repo(self, options):
# self.repo = None
# if self.repository:
# self.repo = self.gh.repository(*self.repository)
#
# if not (self.repo or options.loc_aware):
# self.parser.error('A repository is required.')
#
# def get_user(self):
# if not self.user:
# self.login()
# self.user = self.gh.user()
#
# def login(self):
# # Get the full path to the configuration file
# config = github_config()
# parser = ConfigParser()
#
# # Check to make sure the file exists and we are allowed to read it
# if os.path.isfile(config) and os.access(config, os.R_OK | os.W_OK):
# parser.readfp(open(config))
# self.gh.login(token=parser.get('github', 'token'))
# else:
# # Either the file didn't exist or we didn't have the correct
# # permissions
# user = ''
# while not user:
# # We will not stop until we are given a username
# user = input('Username: ')
#
# self.user = user
#
# pw = ''
# while not pw:
# # Nor will we stop until we're given a password
# pw = getpass('Password: ')
#
# # Get an authorization for this
# auth = self.gh.authorize(
# user, pw, ['user', 'repo', 'gist'], 'github-cli',
# 'http://git.io/MEmEmw'
# )
# parser.add_section('github')
# parser.set('github', 'token', auth.token)
# self.gh.login(token=auth.token)
# # Create the file if it doesn't exist. Otherwise completely blank
# # out what was there before. Kind of dangerous and destructive but
# # somewhat necessary
# parser.write(open(config, 'w+'))
#
# def help(self):
# self.parser.print_help()
# if self.subcommands:
# print('\nSubcommands:')
# for command in sorted(self.subcommands.keys()):
# print(' {0}:\n\t{1}'.format(
# command, self.subcommands[command]
# ))
# sys.exit(0)
#
# Path: gh/util.py
# def get_issue_number(args, parser, error):
# if not args:
# print(error, file=sys.stderr)
# return None
#
# number = trim_numbers(args[0])
# if not number.isdigit():
# print('A valid integer is required', file=sys.stderr)
# return None
#
# return number
. Output only the next line. | number = get_issue_number( |
Predict the next line for this snippet: <|code_start|> add('-u', '--username',
dest='username',
help="Lists this user's gists",
type='str',
default='',
nargs=1,
)
add('-n', '--number',
dest='number',
help='Number of gists to list',
type=int,
default=-1,
nargs=1,
)
def run(self, options, args):
opts, args = self.parser.parse_args(args)
if opts.help:
self.help()
if not opts.username:
self.login()
for g in self.gh.iter_gists(opts.username, opts.number):
self.short_gist(g)
return self.SUCCESS
def short_gist(self, gist):
<|code_end|>
with the help of current file imports:
from gh.base import Command
from gh.util import tc, wrap
from gh.compat import fix_encoding
and context from other files:
# Path: gh/base.py
# class Command(object):
# __metaclass__ = ABCMeta
# name = None
# usage = None
# repository = ()
# user = ''
# subcommands = {}
# SUCCESS = 0
# FAILURE = 1
# COMMAND_UNKNOWN = 127
#
# def __init__(self):
# super(Command, self).__init__()
# assert self.name
# commands[self.name] = self
# self.gh = GitHub()
# self.gh.set_user_agent('github-cli/{0} (http://git.io/MEmEmw)'.format(
# __version__
# ))
# self.parser = CustomOptionParser(usage=self.usage)
#
# @abstractmethod
# def run(self, options, args):
# return self.FAILURE
#
# def get_repo(self, options):
# self.repo = None
# if self.repository:
# self.repo = self.gh.repository(*self.repository)
#
# if not (self.repo or options.loc_aware):
# self.parser.error('A repository is required.')
#
# def get_user(self):
# if not self.user:
# self.login()
# self.user = self.gh.user()
#
# def login(self):
# # Get the full path to the configuration file
# config = github_config()
# parser = ConfigParser()
#
# # Check to make sure the file exists and we are allowed to read it
# if os.path.isfile(config) and os.access(config, os.R_OK | os.W_OK):
# parser.readfp(open(config))
# self.gh.login(token=parser.get('github', 'token'))
# else:
# # Either the file didn't exist or we didn't have the correct
# # permissions
# user = ''
# while not user:
# # We will not stop until we are given a username
# user = input('Username: ')
#
# self.user = user
#
# pw = ''
# while not pw:
# # Nor will we stop until we're given a password
# pw = getpass('Password: ')
#
# # Get an authorization for this
# auth = self.gh.authorize(
# user, pw, ['user', 'repo', 'gist'], 'github-cli',
# 'http://git.io/MEmEmw'
# )
# parser.add_section('github')
# parser.set('github', 'token', auth.token)
# self.gh.login(token=auth.token)
# # Create the file if it doesn't exist. Otherwise completely blank
# # out what was there before. Kind of dangerous and destructive but
# # somewhat necessary
# parser.write(open(config, 'w+'))
#
# def help(self):
# self.parser.print_help()
# if self.subcommands:
# print('\nSubcommands:')
# for command in sorted(self.subcommands.keys()):
# print(' {0}:\n\t{1}'.format(
# command, self.subcommands[command]
# ))
# sys.exit(0)
#
# Path: gh/util.py
# def get_repository_tuple():
# def find_git_config():
# def github_config():
# def trim_numbers(number):
# def read_stdin():
# def mktmpfile(prefix='gh-'):
# def rmtmpfile(name):
# def wrap(text):
# def get_issue_number(args, parser, error):
#
# Path: gh/compat.py
# def fix_encoding(content):
# if sys.version_info < (3, 0):
# return content.encode('ascii', 'replace')
# return content
, which may contain function names, class names, or code. Output only the next line. | print(self.gist_fs.format(tc, id=gist.id, desc=gist.description)) |
Given the code snippet: <|code_start|>
class IssueCommentCommand(Command):
name = 'issue.comment'
usage = '%prog [options] issue.comment [#]number'
summary = 'Comment on an issue'
subcommands = {}
def run(self, options, args):
self.get_repo(options)
opts, args = self.parser.parse_args(args)
if opts.help:
self.help()
<|code_end|>
, generate the next line using the imports in this file:
import os
from gh.base import Command
from gh.util import get_issue_number, mktmpfile, rmtmpfile
and context (functions, classes, or occasionally code) from other files:
# Path: gh/base.py
# class Command(object):
# __metaclass__ = ABCMeta
# name = None
# usage = None
# repository = ()
# user = ''
# subcommands = {}
# SUCCESS = 0
# FAILURE = 1
# COMMAND_UNKNOWN = 127
#
# def __init__(self):
# super(Command, self).__init__()
# assert self.name
# commands[self.name] = self
# self.gh = GitHub()
# self.gh.set_user_agent('github-cli/{0} (http://git.io/MEmEmw)'.format(
# __version__
# ))
# self.parser = CustomOptionParser(usage=self.usage)
#
# @abstractmethod
# def run(self, options, args):
# return self.FAILURE
#
# def get_repo(self, options):
# self.repo = None
# if self.repository:
# self.repo = self.gh.repository(*self.repository)
#
# if not (self.repo or options.loc_aware):
# self.parser.error('A repository is required.')
#
# def get_user(self):
# if not self.user:
# self.login()
# self.user = self.gh.user()
#
# def login(self):
# # Get the full path to the configuration file
# config = github_config()
# parser = ConfigParser()
#
# # Check to make sure the file exists and we are allowed to read it
# if os.path.isfile(config) and os.access(config, os.R_OK | os.W_OK):
# parser.readfp(open(config))
# self.gh.login(token=parser.get('github', 'token'))
# else:
# # Either the file didn't exist or we didn't have the correct
# # permissions
# user = ''
# while not user:
# # We will not stop until we are given a username
# user = input('Username: ')
#
# self.user = user
#
# pw = ''
# while not pw:
# # Nor will we stop until we're given a password
# pw = getpass('Password: ')
#
# # Get an authorization for this
# auth = self.gh.authorize(
# user, pw, ['user', 'repo', 'gist'], 'github-cli',
# 'http://git.io/MEmEmw'
# )
# parser.add_section('github')
# parser.set('github', 'token', auth.token)
# self.gh.login(token=auth.token)
# # Create the file if it doesn't exist. Otherwise completely blank
# # out what was there before. Kind of dangerous and destructive but
# # somewhat necessary
# parser.write(open(config, 'w+'))
#
# def help(self):
# self.parser.print_help()
# if self.subcommands:
# print('\nSubcommands:')
# for command in sorted(self.subcommands.keys()):
# print(' {0}:\n\t{1}'.format(
# command, self.subcommands[command]
# ))
# sys.exit(0)
#
# Path: gh/util.py
# def get_issue_number(args, parser, error):
# if not args:
# print(error, file=sys.stderr)
# return None
#
# number = trim_numbers(args[0])
# if not number.isdigit():
# print('A valid integer is required', file=sys.stderr)
# return None
#
# return number
#
# def mktmpfile(prefix='gh-'):
# return NamedTemporaryFile(prefix=prefix, delete=False)
#
# def rmtmpfile(name):
# if name:
# os.remove(name)
. Output only the next line. | number = get_issue_number( |
Continue the code snippet: <|code_start|> def run(self, options, args):
self.get_repo(options)
opts, args = self.parser.parse_args(args)
if opts.help:
self.help()
number = get_issue_number(
args, self.parser, 'issue.comment requires a valid number'
)
if number is None:
return self.FAILURE
return self.comment_on(number)
def comment_on(self, number):
self.login()
user, repo = self.repository
issue = self.gh.issue(user, repo, number)
name = ''
status = self.SUCCESS
# I need to handle this on Windows too somehow
if not os.path.expandvars('$EDITOR'):
print("$EDITOR not set")
return self.FAILURE
<|code_end|>
. Use current file imports:
import os
from gh.base import Command
from gh.util import get_issue_number, mktmpfile, rmtmpfile
and context (classes, functions, or code) from other files:
# Path: gh/base.py
# class Command(object):
# __metaclass__ = ABCMeta
# name = None
# usage = None
# repository = ()
# user = ''
# subcommands = {}
# SUCCESS = 0
# FAILURE = 1
# COMMAND_UNKNOWN = 127
#
# def __init__(self):
# super(Command, self).__init__()
# assert self.name
# commands[self.name] = self
# self.gh = GitHub()
# self.gh.set_user_agent('github-cli/{0} (http://git.io/MEmEmw)'.format(
# __version__
# ))
# self.parser = CustomOptionParser(usage=self.usage)
#
# @abstractmethod
# def run(self, options, args):
# return self.FAILURE
#
# def get_repo(self, options):
# self.repo = None
# if self.repository:
# self.repo = self.gh.repository(*self.repository)
#
# if not (self.repo or options.loc_aware):
# self.parser.error('A repository is required.')
#
# def get_user(self):
# if not self.user:
# self.login()
# self.user = self.gh.user()
#
# def login(self):
# # Get the full path to the configuration file
# config = github_config()
# parser = ConfigParser()
#
# # Check to make sure the file exists and we are allowed to read it
# if os.path.isfile(config) and os.access(config, os.R_OK | os.W_OK):
# parser.readfp(open(config))
# self.gh.login(token=parser.get('github', 'token'))
# else:
# # Either the file didn't exist or we didn't have the correct
# # permissions
# user = ''
# while not user:
# # We will not stop until we are given a username
# user = input('Username: ')
#
# self.user = user
#
# pw = ''
# while not pw:
# # Nor will we stop until we're given a password
# pw = getpass('Password: ')
#
# # Get an authorization for this
# auth = self.gh.authorize(
# user, pw, ['user', 'repo', 'gist'], 'github-cli',
# 'http://git.io/MEmEmw'
# )
# parser.add_section('github')
# parser.set('github', 'token', auth.token)
# self.gh.login(token=auth.token)
# # Create the file if it doesn't exist. Otherwise completely blank
# # out what was there before. Kind of dangerous and destructive but
# # somewhat necessary
# parser.write(open(config, 'w+'))
#
# def help(self):
# self.parser.print_help()
# if self.subcommands:
# print('\nSubcommands:')
# for command in sorted(self.subcommands.keys()):
# print(' {0}:\n\t{1}'.format(
# command, self.subcommands[command]
# ))
# sys.exit(0)
#
# Path: gh/util.py
# def get_issue_number(args, parser, error):
# if not args:
# print(error, file=sys.stderr)
# return None
#
# number = trim_numbers(args[0])
# if not number.isdigit():
# print('A valid integer is required', file=sys.stderr)
# return None
#
# return number
#
# def mktmpfile(prefix='gh-'):
# return NamedTemporaryFile(prefix=prefix, delete=False)
#
# def rmtmpfile(name):
# if name:
# os.remove(name)
. Output only the next line. | with mktmpfile('gh-issuecomment-') as fd: |
Continue the code snippet: <|code_start|> if number is None:
return self.FAILURE
return self.comment_on(number)
def comment_on(self, number):
self.login()
user, repo = self.repository
issue = self.gh.issue(user, repo, number)
name = ''
status = self.SUCCESS
# I need to handle this on Windows too somehow
if not os.path.expandvars('$EDITOR'):
print("$EDITOR not set")
return self.FAILURE
with mktmpfile('gh-issuecomment-') as fd:
name = fd.name
os.system('$EDITOR {0}'.format(fd.name))
comment = issue.create_comment(open(name).read())
if not comment:
status = self.FAILURE
print('Comment creation failed. Comment stored at {0}'.format(
name))
else:
print('Comment created successfully. {0}'.format(
comment.html_url))
<|code_end|>
. Use current file imports:
import os
from gh.base import Command
from gh.util import get_issue_number, mktmpfile, rmtmpfile
and context (classes, functions, or code) from other files:
# Path: gh/base.py
# class Command(object):
# __metaclass__ = ABCMeta
# name = None
# usage = None
# repository = ()
# user = ''
# subcommands = {}
# SUCCESS = 0
# FAILURE = 1
# COMMAND_UNKNOWN = 127
#
# def __init__(self):
# super(Command, self).__init__()
# assert self.name
# commands[self.name] = self
# self.gh = GitHub()
# self.gh.set_user_agent('github-cli/{0} (http://git.io/MEmEmw)'.format(
# __version__
# ))
# self.parser = CustomOptionParser(usage=self.usage)
#
# @abstractmethod
# def run(self, options, args):
# return self.FAILURE
#
# def get_repo(self, options):
# self.repo = None
# if self.repository:
# self.repo = self.gh.repository(*self.repository)
#
# if not (self.repo or options.loc_aware):
# self.parser.error('A repository is required.')
#
# def get_user(self):
# if not self.user:
# self.login()
# self.user = self.gh.user()
#
# def login(self):
# # Get the full path to the configuration file
# config = github_config()
# parser = ConfigParser()
#
# # Check to make sure the file exists and we are allowed to read it
# if os.path.isfile(config) and os.access(config, os.R_OK | os.W_OK):
# parser.readfp(open(config))
# self.gh.login(token=parser.get('github', 'token'))
# else:
# # Either the file didn't exist or we didn't have the correct
# # permissions
# user = ''
# while not user:
# # We will not stop until we are given a username
# user = input('Username: ')
#
# self.user = user
#
# pw = ''
# while not pw:
# # Nor will we stop until we're given a password
# pw = getpass('Password: ')
#
# # Get an authorization for this
# auth = self.gh.authorize(
# user, pw, ['user', 'repo', 'gist'], 'github-cli',
# 'http://git.io/MEmEmw'
# )
# parser.add_section('github')
# parser.set('github', 'token', auth.token)
# self.gh.login(token=auth.token)
# # Create the file if it doesn't exist. Otherwise completely blank
# # out what was there before. Kind of dangerous and destructive but
# # somewhat necessary
# parser.write(open(config, 'w+'))
#
# def help(self):
# self.parser.print_help()
# if self.subcommands:
# print('\nSubcommands:')
# for command in sorted(self.subcommands.keys()):
# print(' {0}:\n\t{1}'.format(
# command, self.subcommands[command]
# ))
# sys.exit(0)
#
# Path: gh/util.py
# def get_issue_number(args, parser, error):
# if not args:
# print(error, file=sys.stderr)
# return None
#
# number = trim_numbers(args[0])
# if not number.isdigit():
# print('A valid integer is required', file=sys.stderr)
# return None
#
# return number
#
# def mktmpfile(prefix='gh-'):
# return NamedTemporaryFile(prefix=prefix, delete=False)
#
# def rmtmpfile(name):
# if name:
# os.remove(name)
. Output only the next line. | rmtmpfile(name) |
Here is a snippet: <|code_start|>
class TestCommand(TestCase):
def test_run(self):
class A(Command):
pass
try:
a = A()
a.run([], [])
except (TypeError, AssertionError):
pass
class TestCustomOptionParser(TestCase):
def test_help(self):
<|code_end|>
. Write the next line using the current file imports:
from unittest import TestCase
from gh.base import (Command, CustomOptionParser, load_command, commands,
main_parser)
import sys
and context from other files:
# Path: gh/base.py
# class Command(object):
# class CustomOptionParser(OptionParser):
# SUCCESS = 0
# FAILURE = 1
# COMMAND_UNKNOWN = 127
# def __init__(self):
# def run(self, options, args):
# def get_repo(self, options):
# def get_user(self):
# def login(self):
# def help(self):
# def __init__(self, *args, **kwargs):
# def load_command(name):
, which may include functions, classes, or code. Output only the next line. | c = CustomOptionParser() |
Given the following code snippet before the placeholder: <|code_start|> a = A()
a.run([], [])
except (TypeError, AssertionError):
pass
class TestCustomOptionParser(TestCase):
def test_help(self):
c = CustomOptionParser()
assert c.has_option('-h') is True
assert c.defaults == {'help': False}
class TestBase(TestCase):
command = 'issue'
mod = 'gh.commands.issue'
def setUp(self):
self.mods = sys.modules.copy()
if self.mod in sys.modules:
del sys.modules[self.mod]
global commands
if self.command in commands:
del commands[self.command]
def tearDown(self):
sys.modules.update(self.mods)
def test_load_command(self):
<|code_end|>
, predict the next line using imports from the current file:
from unittest import TestCase
from gh.base import (Command, CustomOptionParser, load_command, commands,
main_parser)
import sys
and context including class names, function names, and sometimes code from other files:
# Path: gh/base.py
# class Command(object):
# class CustomOptionParser(OptionParser):
# SUCCESS = 0
# FAILURE = 1
# COMMAND_UNKNOWN = 127
# def __init__(self):
# def run(self, options, args):
# def get_repo(self, options):
# def get_user(self):
# def login(self):
# def help(self):
# def __init__(self, *args, **kwargs):
# def load_command(name):
. Output only the next line. | load_command(self.command) |
Next line prediction: <|code_start|>
class TestCommand(TestCase):
def test_run(self):
class A(Command):
pass
try:
a = A()
a.run([], [])
except (TypeError, AssertionError):
pass
class TestCustomOptionParser(TestCase):
def test_help(self):
c = CustomOptionParser()
assert c.has_option('-h') is True
assert c.defaults == {'help': False}
class TestBase(TestCase):
command = 'issue'
mod = 'gh.commands.issue'
def setUp(self):
self.mods = sys.modules.copy()
if self.mod in sys.modules:
del sys.modules[self.mod]
<|code_end|>
. Use current file imports:
(from unittest import TestCase
from gh.base import (Command, CustomOptionParser, load_command, commands,
main_parser)
import sys)
and context including class names, function names, or small code snippets from other files:
# Path: gh/base.py
# class Command(object):
# class CustomOptionParser(OptionParser):
# SUCCESS = 0
# FAILURE = 1
# COMMAND_UNKNOWN = 127
# def __init__(self):
# def run(self, options, args):
# def get_repo(self, options):
# def get_user(self):
# def login(self):
# def help(self):
# def __init__(self, *args, **kwargs):
# def load_command(name):
. Output only the next line. | global commands |
Based on the snippet: <|code_start|>
class TestBase(TestCase):
command = 'issue'
mod = 'gh.commands.issue'
def setUp(self):
self.mods = sys.modules.copy()
if self.mod in sys.modules:
del sys.modules[self.mod]
global commands
if self.command in commands:
del commands[self.command]
def tearDown(self):
sys.modules.update(self.mods)
def test_load_command(self):
load_command(self.command)
assert self.mod in sys.modules
load_command('foobarbogus')
assert 'gh.commands.foobarbogus' not in sys.modules
def test_commands(self):
assert self.command not in commands
load_command(self.command)
error = '{0} not in commands dict'.format(self.command)
assert self.command in commands, error
def test_main_parser(self):
<|code_end|>
, predict the immediate next line with the help of imports:
from unittest import TestCase
from gh.base import (Command, CustomOptionParser, load_command, commands,
main_parser)
import sys
and context (classes, functions, sometimes code) from other files:
# Path: gh/base.py
# class Command(object):
# class CustomOptionParser(OptionParser):
# SUCCESS = 0
# FAILURE = 1
# COMMAND_UNKNOWN = 127
# def __init__(self):
# def run(self, options, args):
# def get_repo(self, options):
# def get_user(self):
# def login(self):
# def help(self):
# def __init__(self, *args, **kwargs):
# def load_command(name):
. Output only the next line. | opts, args = main_parser.parse_args(['-h']) |
Next line prediction: <|code_start|>
class TestUtil(TestCase):
def setUp(self):
self.orig = os.path.abspath(os.curdir)
os.makedirs('proj/.git/')
os.makedirs('proj/subdir/subdir2/subdir3')
with open('proj/.git/config', 'w+') as fd:
fd.writelines([
'[core]',
'bare = false',
'[remote "origin"]'
'url = git@github.com:sigmavirus24/Todo.txt-python.git'
]
)
os.chdir('proj')
def tearDown(self):
os.chdir(self.orig)
shutil.rmtree('proj')
def test_find_git_config(self):
dirs = ['./subdir', './subdir/subdir2', './subdir/subdir2/subdir3']
dirs = [os.path.abspath(d) for d in dirs]
path = os.path.join(os.path.abspath(self.orig), 'proj', '.git',
'config')
for d in dirs:
os.chdir(d)
<|code_end|>
. Use current file imports:
(from unittest import TestCase
from gh.util import find_git_config, get_repository_tuple, wrap
import os
import shutil)
and context including class names, function names, or small code snippets from other files:
# Path: gh/util.py
# def find_git_config():
# """Attempt to find the git config file for this repository in this
# directory and it's parent.
# """
# original = cur_dir = os.path.abspath(os.curdir)
# home = os.path.abspath(os.environ.get('HOME', ''))
#
# while cur_dir != home:
# if os.path.isdir('.git') and os.access('.git/config', os.R_OK):
# os.chdir(original)
# return os.path.join(cur_dir, '.git', 'config')
# else:
# os.chdir(os.pardir)
# cur_dir = os.path.abspath(os.curdir)
#
# os.chdir(original)
# return ''
#
# def get_repository_tuple():
# """Parse the git config file for this repository if it exists.
#
# :returns: namedtuple with attributes, owner and repo
# """
# # If there are multiple remotes, this could choose the wrong one
# reg = compile(
# '(?:https://|git@)github\.com(?::|/)([^\./-]*)/(.*)'
# )
# config = find_git_config()
# r = ()
# if config:
# fd = open(config)
# for line in fd:
# match = reg.search(line)
# if match and match.groups():
# r = match.groups()
# break
#
# fd.close()
#
# if r and r[1].endswith('.git'):
# r = (r[0], r[1][:-4])
# return r
#
# def wrap(text):
# if hasattr(wrap, 'tw'):
# tw = wrap.tw
# else:
# tw = TextWrapper(width=72, replace_whitespace=False)
#
# paragraphs = [p.replace('\n', ' ') for p in text.split('\n\n')]
# paragraphs = ['\n'.join(tw.wrap(p)) for p in paragraphs]
# return '\n\n'.join(paragraphs)
. Output only the next line. | ret = find_git_config() |
Continue the code snippet: <|code_start|> def setUp(self):
self.orig = os.path.abspath(os.curdir)
os.makedirs('proj/.git/')
os.makedirs('proj/subdir/subdir2/subdir3')
with open('proj/.git/config', 'w+') as fd:
fd.writelines([
'[core]',
'bare = false',
'[remote "origin"]'
'url = git@github.com:sigmavirus24/Todo.txt-python.git'
]
)
os.chdir('proj')
def tearDown(self):
os.chdir(self.orig)
shutil.rmtree('proj')
def test_find_git_config(self):
dirs = ['./subdir', './subdir/subdir2', './subdir/subdir2/subdir3']
dirs = [os.path.abspath(d) for d in dirs]
path = os.path.join(os.path.abspath(self.orig), 'proj', '.git',
'config')
for d in dirs:
os.chdir(d)
ret = find_git_config()
assert path == ret
assert os.path.abspath(os.curdir) == d
def test_get_repository_tuple(self):
<|code_end|>
. Use current file imports:
from unittest import TestCase
from gh.util import find_git_config, get_repository_tuple, wrap
import os
import shutil
and context (classes, functions, or code) from other files:
# Path: gh/util.py
# def find_git_config():
# """Attempt to find the git config file for this repository in this
# directory and it's parent.
# """
# original = cur_dir = os.path.abspath(os.curdir)
# home = os.path.abspath(os.environ.get('HOME', ''))
#
# while cur_dir != home:
# if os.path.isdir('.git') and os.access('.git/config', os.R_OK):
# os.chdir(original)
# return os.path.join(cur_dir, '.git', 'config')
# else:
# os.chdir(os.pardir)
# cur_dir = os.path.abspath(os.curdir)
#
# os.chdir(original)
# return ''
#
# def get_repository_tuple():
# """Parse the git config file for this repository if it exists.
#
# :returns: namedtuple with attributes, owner and repo
# """
# # If there are multiple remotes, this could choose the wrong one
# reg = compile(
# '(?:https://|git@)github\.com(?::|/)([^\./-]*)/(.*)'
# )
# config = find_git_config()
# r = ()
# if config:
# fd = open(config)
# for line in fd:
# match = reg.search(line)
# if match and match.groups():
# r = match.groups()
# break
#
# fd.close()
#
# if r and r[1].endswith('.git'):
# r = (r[0], r[1][:-4])
# return r
#
# def wrap(text):
# if hasattr(wrap, 'tw'):
# tw = wrap.tw
# else:
# tw = TextWrapper(width=72, replace_whitespace=False)
#
# paragraphs = [p.replace('\n', ' ') for p in text.split('\n\n')]
# paragraphs = ['\n'.join(tw.wrap(p)) for p in paragraphs]
# return '\n\n'.join(paragraphs)
. Output only the next line. | ret = get_repository_tuple() |
Continue the code snippet: <|code_start|> with open('proj/.git/config', 'w+') as fd:
fd.writelines([
'[core]',
'bare = false',
'[remote "origin"]'
'url = git@github.com:sigmavirus24/Todo.txt-python.git'
]
)
os.chdir('proj')
def tearDown(self):
os.chdir(self.orig)
shutil.rmtree('proj')
def test_find_git_config(self):
dirs = ['./subdir', './subdir/subdir2', './subdir/subdir2/subdir3']
dirs = [os.path.abspath(d) for d in dirs]
path = os.path.join(os.path.abspath(self.orig), 'proj', '.git',
'config')
for d in dirs:
os.chdir(d)
ret = find_git_config()
assert path == ret
assert os.path.abspath(os.curdir) == d
def test_get_repository_tuple(self):
ret = get_repository_tuple()
assert ('sigmavirus24', 'Todo.txt-python') == ret
def test_wrap(self):
<|code_end|>
. Use current file imports:
from unittest import TestCase
from gh.util import find_git_config, get_repository_tuple, wrap
import os
import shutil
and context (classes, functions, or code) from other files:
# Path: gh/util.py
# def find_git_config():
# """Attempt to find the git config file for this repository in this
# directory and it's parent.
# """
# original = cur_dir = os.path.abspath(os.curdir)
# home = os.path.abspath(os.environ.get('HOME', ''))
#
# while cur_dir != home:
# if os.path.isdir('.git') and os.access('.git/config', os.R_OK):
# os.chdir(original)
# return os.path.join(cur_dir, '.git', 'config')
# else:
# os.chdir(os.pardir)
# cur_dir = os.path.abspath(os.curdir)
#
# os.chdir(original)
# return ''
#
# def get_repository_tuple():
# """Parse the git config file for this repository if it exists.
#
# :returns: namedtuple with attributes, owner and repo
# """
# # If there are multiple remotes, this could choose the wrong one
# reg = compile(
# '(?:https://|git@)github\.com(?::|/)([^\./-]*)/(.*)'
# )
# config = find_git_config()
# r = ()
# if config:
# fd = open(config)
# for line in fd:
# match = reg.search(line)
# if match and match.groups():
# r = match.groups()
# break
#
# fd.close()
#
# if r and r[1].endswith('.git'):
# r = (r[0], r[1][:-4])
# return r
#
# def wrap(text):
# if hasattr(wrap, 'tw'):
# tw = wrap.tw
# else:
# tw = TextWrapper(width=72, replace_whitespace=False)
#
# paragraphs = [p.replace('\n', ' ') for p in text.split('\n\n')]
# paragraphs = ['\n'.join(tw.wrap(p)) for p in paragraphs]
# return '\n\n'.join(paragraphs)
. Output only the next line. | assert ''.join(wrap('foo')) == 'foo' |
Predict the next line after this snippet: <|code_start|>
class IssueAssignCommand(Command):
name = 'issue.assign'
usage = '%prog [options] issue.assign [#]number assignee'
summary = 'Assign an issue'
subcommands = {}
def run(self, options, args):
self.get_repo(options)
opts, args = self.parser.parse_args(args)
if len(args) != 2:
print('issue.assign requires 2 arguments.')
self.help()
return self.FAILURE
if opts.help:
self.help()
<|code_end|>
using the current file's imports:
from gh.base import Command
from gh.util import get_issue_number
from gh.util import mktmpfile, rmtmpfile
and any relevant context from other files:
# Path: gh/base.py
# class Command(object):
# __metaclass__ = ABCMeta
# name = None
# usage = None
# repository = ()
# user = ''
# subcommands = {}
# SUCCESS = 0
# FAILURE = 1
# COMMAND_UNKNOWN = 127
#
# def __init__(self):
# super(Command, self).__init__()
# assert self.name
# commands[self.name] = self
# self.gh = GitHub()
# self.gh.set_user_agent('github-cli/{0} (http://git.io/MEmEmw)'.format(
# __version__
# ))
# self.parser = CustomOptionParser(usage=self.usage)
#
# @abstractmethod
# def run(self, options, args):
# return self.FAILURE
#
# def get_repo(self, options):
# self.repo = None
# if self.repository:
# self.repo = self.gh.repository(*self.repository)
#
# if not (self.repo or options.loc_aware):
# self.parser.error('A repository is required.')
#
# def get_user(self):
# if not self.user:
# self.login()
# self.user = self.gh.user()
#
# def login(self):
# # Get the full path to the configuration file
# config = github_config()
# parser = ConfigParser()
#
# # Check to make sure the file exists and we are allowed to read it
# if os.path.isfile(config) and os.access(config, os.R_OK | os.W_OK):
# parser.readfp(open(config))
# self.gh.login(token=parser.get('github', 'token'))
# else:
# # Either the file didn't exist or we didn't have the correct
# # permissions
# user = ''
# while not user:
# # We will not stop until we are given a username
# user = input('Username: ')
#
# self.user = user
#
# pw = ''
# while not pw:
# # Nor will we stop until we're given a password
# pw = getpass('Password: ')
#
# # Get an authorization for this
# auth = self.gh.authorize(
# user, pw, ['user', 'repo', 'gist'], 'github-cli',
# 'http://git.io/MEmEmw'
# )
# parser.add_section('github')
# parser.set('github', 'token', auth.token)
# self.gh.login(token=auth.token)
# # Create the file if it doesn't exist. Otherwise completely blank
# # out what was there before. Kind of dangerous and destructive but
# # somewhat necessary
# parser.write(open(config, 'w+'))
#
# def help(self):
# self.parser.print_help()
# if self.subcommands:
# print('\nSubcommands:')
# for command in sorted(self.subcommands.keys()):
# print(' {0}:\n\t{1}'.format(
# command, self.subcommands[command]
# ))
# sys.exit(0)
#
# Path: gh/util.py
# def get_issue_number(args, parser, error):
# if not args:
# print(error, file=sys.stderr)
# return None
#
# number = trim_numbers(args[0])
# if not number.isdigit():
# print('A valid integer is required', file=sys.stderr)
# return None
#
# return number
#
# Path: gh/util.py
# def mktmpfile(prefix='gh-'):
# return NamedTemporaryFile(prefix=prefix, delete=False)
#
# def rmtmpfile(name):
# if name:
# os.remove(name)
. Output only the next line. | number = get_issue_number( |
Given the code snippet: <|code_start|>
class IssueCloseCommand(Command):
name = 'issue.close'
usage = '%prog [options] issue.close [#]number'
summary = 'Close an issue'
subcommands = {}
def run(self, options, args):
self.get_repo(options)
opts, args = self.parser.parse_args(args)
if opts.help:
self.help()
<|code_end|>
, generate the next line using the imports in this file:
from gh.base import Command
from gh.util import get_issue_number
and context (functions, classes, or occasionally code) from other files:
# Path: gh/base.py
# class Command(object):
# __metaclass__ = ABCMeta
# name = None
# usage = None
# repository = ()
# user = ''
# subcommands = {}
# SUCCESS = 0
# FAILURE = 1
# COMMAND_UNKNOWN = 127
#
# def __init__(self):
# super(Command, self).__init__()
# assert self.name
# commands[self.name] = self
# self.gh = GitHub()
# self.gh.set_user_agent('github-cli/{0} (http://git.io/MEmEmw)'.format(
# __version__
# ))
# self.parser = CustomOptionParser(usage=self.usage)
#
# @abstractmethod
# def run(self, options, args):
# return self.FAILURE
#
# def get_repo(self, options):
# self.repo = None
# if self.repository:
# self.repo = self.gh.repository(*self.repository)
#
# if not (self.repo or options.loc_aware):
# self.parser.error('A repository is required.')
#
# def get_user(self):
# if not self.user:
# self.login()
# self.user = self.gh.user()
#
# def login(self):
# # Get the full path to the configuration file
# config = github_config()
# parser = ConfigParser()
#
# # Check to make sure the file exists and we are allowed to read it
# if os.path.isfile(config) and os.access(config, os.R_OK | os.W_OK):
# parser.readfp(open(config))
# self.gh.login(token=parser.get('github', 'token'))
# else:
# # Either the file didn't exist or we didn't have the correct
# # permissions
# user = ''
# while not user:
# # We will not stop until we are given a username
# user = input('Username: ')
#
# self.user = user
#
# pw = ''
# while not pw:
# # Nor will we stop until we're given a password
# pw = getpass('Password: ')
#
# # Get an authorization for this
# auth = self.gh.authorize(
# user, pw, ['user', 'repo', 'gist'], 'github-cli',
# 'http://git.io/MEmEmw'
# )
# parser.add_section('github')
# parser.set('github', 'token', auth.token)
# self.gh.login(token=auth.token)
# # Create the file if it doesn't exist. Otherwise completely blank
# # out what was there before. Kind of dangerous and destructive but
# # somewhat necessary
# parser.write(open(config, 'w+'))
#
# def help(self):
# self.parser.print_help()
# if self.subcommands:
# print('\nSubcommands:')
# for command in sorted(self.subcommands.keys()):
# print(' {0}:\n\t{1}'.format(
# command, self.subcommands[command]
# ))
# sys.exit(0)
#
# Path: gh/util.py
# def get_issue_number(args, parser, error):
# if not args:
# print(error, file=sys.stderr)
# return None
#
# number = trim_numbers(args[0])
# if not number.isdigit():
# print('A valid integer is required', file=sys.stderr)
# return None
#
# return number
. Output only the next line. | number = get_issue_number( |
Given snippet: <|code_start|> def __init__(self):
super(IssueCommentsCommand, self).__init__()
add = self.parser.add_option
add('-n', '--number',
dest='number',
help='Number of comments to list',
default=-1,
type='int',
)
def run(self, options, args):
self.get_repo(options)
opts, args = self.parser.parse_args(args)
if opts.help:
self.help()
number = get_issue_number(
args, self.parser, 'issue.comments requires a valid issue number'
)
if number is None:
return self.FAILURE
return self.print_comments(number, opts)
def format_comment(self, comment):
fs = '@{uline}{u.login}{default} -- {date}\n{body}\n'
body = wrap(comment.body_text)
date = comment.created_at.strftime('%Y-%m-%d %H:%M:%S')
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from gh.base import Command
from gh.util import tc, wrap, trim_numbers, get_issue_number
and context:
# Path: gh/base.py
# class Command(object):
# __metaclass__ = ABCMeta
# name = None
# usage = None
# repository = ()
# user = ''
# subcommands = {}
# SUCCESS = 0
# FAILURE = 1
# COMMAND_UNKNOWN = 127
#
# def __init__(self):
# super(Command, self).__init__()
# assert self.name
# commands[self.name] = self
# self.gh = GitHub()
# self.gh.set_user_agent('github-cli/{0} (http://git.io/MEmEmw)'.format(
# __version__
# ))
# self.parser = CustomOptionParser(usage=self.usage)
#
# @abstractmethod
# def run(self, options, args):
# return self.FAILURE
#
# def get_repo(self, options):
# self.repo = None
# if self.repository:
# self.repo = self.gh.repository(*self.repository)
#
# if not (self.repo or options.loc_aware):
# self.parser.error('A repository is required.')
#
# def get_user(self):
# if not self.user:
# self.login()
# self.user = self.gh.user()
#
# def login(self):
# # Get the full path to the configuration file
# config = github_config()
# parser = ConfigParser()
#
# # Check to make sure the file exists and we are allowed to read it
# if os.path.isfile(config) and os.access(config, os.R_OK | os.W_OK):
# parser.readfp(open(config))
# self.gh.login(token=parser.get('github', 'token'))
# else:
# # Either the file didn't exist or we didn't have the correct
# # permissions
# user = ''
# while not user:
# # We will not stop until we are given a username
# user = input('Username: ')
#
# self.user = user
#
# pw = ''
# while not pw:
# # Nor will we stop until we're given a password
# pw = getpass('Password: ')
#
# # Get an authorization for this
# auth = self.gh.authorize(
# user, pw, ['user', 'repo', 'gist'], 'github-cli',
# 'http://git.io/MEmEmw'
# )
# parser.add_section('github')
# parser.set('github', 'token', auth.token)
# self.gh.login(token=auth.token)
# # Create the file if it doesn't exist. Otherwise completely blank
# # out what was there before. Kind of dangerous and destructive but
# # somewhat necessary
# parser.write(open(config, 'w+'))
#
# def help(self):
# self.parser.print_help()
# if self.subcommands:
# print('\nSubcommands:')
# for command in sorted(self.subcommands.keys()):
# print(' {0}:\n\t{1}'.format(
# command, self.subcommands[command]
# ))
# sys.exit(0)
#
# Path: gh/util.py
# def get_repository_tuple():
# def find_git_config():
# def github_config():
# def trim_numbers(number):
# def read_stdin():
# def mktmpfile(prefix='gh-'):
# def rmtmpfile(name):
# def wrap(text):
# def get_issue_number(args, parser, error):
which might include code, classes, or functions. Output only the next line. | return fs.format(u=comment.user, uline=tc['underline'], |
Here is a snippet: <|code_start|> subcommands = {}
def __init__(self):
super(IssueCommentsCommand, self).__init__()
add = self.parser.add_option
add('-n', '--number',
dest='number',
help='Number of comments to list',
default=-1,
type='int',
)
def run(self, options, args):
self.get_repo(options)
opts, args = self.parser.parse_args(args)
if opts.help:
self.help()
number = get_issue_number(
args, self.parser, 'issue.comments requires a valid issue number'
)
if number is None:
return self.FAILURE
return self.print_comments(number, opts)
def format_comment(self, comment):
fs = '@{uline}{u.login}{default} -- {date}\n{body}\n'
<|code_end|>
. Write the next line using the current file imports:
from gh.base import Command
from gh.util import tc, wrap, trim_numbers, get_issue_number
and context from other files:
# Path: gh/base.py
# class Command(object):
# __metaclass__ = ABCMeta
# name = None
# usage = None
# repository = ()
# user = ''
# subcommands = {}
# SUCCESS = 0
# FAILURE = 1
# COMMAND_UNKNOWN = 127
#
# def __init__(self):
# super(Command, self).__init__()
# assert self.name
# commands[self.name] = self
# self.gh = GitHub()
# self.gh.set_user_agent('github-cli/{0} (http://git.io/MEmEmw)'.format(
# __version__
# ))
# self.parser = CustomOptionParser(usage=self.usage)
#
# @abstractmethod
# def run(self, options, args):
# return self.FAILURE
#
# def get_repo(self, options):
# self.repo = None
# if self.repository:
# self.repo = self.gh.repository(*self.repository)
#
# if not (self.repo or options.loc_aware):
# self.parser.error('A repository is required.')
#
# def get_user(self):
# if not self.user:
# self.login()
# self.user = self.gh.user()
#
# def login(self):
# # Get the full path to the configuration file
# config = github_config()
# parser = ConfigParser()
#
# # Check to make sure the file exists and we are allowed to read it
# if os.path.isfile(config) and os.access(config, os.R_OK | os.W_OK):
# parser.readfp(open(config))
# self.gh.login(token=parser.get('github', 'token'))
# else:
# # Either the file didn't exist or we didn't have the correct
# # permissions
# user = ''
# while not user:
# # We will not stop until we are given a username
# user = input('Username: ')
#
# self.user = user
#
# pw = ''
# while not pw:
# # Nor will we stop until we're given a password
# pw = getpass('Password: ')
#
# # Get an authorization for this
# auth = self.gh.authorize(
# user, pw, ['user', 'repo', 'gist'], 'github-cli',
# 'http://git.io/MEmEmw'
# )
# parser.add_section('github')
# parser.set('github', 'token', auth.token)
# self.gh.login(token=auth.token)
# # Create the file if it doesn't exist. Otherwise completely blank
# # out what was there before. Kind of dangerous and destructive but
# # somewhat necessary
# parser.write(open(config, 'w+'))
#
# def help(self):
# self.parser.print_help()
# if self.subcommands:
# print('\nSubcommands:')
# for command in sorted(self.subcommands.keys()):
# print(' {0}:\n\t{1}'.format(
# command, self.subcommands[command]
# ))
# sys.exit(0)
#
# Path: gh/util.py
# def get_repository_tuple():
# def find_git_config():
# def github_config():
# def trim_numbers(number):
# def read_stdin():
# def mktmpfile(prefix='gh-'):
# def rmtmpfile(name):
# def wrap(text):
# def get_issue_number(args, parser, error):
, which may include functions, classes, or code. Output only the next line. | body = wrap(comment.body_text) |
Continue the code snippet: <|code_start|>
class IssueCommentsCommand(Command):
name = 'issue.comments'
usage = '%prog [options] issue.comments [#]number'
summary = 'Print the comments for an issue'
subcommands = {}
def __init__(self):
super(IssueCommentsCommand, self).__init__()
add = self.parser.add_option
add('-n', '--number',
dest='number',
help='Number of comments to list',
default=-1,
type='int',
)
def run(self, options, args):
self.get_repo(options)
opts, args = self.parser.parse_args(args)
if opts.help:
self.help()
<|code_end|>
. Use current file imports:
from gh.base import Command
from gh.util import tc, wrap, trim_numbers, get_issue_number
and context (classes, functions, or code) from other files:
# Path: gh/base.py
# class Command(object):
# __metaclass__ = ABCMeta
# name = None
# usage = None
# repository = ()
# user = ''
# subcommands = {}
# SUCCESS = 0
# FAILURE = 1
# COMMAND_UNKNOWN = 127
#
# def __init__(self):
# super(Command, self).__init__()
# assert self.name
# commands[self.name] = self
# self.gh = GitHub()
# self.gh.set_user_agent('github-cli/{0} (http://git.io/MEmEmw)'.format(
# __version__
# ))
# self.parser = CustomOptionParser(usage=self.usage)
#
# @abstractmethod
# def run(self, options, args):
# return self.FAILURE
#
# def get_repo(self, options):
# self.repo = None
# if self.repository:
# self.repo = self.gh.repository(*self.repository)
#
# if not (self.repo or options.loc_aware):
# self.parser.error('A repository is required.')
#
# def get_user(self):
# if not self.user:
# self.login()
# self.user = self.gh.user()
#
# def login(self):
# # Get the full path to the configuration file
# config = github_config()
# parser = ConfigParser()
#
# # Check to make sure the file exists and we are allowed to read it
# if os.path.isfile(config) and os.access(config, os.R_OK | os.W_OK):
# parser.readfp(open(config))
# self.gh.login(token=parser.get('github', 'token'))
# else:
# # Either the file didn't exist or we didn't have the correct
# # permissions
# user = ''
# while not user:
# # We will not stop until we are given a username
# user = input('Username: ')
#
# self.user = user
#
# pw = ''
# while not pw:
# # Nor will we stop until we're given a password
# pw = getpass('Password: ')
#
# # Get an authorization for this
# auth = self.gh.authorize(
# user, pw, ['user', 'repo', 'gist'], 'github-cli',
# 'http://git.io/MEmEmw'
# )
# parser.add_section('github')
# parser.set('github', 'token', auth.token)
# self.gh.login(token=auth.token)
# # Create the file if it doesn't exist. Otherwise completely blank
# # out what was there before. Kind of dangerous and destructive but
# # somewhat necessary
# parser.write(open(config, 'w+'))
#
# def help(self):
# self.parser.print_help()
# if self.subcommands:
# print('\nSubcommands:')
# for command in sorted(self.subcommands.keys()):
# print(' {0}:\n\t{1}'.format(
# command, self.subcommands[command]
# ))
# sys.exit(0)
#
# Path: gh/util.py
# def get_repository_tuple():
# def find_git_config():
# def github_config():
# def trim_numbers(number):
# def read_stdin():
# def mktmpfile(prefix='gh-'):
# def rmtmpfile(name):
# def wrap(text):
# def get_issue_number(args, parser, error):
. Output only the next line. | number = get_issue_number( |
Predict the next line after this snippet: <|code_start|>class MiasmEngine(Engine):
"""Engine based on Miasm"""
def __init__(self, machine, jit_engine):
jitter = machine.jitter(jit_engine)
jitter.set_breakpoint(END_ADDR, MiasmEngine._code_sentinelle)
self.jitter = jitter
# Signal handling
#
# Due to Python signal handling implementation, signals aren't handled
# nor passed to Jitted code in case of registration with signal API
if jit_engine == "python":
signal.signal(signal.SIGALRM, MiasmEngine._timeout)
elif jit_engine in ["llvm", "tcc", "gcc"]:
self.jitter.vm.set_alarm()
else:
raise ValueError("Unknown engine: %s" % jit_engine)
super(MiasmEngine, self).__init__(machine)
@staticmethod
def _code_sentinelle(jitter):
jitter.run = False
jitter.pc = 0
return True
@staticmethod
def _timeout(signum, frame):
<|code_end|>
using the current file's imports:
import signal
from sibyl.engine.engine import Engine
from sibyl.commons import TimeoutException, END_ADDR
and any relevant context from other files:
# Path: sibyl/engine/engine.py
# class Engine(object):
# """Wrapper on execution engine"""
#
# def __init__(self, machine):
# """Instanciate an Engine
# @machine: miasm2.analysis.machine:Machine instance"""
# self.logger = init_logger(self.__class__.__name__)
#
# def take_snapshot(self):
# self.vm_mem = self.jitter.vm.get_all_memory()
# self.vm_regs = self.jitter.cpu.get_gpreg()
#
# def restore_snapshot(self, memory=True):
# raise NotImplementedError("Abstract method")
#
# def run(self, address, timeout_seconds):
# raise NotImplementedError("Abstract method")
#
# def prepare_run(self):
# pass
#
# def restore_snapshot(self, memory=True):
# raise NotImplementedError("Abstract method")
#
# Path: sibyl/commons.py
# class TimeoutException(Exception):
# """Exception to be called on timeouts"""
# pass
#
# END_ADDR = 0x1337babe
. Output only the next line. | raise TimeoutException() |
Here is a snippet: <|code_start|>
class MiasmEngine(Engine):
"""Engine based on Miasm"""
def __init__(self, machine, jit_engine):
jitter = machine.jitter(jit_engine)
<|code_end|>
. Write the next line using the current file imports:
import signal
from sibyl.engine.engine import Engine
from sibyl.commons import TimeoutException, END_ADDR
and context from other files:
# Path: sibyl/engine/engine.py
# class Engine(object):
# """Wrapper on execution engine"""
#
# def __init__(self, machine):
# """Instanciate an Engine
# @machine: miasm2.analysis.machine:Machine instance"""
# self.logger = init_logger(self.__class__.__name__)
#
# def take_snapshot(self):
# self.vm_mem = self.jitter.vm.get_all_memory()
# self.vm_regs = self.jitter.cpu.get_gpreg()
#
# def restore_snapshot(self, memory=True):
# raise NotImplementedError("Abstract method")
#
# def run(self, address, timeout_seconds):
# raise NotImplementedError("Abstract method")
#
# def prepare_run(self):
# pass
#
# def restore_snapshot(self, memory=True):
# raise NotImplementedError("Abstract method")
#
# Path: sibyl/commons.py
# class TimeoutException(Exception):
# """Exception to be called on timeouts"""
# pass
#
# END_ADDR = 0x1337babe
, which may include functions, classes, or code. Output only the next line. | jitter.set_breakpoint(END_ADDR, MiasmEngine._code_sentinelle) |
Based on the snippet: <|code_start|> my_string = "Hello, w%srld !"
def init(self):
self.my_addr = self._alloc_string(self.my_string)
self._add_arg(0, self.my_addr)
def check(self):
result = self._get_result()
if result != len(self.my_string):
return False
return self._ensure_mem(self.my_addr, self.my_string + "\x00")
# Test2
def init2(self):
self.my_addr = self._alloc_string(self.my_string * 4)
self._add_arg(0, self.my_addr)
def check2(self):
result = self._get_result()
if result != len(self.my_string * 4):
return False
return self._ensure_mem(self.my_addr, self.my_string * 4 + "\x00")
# Properties
func = "strlen"
<|code_end|>
, predict the immediate next line with the help of imports:
from sibyl.test.test import Test, TestSetTest
and context (classes, functions, sometimes code) from other files:
# Path: sibyl/test/test.py
# class Test(object):
# "Main class for tests"
#
# # Elements to override
#
# func = "" # Possible function if test passes
# tests = [] # List of tests (init, check) to pass
# reset_mem = True # Reset memory between tests
#
# def init(self):
# "Called for setting up the test case"
# pass
#
# def check(self):
# """Called to check test result
# Return True if all checks are passed"""
# return True
#
# def reset_full(self):
# """Reset the test case between two functions"""
# self.alloc_pool = 0x20000000
#
# def reset(self):
# """Reset the test case between two subtests"""
# self.reset_full()
#
# # Utils
#
# def __init__(self, jitter, abi):
# self.jitter = jitter
# self.alloc_pool = 0x20000000
# self.abi = abi
#
# def _reserv_mem(self, size, read=True, write=False):
# right = 0
# if read:
# right |= PAGE_READ
# if write:
# right |= PAGE_WRITE
#
# # Memory alignement
# size += 16 - size % 16
#
# to_ret = self.alloc_pool
# self.alloc_pool += size + 1
#
# return to_ret
#
# def __alloc_mem(self, mem, read=True, write=False):
# right = 0
# if read:
# right |= PAGE_READ
# if write:
# right |= PAGE_WRITE
#
# # Memory alignement
# mem += "".join([chr(random.randint(0, 255)) \
# for _ in xrange((16 - len(mem) % 16))])
#
# self.jitter.vm.add_memory_page(self.alloc_pool, right, mem)
# to_ret = self.alloc_pool
# self.alloc_pool += len(mem) + 1
#
# return to_ret
#
# def _alloc_mem(self, size, read=True, write=False):
# mem = "".join([chr(random.randint(0, 255)) for _ in xrange(size)])
# return self.__alloc_mem(mem, read=read, write=write)
#
# def _alloc_string(self, string, read=True, write=False):
# return self.__alloc_mem(string + "\x00", read=read, write=write)
#
# def _alloc_pointer(self, pointer, read=True, write=False):
# pointer_size = self.abi.ira.sizeof_pointer()
# return self.__alloc_mem(Test.pack(pointer, pointer_size),
# read=read,
# write=write)
#
# def _write_mem(self, addr, element):
# self.jitter.vm.set_mem(addr, element)
#
# def _write_string(self, addr, element):
# self._write_mem(addr, element + "\x00")
#
# def _add_arg(self, number, element):
# self.abi.add_arg(number, element)
#
# def _get_result(self):
# return self.abi.get_result()
#
# def _ensure_mem(self, addr, element):
# try:
# return self.jitter.vm.get_mem(addr, len(element)) == element
# except RuntimeError:
# return False
#
# def _ensure_mem_sparse(self, addr, element, offsets):
# """@offsets: offsets to ignore"""
# for i, sub_element in enumerate(element):
# if i in offsets:
# continue
# if not self._ensure_mem(addr + i, sub_element):
# return False
# return True
#
# def _as_int(self, element):
# int_size = self.abi.ira.sizeof_int()
# max_val = 2**int_size
# return (element + max_val) % max_val
#
# def _to_int(self, element):
# int_size = self.abi.ira.sizeof_int()
# return mod_size2int[int_size](element)
#
# def _memread_pointer(self, addr):
# pointer_size = self.abi.ira.sizeof_pointer() / 8
# try:
# element = self.jitter.vm.get_mem(addr, pointer_size)
# except RuntimeError:
# return False
# return Test.unpack(element)
#
# @staticmethod
# def pack(element, size):
# out = ""
# while element != 0:
# out += chr(element % 0x100)
# element >>= 8
# if len(out) > size / 8:
# raise ValueError("To big to be packed")
# out = out + "\x00" * ((size / 8) - len(out))
# return out
#
# @staticmethod
# def unpack(element):
# return int(element[::-1].encode("hex"), 16)
#
# class TestSetTest(TestSet):
# """Terminal node of TestSet
#
# Stand for a check in a test case
#
# init: initialization function, called before launching the target address
# check: checking function, verifying the final state
# """
#
# def __init__(self, init, check):
# super(TestSetTest, self).__init__()
# self._init = init
# self._check = check
#
# def __repr__(self):
# return "<TST %r,%r>" % (self._init, self._check)
#
# def execute(self, callback):
# return callback(self._init, self._check)
. Output only the next line. | tests = TestSetTest(init, check) & TestSetTest(init2, check2) |
Predict the next line after this snippet: <|code_start|> script_name = os.path.basename(config.ghidra_export_function)
run = subprocess.Popen(
[
ghidra_headless_path, tmp_project_location, "fakeproj",
"-import", func_heur.filename,
"-preScript", script_name,
"-scriptPath", script_path,
"-scriptlog", tmp_log.name,
],
env=env,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
run.communicate()
# Get back addresses
tmp_log.seek(0)
addresses = {}
for line in tmp_log:
info = re.findall(script_name + "> 0x([0-9a-f]+)", line)
if info:
addresses[int(info[0], 16)] = 1
# Clean-up
tmp_log.close()
shutil.rmtree(tmp_project_location)
return addresses
<|code_end|>
using the current file's imports:
import logging
import re
import tempfile
import subprocess
import shutil
import os
import sibyl.heuristics.csts as csts
from miasm2.core.asmblock import AsmBlockBad, log_asmblock
from sibyl.heuristics.heuristic import Heuristic
from sibyl.config import config
and any relevant context from other files:
# Path: sibyl/heuristics/heuristic.py
# class Heuristic(object):
# """Main class for heuristics, handle common methods related to them"""
#
# # Enabled passes
# # passes are functions taking 'self' and returning a dict:
# # candidates -> estimated probability
# heuristics = []
#
# def __init__(self):
# self._votes = None
#
# def do_votes(self):
# """Call heuristics and get back votes
# Use a cumulative linear strategy for comparison
# """
# votes = {}
# for heuristic in self.heuristics:
# for name, vote in heuristic(self).iteritems():
# votes[name] = votes.get(name, 0) + vote
# self._votes = votes
#
# @property
# def votes(self):
# """Cumulative votes for each candidates"""
# if not self._votes:
# self.do_votes()
# return self._votes
#
# @property
# def heuristic_names(self):
# """Return the list of available heuristics"""
# return [func.__name__ for func in self.heuristics]
#
# def name2heuristic(self, name):
# """Return the heuristic named @name"""
# for func in self.heuristics:
# if func.__name__ == name:
# return func
# else:
# raise KeyError("Unable to find %s" % name)
#
# def guess(self):
# """Return the best candidate"""
# sorted_votes = sorted(self.votes.iteritems(), key=lambda x:x[1])
# if not sorted_votes:
# # No solution
# return False
# best, _ = sorted_votes[-1]
# return best
#
# Path: sibyl/config.py
# class Config(object):
# def __init__(self, default_config, files):
# def expandpath(path):
# def parse_files(self, files):
# def dump(self):
# def jit_engine(self):
# def available_tests(self):
# def miasm_engine(self):
# def pin_root(self):
# def pin_tracer(self):
# def prune_strategy(self):
# def prune_keep(self):
# def prune_keep_max(self):
# def stubs(self):
# def idaq64_path(self):
# def ghidra_headless_path(self):
# def ghidra_export_function(self):
. Output only the next line. | class FuncHeuristic(Heuristic): |
Predict the next line for this snippet: <|code_start|>
# Search for function prologs
pattern = "(" + ")|(".join(prologs) + ")"
for find_iter, vaddr_base in _virt_find(data, pattern):
for match in find_iter:
addr = match.start() + vaddr_base
addresses[addr] = 1
return addresses
def named_symbols(func_heur):
"""Return the addresses of named symbols"""
cont = func_heur.cont
loc_db = cont.loc_db
# Use the entry point
addresses = [cont.entry_point]
# Add address of symbol with a name (like 'main')
addresses += [loc_db.get_location_offset(loc)
for loc in loc_db.loc_keys
if loc_db.get_location_names(loc) is not None]
return {addr: 1 for addr in addresses}
def ida_funcs(func_heur):
"""Use IDA heuristics to find functions"""
<|code_end|>
with the help of current file imports:
import logging
import re
import tempfile
import subprocess
import shutil
import os
import sibyl.heuristics.csts as csts
from miasm2.core.asmblock import AsmBlockBad, log_asmblock
from sibyl.heuristics.heuristic import Heuristic
from sibyl.config import config
and context from other files:
# Path: sibyl/heuristics/heuristic.py
# class Heuristic(object):
# """Main class for heuristics, handle common methods related to them"""
#
# # Enabled passes
# # passes are functions taking 'self' and returning a dict:
# # candidates -> estimated probability
# heuristics = []
#
# def __init__(self):
# self._votes = None
#
# def do_votes(self):
# """Call heuristics and get back votes
# Use a cumulative linear strategy for comparison
# """
# votes = {}
# for heuristic in self.heuristics:
# for name, vote in heuristic(self).iteritems():
# votes[name] = votes.get(name, 0) + vote
# self._votes = votes
#
# @property
# def votes(self):
# """Cumulative votes for each candidates"""
# if not self._votes:
# self.do_votes()
# return self._votes
#
# @property
# def heuristic_names(self):
# """Return the list of available heuristics"""
# return [func.__name__ for func in self.heuristics]
#
# def name2heuristic(self, name):
# """Return the heuristic named @name"""
# for func in self.heuristics:
# if func.__name__ == name:
# return func
# else:
# raise KeyError("Unable to find %s" % name)
#
# def guess(self):
# """Return the best candidate"""
# sorted_votes = sorted(self.votes.iteritems(), key=lambda x:x[1])
# if not sorted_votes:
# # No solution
# return False
# best, _ = sorted_votes[-1]
# return best
#
# Path: sibyl/config.py
# class Config(object):
# def __init__(self, default_config, files):
# def expandpath(path):
# def parse_files(self, files):
# def dump(self):
# def jit_engine(self):
# def available_tests(self):
# def miasm_engine(self):
# def pin_root(self):
# def pin_tracer(self):
# def prune_strategy(self):
# def prune_keep(self):
# def prune_keep_max(self):
# def stubs(self):
# def idaq64_path(self):
# def ghidra_headless_path(self):
# def ghidra_export_function(self):
, which may contain function names, class names, or code. Output only the next line. | idaq64_path = config.idaq64_path |
Using the snippet: <|code_start|> '''Compare the expected result with the real one to determine if the function is recognize or not'''
func_found = True
for reg, value in self.snapshot.output_reg.iteritems():
if value != getattr(jitter.cpu, reg):
self.replayexception += ["output register %s wrong : %i expected, %i found" % (reg, value, getattr(jitter.cpu, reg))]
func_found = False
for addr, mem in self.snapshot.out_memory.iteritems():
self.logger.debug("Check @%s, %s bytes: %r", hex(addr), hex(mem.size), mem.data[:0x10])
if mem.data != jitter.vm.get_mem(addr, mem.size):
self.replayexception += ["output memory wrong at 0x%x: %s expected, %s found" % (addr + offset, repr(mem.data), repr(jitter.vm.get_mem(addr + offset, mem.size)))]
func_found = False
return func_found
def end_func(self, jitter):
if jitter.vm.is_mapped(getattr(jitter.cpu, self.ira.ret_reg.name), 1):
self.replayexception += ["return value might be a pointer"]
self.isFuncFound = self.compare_snapshot(jitter)
jitter.run = False
return False
def run(self):
'''Main function that is in charge of running the test and return the result:
true if the snapshot has recognized the function, false else.'''
# Retrieve miasm tools
<|code_end|>
, determine the next line of code. You have imports:
import struct
from miasm2.jitter.loader.elf import vm_load_elf
from miasm2.analysis.machine import Machine
from miasm2.jitter.csts import PAGE_READ, PAGE_WRITE, EXCEPT_ACCESS_VIOL, EXCEPT_DIV_BY_ZERO, EXCEPT_PRIV_INSN
from sibyl.config import config
and context (class names, function names, or code) available:
# Path: sibyl/config.py
# class Config(object):
# def __init__(self, default_config, files):
# def expandpath(path):
# def parse_files(self, files):
# def dump(self):
# def jit_engine(self):
# def available_tests(self):
# def miasm_engine(self):
# def pin_root(self):
# def pin_tracer(self):
# def prune_strategy(self):
# def prune_keep(self):
# def prune_keep_max(self):
# def stubs(self):
# def idaq64_path(self):
# def ghidra_headless_path(self):
# def ghidra_export_function(self):
. Output only the next line. | jitter = self.machine.jitter(config.miasm_engine) |
Predict the next line for this snippet: <|code_start|> def compare_snapshot(self, jitter):
'''Compare the expected result with the real one to determine if the function is recognize or not'''
func_found = True
for reg, value in self.snapshot.output_reg.iteritems():
if value != getattr(jitter.cpu, reg):
self.replayexception += ["output register %s wrong : %i expected, %i found" % (reg, value, getattr(jitter.cpu, reg))]
func_found = False
for addr, mem in self.snapshot.out_memory.iteritems():
self.logger.debug("Check @%s, %s bytes: %r", hex(addr), hex(mem.size), mem.data[:0x10])
if mem.data != jitter.vm.get_mem(addr, mem.size):
self.replayexception += ["output memory wrong at 0x%x: %s expected, %s found" % (addr + offset, repr(mem.data), repr(jitter.vm.get_mem(addr + offset, mem.size)))]
func_found = False
return func_found
def end_func(self, jitter):
if jitter.vm.is_mapped(getattr(jitter.cpu, self.ira.ret_reg.name), 1):
self.replayexception += ["return value might be a pointer"]
self.isFuncFound = self.compare_snapshot(jitter)
jitter.run = False
return False
def is_pointer(self, expr):
"""Return True if expr may be a pointer"""
target_types = self.c_handler.expr_to_types(expr)
<|code_end|>
with the help of current file imports:
import struct
import logging
import miasm2.expression.expression as m2_expr
from miasm2.jitter.loader.elf import vm_load_elf
from miasm2.analysis.machine import Machine
from miasm2.jitter.csts import PAGE_READ, PAGE_WRITE, EXCEPT_ACCESS_VIOL, EXCEPT_DIV_BY_ZERO, EXCEPT_PRIV_INSN
from miasm2.core.bin_stream import bin_stream_vm
from miasm2.analysis.dse import ESETrackModif
from miasm2.ir.ir import AssignBlock
from miasm2.core.objc import CHandler
from sibyl.commons import objc_is_dereferenceable
from sibyl.config import config
and context from other files:
# Path: sibyl/commons.py
# def objc_is_dereferenceable(target_type):
# """Return True if target_type may be used as a pointer
# @target_type: ObjC"""
# return isinstance(target_type, (ObjCPtr, ObjCArray))
#
# Path: sibyl/config.py
# class Config(object):
# def __init__(self, default_config, files):
# def expandpath(path):
# def parse_files(self, files):
# def dump(self):
# def jit_engine(self):
# def available_tests(self):
# def miasm_engine(self):
# def pin_root(self):
# def pin_tracer(self):
# def prune_strategy(self):
# def prune_keep(self):
# def prune_keep_max(self):
# def stubs(self):
# def idaq64_path(self):
# def ghidra_headless_path(self):
# def ghidra_export_function(self):
, which may contain function names, class names, or code. Output only the next line. | return any(objc_is_dereferenceable(target_type) |
Given snippet: <|code_start|> self.symb.symbols = self.symbols_init
for expr in self.memories_read:
# Eval the expression with the *input* state
original_expr = expr.replace_expr(self.init_values)
value = self.symb.eval_expr(original_expr)
assert isinstance(value, m2_expr.ExprInt)
memory_in[expr] = value
self.symb.symbols = saved_symbols
if self.logger.isEnabledFor(logging.DEBUG):
print "In:"
print memory_in
print "Out:"
print memory_out
print "Final value:"
print output_value
self.snapshot.memory_in = AssignBlock(memory_in)
self.snapshot.memory_out = AssignBlock(memory_out)
self.snapshot.output_value = output_value
self.snapshot.c_handler = self.c_handler
self.snapshot.typed_C_ids = self.typed_C_ids
self.snapshot.arguments_symbols = self.args_symbols
self.snapshot.init_values = self.init_values
def run(self):
'''Main function that is in charge of running the test and return the result:
true if the snapshot has recognized the function, false else.'''
# TODO inherit from Replay
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import struct
import logging
import miasm2.expression.expression as m2_expr
from miasm2.jitter.loader.elf import vm_load_elf
from miasm2.analysis.machine import Machine
from miasm2.jitter.csts import PAGE_READ, PAGE_WRITE, EXCEPT_ACCESS_VIOL, EXCEPT_DIV_BY_ZERO, EXCEPT_PRIV_INSN
from miasm2.core.bin_stream import bin_stream_vm
from miasm2.analysis.dse import ESETrackModif
from miasm2.ir.ir import AssignBlock
from miasm2.core.objc import CHandler
from sibyl.commons import objc_is_dereferenceable
from sibyl.config import config
and context:
# Path: sibyl/commons.py
# def objc_is_dereferenceable(target_type):
# """Return True if target_type may be used as a pointer
# @target_type: ObjC"""
# return isinstance(target_type, (ObjCPtr, ObjCArray))
#
# Path: sibyl/config.py
# class Config(object):
# def __init__(self, default_config, files):
# def expandpath(path):
# def parse_files(self, files):
# def dump(self):
# def jit_engine(self):
# def available_tests(self):
# def miasm_engine(self):
# def pin_root(self):
# def pin_tracer(self):
# def prune_strategy(self):
# def prune_keep(self):
# def prune_keep_max(self):
# def stubs(self):
# def idaq64_path(self):
# def ghidra_headless_path(self):
# def ghidra_export_function(self):
which might include code, classes, or functions. Output only the next line. | jitter = self.machine.jitter(config.miasm_engine) |
Based on the snippet: <|code_start|>#
# Sibyl is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Sibyl is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
# License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Sibyl. If not, see <http://www.gnu.org/licenses/>.
class ActionConfig(Action):
"""Configuration management"""
_name_ = "config"
_desc_ = "Configuration management"
_args_ = [
(("-V", "--value"), {"help": "Return the value of a specific option"}),
(("-d", "--dump"), {"help": "Dump the current configuration",
"action": "store_true"}),
]
def run(self):
if self.args.dump:
<|code_end|>
, predict the immediate next line with the help of imports:
import os
from sibyl.config import config, config_paths
from sibyl.actions.action import Action
and context (classes, functions, sometimes code) from other files:
# Path: sibyl/config.py
# class Config(object):
# def __init__(self, default_config, files):
# def expandpath(path):
# def parse_files(self, files):
# def dump(self):
# def jit_engine(self):
# def available_tests(self):
# def miasm_engine(self):
# def pin_root(self):
# def pin_tracer(self):
# def prune_strategy(self):
# def prune_keep(self):
# def prune_keep_max(self):
# def stubs(self):
# def idaq64_path(self):
# def ghidra_headless_path(self):
# def ghidra_export_function(self):
#
# Path: sibyl/actions/action.py
# class Action(object):
#
# "Parent class for actions"
#
# _name_ = ""
# _desc_ = ""
# _args_ = [] # List of (*args, **kwargs)
#
# def __init__(self, command_line):
# # Parse command line
# parser = argparse.ArgumentParser(
# prog="%s %s" % (sys.argv[0], self._name_))
# for args, kwargs in self._args_:
# parser.add_argument(*args, **kwargs)
# self.args = parser.parse_args(command_line)
#
# # Run action
# self.run()
#
# def run(self):
# raise NotImplementedError("Abstract method")
#
# @property
# def name(self):
# """Action name"""
# return self._name_
#
# @property
# def description(self):
# """Action description"""
# return self._desc_
. Output only the next line. | print "\n".join(config.dump()) |
Continue the code snippet: <|code_start|>
class ActionConfig(Action):
"""Configuration management"""
_name_ = "config"
_desc_ = "Configuration management"
_args_ = [
(("-V", "--value"), {"help": "Return the value of a specific option"}),
(("-d", "--dump"), {"help": "Dump the current configuration",
"action": "store_true"}),
]
def run(self):
if self.args.dump:
print "\n".join(config.dump())
elif self.args.value:
if self.args.value.endswith("_keys") and hasattr(config,
self.args.value[:-5]):
val = getattr(config, self.args.value[:-5]).keys()
elif hasattr(config, self.args.value):
val = getattr(config, self.args.value)
else:
val = "ERROR"
print val
else:
self.show()
def show(self):
# Configuration files
<|code_end|>
. Use current file imports:
import os
from sibyl.config import config, config_paths
from sibyl.actions.action import Action
and context (classes, functions, or code) from other files:
# Path: sibyl/config.py
# class Config(object):
# def __init__(self, default_config, files):
# def expandpath(path):
# def parse_files(self, files):
# def dump(self):
# def jit_engine(self):
# def available_tests(self):
# def miasm_engine(self):
# def pin_root(self):
# def pin_tracer(self):
# def prune_strategy(self):
# def prune_keep(self):
# def prune_keep_max(self):
# def stubs(self):
# def idaq64_path(self):
# def ghidra_headless_path(self):
# def ghidra_export_function(self):
#
# Path: sibyl/actions/action.py
# class Action(object):
#
# "Parent class for actions"
#
# _name_ = ""
# _desc_ = ""
# _args_ = [] # List of (*args, **kwargs)
#
# def __init__(self, command_line):
# # Parse command line
# parser = argparse.ArgumentParser(
# prog="%s %s" % (sys.argv[0], self._name_))
# for args, kwargs in self._args_:
# parser.add_argument(*args, **kwargs)
# self.args = parser.parse_args(command_line)
#
# # Run action
# self.run()
#
# def run(self):
# raise NotImplementedError("Abstract method")
#
# @property
# def name(self):
# """Action name"""
# return self._name_
#
# @property
# def description(self):
# """Action description"""
# return self._desc_
. Output only the next line. | files = [fpath for fpath in config_paths if os.path.isfile(fpath)] |
Predict the next line after this snippet: <|code_start|>
class Engine(object):
"""Wrapper on execution engine"""
def __init__(self, machine):
"""Instanciate an Engine
@machine: miasm2.analysis.machine:Machine instance"""
<|code_end|>
using the current file's imports:
from sibyl.commons import init_logger
and any relevant context from other files:
# Path: sibyl/commons.py
# def init_logger(name):
# logger = logging.getLogger(name)
#
# console_handler = logging.StreamHandler()
# log_format = "%(levelname)-5s: %(message)s"
# console_handler.setFormatter(logging.Formatter(log_format))
# logger.addHandler(console_handler)
#
# logger.setLevel(logging.ERROR)
# return logger
. Output only the next line. | self.logger = init_logger(self.__class__.__name__) |
Here is a snippet: <|code_start|># This file is part of Sibyl.
# Copyright 2014 Camille MOUGEY <camille.mougey@cea.fr>
#
# Sibyl is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Sibyl is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
# License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Sibyl. If not, see <http://www.gnu.org/licenses/>.
"""This module provides a way to prepare and launch Sibyl tests on a binary"""
class TestLauncher(object):
"Launch tests for a function and report matching candidates"
def __init__(self, filename, machine, abicls, tests_cls, engine_name,
map_addr=0):
# Logging facilities
<|code_end|>
. Write the next line using the current file imports:
import time
import signal
import logging
from miasm2.analysis.binary import Container, ContainerPE, ContainerELF
from sibyl.commons import init_logger, TimeoutException, END_ADDR
from sibyl.engine import QEMUEngine, MiasmEngine
from sibyl.config import config
from miasm2.jitter.loader.pe import preload_pe, libimp_pe
from miasm2.jitter.loader.elf import preload_elf, libimp_elf
and context from other files:
# Path: sibyl/commons.py
# def init_logger(name):
# logger = logging.getLogger(name)
#
# console_handler = logging.StreamHandler()
# log_format = "%(levelname)-5s: %(message)s"
# console_handler.setFormatter(logging.Formatter(log_format))
# logger.addHandler(console_handler)
#
# logger.setLevel(logging.ERROR)
# return logger
#
# class TimeoutException(Exception):
# """Exception to be called on timeouts"""
# pass
#
# END_ADDR = 0x1337babe
#
# Path: sibyl/engine/qemu.py
# class QEMUEngine(Engine):
# """Engine based on QEMU, using unicorn as a wrapper"""
#
# def __init__(self, machine):
# if unicorn is None:
# raise ImportError("QEMU engine unavailable: 'unicorn' import error")
#
# self.jitter = UcWrapJitter(machine)
# super(QEMUEngine, self).__init__(machine)
#
#
# def run(self, address, timeout_seconds):
# try:
# self.jitter.run(address, timeout_seconds)
# except UnexpectedStopException as _:
# return False
# except Exception as error:
# self.logger.exception(error)
# return False
#
# return True
#
# def prepare_run(self):
# # XXX HACK: Avoid a slow down of unicorn (apparently to too many
# # threads...)
# self.jitter.renew()
#
# def restore_snapshot(self, memory=True):
# # Restore VM
# if memory:
# self.jitter.vm.restore_mem_state(self.vm_mem)
#
# # Restore registers
# self.jitter.cpu.set_gpreg(self.vm_regs)
#
# Path: sibyl/engine/miasm.py
# class MiasmEngine(Engine):
# """Engine based on Miasm"""
#
# def __init__(self, machine, jit_engine):
# jitter = machine.jitter(jit_engine)
# jitter.set_breakpoint(END_ADDR, MiasmEngine._code_sentinelle)
# self.jitter = jitter
#
# # Signal handling
# #
# # Due to Python signal handling implementation, signals aren't handled
# # nor passed to Jitted code in case of registration with signal API
# if jit_engine == "python":
# signal.signal(signal.SIGALRM, MiasmEngine._timeout)
# elif jit_engine in ["llvm", "tcc", "gcc"]:
# self.jitter.vm.set_alarm()
# else:
# raise ValueError("Unknown engine: %s" % jit_engine)
#
# super(MiasmEngine, self).__init__(machine)
#
#
# @staticmethod
# def _code_sentinelle(jitter):
# jitter.run = False
# jitter.pc = 0
# return True
#
# @staticmethod
# def _timeout(signum, frame):
# raise TimeoutException()
#
# def run(self, address, timeout_seconds):
# self.jitter.init_run(address)
#
# try:
# signal.alarm(timeout_seconds)
# self.jitter.continue_run()
# except (AssertionError, RuntimeError, ValueError,
# KeyError, IndexError, TimeoutException) as _:
# return False
# except Exception as error:
# self.logger.exception(error)
# return False
# finally:
# signal.alarm(0)
#
# return True
#
# def restore_snapshot(self, memory=True):
# # Restore memory
# if memory:
# self.jitter.vm.reset_memory_page_pool()
# self.jitter.vm.reset_code_bloc_pool()
# for addr, metadata in self.vm_mem.iteritems():
# self.jitter.vm.add_memory_page(addr,
# metadata["access"],
# metadata["data"])
#
# # Restore registers
# self.jitter.cpu.init_regs()
# self.jitter.cpu.set_gpreg(self.vm_regs)
#
# # Reset intern elements
# self.jitter.vm.set_exception(0)
# self.jitter.cpu.set_exception(0)
# self.jitter.bs._atomic_mode = False
#
# Path: sibyl/config.py
# class Config(object):
# def __init__(self, default_config, files):
# def expandpath(path):
# def parse_files(self, files):
# def dump(self):
# def jit_engine(self):
# def available_tests(self):
# def miasm_engine(self):
# def pin_root(self):
# def pin_tracer(self):
# def prune_strategy(self):
# def prune_keep(self):
# def prune_keep_max(self):
# def stubs(self):
# def idaq64_path(self):
# def ghidra_headless_path(self):
# def ghidra_export_function(self):
, which may include functions, classes, or code. Output only the next line. | self.logger = init_logger("testlauncher") |
Predict the next line for this snippet: <|code_start|>
def init_engine(self, engine_name):
if engine_name == "qemu":
self.engine = QEMUEngine(self.machine)
else:
self.engine = MiasmEngine(self.machine, engine_name)
self.jitter = self.engine.jitter
def init_abi(self, abicls):
ira = self.machine.ira()
self.abi = abicls(self.jitter, ira)
def launch_tests(self, test, address, timeout_seconds=0):
# Variables to remind between two "launch_test"
self._temp_reset_mem = True
# Reset between functions
test.reset_full()
# Callback to launch
def launch_test(init, check):
"""Launch a test associated with @init, @check"""
# Reset state
self.engine.restore_snapshot(memory=self._temp_reset_mem)
self.abi.reset()
test.reset()
# Prepare VM
init(test)
<|code_end|>
with the help of current file imports:
import time
import signal
import logging
from miasm2.analysis.binary import Container, ContainerPE, ContainerELF
from sibyl.commons import init_logger, TimeoutException, END_ADDR
from sibyl.engine import QEMUEngine, MiasmEngine
from sibyl.config import config
from miasm2.jitter.loader.pe import preload_pe, libimp_pe
from miasm2.jitter.loader.elf import preload_elf, libimp_elf
and context from other files:
# Path: sibyl/commons.py
# def init_logger(name):
# logger = logging.getLogger(name)
#
# console_handler = logging.StreamHandler()
# log_format = "%(levelname)-5s: %(message)s"
# console_handler.setFormatter(logging.Formatter(log_format))
# logger.addHandler(console_handler)
#
# logger.setLevel(logging.ERROR)
# return logger
#
# class TimeoutException(Exception):
# """Exception to be called on timeouts"""
# pass
#
# END_ADDR = 0x1337babe
#
# Path: sibyl/engine/qemu.py
# class QEMUEngine(Engine):
# """Engine based on QEMU, using unicorn as a wrapper"""
#
# def __init__(self, machine):
# if unicorn is None:
# raise ImportError("QEMU engine unavailable: 'unicorn' import error")
#
# self.jitter = UcWrapJitter(machine)
# super(QEMUEngine, self).__init__(machine)
#
#
# def run(self, address, timeout_seconds):
# try:
# self.jitter.run(address, timeout_seconds)
# except UnexpectedStopException as _:
# return False
# except Exception as error:
# self.logger.exception(error)
# return False
#
# return True
#
# def prepare_run(self):
# # XXX HACK: Avoid a slow down of unicorn (apparently to too many
# # threads...)
# self.jitter.renew()
#
# def restore_snapshot(self, memory=True):
# # Restore VM
# if memory:
# self.jitter.vm.restore_mem_state(self.vm_mem)
#
# # Restore registers
# self.jitter.cpu.set_gpreg(self.vm_regs)
#
# Path: sibyl/engine/miasm.py
# class MiasmEngine(Engine):
# """Engine based on Miasm"""
#
# def __init__(self, machine, jit_engine):
# jitter = machine.jitter(jit_engine)
# jitter.set_breakpoint(END_ADDR, MiasmEngine._code_sentinelle)
# self.jitter = jitter
#
# # Signal handling
# #
# # Due to Python signal handling implementation, signals aren't handled
# # nor passed to Jitted code in case of registration with signal API
# if jit_engine == "python":
# signal.signal(signal.SIGALRM, MiasmEngine._timeout)
# elif jit_engine in ["llvm", "tcc", "gcc"]:
# self.jitter.vm.set_alarm()
# else:
# raise ValueError("Unknown engine: %s" % jit_engine)
#
# super(MiasmEngine, self).__init__(machine)
#
#
# @staticmethod
# def _code_sentinelle(jitter):
# jitter.run = False
# jitter.pc = 0
# return True
#
# @staticmethod
# def _timeout(signum, frame):
# raise TimeoutException()
#
# def run(self, address, timeout_seconds):
# self.jitter.init_run(address)
#
# try:
# signal.alarm(timeout_seconds)
# self.jitter.continue_run()
# except (AssertionError, RuntimeError, ValueError,
# KeyError, IndexError, TimeoutException) as _:
# return False
# except Exception as error:
# self.logger.exception(error)
# return False
# finally:
# signal.alarm(0)
#
# return True
#
# def restore_snapshot(self, memory=True):
# # Restore memory
# if memory:
# self.jitter.vm.reset_memory_page_pool()
# self.jitter.vm.reset_code_bloc_pool()
# for addr, metadata in self.vm_mem.iteritems():
# self.jitter.vm.add_memory_page(addr,
# metadata["access"],
# metadata["data"])
#
# # Restore registers
# self.jitter.cpu.init_regs()
# self.jitter.cpu.set_gpreg(self.vm_regs)
#
# # Reset intern elements
# self.jitter.vm.set_exception(0)
# self.jitter.cpu.set_exception(0)
# self.jitter.bs._atomic_mode = False
#
# Path: sibyl/config.py
# class Config(object):
# def __init__(self, default_config, files):
# def expandpath(path):
# def parse_files(self, files):
# def dump(self):
# def jit_engine(self):
# def available_tests(self):
# def miasm_engine(self):
# def pin_root(self):
# def pin_tracer(self):
# def prune_strategy(self):
# def prune_keep(self):
# def prune_keep_max(self):
# def stubs(self):
# def idaq64_path(self):
# def ghidra_headless_path(self):
# def ghidra_export_function(self):
, which may contain function names, class names, or code. Output only the next line. | self.abi.prepare_call(ret_addr=END_ADDR) |
Given the following code snippet before the placeholder: <|code_start|>
libs = None
if isinstance(self.ctr, ContainerPE):
libs = libimp_pe()
preload_pe(self.jitter.vm, self.ctr.executable, libs)
elif isinstance(self.ctr, ContainerELF):
libs = libimp_elf()
preload_elf(self.jitter.vm, self.ctr.executable, libs)
else:
return
# Add associated breakpoints
self.jitter.add_lib_handler(libs, context)
def initialize_tests(self, tests_cls):
tests = []
for testcls in tests_cls:
tests.append(testcls(self.jitter, self.abi))
self.tests = tests
def load_vm(self, filename, map_addr):
self.ctr = Container.from_stream(open(filename), vm=self.jitter.vm,
addr=map_addr)
self.jitter.cpu.init_regs()
self.jitter.init_stack()
def init_engine(self, engine_name):
if engine_name == "qemu":
<|code_end|>
, predict the next line using imports from the current file:
import time
import signal
import logging
from miasm2.analysis.binary import Container, ContainerPE, ContainerELF
from sibyl.commons import init_logger, TimeoutException, END_ADDR
from sibyl.engine import QEMUEngine, MiasmEngine
from sibyl.config import config
from miasm2.jitter.loader.pe import preload_pe, libimp_pe
from miasm2.jitter.loader.elf import preload_elf, libimp_elf
and context including class names, function names, and sometimes code from other files:
# Path: sibyl/commons.py
# def init_logger(name):
# logger = logging.getLogger(name)
#
# console_handler = logging.StreamHandler()
# log_format = "%(levelname)-5s: %(message)s"
# console_handler.setFormatter(logging.Formatter(log_format))
# logger.addHandler(console_handler)
#
# logger.setLevel(logging.ERROR)
# return logger
#
# class TimeoutException(Exception):
# """Exception to be called on timeouts"""
# pass
#
# END_ADDR = 0x1337babe
#
# Path: sibyl/engine/qemu.py
# class QEMUEngine(Engine):
# """Engine based on QEMU, using unicorn as a wrapper"""
#
# def __init__(self, machine):
# if unicorn is None:
# raise ImportError("QEMU engine unavailable: 'unicorn' import error")
#
# self.jitter = UcWrapJitter(machine)
# super(QEMUEngine, self).__init__(machine)
#
#
# def run(self, address, timeout_seconds):
# try:
# self.jitter.run(address, timeout_seconds)
# except UnexpectedStopException as _:
# return False
# except Exception as error:
# self.logger.exception(error)
# return False
#
# return True
#
# def prepare_run(self):
# # XXX HACK: Avoid a slow down of unicorn (apparently to too many
# # threads...)
# self.jitter.renew()
#
# def restore_snapshot(self, memory=True):
# # Restore VM
# if memory:
# self.jitter.vm.restore_mem_state(self.vm_mem)
#
# # Restore registers
# self.jitter.cpu.set_gpreg(self.vm_regs)
#
# Path: sibyl/engine/miasm.py
# class MiasmEngine(Engine):
# """Engine based on Miasm"""
#
# def __init__(self, machine, jit_engine):
# jitter = machine.jitter(jit_engine)
# jitter.set_breakpoint(END_ADDR, MiasmEngine._code_sentinelle)
# self.jitter = jitter
#
# # Signal handling
# #
# # Due to Python signal handling implementation, signals aren't handled
# # nor passed to Jitted code in case of registration with signal API
# if jit_engine == "python":
# signal.signal(signal.SIGALRM, MiasmEngine._timeout)
# elif jit_engine in ["llvm", "tcc", "gcc"]:
# self.jitter.vm.set_alarm()
# else:
# raise ValueError("Unknown engine: %s" % jit_engine)
#
# super(MiasmEngine, self).__init__(machine)
#
#
# @staticmethod
# def _code_sentinelle(jitter):
# jitter.run = False
# jitter.pc = 0
# return True
#
# @staticmethod
# def _timeout(signum, frame):
# raise TimeoutException()
#
# def run(self, address, timeout_seconds):
# self.jitter.init_run(address)
#
# try:
# signal.alarm(timeout_seconds)
# self.jitter.continue_run()
# except (AssertionError, RuntimeError, ValueError,
# KeyError, IndexError, TimeoutException) as _:
# return False
# except Exception as error:
# self.logger.exception(error)
# return False
# finally:
# signal.alarm(0)
#
# return True
#
# def restore_snapshot(self, memory=True):
# # Restore memory
# if memory:
# self.jitter.vm.reset_memory_page_pool()
# self.jitter.vm.reset_code_bloc_pool()
# for addr, metadata in self.vm_mem.iteritems():
# self.jitter.vm.add_memory_page(addr,
# metadata["access"],
# metadata["data"])
#
# # Restore registers
# self.jitter.cpu.init_regs()
# self.jitter.cpu.set_gpreg(self.vm_regs)
#
# # Reset intern elements
# self.jitter.vm.set_exception(0)
# self.jitter.cpu.set_exception(0)
# self.jitter.bs._atomic_mode = False
#
# Path: sibyl/config.py
# class Config(object):
# def __init__(self, default_config, files):
# def expandpath(path):
# def parse_files(self, files):
# def dump(self):
# def jit_engine(self):
# def available_tests(self):
# def miasm_engine(self):
# def pin_root(self):
# def pin_tracer(self):
# def prune_strategy(self):
# def prune_keep(self):
# def prune_keep_max(self):
# def stubs(self):
# def idaq64_path(self):
# def ghidra_headless_path(self):
# def ghidra_export_function(self):
. Output only the next line. | self.engine = QEMUEngine(self.machine) |
Given the code snippet: <|code_start|>
"""This module provides a way to prepare and launch Sibyl tests on a binary"""
class TestLauncher(object):
"Launch tests for a function and report matching candidates"
def __init__(self, filename, machine, abicls, tests_cls, engine_name,
map_addr=0):
# Logging facilities
self.logger = init_logger("testlauncher")
# Prepare JiT engine
self.machine = machine
self.init_engine(engine_name)
# Init and snapshot VM
self.load_vm(filename, map_addr)
self.init_stub()
self.snapshot = self.engine.take_snapshot()
# Init tests
self.init_abi(abicls)
self.initialize_tests(tests_cls)
def init_stub(self):
"""Initialize stubbing capabilities"""
<|code_end|>
, generate the next line using the imports in this file:
import time
import signal
import logging
from miasm2.analysis.binary import Container, ContainerPE, ContainerELF
from sibyl.commons import init_logger, TimeoutException, END_ADDR
from sibyl.engine import QEMUEngine, MiasmEngine
from sibyl.config import config
from miasm2.jitter.loader.pe import preload_pe, libimp_pe
from miasm2.jitter.loader.elf import preload_elf, libimp_elf
and context (functions, classes, or occasionally code) from other files:
# Path: sibyl/commons.py
# def init_logger(name):
# logger = logging.getLogger(name)
#
# console_handler = logging.StreamHandler()
# log_format = "%(levelname)-5s: %(message)s"
# console_handler.setFormatter(logging.Formatter(log_format))
# logger.addHandler(console_handler)
#
# logger.setLevel(logging.ERROR)
# return logger
#
# class TimeoutException(Exception):
# """Exception to be called on timeouts"""
# pass
#
# END_ADDR = 0x1337babe
#
# Path: sibyl/engine/qemu.py
# class QEMUEngine(Engine):
# """Engine based on QEMU, using unicorn as a wrapper"""
#
# def __init__(self, machine):
# if unicorn is None:
# raise ImportError("QEMU engine unavailable: 'unicorn' import error")
#
# self.jitter = UcWrapJitter(machine)
# super(QEMUEngine, self).__init__(machine)
#
#
# def run(self, address, timeout_seconds):
# try:
# self.jitter.run(address, timeout_seconds)
# except UnexpectedStopException as _:
# return False
# except Exception as error:
# self.logger.exception(error)
# return False
#
# return True
#
# def prepare_run(self):
# # XXX HACK: Avoid a slow down of unicorn (apparently to too many
# # threads...)
# self.jitter.renew()
#
# def restore_snapshot(self, memory=True):
# # Restore VM
# if memory:
# self.jitter.vm.restore_mem_state(self.vm_mem)
#
# # Restore registers
# self.jitter.cpu.set_gpreg(self.vm_regs)
#
# Path: sibyl/engine/miasm.py
# class MiasmEngine(Engine):
# """Engine based on Miasm"""
#
# def __init__(self, machine, jit_engine):
# jitter = machine.jitter(jit_engine)
# jitter.set_breakpoint(END_ADDR, MiasmEngine._code_sentinelle)
# self.jitter = jitter
#
# # Signal handling
# #
# # Due to Python signal handling implementation, signals aren't handled
# # nor passed to Jitted code in case of registration with signal API
# if jit_engine == "python":
# signal.signal(signal.SIGALRM, MiasmEngine._timeout)
# elif jit_engine in ["llvm", "tcc", "gcc"]:
# self.jitter.vm.set_alarm()
# else:
# raise ValueError("Unknown engine: %s" % jit_engine)
#
# super(MiasmEngine, self).__init__(machine)
#
#
# @staticmethod
# def _code_sentinelle(jitter):
# jitter.run = False
# jitter.pc = 0
# return True
#
# @staticmethod
# def _timeout(signum, frame):
# raise TimeoutException()
#
# def run(self, address, timeout_seconds):
# self.jitter.init_run(address)
#
# try:
# signal.alarm(timeout_seconds)
# self.jitter.continue_run()
# except (AssertionError, RuntimeError, ValueError,
# KeyError, IndexError, TimeoutException) as _:
# return False
# except Exception as error:
# self.logger.exception(error)
# return False
# finally:
# signal.alarm(0)
#
# return True
#
# def restore_snapshot(self, memory=True):
# # Restore memory
# if memory:
# self.jitter.vm.reset_memory_page_pool()
# self.jitter.vm.reset_code_bloc_pool()
# for addr, metadata in self.vm_mem.iteritems():
# self.jitter.vm.add_memory_page(addr,
# metadata["access"],
# metadata["data"])
#
# # Restore registers
# self.jitter.cpu.init_regs()
# self.jitter.cpu.set_gpreg(self.vm_regs)
#
# # Reset intern elements
# self.jitter.vm.set_exception(0)
# self.jitter.cpu.set_exception(0)
# self.jitter.bs._atomic_mode = False
#
# Path: sibyl/config.py
# class Config(object):
# def __init__(self, default_config, files):
# def expandpath(path):
# def parse_files(self, files):
# def dump(self):
# def jit_engine(self):
# def available_tests(self):
# def miasm_engine(self):
# def pin_root(self):
# def pin_tracer(self):
# def prune_strategy(self):
# def prune_keep(self):
# def prune_keep_max(self):
# def stubs(self):
# def idaq64_path(self):
# def ghidra_headless_path(self):
# def ghidra_export_function(self):
. Output only the next line. | if not isinstance(self.engine, MiasmEngine): |
Given the code snippet: <|code_start|>class TestLauncher(object):
"Launch tests for a function and report matching candidates"
def __init__(self, filename, machine, abicls, tests_cls, engine_name,
map_addr=0):
# Logging facilities
self.logger = init_logger("testlauncher")
# Prepare JiT engine
self.machine = machine
self.init_engine(engine_name)
# Init and snapshot VM
self.load_vm(filename, map_addr)
self.init_stub()
self.snapshot = self.engine.take_snapshot()
# Init tests
self.init_abi(abicls)
self.initialize_tests(tests_cls)
def init_stub(self):
"""Initialize stubbing capabilities"""
if not isinstance(self.engine, MiasmEngine):
# Unsupported capability
return
# Get stubs' implementation
context = {}
<|code_end|>
, generate the next line using the imports in this file:
import time
import signal
import logging
from miasm2.analysis.binary import Container, ContainerPE, ContainerELF
from sibyl.commons import init_logger, TimeoutException, END_ADDR
from sibyl.engine import QEMUEngine, MiasmEngine
from sibyl.config import config
from miasm2.jitter.loader.pe import preload_pe, libimp_pe
from miasm2.jitter.loader.elf import preload_elf, libimp_elf
and context (functions, classes, or occasionally code) from other files:
# Path: sibyl/commons.py
# def init_logger(name):
# logger = logging.getLogger(name)
#
# console_handler = logging.StreamHandler()
# log_format = "%(levelname)-5s: %(message)s"
# console_handler.setFormatter(logging.Formatter(log_format))
# logger.addHandler(console_handler)
#
# logger.setLevel(logging.ERROR)
# return logger
#
# class TimeoutException(Exception):
# """Exception to be called on timeouts"""
# pass
#
# END_ADDR = 0x1337babe
#
# Path: sibyl/engine/qemu.py
# class QEMUEngine(Engine):
# """Engine based on QEMU, using unicorn as a wrapper"""
#
# def __init__(self, machine):
# if unicorn is None:
# raise ImportError("QEMU engine unavailable: 'unicorn' import error")
#
# self.jitter = UcWrapJitter(machine)
# super(QEMUEngine, self).__init__(machine)
#
#
# def run(self, address, timeout_seconds):
# try:
# self.jitter.run(address, timeout_seconds)
# except UnexpectedStopException as _:
# return False
# except Exception as error:
# self.logger.exception(error)
# return False
#
# return True
#
# def prepare_run(self):
# # XXX HACK: Avoid a slow down of unicorn (apparently to too many
# # threads...)
# self.jitter.renew()
#
# def restore_snapshot(self, memory=True):
# # Restore VM
# if memory:
# self.jitter.vm.restore_mem_state(self.vm_mem)
#
# # Restore registers
# self.jitter.cpu.set_gpreg(self.vm_regs)
#
# Path: sibyl/engine/miasm.py
# class MiasmEngine(Engine):
# """Engine based on Miasm"""
#
# def __init__(self, machine, jit_engine):
# jitter = machine.jitter(jit_engine)
# jitter.set_breakpoint(END_ADDR, MiasmEngine._code_sentinelle)
# self.jitter = jitter
#
# # Signal handling
# #
# # Due to Python signal handling implementation, signals aren't handled
# # nor passed to Jitted code in case of registration with signal API
# if jit_engine == "python":
# signal.signal(signal.SIGALRM, MiasmEngine._timeout)
# elif jit_engine in ["llvm", "tcc", "gcc"]:
# self.jitter.vm.set_alarm()
# else:
# raise ValueError("Unknown engine: %s" % jit_engine)
#
# super(MiasmEngine, self).__init__(machine)
#
#
# @staticmethod
# def _code_sentinelle(jitter):
# jitter.run = False
# jitter.pc = 0
# return True
#
# @staticmethod
# def _timeout(signum, frame):
# raise TimeoutException()
#
# def run(self, address, timeout_seconds):
# self.jitter.init_run(address)
#
# try:
# signal.alarm(timeout_seconds)
# self.jitter.continue_run()
# except (AssertionError, RuntimeError, ValueError,
# KeyError, IndexError, TimeoutException) as _:
# return False
# except Exception as error:
# self.logger.exception(error)
# return False
# finally:
# signal.alarm(0)
#
# return True
#
# def restore_snapshot(self, memory=True):
# # Restore memory
# if memory:
# self.jitter.vm.reset_memory_page_pool()
# self.jitter.vm.reset_code_bloc_pool()
# for addr, metadata in self.vm_mem.iteritems():
# self.jitter.vm.add_memory_page(addr,
# metadata["access"],
# metadata["data"])
#
# # Restore registers
# self.jitter.cpu.init_regs()
# self.jitter.cpu.set_gpreg(self.vm_regs)
#
# # Reset intern elements
# self.jitter.vm.set_exception(0)
# self.jitter.cpu.set_exception(0)
# self.jitter.bs._atomic_mode = False
#
# Path: sibyl/config.py
# class Config(object):
# def __init__(self, default_config, files):
# def expandpath(path):
# def parse_files(self, files):
# def dump(self):
# def jit_engine(self):
# def available_tests(self):
# def miasm_engine(self):
# def pin_root(self):
# def pin_tracer(self):
# def prune_strategy(self):
# def prune_keep(self):
# def prune_keep_max(self):
# def stubs(self):
# def idaq64_path(self):
# def ghidra_headless_path(self):
# def ghidra_export_function(self):
. Output only the next line. | for fpath in config.stubs: |
Given snippet: <|code_start|> with open(c_file) as fdesc:
data = fdesc.read()
funcs = []
for match in match_C.finditer(data):
funcs.append(match.groups()[0])
funcs = list(name for name in set(funcs) if name not in whitelist_funcs)
# Find corresponding binary offset
to_check = []
with open(filename) as fdesc:
elf = ELF(fdesc.read())
symbols = {}
for name, symb in elf.getsectionbyname(".symtab").symbols.iteritems():
offset = symb.value
if name.startswith("__"):
name = name[2:]
symbols.setdefault(name, set()).add(offset)
if name in funcs:
if name.startswith(custom_tag):
## Custom tags can be used to write equivalent functions like
## 'my_strlen' for a custom strlen
name = name[len(custom_tag):]
to_check.append((offset, name))
return to_check, symbols
def get_funcs_heuristics(c_file, filename):
"""Get function from Sibyl heuristics"""
# Force the activation of all heuristics
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import re
import subprocess
from argparse import ArgumentParser
from utils.log import log_error, log_success, log_info
from elfesteem.elf_init import ELF
from sibyl.heuristics.func import FuncHeuristic
and context:
# Path: sibyl/heuristics/func.py
# class FuncHeuristic(Heuristic):
# """Provide heuristic for function start address detection"""
#
# # Enabled passes
# heuristics = [
# named_symbols,
# pattern_matching,
# recursive_call,
# ida_funcs,
# ghidra_funcs,
# ]
#
# def __init__(self, cont, machine, filename):
# """
# @cont: miasm2's Container instance
# @machine: miasm2's Machine instance
# @filename: target's filename
# """
# super(FuncHeuristic, self).__init__()
# self.cont = cont
# self.machine = machine
# self.filename = filename
#
# def do_votes(self):
# """Call recursive_call at the end"""
# do_recursive = False
# if recursive_call in self.heuristics:
# do_recursive = True
# self.heuristics.remove(recursive_call)
#
# super(FuncHeuristic, self).do_votes()
# addresses = self._votes
#
# if do_recursive:
# new_addresses = recursive_call(self,
# [addr
# for addr, vote in addresses.iteritems()
# if vote > 0])
# for addr, vote in new_addresses.iteritems():
# addresses[addr] = addresses.get(addr, 0) + vote
# self._votes = addresses
#
# def guess(self):
# for address, value in self.votes.iteritems():
# # Heuristic may vote negatively
# if value > 0:
# yield address
which might include code, classes, or functions. Output only the next line. | fh = FuncHeuristic(None, None, "") |
Predict the next line for this snippet: <|code_start|> | |--
| | |-- !
| | | |-- isalnum
| | | `-- isgraph
| | -- \\x00
| | |-- isascii
| | `-- isprint
| `-- A
| |-- isalpha
| `-- islower
`-- \\t (return 0)
|--
| |-- iscntrl
| `-- \\n
| |-- isblank
| `-- isspace
`-- A
|-- 0
| |-- isupper
| `-- isxdigit
`-- 0
|-- ispunct
`-- isdigit
"""
def reset_full(self, *args, **kwargs):
super(TestIsCharset, self).reset_full(*args, **kwargs)
# Reset tests tree
self.cur_tree = self.decision_tree
self.next_test = self.cur_tree["t"]
<|code_end|>
with the help of current file imports:
from sibyl.test.test import Test, TestSetGenerator
and context from other files:
# Path: sibyl/test/test.py
# class Test(object):
# "Main class for tests"
#
# # Elements to override
#
# func = "" # Possible function if test passes
# tests = [] # List of tests (init, check) to pass
# reset_mem = True # Reset memory between tests
#
# def init(self):
# "Called for setting up the test case"
# pass
#
# def check(self):
# """Called to check test result
# Return True if all checks are passed"""
# return True
#
# def reset_full(self):
# """Reset the test case between two functions"""
# self.alloc_pool = 0x20000000
#
# def reset(self):
# """Reset the test case between two subtests"""
# self.reset_full()
#
# # Utils
#
# def __init__(self, jitter, abi):
# self.jitter = jitter
# self.alloc_pool = 0x20000000
# self.abi = abi
#
# def _reserv_mem(self, size, read=True, write=False):
# right = 0
# if read:
# right |= PAGE_READ
# if write:
# right |= PAGE_WRITE
#
# # Memory alignement
# size += 16 - size % 16
#
# to_ret = self.alloc_pool
# self.alloc_pool += size + 1
#
# return to_ret
#
# def __alloc_mem(self, mem, read=True, write=False):
# right = 0
# if read:
# right |= PAGE_READ
# if write:
# right |= PAGE_WRITE
#
# # Memory alignement
# mem += "".join([chr(random.randint(0, 255)) \
# for _ in xrange((16 - len(mem) % 16))])
#
# self.jitter.vm.add_memory_page(self.alloc_pool, right, mem)
# to_ret = self.alloc_pool
# self.alloc_pool += len(mem) + 1
#
# return to_ret
#
# def _alloc_mem(self, size, read=True, write=False):
# mem = "".join([chr(random.randint(0, 255)) for _ in xrange(size)])
# return self.__alloc_mem(mem, read=read, write=write)
#
# def _alloc_string(self, string, read=True, write=False):
# return self.__alloc_mem(string + "\x00", read=read, write=write)
#
# def _alloc_pointer(self, pointer, read=True, write=False):
# pointer_size = self.abi.ira.sizeof_pointer()
# return self.__alloc_mem(Test.pack(pointer, pointer_size),
# read=read,
# write=write)
#
# def _write_mem(self, addr, element):
# self.jitter.vm.set_mem(addr, element)
#
# def _write_string(self, addr, element):
# self._write_mem(addr, element + "\x00")
#
# def _add_arg(self, number, element):
# self.abi.add_arg(number, element)
#
# def _get_result(self):
# return self.abi.get_result()
#
# def _ensure_mem(self, addr, element):
# try:
# return self.jitter.vm.get_mem(addr, len(element)) == element
# except RuntimeError:
# return False
#
# def _ensure_mem_sparse(self, addr, element, offsets):
# """@offsets: offsets to ignore"""
# for i, sub_element in enumerate(element):
# if i in offsets:
# continue
# if not self._ensure_mem(addr + i, sub_element):
# return False
# return True
#
# def _as_int(self, element):
# int_size = self.abi.ira.sizeof_int()
# max_val = 2**int_size
# return (element + max_val) % max_val
#
# def _to_int(self, element):
# int_size = self.abi.ira.sizeof_int()
# return mod_size2int[int_size](element)
#
# def _memread_pointer(self, addr):
# pointer_size = self.abi.ira.sizeof_pointer() / 8
# try:
# element = self.jitter.vm.get_mem(addr, pointer_size)
# except RuntimeError:
# return False
# return Test.unpack(element)
#
# @staticmethod
# def pack(element, size):
# out = ""
# while element != 0:
# out += chr(element % 0x100)
# element >>= 8
# if len(out) > size / 8:
# raise ValueError("To big to be packed")
# out = out + "\x00" * ((size / 8) - len(out))
# return out
#
# @staticmethod
# def unpack(element):
# return int(element[::-1].encode("hex"), 16)
#
# class TestSetGenerator(TestSet):
# """TestSet based using a generator to retrieve tests"""
#
# def __init__(self, generator):
# self._generator = generator
#
# def execute(self, callback):
# for (init, check) in self._generator:
# if not callback(init, check):
# return False
# return True
, which may contain function names, class names, or code. Output only the next line. | self.tests = TestSetGenerator(self.test_iter()) |
Continue the code snippet: <|code_start|>try:
except ImportError:
unicorn = None
class UnexpectedStopException(Exception):
"""Exception to be called on timeouts"""
pass
<|code_end|>
. Use current file imports:
from miasm2.core.utils import pck32, pck64
from miasm2.jitter.csts import PAGE_READ, PAGE_WRITE
from sibyl.engine.engine import Engine
from sibyl.commons import END_ADDR, init_logger
import unicorn
import unicorn.x86_const as csts
import unicorn.x86_const as csts
import unicorn.arm_const as csts
import unicorn.arm_const as csts
import unicorn.mips_const as csts
and context (classes, functions, or code) from other files:
# Path: sibyl/engine/engine.py
# class Engine(object):
# """Wrapper on execution engine"""
#
# def __init__(self, machine):
# """Instanciate an Engine
# @machine: miasm2.analysis.machine:Machine instance"""
# self.logger = init_logger(self.__class__.__name__)
#
# def take_snapshot(self):
# self.vm_mem = self.jitter.vm.get_all_memory()
# self.vm_regs = self.jitter.cpu.get_gpreg()
#
# def restore_snapshot(self, memory=True):
# raise NotImplementedError("Abstract method")
#
# def run(self, address, timeout_seconds):
# raise NotImplementedError("Abstract method")
#
# def prepare_run(self):
# pass
#
# def restore_snapshot(self, memory=True):
# raise NotImplementedError("Abstract method")
#
# Path: sibyl/commons.py
# END_ADDR = 0x1337babe
#
# def init_logger(name):
# logger = logging.getLogger(name)
#
# console_handler = logging.StreamHandler()
# log_format = "%(levelname)-5s: %(message)s"
# console_handler.setFormatter(logging.Formatter(log_format))
# logger.addHandler(console_handler)
#
# logger.setLevel(logging.ERROR)
# return logger
. Output only the next line. | class QEMUEngine(Engine): |
Predict the next line for this snippet: <|code_start|> raise ValueError("Unimplemented architecture (%s, %s)" % (ask_arch,
ask_attrib))
arch, mode = cpucls.uc_arch, cpucls.uc_mode
self.ask_arch = ask_arch
self.ask_attrib = ask_attrib
self.mu = unicorn.Uc(arch, mode)
self.vm = UcWrapVM(self.mu)
self.cpu = cpucls(self.mu)
def init_stack(self):
self.vm.add_memory_page(0x1230000, PAGE_WRITE | PAGE_READ,
"\x00" * 0x10000, "Stack")
setattr(self.cpu, self.ira.sp.name, 0x1230000 + 0x10000)
def push_uint32_t(self, value):
setattr(self.cpu, self.ira.sp.name,
getattr(self.cpu, self.ira.sp.name) - self.ira.sp.size / 8)
self.vm.set_mem(getattr(self.cpu, self.ira.sp.name), pck32(value))
def push_uint64_t(self, value):
setattr(self.cpu, self.ira.sp.name,
getattr(self.cpu, self.ira.sp.name) - self.ira.sp.size / 8)
self.vm.set_mem(getattr(self.cpu, self.ira.sp.name), pck64(value))
def run(self, pc, timeout_seconds=1):
# checking which instruction you want to emulate: THUMB/THUMB2 or others
# Note we start at ADDRESS | 1 to indicate THUMB mode.
try:
if self.ask_arch == 'armt' and self.ask_attrib == 'l':
<|code_end|>
with the help of current file imports:
from miasm2.core.utils import pck32, pck64
from miasm2.jitter.csts import PAGE_READ, PAGE_WRITE
from sibyl.engine.engine import Engine
from sibyl.commons import END_ADDR, init_logger
import unicorn
import unicorn.x86_const as csts
import unicorn.x86_const as csts
import unicorn.arm_const as csts
import unicorn.arm_const as csts
import unicorn.mips_const as csts
and context from other files:
# Path: sibyl/engine/engine.py
# class Engine(object):
# """Wrapper on execution engine"""
#
# def __init__(self, machine):
# """Instanciate an Engine
# @machine: miasm2.analysis.machine:Machine instance"""
# self.logger = init_logger(self.__class__.__name__)
#
# def take_snapshot(self):
# self.vm_mem = self.jitter.vm.get_all_memory()
# self.vm_regs = self.jitter.cpu.get_gpreg()
#
# def restore_snapshot(self, memory=True):
# raise NotImplementedError("Abstract method")
#
# def run(self, address, timeout_seconds):
# raise NotImplementedError("Abstract method")
#
# def prepare_run(self):
# pass
#
# def restore_snapshot(self, memory=True):
# raise NotImplementedError("Abstract method")
#
# Path: sibyl/commons.py
# END_ADDR = 0x1337babe
#
# def init_logger(name):
# logger = logging.getLogger(name)
#
# console_handler = logging.StreamHandler()
# log_format = "%(levelname)-5s: %(message)s"
# console_handler.setFormatter(logging.Formatter(log_format))
# logger.addHandler(console_handler)
#
# logger.setLevel(logging.ERROR)
# return logger
, which may contain function names, class names, or code. Output only the next line. | self.mu.emu_start(pc | 1, END_ADDR, timeout_seconds * unicorn.UC_SECOND_SCALE) |
Based on the snippet: <|code_start|> for addr, page in mem_state.iteritems():
# Add missing pages
if addr not in addrs:
self.mu.mem_map(addr, page["size"])
self.set_mem(addr, page["data"])
new_mem_page.append({"addr": addr,
"size": page["size"],
"name": "",
"access": page["access"]})
self.mem_page = new_mem_page
class UcWrapCPU(object):
# name -> Uc value
regs = None
# PC registers, name and Uc value
pc_reg_name = None
pc_reg_value = None
# Registers mask (int -> uint)
reg_mask = None
# (arch, attrib) -> CPU class
available_cpus = {}
# Uc architecture and mode
uc_arch = None
uc_mode = None
def __init__(self, mu):
self.mu = mu
<|code_end|>
, predict the immediate next line with the help of imports:
from miasm2.core.utils import pck32, pck64
from miasm2.jitter.csts import PAGE_READ, PAGE_WRITE
from sibyl.engine.engine import Engine
from sibyl.commons import END_ADDR, init_logger
import unicorn
import unicorn.x86_const as csts
import unicorn.x86_const as csts
import unicorn.arm_const as csts
import unicorn.arm_const as csts
import unicorn.mips_const as csts
and context (classes, functions, sometimes code) from other files:
# Path: sibyl/engine/engine.py
# class Engine(object):
# """Wrapper on execution engine"""
#
# def __init__(self, machine):
# """Instanciate an Engine
# @machine: miasm2.analysis.machine:Machine instance"""
# self.logger = init_logger(self.__class__.__name__)
#
# def take_snapshot(self):
# self.vm_mem = self.jitter.vm.get_all_memory()
# self.vm_regs = self.jitter.cpu.get_gpreg()
#
# def restore_snapshot(self, memory=True):
# raise NotImplementedError("Abstract method")
#
# def run(self, address, timeout_seconds):
# raise NotImplementedError("Abstract method")
#
# def prepare_run(self):
# pass
#
# def restore_snapshot(self, memory=True):
# raise NotImplementedError("Abstract method")
#
# Path: sibyl/commons.py
# END_ADDR = 0x1337babe
#
# def init_logger(name):
# logger = logging.getLogger(name)
#
# console_handler = logging.StreamHandler()
# log_format = "%(levelname)-5s: %(message)s"
# console_handler.setFormatter(logging.Formatter(log_format))
# logger.addHandler(console_handler)
#
# logger.setLevel(logging.ERROR)
# return logger
. Output only the next line. | self.logger = init_logger("UcWrapCPU") |
Predict the next line for this snippet: <|code_start|>"Module for architecture guessing"
def container_guess(archinfo):
"""Use the architecture provided by the container, if any
@archinfo: ArchHeuristic instance
"""
cont = Container.from_stream(archinfo.stream)
if isinstance(cont, ContainerUnknown) or not cont.arch:
return {}
return {cont.arch: 1}
<|code_end|>
with the help of current file imports:
from miasm2.analysis.binary import Container, ContainerUnknown
from sibyl.heuristics.heuristic import Heuristic
and context from other files:
# Path: sibyl/heuristics/heuristic.py
# class Heuristic(object):
# """Main class for heuristics, handle common methods related to them"""
#
# # Enabled passes
# # passes are functions taking 'self' and returning a dict:
# # candidates -> estimated probability
# heuristics = []
#
# def __init__(self):
# self._votes = None
#
# def do_votes(self):
# """Call heuristics and get back votes
# Use a cumulative linear strategy for comparison
# """
# votes = {}
# for heuristic in self.heuristics:
# for name, vote in heuristic(self).iteritems():
# votes[name] = votes.get(name, 0) + vote
# self._votes = votes
#
# @property
# def votes(self):
# """Cumulative votes for each candidates"""
# if not self._votes:
# self.do_votes()
# return self._votes
#
# @property
# def heuristic_names(self):
# """Return the list of available heuristics"""
# return [func.__name__ for func in self.heuristics]
#
# def name2heuristic(self, name):
# """Return the heuristic named @name"""
# for func in self.heuristics:
# if func.__name__ == name:
# return func
# else:
# raise KeyError("Unable to find %s" % name)
#
# def guess(self):
# """Return the best candidate"""
# sorted_votes = sorted(self.votes.iteritems(), key=lambda x:x[1])
# if not sorted_votes:
# # No solution
# return False
# best, _ = sorted_votes[-1]
# return best
, which may contain function names, class names, or code. Output only the next line. | class ArchHeuristic(Heuristic): |
Next line prediction: <|code_start|>
class TestSetGenerator(TestSet):
"""TestSet based using a generator to retrieve tests"""
def __init__(self, generator):
self._generator = generator
def execute(self, callback):
for (init, check) in self._generator:
if not callback(init, check):
return False
return True
class TestHeader(Test):
"""Test extension with support for header parsing, and handling of struct
offset, size, ...
"""
header = None
def __init__(self, *args, **kwargs):
super(TestHeader, self).__init__(*args, **kwargs)
# Requirement check
if pycparser is None:
raise ImportError("pycparser module is needed to launch tests based"
"on header files")
ctype_manager = CTypesManagerNotPacked(CAstTypes(), CTypeAMD64_unk())
<|code_end|>
. Use current file imports:
(import random
import pycparser
from miasm2.jitter.csts import PAGE_READ, PAGE_WRITE
from miasm2.expression.modint import mod_size2int
from miasm2.expression.simplifications import expr_simp
from miasm2.core.objc import CTypesManagerNotPacked, CHandler
from miasm2.core.ctypesmngr import CAstTypes
from miasm2.arch.x86.ctype import CTypeAMD64_unk
from sibyl.commons import HeaderFile)
and context including class names, function names, or small code snippets from other files:
# Path: sibyl/commons.py
# class HeaderFile(object):
# """Abstract representation of a Header file"""
#
# def __init__(self, header_data, ctype_manager):
# """Parse @header_data to fill @ctype_manager
# @header_data: str of a C-like header file
# @ctype_manager: miasm2.core.objc.CTypesManager instance"""
# self.data = header_data
# self.ctype_manager = ctype_manager
#
# self.ast = self.parse_header(header_data)
# self.ctype_manager.types_ast.add_c_decl(header_data)
# self.functions = {} # function name -> FuncPrototype
#
# if pycparser is None:
# raise ImportError("pycparser module is needed to parse header file")
# self.parse_functions()
#
# @staticmethod
# def parse_header(header_data):
# """Return the AST corresponding to @header_data
# @header_data: str of a C-like header file
# """
# # We can't use add_c_decl, because we need the AST to get back
# # function's arguments name
# parser = pycparser.c_parser.CParser()
# return c_to_ast(parser, header_data)
#
# def parse_functions(self):
# """Search for function declarations"""
#
# for ext in self.ast.ext:
# if not (isinstance(ext, pycparser.c_ast.Decl) and
# isinstance(ext.type, (pycparser.c_ast.FuncDecl,
# pycparser.c_ast.FuncDef))):
# continue
# func_name = ext.name
# objc_func = self.ctype_manager.get_objc(CTypeFunc(func_name))
#
# args_order = []
# args = {}
# for i, param in enumerate(ext.type.args.params):
# args_order.append(param.name)
# args[param.name] = objc_func.args[i][1]
#
# self.functions[func_name] = FuncPrototype(func_name,
# objc_func.type_ret,
# *args_order, **args)
. Output only the next line. | hdr = HeaderFile(self.header, ctype_manager) |
Predict the next line after this snippet: <|code_start|>
ret = ret and all([self._ensure_mem(offset + self.segBase{n}[segment], data) for ((offset, segment),data) in addrList])
'''
def my_unpack(value):
return struct.unpack('@P', value)[0]
def argListStr(t):
'''Return a string representing t which can be a tuple or an int'''
return "(0x%x, %i)" % (t[0], t[1]) if isinstance(t, tuple) else str(t)
def accessToStr(access):
'''Return a string representing the access right given in argument'''
ret = ""
if access & PAGE_READ:
ret += "PAGE_READ | "
if access & PAGE_WRITE:
ret += "PAGE_WRITE"
return ret.rstrip(" |")
def addrTupleStr(t):
'''Return a string representing the memory aera given in argument'''
((offset, seg), value, access) = t
return "((0x%x, %i), %r, %s)" % (offset, seg, value, accessToStr(access))
<|code_end|>
using the current file's imports:
import struct
from sibyl.learn.generator.generator import Generator
from sibyl.learn.generator import templates as TPL
from sibyl.learn.trace import MemoryAccess
from miasm2.ir.ir import AssignBlock
from miasm2.jitter.csts import PAGE_READ, PAGE_WRITE
from miasm2.expression.expression import *
from miasm2.expression.simplifications import expr_simp
from sibyl.commons import objc_is_dereferenceable
and any relevant context from other files:
# Path: sibyl/learn/generator/generator.py
# class Generator(object):
# '''
# Abstract class used to represent a generator
# A generator is a class that create a test from a snapshot
# Here a test is a sibyl test init function and a sibyl test check function
# '''
#
# def __init__(self, testcreator):
# '''
# @testcreator: TestCreator instance with associated information
# '''
# self.trace = testcreator.trace
# self.prototype = testcreator.prototype
# self.learnexceptiontext = testcreator.learnexceptiontext
# self.types = testcreator.types
# self.printer = Printer()
# self.headerfile = testcreator.headerfile
# self.ira = Machine(testcreator.machine).ira()
# self.ptr_size = self.ira.sizeof_pointer()/8
# self.logger = testcreator.logger
#
# def generate_test(self):
# '''Abstract method that should return the string corresponding to the code of the init test'''
# raise NotImplementedError("Abstract method")
#
# Path: sibyl/learn/generator/templates.py
#
# Path: sibyl/learn/trace.py
# class MemoryAccess(object):
# '''Represent a memory block, read or write by the learned function'''
#
# def __init__(self, size, data, access):
#
# self.size = size
# self.data = data
# self.access = access
#
# def __str__(self):
# str_access = ""
# if self.access & PAGE_READ:
# str_access += "READ"
# if self.access & PAGE_WRITE:
# if str_access != "":
# str_access += " "
# str_access += "WRITE"
#
# return "size: " + str(self.size) + ", data: " + repr(self.data) + ", access: " + str_access
#
# def __repr__(self):
# return "<" + str(self) + ">"
#
# Path: sibyl/commons.py
# def objc_is_dereferenceable(target_type):
# """Return True if target_type may be used as a pointer
# @target_type: ObjC"""
# return isinstance(target_type, (ObjCPtr, ObjCArray))
. Output only the next line. | class PythonGenerator(Generator): |
Next line prediction: <|code_start|>
def my_unpack(value):
return struct.unpack('@P', value)[0]
def argListStr(t):
'''Return a string representing t which can be a tuple or an int'''
return "(0x%x, %i)" % (t[0], t[1]) if isinstance(t, tuple) else str(t)
def accessToStr(access):
'''Return a string representing the access right given in argument'''
ret = ""
if access & PAGE_READ:
ret += "PAGE_READ | "
if access & PAGE_WRITE:
ret += "PAGE_WRITE"
return ret.rstrip(" |")
def addrTupleStr(t):
'''Return a string representing the memory aera given in argument'''
((offset, seg), value, access) = t
return "((0x%x, %i), %r, %s)" % (offset, seg, value, accessToStr(access))
class PythonGenerator(Generator):
def generate_test(self):
<|code_end|>
. Use current file imports:
(import struct
from sibyl.learn.generator.generator import Generator
from sibyl.learn.generator import templates as TPL
from sibyl.learn.trace import MemoryAccess
from miasm2.ir.ir import AssignBlock
from miasm2.jitter.csts import PAGE_READ, PAGE_WRITE
from miasm2.expression.expression import *
from miasm2.expression.simplifications import expr_simp
from sibyl.commons import objc_is_dereferenceable)
and context including class names, function names, or small code snippets from other files:
# Path: sibyl/learn/generator/generator.py
# class Generator(object):
# '''
# Abstract class used to represent a generator
# A generator is a class that create a test from a snapshot
# Here a test is a sibyl test init function and a sibyl test check function
# '''
#
# def __init__(self, testcreator):
# '''
# @testcreator: TestCreator instance with associated information
# '''
# self.trace = testcreator.trace
# self.prototype = testcreator.prototype
# self.learnexceptiontext = testcreator.learnexceptiontext
# self.types = testcreator.types
# self.printer = Printer()
# self.headerfile = testcreator.headerfile
# self.ira = Machine(testcreator.machine).ira()
# self.ptr_size = self.ira.sizeof_pointer()/8
# self.logger = testcreator.logger
#
# def generate_test(self):
# '''Abstract method that should return the string corresponding to the code of the init test'''
# raise NotImplementedError("Abstract method")
#
# Path: sibyl/learn/generator/templates.py
#
# Path: sibyl/learn/trace.py
# class MemoryAccess(object):
# '''Represent a memory block, read or write by the learned function'''
#
# def __init__(self, size, data, access):
#
# self.size = size
# self.data = data
# self.access = access
#
# def __str__(self):
# str_access = ""
# if self.access & PAGE_READ:
# str_access += "READ"
# if self.access & PAGE_WRITE:
# if str_access != "":
# str_access += " "
# str_access += "WRITE"
#
# return "size: " + str(self.size) + ", data: " + repr(self.data) + ", access: " + str_access
#
# def __repr__(self):
# return "<" + str(self) + ">"
#
# Path: sibyl/commons.py
# def objc_is_dereferenceable(target_type):
# """Return True if target_type may be used as a pointer
# @target_type: ObjC"""
# return isinstance(target_type, (ObjCPtr, ObjCArray))
. Output only the next line. | self.printer.add_block(TPL.imports) |
Here is a snippet: <|code_start|> self.printer.add_lvl()
memory_in = snapshot.memory_in
memory_out = snapshot.memory_out
c_handler = snapshot.c_handler
typed_C_ids = snapshot.typed_C_ids
arguments_symbols = snapshot.arguments_symbols
output_value = snapshot.output_value
# Sanitize memory accesses
memory_in, _ = self.sanitize_memory_accesses(memory_in, c_handler, typed_C_ids)
memory_out, _ = self.sanitize_memory_accesses(memory_out, c_handler, typed_C_ids)
# Allocate zones if needed
## First, resolve common bases
bases_to_C = {} # expr -> C-like
to_resolve = set()
for expr in memory_in.keys() + memory_out.keys():
to_resolve.update(expr.ptr.get_r(mem_read=True))
fixed = {}
for i, expr in enumerate(to_resolve):
fixed[expr] = ExprId("base%d_ptr" % i, size=expr.size)
info_type = list(c_handler.expr_to_types(expr))
info_C = list(c_handler.expr_to_c(expr))
assert len(info_type) == 1
assert len(info_C) == 1
arg_type = info_type[0]
# Must be a pointer to be present in expr.get_r
<|code_end|>
. Write the next line using the current file imports:
import struct
from sibyl.learn.generator.generator import Generator
from sibyl.learn.generator import templates as TPL
from sibyl.learn.trace import MemoryAccess
from miasm2.ir.ir import AssignBlock
from miasm2.jitter.csts import PAGE_READ, PAGE_WRITE
from miasm2.expression.expression import *
from miasm2.expression.simplifications import expr_simp
from sibyl.commons import objc_is_dereferenceable
and context from other files:
# Path: sibyl/learn/generator/generator.py
# class Generator(object):
# '''
# Abstract class used to represent a generator
# A generator is a class that create a test from a snapshot
# Here a test is a sibyl test init function and a sibyl test check function
# '''
#
# def __init__(self, testcreator):
# '''
# @testcreator: TestCreator instance with associated information
# '''
# self.trace = testcreator.trace
# self.prototype = testcreator.prototype
# self.learnexceptiontext = testcreator.learnexceptiontext
# self.types = testcreator.types
# self.printer = Printer()
# self.headerfile = testcreator.headerfile
# self.ira = Machine(testcreator.machine).ira()
# self.ptr_size = self.ira.sizeof_pointer()/8
# self.logger = testcreator.logger
#
# def generate_test(self):
# '''Abstract method that should return the string corresponding to the code of the init test'''
# raise NotImplementedError("Abstract method")
#
# Path: sibyl/learn/generator/templates.py
#
# Path: sibyl/learn/trace.py
# class MemoryAccess(object):
# '''Represent a memory block, read or write by the learned function'''
#
# def __init__(self, size, data, access):
#
# self.size = size
# self.data = data
# self.access = access
#
# def __str__(self):
# str_access = ""
# if self.access & PAGE_READ:
# str_access += "READ"
# if self.access & PAGE_WRITE:
# if str_access != "":
# str_access += " "
# str_access += "WRITE"
#
# return "size: " + str(self.size) + ", data: " + repr(self.data) + ", access: " + str_access
#
# def __repr__(self):
# return "<" + str(self) + ">"
#
# Path: sibyl/commons.py
# def objc_is_dereferenceable(target_type):
# """Return True if target_type may be used as a pointer
# @target_type: ObjC"""
# return isinstance(target_type, (ObjCPtr, ObjCArray))
, which may include functions, classes, or code. Output only the next line. | assert objc_is_dereferenceable(arg_type) |
Predict the next line after this snippet: <|code_start|># License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Sibyl. If not, see <http://www.gnu.org/licenses/>.
class TestAbs(Test):
value = 42
# Test1
def init1(self):
self._add_arg(0, self.value + 1)
def check1(self):
result = self._get_result()
return result == (self.value + 1)
# Test2
def init2(self):
self._add_arg(0, self._as_int(-1 * self.value))
def check2(self):
result = self._get_result()
return result == self.value
# Properties
func = "abs"
<|code_end|>
using the current file's imports:
from sibyl.test.test import Test, TestSetTest
and any relevant context from other files:
# Path: sibyl/test/test.py
# class Test(object):
# "Main class for tests"
#
# # Elements to override
#
# func = "" # Possible function if test passes
# tests = [] # List of tests (init, check) to pass
# reset_mem = True # Reset memory between tests
#
# def init(self):
# "Called for setting up the test case"
# pass
#
# def check(self):
# """Called to check test result
# Return True if all checks are passed"""
# return True
#
# def reset_full(self):
# """Reset the test case between two functions"""
# self.alloc_pool = 0x20000000
#
# def reset(self):
# """Reset the test case between two subtests"""
# self.reset_full()
#
# # Utils
#
# def __init__(self, jitter, abi):
# self.jitter = jitter
# self.alloc_pool = 0x20000000
# self.abi = abi
#
# def _reserv_mem(self, size, read=True, write=False):
# right = 0
# if read:
# right |= PAGE_READ
# if write:
# right |= PAGE_WRITE
#
# # Memory alignement
# size += 16 - size % 16
#
# to_ret = self.alloc_pool
# self.alloc_pool += size + 1
#
# return to_ret
#
# def __alloc_mem(self, mem, read=True, write=False):
# right = 0
# if read:
# right |= PAGE_READ
# if write:
# right |= PAGE_WRITE
#
# # Memory alignement
# mem += "".join([chr(random.randint(0, 255)) \
# for _ in xrange((16 - len(mem) % 16))])
#
# self.jitter.vm.add_memory_page(self.alloc_pool, right, mem)
# to_ret = self.alloc_pool
# self.alloc_pool += len(mem) + 1
#
# return to_ret
#
# def _alloc_mem(self, size, read=True, write=False):
# mem = "".join([chr(random.randint(0, 255)) for _ in xrange(size)])
# return self.__alloc_mem(mem, read=read, write=write)
#
# def _alloc_string(self, string, read=True, write=False):
# return self.__alloc_mem(string + "\x00", read=read, write=write)
#
# def _alloc_pointer(self, pointer, read=True, write=False):
# pointer_size = self.abi.ira.sizeof_pointer()
# return self.__alloc_mem(Test.pack(pointer, pointer_size),
# read=read,
# write=write)
#
# def _write_mem(self, addr, element):
# self.jitter.vm.set_mem(addr, element)
#
# def _write_string(self, addr, element):
# self._write_mem(addr, element + "\x00")
#
# def _add_arg(self, number, element):
# self.abi.add_arg(number, element)
#
# def _get_result(self):
# return self.abi.get_result()
#
# def _ensure_mem(self, addr, element):
# try:
# return self.jitter.vm.get_mem(addr, len(element)) == element
# except RuntimeError:
# return False
#
# def _ensure_mem_sparse(self, addr, element, offsets):
# """@offsets: offsets to ignore"""
# for i, sub_element in enumerate(element):
# if i in offsets:
# continue
# if not self._ensure_mem(addr + i, sub_element):
# return False
# return True
#
# def _as_int(self, element):
# int_size = self.abi.ira.sizeof_int()
# max_val = 2**int_size
# return (element + max_val) % max_val
#
# def _to_int(self, element):
# int_size = self.abi.ira.sizeof_int()
# return mod_size2int[int_size](element)
#
# def _memread_pointer(self, addr):
# pointer_size = self.abi.ira.sizeof_pointer() / 8
# try:
# element = self.jitter.vm.get_mem(addr, pointer_size)
# except RuntimeError:
# return False
# return Test.unpack(element)
#
# @staticmethod
# def pack(element, size):
# out = ""
# while element != 0:
# out += chr(element % 0x100)
# element >>= 8
# if len(out) > size / 8:
# raise ValueError("To big to be packed")
# out = out + "\x00" * ((size / 8) - len(out))
# return out
#
# @staticmethod
# def unpack(element):
# return int(element[::-1].encode("hex"), 16)
#
# class TestSetTest(TestSet):
# """Terminal node of TestSet
#
# Stand for a check in a test case
#
# init: initialization function, called before launching the target address
# check: checking function, verifying the final state
# """
#
# def __init__(self, init, check):
# super(TestSetTest, self).__init__()
# self._init = init
# self._check = check
#
# def __repr__(self):
# return "<TST %r,%r>" % (self._init, self._check)
#
# def execute(self, callback):
# return callback(self._init, self._check)
. Output only the next line. | tests = TestSetTest(init1, check1) & TestSetTest(init2, check2) |
Next line prediction: <|code_start|> if not user:
try:
user = User.objects.get(email=email)
except User.DoesNotExist:
return
user.unsubscribe(newsletter_list, lang=lang)
def send_mails(self, newsletter, fail_silently=False, subscribers=None):
connection = mail.get_connection(fail_silently=fail_silently)
emails = []
old_language = translation.get_language()
for subscriber in subscribers:
if (
newsletter.newsletter_segment.lang
and newsletter.newsletter_segment.lang != subscriber.lang
):
continue
translation.activate(subscriber.lang)
email = EmailMultiAlternatives(
newsletter.name,
render_to_string(
"courriers/newsletter_raw_detail.txt",
{"object": newsletter, "subscriber": subscriber},
),
<|code_end|>
. Use current file imports:
(from .base import BaseBackend
from django.core import mail
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
from django.utils import translation
from django.contrib.auth import get_user_model
from ..settings import DEFAULT_FROM_EMAIL, PRE_PROCESSORS
from ..utils import load_class)
and context including class names, function names, or small code snippets from other files:
# Path: courriers/backends/base.py
# class BaseBackend(object):
# def register(self, email, lang=None, user=None):
# raise NotImplemented
#
# def unregister(self, email, user=None):
# raise NotImplemented
#
# def exists(self, email, user=None):
# raise NotImplemented
#
# def send_mails(self, newsletter):
# raise NotImplemented
#
# Path: courriers/settings.py
# DEFAULT_FROM_EMAIL = getattr(
# settings, "COURRIERS_DEFAULT_FROM_EMAIL", settings.DEFAULT_FROM_EMAIL
# )
#
# PRE_PROCESSORS = getattr(settings, "COURRIERS_PRE_PROCESSORS", ())
#
# Path: courriers/utils.py
# def load_class(class_path, setting_name=None):
# """
# Loads a class given a class_path. The setting value may be a string or a
# tuple.
#
# The setting_name parameter is only there for pretty error output, and
# therefore is optional
# """
# if not isinstance(class_path, str):
# try:
# class_path, app_label = class_path
# except Exception:
# if setting_name:
# raise exceptions.ImproperlyConfigured(
# CLASS_PATH_ERROR % (setting_name, setting_name)
# )
# else:
# raise exceptions.ImproperlyConfigured(
# CLASS_PATH_ERROR % ("this setting", "It")
# )
#
# try:
# class_module, class_name = class_path.rsplit(".", 1)
# except ValueError:
# if setting_name:
# txt = "%s isn't a valid module. Check your %s setting" % (
# class_path,
# setting_name,
# )
# else:
# txt = "%s isn't a valid module." % class_path
# raise exceptions.ImproperlyConfigured(txt)
#
# try:
# mod = import_module(class_module)
# except ImportError as e:
# if setting_name:
# txt = 'Error importing backend %s: "%s". Check your %s setting' % (
# class_module,
# e,
# setting_name,
# )
# else:
# txt = 'Error importing backend %s: "%s".' % (class_module, e)
#
# raise exceptions.ImproperlyConfigured(txt)
#
# try:
# clazz = getattr(mod, class_name)
# except AttributeError:
# if setting_name:
# txt = (
# 'Backend module "%s" does not define a "%s" class. Check'
# " your %s setting" % (class_module, class_name, setting_name)
# )
# else:
# txt = 'Backend module "%s" does not define a "%s" class.' % (
# class_module,
# class_name,
# )
# raise exceptions.ImproperlyConfigured(txt)
# return clazz
. Output only the next line. | DEFAULT_FROM_EMAIL, |
Here is a snippet: <|code_start|>
for subscriber in subscribers:
if (
newsletter.newsletter_segment.lang
and newsletter.newsletter_segment.lang != subscriber.lang
):
continue
translation.activate(subscriber.lang)
email = EmailMultiAlternatives(
newsletter.name,
render_to_string(
"courriers/newsletter_raw_detail.txt",
{"object": newsletter, "subscriber": subscriber},
),
DEFAULT_FROM_EMAIL,
[subscriber.email],
connection=connection,
)
html = render_to_string(
"courriers/newsletter_raw_detail.html",
{
"object": newsletter,
"items": newsletter.items.all().prefetch_related("newsletter"),
"subscriber": subscriber,
},
)
<|code_end|>
. Write the next line using the current file imports:
from .base import BaseBackend
from django.core import mail
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
from django.utils import translation
from django.contrib.auth import get_user_model
from ..settings import DEFAULT_FROM_EMAIL, PRE_PROCESSORS
from ..utils import load_class
and context from other files:
# Path: courriers/backends/base.py
# class BaseBackend(object):
# def register(self, email, lang=None, user=None):
# raise NotImplemented
#
# def unregister(self, email, user=None):
# raise NotImplemented
#
# def exists(self, email, user=None):
# raise NotImplemented
#
# def send_mails(self, newsletter):
# raise NotImplemented
#
# Path: courriers/settings.py
# DEFAULT_FROM_EMAIL = getattr(
# settings, "COURRIERS_DEFAULT_FROM_EMAIL", settings.DEFAULT_FROM_EMAIL
# )
#
# PRE_PROCESSORS = getattr(settings, "COURRIERS_PRE_PROCESSORS", ())
#
# Path: courriers/utils.py
# def load_class(class_path, setting_name=None):
# """
# Loads a class given a class_path. The setting value may be a string or a
# tuple.
#
# The setting_name parameter is only there for pretty error output, and
# therefore is optional
# """
# if not isinstance(class_path, str):
# try:
# class_path, app_label = class_path
# except Exception:
# if setting_name:
# raise exceptions.ImproperlyConfigured(
# CLASS_PATH_ERROR % (setting_name, setting_name)
# )
# else:
# raise exceptions.ImproperlyConfigured(
# CLASS_PATH_ERROR % ("this setting", "It")
# )
#
# try:
# class_module, class_name = class_path.rsplit(".", 1)
# except ValueError:
# if setting_name:
# txt = "%s isn't a valid module. Check your %s setting" % (
# class_path,
# setting_name,
# )
# else:
# txt = "%s isn't a valid module." % class_path
# raise exceptions.ImproperlyConfigured(txt)
#
# try:
# mod = import_module(class_module)
# except ImportError as e:
# if setting_name:
# txt = 'Error importing backend %s: "%s". Check your %s setting' % (
# class_module,
# e,
# setting_name,
# )
# else:
# txt = 'Error importing backend %s: "%s".' % (class_module, e)
#
# raise exceptions.ImproperlyConfigured(txt)
#
# try:
# clazz = getattr(mod, class_name)
# except AttributeError:
# if setting_name:
# txt = (
# 'Backend module "%s" does not define a "%s" class. Check'
# " your %s setting" % (class_module, class_name, setting_name)
# )
# else:
# txt = 'Backend module "%s" does not define a "%s" class.' % (
# class_module,
# class_name,
# )
# raise exceptions.ImproperlyConfigured(txt)
# return clazz
, which may include functions, classes, or code. Output only the next line. | for pre_processor in PRE_PROCESSORS: |
Given the following code snippet before the placeholder: <|code_start|> for subscriber in subscribers:
if (
newsletter.newsletter_segment.lang
and newsletter.newsletter_segment.lang != subscriber.lang
):
continue
translation.activate(subscriber.lang)
email = EmailMultiAlternatives(
newsletter.name,
render_to_string(
"courriers/newsletter_raw_detail.txt",
{"object": newsletter, "subscriber": subscriber},
),
DEFAULT_FROM_EMAIL,
[subscriber.email],
connection=connection,
)
html = render_to_string(
"courriers/newsletter_raw_detail.html",
{
"object": newsletter,
"items": newsletter.items.all().prefetch_related("newsletter"),
"subscriber": subscriber,
},
)
for pre_processor in PRE_PROCESSORS:
<|code_end|>
, predict the next line using imports from the current file:
from .base import BaseBackend
from django.core import mail
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
from django.utils import translation
from django.contrib.auth import get_user_model
from ..settings import DEFAULT_FROM_EMAIL, PRE_PROCESSORS
from ..utils import load_class
and context including class names, function names, and sometimes code from other files:
# Path: courriers/backends/base.py
# class BaseBackend(object):
# def register(self, email, lang=None, user=None):
# raise NotImplemented
#
# def unregister(self, email, user=None):
# raise NotImplemented
#
# def exists(self, email, user=None):
# raise NotImplemented
#
# def send_mails(self, newsletter):
# raise NotImplemented
#
# Path: courriers/settings.py
# DEFAULT_FROM_EMAIL = getattr(
# settings, "COURRIERS_DEFAULT_FROM_EMAIL", settings.DEFAULT_FROM_EMAIL
# )
#
# PRE_PROCESSORS = getattr(settings, "COURRIERS_PRE_PROCESSORS", ())
#
# Path: courriers/utils.py
# def load_class(class_path, setting_name=None):
# """
# Loads a class given a class_path. The setting value may be a string or a
# tuple.
#
# The setting_name parameter is only there for pretty error output, and
# therefore is optional
# """
# if not isinstance(class_path, str):
# try:
# class_path, app_label = class_path
# except Exception:
# if setting_name:
# raise exceptions.ImproperlyConfigured(
# CLASS_PATH_ERROR % (setting_name, setting_name)
# )
# else:
# raise exceptions.ImproperlyConfigured(
# CLASS_PATH_ERROR % ("this setting", "It")
# )
#
# try:
# class_module, class_name = class_path.rsplit(".", 1)
# except ValueError:
# if setting_name:
# txt = "%s isn't a valid module. Check your %s setting" % (
# class_path,
# setting_name,
# )
# else:
# txt = "%s isn't a valid module." % class_path
# raise exceptions.ImproperlyConfigured(txt)
#
# try:
# mod = import_module(class_module)
# except ImportError as e:
# if setting_name:
# txt = 'Error importing backend %s: "%s". Check your %s setting' % (
# class_module,
# e,
# setting_name,
# )
# else:
# txt = 'Error importing backend %s: "%s".' % (class_module, e)
#
# raise exceptions.ImproperlyConfigured(txt)
#
# try:
# clazz = getattr(mod, class_name)
# except AttributeError:
# if setting_name:
# txt = (
# 'Backend module "%s" does not define a "%s" class. Check'
# " your %s setting" % (class_module, class_name, setting_name)
# )
# else:
# txt = 'Backend module "%s" does not define a "%s" class.' % (
# class_module,
# class_name,
# )
# raise exceptions.ImproperlyConfigured(txt)
# return clazz
. Output only the next line. | html = load_class(pre_processor)(html) |
Given snippet: <|code_start|>from __future__ import absolute_import, unicode_literals
class MailjetRESTBackend(CampaignBackend):
def __init__(self):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from mailjet_rest import Client
from django.core.exceptions import ImproperlyConfigured
from django.template.loader import render_to_string
from ..settings import (
MAILJET_API_KEY,
DEFAULT_FROM_EMAIL,
DEFAULT_FROM_NAME,
MAILJET_API_SECRET_KEY,
PRE_PROCESSORS,
)
from .campaign import CampaignBackend
from ..utils import load_class
and context:
# Path: courriers/settings.py
# MAILJET_API_KEY = getattr(settings, "COURRIERS_MAILJET_API_KEY", "")
#
# DEFAULT_FROM_EMAIL = getattr(
# settings, "COURRIERS_DEFAULT_FROM_EMAIL", settings.DEFAULT_FROM_EMAIL
# )
#
# DEFAULT_FROM_NAME = getattr(settings, "COURRIERS_DEFAULT_FROM_NAME", "")
#
# MAILJET_API_SECRET_KEY = getattr(settings, "COURRIERS_MAILJET_API_SECRET_KEY", "")
#
# PRE_PROCESSORS = getattr(settings, "COURRIERS_PRE_PROCESSORS", ())
#
# Path: courriers/backends/campaign.py
# class CampaignBackend(SimpleBackend):
# def send_mails(self, newsletter):
# if not newsletter.is_online():
# raise Exception("This newsletter is not online. You can't send it.")
#
# nl_list = newsletter.newsletter_list
# nl_segment = newsletter.newsletter_segment
# self.send_campaign(newsletter, nl_list.list_id, nl_segment.segment_id)
#
# def _format_slug(self, *args):
# raise NotImplementedError
#
# def send_campaign(self, newsletter, list_id, segment_id):
# if not DEFAULT_FROM_EMAIL:
# raise ImproperlyConfigured(
# "You have to specify a DEFAULT_FROM_EMAIL in Django settings."
# )
# if not DEFAULT_FROM_NAME:
# raise ImproperlyConfigured(
# "You have to specify a DEFAULT_FROM_NAME in Django settings."
# )
#
# old_language = translation.get_language()
# language = newsletter.newsletter_segment.lang or settings.LANGUAGE_CODE
#
# translation.activate(language)
#
# try:
# self._send_campaign(newsletter, list_id, segment_id=segment_id)
# except Exception as e:
# logger.exception(e)
#
# if not FAIL_SILENTLY:
# raise e
# else:
# newsletter.sent = True
# newsletter.save(update_fields=("sent",))
#
# translation.activate(old_language)
#
# def subscribe(self, email, list_id):
# pass
#
# def unsubscribe(self, email, list_id):
# pass
#
# Path: courriers/utils.py
# def load_class(class_path, setting_name=None):
# """
# Loads a class given a class_path. The setting value may be a string or a
# tuple.
#
# The setting_name parameter is only there for pretty error output, and
# therefore is optional
# """
# if not isinstance(class_path, str):
# try:
# class_path, app_label = class_path
# except Exception:
# if setting_name:
# raise exceptions.ImproperlyConfigured(
# CLASS_PATH_ERROR % (setting_name, setting_name)
# )
# else:
# raise exceptions.ImproperlyConfigured(
# CLASS_PATH_ERROR % ("this setting", "It")
# )
#
# try:
# class_module, class_name = class_path.rsplit(".", 1)
# except ValueError:
# if setting_name:
# txt = "%s isn't a valid module. Check your %s setting" % (
# class_path,
# setting_name,
# )
# else:
# txt = "%s isn't a valid module." % class_path
# raise exceptions.ImproperlyConfigured(txt)
#
# try:
# mod = import_module(class_module)
# except ImportError as e:
# if setting_name:
# txt = 'Error importing backend %s: "%s". Check your %s setting' % (
# class_module,
# e,
# setting_name,
# )
# else:
# txt = 'Error importing backend %s: "%s".' % (class_module, e)
#
# raise exceptions.ImproperlyConfigured(txt)
#
# try:
# clazz = getattr(mod, class_name)
# except AttributeError:
# if setting_name:
# txt = (
# 'Backend module "%s" does not define a "%s" class. Check'
# " your %s setting" % (class_module, class_name, setting_name)
# )
# else:
# txt = 'Backend module "%s" does not define a "%s" class.' % (
# class_module,
# class_name,
# )
# raise exceptions.ImproperlyConfigured(txt)
# return clazz
which might include code, classes, or functions. Output only the next line. | if not MAILJET_API_KEY: |
Given the code snippet: <|code_start|>from __future__ import absolute_import, unicode_literals
class MailjetRESTBackend(CampaignBackend):
def __init__(self):
if not MAILJET_API_KEY:
raise ImproperlyConfigured(
"Please specify your MAILJET API key in Django settings"
)
if not MAILJET_API_SECRET_KEY:
raise ImproperlyConfigured(
"Please specify your MAILJET API SECRET key in Django settings"
)
self.client = Client(auth=(MAILJET_API_KEY, MAILJET_API_SECRET_KEY))
def _send_campaign(self, newsletter, list_id, segment_id=None):
subject = newsletter.name
options = {
"Subject": subject,
"ContactsListID": list_id,
"Locale": "en",
<|code_end|>
, generate the next line using the imports in this file:
from mailjet_rest import Client
from django.core.exceptions import ImproperlyConfigured
from django.template.loader import render_to_string
from ..settings import (
MAILJET_API_KEY,
DEFAULT_FROM_EMAIL,
DEFAULT_FROM_NAME,
MAILJET_API_SECRET_KEY,
PRE_PROCESSORS,
)
from .campaign import CampaignBackend
from ..utils import load_class
and context (functions, classes, or occasionally code) from other files:
# Path: courriers/settings.py
# MAILJET_API_KEY = getattr(settings, "COURRIERS_MAILJET_API_KEY", "")
#
# DEFAULT_FROM_EMAIL = getattr(
# settings, "COURRIERS_DEFAULT_FROM_EMAIL", settings.DEFAULT_FROM_EMAIL
# )
#
# DEFAULT_FROM_NAME = getattr(settings, "COURRIERS_DEFAULT_FROM_NAME", "")
#
# MAILJET_API_SECRET_KEY = getattr(settings, "COURRIERS_MAILJET_API_SECRET_KEY", "")
#
# PRE_PROCESSORS = getattr(settings, "COURRIERS_PRE_PROCESSORS", ())
#
# Path: courriers/backends/campaign.py
# class CampaignBackend(SimpleBackend):
# def send_mails(self, newsletter):
# if not newsletter.is_online():
# raise Exception("This newsletter is not online. You can't send it.")
#
# nl_list = newsletter.newsletter_list
# nl_segment = newsletter.newsletter_segment
# self.send_campaign(newsletter, nl_list.list_id, nl_segment.segment_id)
#
# def _format_slug(self, *args):
# raise NotImplementedError
#
# def send_campaign(self, newsletter, list_id, segment_id):
# if not DEFAULT_FROM_EMAIL:
# raise ImproperlyConfigured(
# "You have to specify a DEFAULT_FROM_EMAIL in Django settings."
# )
# if not DEFAULT_FROM_NAME:
# raise ImproperlyConfigured(
# "You have to specify a DEFAULT_FROM_NAME in Django settings."
# )
#
# old_language = translation.get_language()
# language = newsletter.newsletter_segment.lang or settings.LANGUAGE_CODE
#
# translation.activate(language)
#
# try:
# self._send_campaign(newsletter, list_id, segment_id=segment_id)
# except Exception as e:
# logger.exception(e)
#
# if not FAIL_SILENTLY:
# raise e
# else:
# newsletter.sent = True
# newsletter.save(update_fields=("sent",))
#
# translation.activate(old_language)
#
# def subscribe(self, email, list_id):
# pass
#
# def unsubscribe(self, email, list_id):
# pass
#
# Path: courriers/utils.py
# def load_class(class_path, setting_name=None):
# """
# Loads a class given a class_path. The setting value may be a string or a
# tuple.
#
# The setting_name parameter is only there for pretty error output, and
# therefore is optional
# """
# if not isinstance(class_path, str):
# try:
# class_path, app_label = class_path
# except Exception:
# if setting_name:
# raise exceptions.ImproperlyConfigured(
# CLASS_PATH_ERROR % (setting_name, setting_name)
# )
# else:
# raise exceptions.ImproperlyConfigured(
# CLASS_PATH_ERROR % ("this setting", "It")
# )
#
# try:
# class_module, class_name = class_path.rsplit(".", 1)
# except ValueError:
# if setting_name:
# txt = "%s isn't a valid module. Check your %s setting" % (
# class_path,
# setting_name,
# )
# else:
# txt = "%s isn't a valid module." % class_path
# raise exceptions.ImproperlyConfigured(txt)
#
# try:
# mod = import_module(class_module)
# except ImportError as e:
# if setting_name:
# txt = 'Error importing backend %s: "%s". Check your %s setting' % (
# class_module,
# e,
# setting_name,
# )
# else:
# txt = 'Error importing backend %s: "%s".' % (class_module, e)
#
# raise exceptions.ImproperlyConfigured(txt)
#
# try:
# clazz = getattr(mod, class_name)
# except AttributeError:
# if setting_name:
# txt = (
# 'Backend module "%s" does not define a "%s" class. Check'
# " your %s setting" % (class_module, class_name, setting_name)
# )
# else:
# txt = 'Backend module "%s" does not define a "%s" class.' % (
# class_module,
# class_name,
# )
# raise exceptions.ImproperlyConfigured(txt)
# return clazz
. Output only the next line. | "SenderEmail": DEFAULT_FROM_EMAIL, |
Given snippet: <|code_start|>from __future__ import absolute_import, unicode_literals
class MailjetRESTBackend(CampaignBackend):
def __init__(self):
if not MAILJET_API_KEY:
raise ImproperlyConfigured(
"Please specify your MAILJET API key in Django settings"
)
if not MAILJET_API_SECRET_KEY:
raise ImproperlyConfigured(
"Please specify your MAILJET API SECRET key in Django settings"
)
self.client = Client(auth=(MAILJET_API_KEY, MAILJET_API_SECRET_KEY))
def _send_campaign(self, newsletter, list_id, segment_id=None):
subject = newsletter.name
options = {
"Subject": subject,
"ContactsListID": list_id,
"Locale": "en",
"SenderEmail": DEFAULT_FROM_EMAIL,
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from mailjet_rest import Client
from django.core.exceptions import ImproperlyConfigured
from django.template.loader import render_to_string
from ..settings import (
MAILJET_API_KEY,
DEFAULT_FROM_EMAIL,
DEFAULT_FROM_NAME,
MAILJET_API_SECRET_KEY,
PRE_PROCESSORS,
)
from .campaign import CampaignBackend
from ..utils import load_class
and context:
# Path: courriers/settings.py
# MAILJET_API_KEY = getattr(settings, "COURRIERS_MAILJET_API_KEY", "")
#
# DEFAULT_FROM_EMAIL = getattr(
# settings, "COURRIERS_DEFAULT_FROM_EMAIL", settings.DEFAULT_FROM_EMAIL
# )
#
# DEFAULT_FROM_NAME = getattr(settings, "COURRIERS_DEFAULT_FROM_NAME", "")
#
# MAILJET_API_SECRET_KEY = getattr(settings, "COURRIERS_MAILJET_API_SECRET_KEY", "")
#
# PRE_PROCESSORS = getattr(settings, "COURRIERS_PRE_PROCESSORS", ())
#
# Path: courriers/backends/campaign.py
# class CampaignBackend(SimpleBackend):
# def send_mails(self, newsletter):
# if not newsletter.is_online():
# raise Exception("This newsletter is not online. You can't send it.")
#
# nl_list = newsletter.newsletter_list
# nl_segment = newsletter.newsletter_segment
# self.send_campaign(newsletter, nl_list.list_id, nl_segment.segment_id)
#
# def _format_slug(self, *args):
# raise NotImplementedError
#
# def send_campaign(self, newsletter, list_id, segment_id):
# if not DEFAULT_FROM_EMAIL:
# raise ImproperlyConfigured(
# "You have to specify a DEFAULT_FROM_EMAIL in Django settings."
# )
# if not DEFAULT_FROM_NAME:
# raise ImproperlyConfigured(
# "You have to specify a DEFAULT_FROM_NAME in Django settings."
# )
#
# old_language = translation.get_language()
# language = newsletter.newsletter_segment.lang or settings.LANGUAGE_CODE
#
# translation.activate(language)
#
# try:
# self._send_campaign(newsletter, list_id, segment_id=segment_id)
# except Exception as e:
# logger.exception(e)
#
# if not FAIL_SILENTLY:
# raise e
# else:
# newsletter.sent = True
# newsletter.save(update_fields=("sent",))
#
# translation.activate(old_language)
#
# def subscribe(self, email, list_id):
# pass
#
# def unsubscribe(self, email, list_id):
# pass
#
# Path: courriers/utils.py
# def load_class(class_path, setting_name=None):
# """
# Loads a class given a class_path. The setting value may be a string or a
# tuple.
#
# The setting_name parameter is only there for pretty error output, and
# therefore is optional
# """
# if not isinstance(class_path, str):
# try:
# class_path, app_label = class_path
# except Exception:
# if setting_name:
# raise exceptions.ImproperlyConfigured(
# CLASS_PATH_ERROR % (setting_name, setting_name)
# )
# else:
# raise exceptions.ImproperlyConfigured(
# CLASS_PATH_ERROR % ("this setting", "It")
# )
#
# try:
# class_module, class_name = class_path.rsplit(".", 1)
# except ValueError:
# if setting_name:
# txt = "%s isn't a valid module. Check your %s setting" % (
# class_path,
# setting_name,
# )
# else:
# txt = "%s isn't a valid module." % class_path
# raise exceptions.ImproperlyConfigured(txt)
#
# try:
# mod = import_module(class_module)
# except ImportError as e:
# if setting_name:
# txt = 'Error importing backend %s: "%s". Check your %s setting' % (
# class_module,
# e,
# setting_name,
# )
# else:
# txt = 'Error importing backend %s: "%s".' % (class_module, e)
#
# raise exceptions.ImproperlyConfigured(txt)
#
# try:
# clazz = getattr(mod, class_name)
# except AttributeError:
# if setting_name:
# txt = (
# 'Backend module "%s" does not define a "%s" class. Check'
# " your %s setting" % (class_module, class_name, setting_name)
# )
# else:
# txt = 'Backend module "%s" does not define a "%s" class.' % (
# class_module,
# class_name,
# )
# raise exceptions.ImproperlyConfigured(txt)
# return clazz
which might include code, classes, or functions. Output only the next line. | "Sender": DEFAULT_FROM_NAME, |
Predict the next line for this snippet: <|code_start|>from __future__ import absolute_import, unicode_literals
class MailjetRESTBackend(CampaignBackend):
def __init__(self):
if not MAILJET_API_KEY:
raise ImproperlyConfigured(
"Please specify your MAILJET API key in Django settings"
)
<|code_end|>
with the help of current file imports:
from mailjet_rest import Client
from django.core.exceptions import ImproperlyConfigured
from django.template.loader import render_to_string
from ..settings import (
MAILJET_API_KEY,
DEFAULT_FROM_EMAIL,
DEFAULT_FROM_NAME,
MAILJET_API_SECRET_KEY,
PRE_PROCESSORS,
)
from .campaign import CampaignBackend
from ..utils import load_class
and context from other files:
# Path: courriers/settings.py
# MAILJET_API_KEY = getattr(settings, "COURRIERS_MAILJET_API_KEY", "")
#
# DEFAULT_FROM_EMAIL = getattr(
# settings, "COURRIERS_DEFAULT_FROM_EMAIL", settings.DEFAULT_FROM_EMAIL
# )
#
# DEFAULT_FROM_NAME = getattr(settings, "COURRIERS_DEFAULT_FROM_NAME", "")
#
# MAILJET_API_SECRET_KEY = getattr(settings, "COURRIERS_MAILJET_API_SECRET_KEY", "")
#
# PRE_PROCESSORS = getattr(settings, "COURRIERS_PRE_PROCESSORS", ())
#
# Path: courriers/backends/campaign.py
# class CampaignBackend(SimpleBackend):
# def send_mails(self, newsletter):
# if not newsletter.is_online():
# raise Exception("This newsletter is not online. You can't send it.")
#
# nl_list = newsletter.newsletter_list
# nl_segment = newsletter.newsletter_segment
# self.send_campaign(newsletter, nl_list.list_id, nl_segment.segment_id)
#
# def _format_slug(self, *args):
# raise NotImplementedError
#
# def send_campaign(self, newsletter, list_id, segment_id):
# if not DEFAULT_FROM_EMAIL:
# raise ImproperlyConfigured(
# "You have to specify a DEFAULT_FROM_EMAIL in Django settings."
# )
# if not DEFAULT_FROM_NAME:
# raise ImproperlyConfigured(
# "You have to specify a DEFAULT_FROM_NAME in Django settings."
# )
#
# old_language = translation.get_language()
# language = newsletter.newsletter_segment.lang or settings.LANGUAGE_CODE
#
# translation.activate(language)
#
# try:
# self._send_campaign(newsletter, list_id, segment_id=segment_id)
# except Exception as e:
# logger.exception(e)
#
# if not FAIL_SILENTLY:
# raise e
# else:
# newsletter.sent = True
# newsletter.save(update_fields=("sent",))
#
# translation.activate(old_language)
#
# def subscribe(self, email, list_id):
# pass
#
# def unsubscribe(self, email, list_id):
# pass
#
# Path: courriers/utils.py
# def load_class(class_path, setting_name=None):
# """
# Loads a class given a class_path. The setting value may be a string or a
# tuple.
#
# The setting_name parameter is only there for pretty error output, and
# therefore is optional
# """
# if not isinstance(class_path, str):
# try:
# class_path, app_label = class_path
# except Exception:
# if setting_name:
# raise exceptions.ImproperlyConfigured(
# CLASS_PATH_ERROR % (setting_name, setting_name)
# )
# else:
# raise exceptions.ImproperlyConfigured(
# CLASS_PATH_ERROR % ("this setting", "It")
# )
#
# try:
# class_module, class_name = class_path.rsplit(".", 1)
# except ValueError:
# if setting_name:
# txt = "%s isn't a valid module. Check your %s setting" % (
# class_path,
# setting_name,
# )
# else:
# txt = "%s isn't a valid module." % class_path
# raise exceptions.ImproperlyConfigured(txt)
#
# try:
# mod = import_module(class_module)
# except ImportError as e:
# if setting_name:
# txt = 'Error importing backend %s: "%s". Check your %s setting' % (
# class_module,
# e,
# setting_name,
# )
# else:
# txt = 'Error importing backend %s: "%s".' % (class_module, e)
#
# raise exceptions.ImproperlyConfigured(txt)
#
# try:
# clazz = getattr(mod, class_name)
# except AttributeError:
# if setting_name:
# txt = (
# 'Backend module "%s" does not define a "%s" class. Check'
# " your %s setting" % (class_module, class_name, setting_name)
# )
# else:
# txt = 'Backend module "%s" does not define a "%s" class.' % (
# class_module,
# class_name,
# )
# raise exceptions.ImproperlyConfigured(txt)
# return clazz
, which may contain function names, class names, or code. Output only the next line. | if not MAILJET_API_SECRET_KEY: |
Based on the snippet: <|code_start|> "Please specify your MAILJET API SECRET key in Django settings"
)
self.client = Client(auth=(MAILJET_API_KEY, MAILJET_API_SECRET_KEY))
def _send_campaign(self, newsletter, list_id, segment_id=None):
subject = newsletter.name
options = {
"Subject": subject,
"ContactsListID": list_id,
"Locale": "en",
"SenderEmail": DEFAULT_FROM_EMAIL,
"Sender": DEFAULT_FROM_NAME,
"SenderName": DEFAULT_FROM_NAME,
"Title": subject,
}
if segment_id:
options["SegmentationID"] = segment_id
context = {
"object": newsletter,
"items": newsletter.items.select_related("newsletter"),
"options": options,
}
html = render_to_string("courriers/newsletter_raw_detail.html", context)
text = render_to_string("courriers/newsletter_raw_detail.txt", context)
<|code_end|>
, predict the immediate next line with the help of imports:
from mailjet_rest import Client
from django.core.exceptions import ImproperlyConfigured
from django.template.loader import render_to_string
from ..settings import (
MAILJET_API_KEY,
DEFAULT_FROM_EMAIL,
DEFAULT_FROM_NAME,
MAILJET_API_SECRET_KEY,
PRE_PROCESSORS,
)
from .campaign import CampaignBackend
from ..utils import load_class
and context (classes, functions, sometimes code) from other files:
# Path: courriers/settings.py
# MAILJET_API_KEY = getattr(settings, "COURRIERS_MAILJET_API_KEY", "")
#
# DEFAULT_FROM_EMAIL = getattr(
# settings, "COURRIERS_DEFAULT_FROM_EMAIL", settings.DEFAULT_FROM_EMAIL
# )
#
# DEFAULT_FROM_NAME = getattr(settings, "COURRIERS_DEFAULT_FROM_NAME", "")
#
# MAILJET_API_SECRET_KEY = getattr(settings, "COURRIERS_MAILJET_API_SECRET_KEY", "")
#
# PRE_PROCESSORS = getattr(settings, "COURRIERS_PRE_PROCESSORS", ())
#
# Path: courriers/backends/campaign.py
# class CampaignBackend(SimpleBackend):
# def send_mails(self, newsletter):
# if not newsletter.is_online():
# raise Exception("This newsletter is not online. You can't send it.")
#
# nl_list = newsletter.newsletter_list
# nl_segment = newsletter.newsletter_segment
# self.send_campaign(newsletter, nl_list.list_id, nl_segment.segment_id)
#
# def _format_slug(self, *args):
# raise NotImplementedError
#
# def send_campaign(self, newsletter, list_id, segment_id):
# if not DEFAULT_FROM_EMAIL:
# raise ImproperlyConfigured(
# "You have to specify a DEFAULT_FROM_EMAIL in Django settings."
# )
# if not DEFAULT_FROM_NAME:
# raise ImproperlyConfigured(
# "You have to specify a DEFAULT_FROM_NAME in Django settings."
# )
#
# old_language = translation.get_language()
# language = newsletter.newsletter_segment.lang or settings.LANGUAGE_CODE
#
# translation.activate(language)
#
# try:
# self._send_campaign(newsletter, list_id, segment_id=segment_id)
# except Exception as e:
# logger.exception(e)
#
# if not FAIL_SILENTLY:
# raise e
# else:
# newsletter.sent = True
# newsletter.save(update_fields=("sent",))
#
# translation.activate(old_language)
#
# def subscribe(self, email, list_id):
# pass
#
# def unsubscribe(self, email, list_id):
# pass
#
# Path: courriers/utils.py
# def load_class(class_path, setting_name=None):
# """
# Loads a class given a class_path. The setting value may be a string or a
# tuple.
#
# The setting_name parameter is only there for pretty error output, and
# therefore is optional
# """
# if not isinstance(class_path, str):
# try:
# class_path, app_label = class_path
# except Exception:
# if setting_name:
# raise exceptions.ImproperlyConfigured(
# CLASS_PATH_ERROR % (setting_name, setting_name)
# )
# else:
# raise exceptions.ImproperlyConfigured(
# CLASS_PATH_ERROR % ("this setting", "It")
# )
#
# try:
# class_module, class_name = class_path.rsplit(".", 1)
# except ValueError:
# if setting_name:
# txt = "%s isn't a valid module. Check your %s setting" % (
# class_path,
# setting_name,
# )
# else:
# txt = "%s isn't a valid module." % class_path
# raise exceptions.ImproperlyConfigured(txt)
#
# try:
# mod = import_module(class_module)
# except ImportError as e:
# if setting_name:
# txt = 'Error importing backend %s: "%s". Check your %s setting' % (
# class_module,
# e,
# setting_name,
# )
# else:
# txt = 'Error importing backend %s: "%s".' % (class_module, e)
#
# raise exceptions.ImproperlyConfigured(txt)
#
# try:
# clazz = getattr(mod, class_name)
# except AttributeError:
# if setting_name:
# txt = (
# 'Backend module "%s" does not define a "%s" class. Check'
# " your %s setting" % (class_module, class_name, setting_name)
# )
# else:
# txt = 'Backend module "%s" does not define a "%s" class.' % (
# class_module,
# class_name,
# )
# raise exceptions.ImproperlyConfigured(txt)
# return clazz
. Output only the next line. | for pre_processor in PRE_PROCESSORS: |
Next line prediction: <|code_start|> )
self.client = Client(auth=(MAILJET_API_KEY, MAILJET_API_SECRET_KEY))
def _send_campaign(self, newsletter, list_id, segment_id=None):
subject = newsletter.name
options = {
"Subject": subject,
"ContactsListID": list_id,
"Locale": "en",
"SenderEmail": DEFAULT_FROM_EMAIL,
"Sender": DEFAULT_FROM_NAME,
"SenderName": DEFAULT_FROM_NAME,
"Title": subject,
}
if segment_id:
options["SegmentationID"] = segment_id
context = {
"object": newsletter,
"items": newsletter.items.select_related("newsletter"),
"options": options,
}
html = render_to_string("courriers/newsletter_raw_detail.html", context)
text = render_to_string("courriers/newsletter_raw_detail.txt", context)
for pre_processor in PRE_PROCESSORS:
<|code_end|>
. Use current file imports:
(from mailjet_rest import Client
from django.core.exceptions import ImproperlyConfigured
from django.template.loader import render_to_string
from ..settings import (
MAILJET_API_KEY,
DEFAULT_FROM_EMAIL,
DEFAULT_FROM_NAME,
MAILJET_API_SECRET_KEY,
PRE_PROCESSORS,
)
from .campaign import CampaignBackend
from ..utils import load_class)
and context including class names, function names, or small code snippets from other files:
# Path: courriers/settings.py
# MAILJET_API_KEY = getattr(settings, "COURRIERS_MAILJET_API_KEY", "")
#
# DEFAULT_FROM_EMAIL = getattr(
# settings, "COURRIERS_DEFAULT_FROM_EMAIL", settings.DEFAULT_FROM_EMAIL
# )
#
# DEFAULT_FROM_NAME = getattr(settings, "COURRIERS_DEFAULT_FROM_NAME", "")
#
# MAILJET_API_SECRET_KEY = getattr(settings, "COURRIERS_MAILJET_API_SECRET_KEY", "")
#
# PRE_PROCESSORS = getattr(settings, "COURRIERS_PRE_PROCESSORS", ())
#
# Path: courriers/backends/campaign.py
# class CampaignBackend(SimpleBackend):
# def send_mails(self, newsletter):
# if not newsletter.is_online():
# raise Exception("This newsletter is not online. You can't send it.")
#
# nl_list = newsletter.newsletter_list
# nl_segment = newsletter.newsletter_segment
# self.send_campaign(newsletter, nl_list.list_id, nl_segment.segment_id)
#
# def _format_slug(self, *args):
# raise NotImplementedError
#
# def send_campaign(self, newsletter, list_id, segment_id):
# if not DEFAULT_FROM_EMAIL:
# raise ImproperlyConfigured(
# "You have to specify a DEFAULT_FROM_EMAIL in Django settings."
# )
# if not DEFAULT_FROM_NAME:
# raise ImproperlyConfigured(
# "You have to specify a DEFAULT_FROM_NAME in Django settings."
# )
#
# old_language = translation.get_language()
# language = newsletter.newsletter_segment.lang or settings.LANGUAGE_CODE
#
# translation.activate(language)
#
# try:
# self._send_campaign(newsletter, list_id, segment_id=segment_id)
# except Exception as e:
# logger.exception(e)
#
# if not FAIL_SILENTLY:
# raise e
# else:
# newsletter.sent = True
# newsletter.save(update_fields=("sent",))
#
# translation.activate(old_language)
#
# def subscribe(self, email, list_id):
# pass
#
# def unsubscribe(self, email, list_id):
# pass
#
# Path: courriers/utils.py
# def load_class(class_path, setting_name=None):
# """
# Loads a class given a class_path. The setting value may be a string or a
# tuple.
#
# The setting_name parameter is only there for pretty error output, and
# therefore is optional
# """
# if not isinstance(class_path, str):
# try:
# class_path, app_label = class_path
# except Exception:
# if setting_name:
# raise exceptions.ImproperlyConfigured(
# CLASS_PATH_ERROR % (setting_name, setting_name)
# )
# else:
# raise exceptions.ImproperlyConfigured(
# CLASS_PATH_ERROR % ("this setting", "It")
# )
#
# try:
# class_module, class_name = class_path.rsplit(".", 1)
# except ValueError:
# if setting_name:
# txt = "%s isn't a valid module. Check your %s setting" % (
# class_path,
# setting_name,
# )
# else:
# txt = "%s isn't a valid module." % class_path
# raise exceptions.ImproperlyConfigured(txt)
#
# try:
# mod = import_module(class_module)
# except ImportError as e:
# if setting_name:
# txt = 'Error importing backend %s: "%s". Check your %s setting' % (
# class_module,
# e,
# setting_name,
# )
# else:
# txt = 'Error importing backend %s: "%s".' % (class_module, e)
#
# raise exceptions.ImproperlyConfigured(txt)
#
# try:
# clazz = getattr(mod, class_name)
# except AttributeError:
# if setting_name:
# txt = (
# 'Backend module "%s" does not define a "%s" class. Check'
# " your %s setting" % (class_module, class_name, setting_name)
# )
# else:
# txt = 'Backend module "%s" does not define a "%s" class.' % (
# class_module,
# class_name,
# )
# raise exceptions.ImproperlyConfigured(txt)
# return clazz
. Output only the next line. | html = load_class(pre_processor)(html) |
Continue the code snippet: <|code_start|> NewsletterDetailView.as_view(),
name="newsletter_detail",
),
url(
r"^(?P<slug>(\w+))/subscribe/$",
NewsletterListSubscribeView.as_view(),
name="newsletter_list_subscribe",
),
url(
r"^(?P<pk>(\d+))/raw/$",
NewsletterRawDetailView.as_view(),
name="newsletter_raw_detail",
),
url(
r"^(?:(?P<slug>(\w+))/)?unsubscribe/$",
NewsletterListUnsubscribeView.as_view(),
name="newsletter_list_unsubscribe",
),
url(
r"^subscribe/done/$",
NewsletterListSubscribeDoneView.as_view(),
name="newsletter_list_subscribe_done",
),
url(
r"^unsubscribe/(?:(?P<slug>(\w+))/)?done/$",
NewsletterListUnsubscribeDoneView.as_view(),
name="newsletter_list_unsubscribe_done",
),
url(
r"^(?P<slug>(\w+))/(?:(?P<lang>(\w+))/)?(?:(?P<page>(\d+))/)?$",
<|code_end|>
. Use current file imports:
from django.conf.urls import url
from .views import (
NewsletterListView,
NewsletterDetailView,
NewsletterListSubscribeView,
NewsletterRawDetailView,
NewsletterListUnsubscribeView,
NewsletterListSubscribeDoneView,
NewsletterListUnsubscribeDoneView,
)
and context (classes, functions, or code) from other files:
# Path: courriers/views.py
# class NewsletterListView(AJAXResponseMixin, ListView):
# model = Newsletter
# context_object_name = "newsletters"
# template_name = "courriers/newsletter_list.html"
# paginate_by = PAGINATE_BY
#
# def dispatch(self, *args, **kwargs):
# return super(NewsletterListView, self).dispatch(*args, **kwargs)
#
# @cached_property
# def newsletter_list(self):
# return get_object_or_404(
# NewsletterList.objects.all(), slug=self.kwargs.get("slug")
# )
#
# def get_queryset(self):
# lang = translation.get_language()
# qs = self.newsletter_list.newsletters.status_online()
# if lang:
# qs = qs.filter(newsletter_segment__lang=lang)
# qs = qs.order_by("-published_at")
# return qs
#
# def get_context_data(self, **kwargs):
# context = super(NewsletterListView, self).get_context_data(**kwargs)
# context["newsletter_list"] = self.newsletter_list
# return context
#
# class NewsletterDetailView(AJAXResponseMixin, DetailView):
# model = Newsletter
# context_object_name = "newsletter"
# template_name = "courriers/newsletter_detail.html"
#
# def get_queryset(self):
# return self.model.objects.status_online()
#
# def get_context_data(self, **kwargs):
# context = super(NewsletterDetailView, self).get_context_data(**kwargs)
#
# context["newsletter_list"] = self.object.newsletter_list
#
# return context
#
# class NewsletterListSubscribeView(BaseNewsletterListFormView):
# template_name = "courriers/newsletter_list_subscribe_form.html"
# form_class = SubscriptionForm
#
# def get_success_url(self):
# return reverse("newsletter_list_subscribe_done")
#
# class NewsletterRawDetailView(AJAXResponseMixin, DetailView):
# model = Newsletter
# template_name = "courriers/newsletter_raw_detail.html"
#
# def get_context_data(self, **kwargs):
# context = super(NewsletterRawDetailView, self).get_context_data(**kwargs)
#
# context["items"] = self.object.items.all()
#
# for item in context["items"]:
# item.newsletter = self.object
#
# return context
#
# class NewsletterListUnsubscribeView(BaseNewsletterListFormView):
# template_name = "courriers/newsletter_list_unsubscribe.html"
#
# def get_form_class(self):
# return UnsubscribeForm
#
# def get_initial(self):
# initial = super(NewsletterListUnsubscribeView, self).get_initial()
# email = self.request.GET.get("email", None)
#
# if email:
# initial["email"] = email
#
# return initial.copy()
#
# def get_success_url(self):
# if self.object:
# return reverse(
# "newsletter_list_unsubscribe_done", kwargs={"slug": self.object.slug}
# )
#
# return reverse("newsletter_list_unsubscribe_done")
#
# class NewsletterListSubscribeDoneView(AJAXResponseMixin, TemplateView):
# template_name = "courriers/newsletter_list_subscribe_done.html"
# model = NewsletterList
# context_object_name = "newsletter_list"
#
# class NewsletterListUnsubscribeDoneView(AJAXResponseMixin, TemplateView):
# template_name = "courriers/newsletter_list_unsubscribe_done.html"
# model = NewsletterList
# context_object_name = "newsletter_list"
#
# def get_context_data(self, **kwargs):
# context = super(NewsletterListUnsubscribeDoneView, self).get_context_data(
# **kwargs
# )
#
# slug = self.kwargs.get("slug", None)
#
# if slug:
# context[self.context_object_name] = get_object_or_404(self.model, slug=slug)
#
# return context
. Output only the next line. | NewsletterListView.as_view(), |
Continue the code snippet: <|code_start|>
urlpatterns = [
url(
r"^(?P<pk>(\d+))/detail/$",
<|code_end|>
. Use current file imports:
from django.conf.urls import url
from .views import (
NewsletterListView,
NewsletterDetailView,
NewsletterListSubscribeView,
NewsletterRawDetailView,
NewsletterListUnsubscribeView,
NewsletterListSubscribeDoneView,
NewsletterListUnsubscribeDoneView,
)
and context (classes, functions, or code) from other files:
# Path: courriers/views.py
# class NewsletterListView(AJAXResponseMixin, ListView):
# model = Newsletter
# context_object_name = "newsletters"
# template_name = "courriers/newsletter_list.html"
# paginate_by = PAGINATE_BY
#
# def dispatch(self, *args, **kwargs):
# return super(NewsletterListView, self).dispatch(*args, **kwargs)
#
# @cached_property
# def newsletter_list(self):
# return get_object_or_404(
# NewsletterList.objects.all(), slug=self.kwargs.get("slug")
# )
#
# def get_queryset(self):
# lang = translation.get_language()
# qs = self.newsletter_list.newsletters.status_online()
# if lang:
# qs = qs.filter(newsletter_segment__lang=lang)
# qs = qs.order_by("-published_at")
# return qs
#
# def get_context_data(self, **kwargs):
# context = super(NewsletterListView, self).get_context_data(**kwargs)
# context["newsletter_list"] = self.newsletter_list
# return context
#
# class NewsletterDetailView(AJAXResponseMixin, DetailView):
# model = Newsletter
# context_object_name = "newsletter"
# template_name = "courriers/newsletter_detail.html"
#
# def get_queryset(self):
# return self.model.objects.status_online()
#
# def get_context_data(self, **kwargs):
# context = super(NewsletterDetailView, self).get_context_data(**kwargs)
#
# context["newsletter_list"] = self.object.newsletter_list
#
# return context
#
# class NewsletterListSubscribeView(BaseNewsletterListFormView):
# template_name = "courriers/newsletter_list_subscribe_form.html"
# form_class = SubscriptionForm
#
# def get_success_url(self):
# return reverse("newsletter_list_subscribe_done")
#
# class NewsletterRawDetailView(AJAXResponseMixin, DetailView):
# model = Newsletter
# template_name = "courriers/newsletter_raw_detail.html"
#
# def get_context_data(self, **kwargs):
# context = super(NewsletterRawDetailView, self).get_context_data(**kwargs)
#
# context["items"] = self.object.items.all()
#
# for item in context["items"]:
# item.newsletter = self.object
#
# return context
#
# class NewsletterListUnsubscribeView(BaseNewsletterListFormView):
# template_name = "courriers/newsletter_list_unsubscribe.html"
#
# def get_form_class(self):
# return UnsubscribeForm
#
# def get_initial(self):
# initial = super(NewsletterListUnsubscribeView, self).get_initial()
# email = self.request.GET.get("email", None)
#
# if email:
# initial["email"] = email
#
# return initial.copy()
#
# def get_success_url(self):
# if self.object:
# return reverse(
# "newsletter_list_unsubscribe_done", kwargs={"slug": self.object.slug}
# )
#
# return reverse("newsletter_list_unsubscribe_done")
#
# class NewsletterListSubscribeDoneView(AJAXResponseMixin, TemplateView):
# template_name = "courriers/newsletter_list_subscribe_done.html"
# model = NewsletterList
# context_object_name = "newsletter_list"
#
# class NewsletterListUnsubscribeDoneView(AJAXResponseMixin, TemplateView):
# template_name = "courriers/newsletter_list_unsubscribe_done.html"
# model = NewsletterList
# context_object_name = "newsletter_list"
#
# def get_context_data(self, **kwargs):
# context = super(NewsletterListUnsubscribeDoneView, self).get_context_data(
# **kwargs
# )
#
# slug = self.kwargs.get("slug", None)
#
# if slug:
# context[self.context_object_name] = get_object_or_404(self.model, slug=slug)
#
# return context
. Output only the next line. | NewsletterDetailView.as_view(), |
Predict the next line for this snippet: <|code_start|>
urlpatterns = [
url(
r"^(?P<pk>(\d+))/detail/$",
NewsletterDetailView.as_view(),
name="newsletter_detail",
),
url(
r"^(?P<slug>(\w+))/subscribe/$",
<|code_end|>
with the help of current file imports:
from django.conf.urls import url
from .views import (
NewsletterListView,
NewsletterDetailView,
NewsletterListSubscribeView,
NewsletterRawDetailView,
NewsletterListUnsubscribeView,
NewsletterListSubscribeDoneView,
NewsletterListUnsubscribeDoneView,
)
and context from other files:
# Path: courriers/views.py
# class NewsletterListView(AJAXResponseMixin, ListView):
# model = Newsletter
# context_object_name = "newsletters"
# template_name = "courriers/newsletter_list.html"
# paginate_by = PAGINATE_BY
#
# def dispatch(self, *args, **kwargs):
# return super(NewsletterListView, self).dispatch(*args, **kwargs)
#
# @cached_property
# def newsletter_list(self):
# return get_object_or_404(
# NewsletterList.objects.all(), slug=self.kwargs.get("slug")
# )
#
# def get_queryset(self):
# lang = translation.get_language()
# qs = self.newsletter_list.newsletters.status_online()
# if lang:
# qs = qs.filter(newsletter_segment__lang=lang)
# qs = qs.order_by("-published_at")
# return qs
#
# def get_context_data(self, **kwargs):
# context = super(NewsletterListView, self).get_context_data(**kwargs)
# context["newsletter_list"] = self.newsletter_list
# return context
#
# class NewsletterDetailView(AJAXResponseMixin, DetailView):
# model = Newsletter
# context_object_name = "newsletter"
# template_name = "courriers/newsletter_detail.html"
#
# def get_queryset(self):
# return self.model.objects.status_online()
#
# def get_context_data(self, **kwargs):
# context = super(NewsletterDetailView, self).get_context_data(**kwargs)
#
# context["newsletter_list"] = self.object.newsletter_list
#
# return context
#
# class NewsletterListSubscribeView(BaseNewsletterListFormView):
# template_name = "courriers/newsletter_list_subscribe_form.html"
# form_class = SubscriptionForm
#
# def get_success_url(self):
# return reverse("newsletter_list_subscribe_done")
#
# class NewsletterRawDetailView(AJAXResponseMixin, DetailView):
# model = Newsletter
# template_name = "courriers/newsletter_raw_detail.html"
#
# def get_context_data(self, **kwargs):
# context = super(NewsletterRawDetailView, self).get_context_data(**kwargs)
#
# context["items"] = self.object.items.all()
#
# for item in context["items"]:
# item.newsletter = self.object
#
# return context
#
# class NewsletterListUnsubscribeView(BaseNewsletterListFormView):
# template_name = "courriers/newsletter_list_unsubscribe.html"
#
# def get_form_class(self):
# return UnsubscribeForm
#
# def get_initial(self):
# initial = super(NewsletterListUnsubscribeView, self).get_initial()
# email = self.request.GET.get("email", None)
#
# if email:
# initial["email"] = email
#
# return initial.copy()
#
# def get_success_url(self):
# if self.object:
# return reverse(
# "newsletter_list_unsubscribe_done", kwargs={"slug": self.object.slug}
# )
#
# return reverse("newsletter_list_unsubscribe_done")
#
# class NewsletterListSubscribeDoneView(AJAXResponseMixin, TemplateView):
# template_name = "courriers/newsletter_list_subscribe_done.html"
# model = NewsletterList
# context_object_name = "newsletter_list"
#
# class NewsletterListUnsubscribeDoneView(AJAXResponseMixin, TemplateView):
# template_name = "courriers/newsletter_list_unsubscribe_done.html"
# model = NewsletterList
# context_object_name = "newsletter_list"
#
# def get_context_data(self, **kwargs):
# context = super(NewsletterListUnsubscribeDoneView, self).get_context_data(
# **kwargs
# )
#
# slug = self.kwargs.get("slug", None)
#
# if slug:
# context[self.context_object_name] = get_object_or_404(self.model, slug=slug)
#
# return context
, which may contain function names, class names, or code. Output only the next line. | NewsletterListSubscribeView.as_view(), |
Predict the next line for this snippet: <|code_start|>
urlpatterns = [
url(
r"^(?P<pk>(\d+))/detail/$",
NewsletterDetailView.as_view(),
name="newsletter_detail",
),
url(
r"^(?P<slug>(\w+))/subscribe/$",
NewsletterListSubscribeView.as_view(),
name="newsletter_list_subscribe",
),
url(
r"^(?P<pk>(\d+))/raw/$",
<|code_end|>
with the help of current file imports:
from django.conf.urls import url
from .views import (
NewsletterListView,
NewsletterDetailView,
NewsletterListSubscribeView,
NewsletterRawDetailView,
NewsletterListUnsubscribeView,
NewsletterListSubscribeDoneView,
NewsletterListUnsubscribeDoneView,
)
and context from other files:
# Path: courriers/views.py
# class NewsletterListView(AJAXResponseMixin, ListView):
# model = Newsletter
# context_object_name = "newsletters"
# template_name = "courriers/newsletter_list.html"
# paginate_by = PAGINATE_BY
#
# def dispatch(self, *args, **kwargs):
# return super(NewsletterListView, self).dispatch(*args, **kwargs)
#
# @cached_property
# def newsletter_list(self):
# return get_object_or_404(
# NewsletterList.objects.all(), slug=self.kwargs.get("slug")
# )
#
# def get_queryset(self):
# lang = translation.get_language()
# qs = self.newsletter_list.newsletters.status_online()
# if lang:
# qs = qs.filter(newsletter_segment__lang=lang)
# qs = qs.order_by("-published_at")
# return qs
#
# def get_context_data(self, **kwargs):
# context = super(NewsletterListView, self).get_context_data(**kwargs)
# context["newsletter_list"] = self.newsletter_list
# return context
#
# class NewsletterDetailView(AJAXResponseMixin, DetailView):
# model = Newsletter
# context_object_name = "newsletter"
# template_name = "courriers/newsletter_detail.html"
#
# def get_queryset(self):
# return self.model.objects.status_online()
#
# def get_context_data(self, **kwargs):
# context = super(NewsletterDetailView, self).get_context_data(**kwargs)
#
# context["newsletter_list"] = self.object.newsletter_list
#
# return context
#
# class NewsletterListSubscribeView(BaseNewsletterListFormView):
# template_name = "courriers/newsletter_list_subscribe_form.html"
# form_class = SubscriptionForm
#
# def get_success_url(self):
# return reverse("newsletter_list_subscribe_done")
#
# class NewsletterRawDetailView(AJAXResponseMixin, DetailView):
# model = Newsletter
# template_name = "courriers/newsletter_raw_detail.html"
#
# def get_context_data(self, **kwargs):
# context = super(NewsletterRawDetailView, self).get_context_data(**kwargs)
#
# context["items"] = self.object.items.all()
#
# for item in context["items"]:
# item.newsletter = self.object
#
# return context
#
# class NewsletterListUnsubscribeView(BaseNewsletterListFormView):
# template_name = "courriers/newsletter_list_unsubscribe.html"
#
# def get_form_class(self):
# return UnsubscribeForm
#
# def get_initial(self):
# initial = super(NewsletterListUnsubscribeView, self).get_initial()
# email = self.request.GET.get("email", None)
#
# if email:
# initial["email"] = email
#
# return initial.copy()
#
# def get_success_url(self):
# if self.object:
# return reverse(
# "newsletter_list_unsubscribe_done", kwargs={"slug": self.object.slug}
# )
#
# return reverse("newsletter_list_unsubscribe_done")
#
# class NewsletterListSubscribeDoneView(AJAXResponseMixin, TemplateView):
# template_name = "courriers/newsletter_list_subscribe_done.html"
# model = NewsletterList
# context_object_name = "newsletter_list"
#
# class NewsletterListUnsubscribeDoneView(AJAXResponseMixin, TemplateView):
# template_name = "courriers/newsletter_list_unsubscribe_done.html"
# model = NewsletterList
# context_object_name = "newsletter_list"
#
# def get_context_data(self, **kwargs):
# context = super(NewsletterListUnsubscribeDoneView, self).get_context_data(
# **kwargs
# )
#
# slug = self.kwargs.get("slug", None)
#
# if slug:
# context[self.context_object_name] = get_object_or_404(self.model, slug=slug)
#
# return context
, which may contain function names, class names, or code. Output only the next line. | NewsletterRawDetailView.as_view(), |
Given the following code snippet before the placeholder: <|code_start|>
urlpatterns = [
url(
r"^(?P<pk>(\d+))/detail/$",
NewsletterDetailView.as_view(),
name="newsletter_detail",
),
url(
r"^(?P<slug>(\w+))/subscribe/$",
NewsletterListSubscribeView.as_view(),
name="newsletter_list_subscribe",
),
url(
r"^(?P<pk>(\d+))/raw/$",
NewsletterRawDetailView.as_view(),
name="newsletter_raw_detail",
),
url(
r"^(?:(?P<slug>(\w+))/)?unsubscribe/$",
<|code_end|>
, predict the next line using imports from the current file:
from django.conf.urls import url
from .views import (
NewsletterListView,
NewsletterDetailView,
NewsletterListSubscribeView,
NewsletterRawDetailView,
NewsletterListUnsubscribeView,
NewsletterListSubscribeDoneView,
NewsletterListUnsubscribeDoneView,
)
and context including class names, function names, and sometimes code from other files:
# Path: courriers/views.py
# class NewsletterListView(AJAXResponseMixin, ListView):
# model = Newsletter
# context_object_name = "newsletters"
# template_name = "courriers/newsletter_list.html"
# paginate_by = PAGINATE_BY
#
# def dispatch(self, *args, **kwargs):
# return super(NewsletterListView, self).dispatch(*args, **kwargs)
#
# @cached_property
# def newsletter_list(self):
# return get_object_or_404(
# NewsletterList.objects.all(), slug=self.kwargs.get("slug")
# )
#
# def get_queryset(self):
# lang = translation.get_language()
# qs = self.newsletter_list.newsletters.status_online()
# if lang:
# qs = qs.filter(newsletter_segment__lang=lang)
# qs = qs.order_by("-published_at")
# return qs
#
# def get_context_data(self, **kwargs):
# context = super(NewsletterListView, self).get_context_data(**kwargs)
# context["newsletter_list"] = self.newsletter_list
# return context
#
# class NewsletterDetailView(AJAXResponseMixin, DetailView):
# model = Newsletter
# context_object_name = "newsletter"
# template_name = "courriers/newsletter_detail.html"
#
# def get_queryset(self):
# return self.model.objects.status_online()
#
# def get_context_data(self, **kwargs):
# context = super(NewsletterDetailView, self).get_context_data(**kwargs)
#
# context["newsletter_list"] = self.object.newsletter_list
#
# return context
#
# class NewsletterListSubscribeView(BaseNewsletterListFormView):
# template_name = "courriers/newsletter_list_subscribe_form.html"
# form_class = SubscriptionForm
#
# def get_success_url(self):
# return reverse("newsletter_list_subscribe_done")
#
# class NewsletterRawDetailView(AJAXResponseMixin, DetailView):
# model = Newsletter
# template_name = "courriers/newsletter_raw_detail.html"
#
# def get_context_data(self, **kwargs):
# context = super(NewsletterRawDetailView, self).get_context_data(**kwargs)
#
# context["items"] = self.object.items.all()
#
# for item in context["items"]:
# item.newsletter = self.object
#
# return context
#
# class NewsletterListUnsubscribeView(BaseNewsletterListFormView):
# template_name = "courriers/newsletter_list_unsubscribe.html"
#
# def get_form_class(self):
# return UnsubscribeForm
#
# def get_initial(self):
# initial = super(NewsletterListUnsubscribeView, self).get_initial()
# email = self.request.GET.get("email", None)
#
# if email:
# initial["email"] = email
#
# return initial.copy()
#
# def get_success_url(self):
# if self.object:
# return reverse(
# "newsletter_list_unsubscribe_done", kwargs={"slug": self.object.slug}
# )
#
# return reverse("newsletter_list_unsubscribe_done")
#
# class NewsletterListSubscribeDoneView(AJAXResponseMixin, TemplateView):
# template_name = "courriers/newsletter_list_subscribe_done.html"
# model = NewsletterList
# context_object_name = "newsletter_list"
#
# class NewsletterListUnsubscribeDoneView(AJAXResponseMixin, TemplateView):
# template_name = "courriers/newsletter_list_unsubscribe_done.html"
# model = NewsletterList
# context_object_name = "newsletter_list"
#
# def get_context_data(self, **kwargs):
# context = super(NewsletterListUnsubscribeDoneView, self).get_context_data(
# **kwargs
# )
#
# slug = self.kwargs.get("slug", None)
#
# if slug:
# context[self.context_object_name] = get_object_or_404(self.model, slug=slug)
#
# return context
. Output only the next line. | NewsletterListUnsubscribeView.as_view(), |
Next line prediction: <|code_start|>
urlpatterns = [
url(
r"^(?P<pk>(\d+))/detail/$",
NewsletterDetailView.as_view(),
name="newsletter_detail",
),
url(
r"^(?P<slug>(\w+))/subscribe/$",
NewsletterListSubscribeView.as_view(),
name="newsletter_list_subscribe",
),
url(
r"^(?P<pk>(\d+))/raw/$",
NewsletterRawDetailView.as_view(),
name="newsletter_raw_detail",
),
url(
r"^(?:(?P<slug>(\w+))/)?unsubscribe/$",
NewsletterListUnsubscribeView.as_view(),
name="newsletter_list_unsubscribe",
),
url(
r"^subscribe/done/$",
<|code_end|>
. Use current file imports:
(from django.conf.urls import url
from .views import (
NewsletterListView,
NewsletterDetailView,
NewsletterListSubscribeView,
NewsletterRawDetailView,
NewsletterListUnsubscribeView,
NewsletterListSubscribeDoneView,
NewsletterListUnsubscribeDoneView,
))
and context including class names, function names, or small code snippets from other files:
# Path: courriers/views.py
# class NewsletterListView(AJAXResponseMixin, ListView):
# model = Newsletter
# context_object_name = "newsletters"
# template_name = "courriers/newsletter_list.html"
# paginate_by = PAGINATE_BY
#
# def dispatch(self, *args, **kwargs):
# return super(NewsletterListView, self).dispatch(*args, **kwargs)
#
# @cached_property
# def newsletter_list(self):
# return get_object_or_404(
# NewsletterList.objects.all(), slug=self.kwargs.get("slug")
# )
#
# def get_queryset(self):
# lang = translation.get_language()
# qs = self.newsletter_list.newsletters.status_online()
# if lang:
# qs = qs.filter(newsletter_segment__lang=lang)
# qs = qs.order_by("-published_at")
# return qs
#
# def get_context_data(self, **kwargs):
# context = super(NewsletterListView, self).get_context_data(**kwargs)
# context["newsletter_list"] = self.newsletter_list
# return context
#
# class NewsletterDetailView(AJAXResponseMixin, DetailView):
# model = Newsletter
# context_object_name = "newsletter"
# template_name = "courriers/newsletter_detail.html"
#
# def get_queryset(self):
# return self.model.objects.status_online()
#
# def get_context_data(self, **kwargs):
# context = super(NewsletterDetailView, self).get_context_data(**kwargs)
#
# context["newsletter_list"] = self.object.newsletter_list
#
# return context
#
# class NewsletterListSubscribeView(BaseNewsletterListFormView):
# template_name = "courriers/newsletter_list_subscribe_form.html"
# form_class = SubscriptionForm
#
# def get_success_url(self):
# return reverse("newsletter_list_subscribe_done")
#
# class NewsletterRawDetailView(AJAXResponseMixin, DetailView):
# model = Newsletter
# template_name = "courriers/newsletter_raw_detail.html"
#
# def get_context_data(self, **kwargs):
# context = super(NewsletterRawDetailView, self).get_context_data(**kwargs)
#
# context["items"] = self.object.items.all()
#
# for item in context["items"]:
# item.newsletter = self.object
#
# return context
#
# class NewsletterListUnsubscribeView(BaseNewsletterListFormView):
# template_name = "courriers/newsletter_list_unsubscribe.html"
#
# def get_form_class(self):
# return UnsubscribeForm
#
# def get_initial(self):
# initial = super(NewsletterListUnsubscribeView, self).get_initial()
# email = self.request.GET.get("email", None)
#
# if email:
# initial["email"] = email
#
# return initial.copy()
#
# def get_success_url(self):
# if self.object:
# return reverse(
# "newsletter_list_unsubscribe_done", kwargs={"slug": self.object.slug}
# )
#
# return reverse("newsletter_list_unsubscribe_done")
#
# class NewsletterListSubscribeDoneView(AJAXResponseMixin, TemplateView):
# template_name = "courriers/newsletter_list_subscribe_done.html"
# model = NewsletterList
# context_object_name = "newsletter_list"
#
# class NewsletterListUnsubscribeDoneView(AJAXResponseMixin, TemplateView):
# template_name = "courriers/newsletter_list_unsubscribe_done.html"
# model = NewsletterList
# context_object_name = "newsletter_list"
#
# def get_context_data(self, **kwargs):
# context = super(NewsletterListUnsubscribeDoneView, self).get_context_data(
# **kwargs
# )
#
# slug = self.kwargs.get("slug", None)
#
# if slug:
# context[self.context_object_name] = get_object_or_404(self.model, slug=slug)
#
# return context
. Output only the next line. | NewsletterListSubscribeDoneView.as_view(), |
Based on the snippet: <|code_start|>
urlpatterns = [
url(
r"^(?P<pk>(\d+))/detail/$",
NewsletterDetailView.as_view(),
name="newsletter_detail",
),
url(
r"^(?P<slug>(\w+))/subscribe/$",
NewsletterListSubscribeView.as_view(),
name="newsletter_list_subscribe",
),
url(
r"^(?P<pk>(\d+))/raw/$",
NewsletterRawDetailView.as_view(),
name="newsletter_raw_detail",
),
url(
r"^(?:(?P<slug>(\w+))/)?unsubscribe/$",
NewsletterListUnsubscribeView.as_view(),
name="newsletter_list_unsubscribe",
),
url(
r"^subscribe/done/$",
NewsletterListSubscribeDoneView.as_view(),
name="newsletter_list_subscribe_done",
),
url(
r"^unsubscribe/(?:(?P<slug>(\w+))/)?done/$",
<|code_end|>
, predict the immediate next line with the help of imports:
from django.conf.urls import url
from .views import (
NewsletterListView,
NewsletterDetailView,
NewsletterListSubscribeView,
NewsletterRawDetailView,
NewsletterListUnsubscribeView,
NewsletterListSubscribeDoneView,
NewsletterListUnsubscribeDoneView,
)
and context (classes, functions, sometimes code) from other files:
# Path: courriers/views.py
# class NewsletterListView(AJAXResponseMixin, ListView):
# model = Newsletter
# context_object_name = "newsletters"
# template_name = "courriers/newsletter_list.html"
# paginate_by = PAGINATE_BY
#
# def dispatch(self, *args, **kwargs):
# return super(NewsletterListView, self).dispatch(*args, **kwargs)
#
# @cached_property
# def newsletter_list(self):
# return get_object_or_404(
# NewsletterList.objects.all(), slug=self.kwargs.get("slug")
# )
#
# def get_queryset(self):
# lang = translation.get_language()
# qs = self.newsletter_list.newsletters.status_online()
# if lang:
# qs = qs.filter(newsletter_segment__lang=lang)
# qs = qs.order_by("-published_at")
# return qs
#
# def get_context_data(self, **kwargs):
# context = super(NewsletterListView, self).get_context_data(**kwargs)
# context["newsletter_list"] = self.newsletter_list
# return context
#
# class NewsletterDetailView(AJAXResponseMixin, DetailView):
# model = Newsletter
# context_object_name = "newsletter"
# template_name = "courriers/newsletter_detail.html"
#
# def get_queryset(self):
# return self.model.objects.status_online()
#
# def get_context_data(self, **kwargs):
# context = super(NewsletterDetailView, self).get_context_data(**kwargs)
#
# context["newsletter_list"] = self.object.newsletter_list
#
# return context
#
# class NewsletterListSubscribeView(BaseNewsletterListFormView):
# template_name = "courriers/newsletter_list_subscribe_form.html"
# form_class = SubscriptionForm
#
# def get_success_url(self):
# return reverse("newsletter_list_subscribe_done")
#
# class NewsletterRawDetailView(AJAXResponseMixin, DetailView):
# model = Newsletter
# template_name = "courriers/newsletter_raw_detail.html"
#
# def get_context_data(self, **kwargs):
# context = super(NewsletterRawDetailView, self).get_context_data(**kwargs)
#
# context["items"] = self.object.items.all()
#
# for item in context["items"]:
# item.newsletter = self.object
#
# return context
#
# class NewsletterListUnsubscribeView(BaseNewsletterListFormView):
# template_name = "courriers/newsletter_list_unsubscribe.html"
#
# def get_form_class(self):
# return UnsubscribeForm
#
# def get_initial(self):
# initial = super(NewsletterListUnsubscribeView, self).get_initial()
# email = self.request.GET.get("email", None)
#
# if email:
# initial["email"] = email
#
# return initial.copy()
#
# def get_success_url(self):
# if self.object:
# return reverse(
# "newsletter_list_unsubscribe_done", kwargs={"slug": self.object.slug}
# )
#
# return reverse("newsletter_list_unsubscribe_done")
#
# class NewsletterListSubscribeDoneView(AJAXResponseMixin, TemplateView):
# template_name = "courriers/newsletter_list_subscribe_done.html"
# model = NewsletterList
# context_object_name = "newsletter_list"
#
# class NewsletterListUnsubscribeDoneView(AJAXResponseMixin, TemplateView):
# template_name = "courriers/newsletter_list_unsubscribe_done.html"
# model = NewsletterList
# context_object_name = "newsletter_list"
#
# def get_context_data(self, **kwargs):
# context = super(NewsletterListUnsubscribeDoneView, self).get_context_data(
# **kwargs
# )
#
# slug = self.kwargs.get("slug", None)
#
# if slug:
# context[self.context_object_name] = get_object_or_404(self.model, slug=slug)
#
# return context
. Output only the next line. | NewsletterListUnsubscribeDoneView.as_view(), |
Using the snippet: <|code_start|> fname, ext = os.path.splitext(filename)
filename = "{}{}".format(slugify(truncatechars(fname, 50)), ext)
return os.path.join("courriers", "uploads", filename)
class NewsletterList(models.Model):
name = models.CharField(max_length=255)
slug = models.SlugField(max_length=255, unique=True)
description = models.TextField(blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True)
list_id = models.IntegerField(null=True)
class Meta:
abstract = True
def __str__(self):
return self.name or ""
def get_absolute_url(self):
return reverse("newsletter_list", kwargs={"slug": self.slug})
class NewsletterSegment(models.Model):
name = models.CharField(max_length=255)
segment_id = models.IntegerField()
newsletter_list = models.ForeignKey(
"courriers.NewsletterList", on_delete=models.PROTECT, related_name="lists"
)
lang = models.CharField(
<|code_end|>
, determine the next line of code. You have imports:
import os
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey
from django.template.defaultfilters import slugify, truncatechars
from django.utils.translation import gettext_lazy as _
from django.utils import timezone as datetime
from django.urls import reverse
from django.db.models.query import QuerySet
from courriers.settings import ALLOWED_LANGUAGES
and context (class names, function names, or code) available:
# Path: courriers/settings.py
# ALLOWED_LANGUAGES = getattr(settings, "COURRIERS_ALLOWED_LANGUAGES", settings.LANGUAGES)
. Output only the next line. | max_length=10, blank=True, null=True, choices=ALLOWED_LANGUAGES |
Predict the next line after this snippet: <|code_start|> if not newsletter.is_online():
raise Exception("This newsletter is not online. You can't send it.")
nl_list = newsletter.newsletter_list
nl_segment = newsletter.newsletter_segment
self.send_campaign(newsletter, nl_list.list_id, nl_segment.segment_id)
def _format_slug(self, *args):
raise NotImplementedError
def send_campaign(self, newsletter, list_id, segment_id):
if not DEFAULT_FROM_EMAIL:
raise ImproperlyConfigured(
"You have to specify a DEFAULT_FROM_EMAIL in Django settings."
)
if not DEFAULT_FROM_NAME:
raise ImproperlyConfigured(
"You have to specify a DEFAULT_FROM_NAME in Django settings."
)
old_language = translation.get_language()
language = newsletter.newsletter_segment.lang or settings.LANGUAGE_CODE
translation.activate(language)
try:
self._send_campaign(newsletter, list_id, segment_id=segment_id)
except Exception as e:
logger.exception(e)
<|code_end|>
using the current file's imports:
import logging
from courriers.settings import FAIL_SILENTLY, DEFAULT_FROM_EMAIL, DEFAULT_FROM_NAME
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.utils import translation
from .simple import SimpleBackend
and any relevant context from other files:
# Path: courriers/settings.py
# FAIL_SILENTLY = getattr(settings, "COURRIERS_FAIL_SILENTLY", False)
#
# DEFAULT_FROM_EMAIL = getattr(
# settings, "COURRIERS_DEFAULT_FROM_EMAIL", settings.DEFAULT_FROM_EMAIL
# )
#
# DEFAULT_FROM_NAME = getattr(settings, "COURRIERS_DEFAULT_FROM_NAME", "")
#
# Path: courriers/backends/simple.py
# class SimpleBackend(BaseBackend):
# def subscribe(self, list_id, email, lang=None, user=None):
# pass
#
# def unsubscribe(self, list_id, email, lang=None, user=None):
# pass
#
# def register(self, email, newsletter_list, lang=None, user=None):
# if not user:
# try:
# user = User.objects.get(email=email)
# except User.DoesNotExist:
# user = User.objects.create(email=email, username=email)
#
# user.subscribe(newsletter_list, lang=lang)
#
# def unregister(self, email, newsletter_list=None, user=None, lang=None):
# if not user:
# try:
# user = User.objects.get(email=email)
# except User.DoesNotExist:
# return
#
# user.unsubscribe(newsletter_list, lang=lang)
#
# def send_mails(self, newsletter, fail_silently=False, subscribers=None):
# connection = mail.get_connection(fail_silently=fail_silently)
#
# emails = []
#
# old_language = translation.get_language()
#
# for subscriber in subscribers:
# if (
# newsletter.newsletter_segment.lang
# and newsletter.newsletter_segment.lang != subscriber.lang
# ):
# continue
#
# translation.activate(subscriber.lang)
#
# email = EmailMultiAlternatives(
# newsletter.name,
# render_to_string(
# "courriers/newsletter_raw_detail.txt",
# {"object": newsletter, "subscriber": subscriber},
# ),
# DEFAULT_FROM_EMAIL,
# [subscriber.email],
# connection=connection,
# )
#
# html = render_to_string(
# "courriers/newsletter_raw_detail.html",
# {
# "object": newsletter,
# "items": newsletter.items.all().prefetch_related("newsletter"),
# "subscriber": subscriber,
# },
# )
#
# for pre_processor in PRE_PROCESSORS:
# html = load_class(pre_processor)(html)
#
# email.attach_alternative(html, "text/html")
#
# emails.append(email)
#
# translation.activate(old_language)
#
# results = connection.send_messages(emails)
#
# newsletter.sent = True
# newsletter.save(update_fields=("sent",))
#
# return results
. Output only the next line. | if not FAIL_SILENTLY: |
Predict the next line after this snippet: <|code_start|>
logger = logging.getLogger("courriers")
class CampaignBackend(SimpleBackend):
def send_mails(self, newsletter):
if not newsletter.is_online():
raise Exception("This newsletter is not online. You can't send it.")
nl_list = newsletter.newsletter_list
nl_segment = newsletter.newsletter_segment
self.send_campaign(newsletter, nl_list.list_id, nl_segment.segment_id)
def _format_slug(self, *args):
raise NotImplementedError
def send_campaign(self, newsletter, list_id, segment_id):
<|code_end|>
using the current file's imports:
import logging
from courriers.settings import FAIL_SILENTLY, DEFAULT_FROM_EMAIL, DEFAULT_FROM_NAME
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.utils import translation
from .simple import SimpleBackend
and any relevant context from other files:
# Path: courriers/settings.py
# FAIL_SILENTLY = getattr(settings, "COURRIERS_FAIL_SILENTLY", False)
#
# DEFAULT_FROM_EMAIL = getattr(
# settings, "COURRIERS_DEFAULT_FROM_EMAIL", settings.DEFAULT_FROM_EMAIL
# )
#
# DEFAULT_FROM_NAME = getattr(settings, "COURRIERS_DEFAULT_FROM_NAME", "")
#
# Path: courriers/backends/simple.py
# class SimpleBackend(BaseBackend):
# def subscribe(self, list_id, email, lang=None, user=None):
# pass
#
# def unsubscribe(self, list_id, email, lang=None, user=None):
# pass
#
# def register(self, email, newsletter_list, lang=None, user=None):
# if not user:
# try:
# user = User.objects.get(email=email)
# except User.DoesNotExist:
# user = User.objects.create(email=email, username=email)
#
# user.subscribe(newsletter_list, lang=lang)
#
# def unregister(self, email, newsletter_list=None, user=None, lang=None):
# if not user:
# try:
# user = User.objects.get(email=email)
# except User.DoesNotExist:
# return
#
# user.unsubscribe(newsletter_list, lang=lang)
#
# def send_mails(self, newsletter, fail_silently=False, subscribers=None):
# connection = mail.get_connection(fail_silently=fail_silently)
#
# emails = []
#
# old_language = translation.get_language()
#
# for subscriber in subscribers:
# if (
# newsletter.newsletter_segment.lang
# and newsletter.newsletter_segment.lang != subscriber.lang
# ):
# continue
#
# translation.activate(subscriber.lang)
#
# email = EmailMultiAlternatives(
# newsletter.name,
# render_to_string(
# "courriers/newsletter_raw_detail.txt",
# {"object": newsletter, "subscriber": subscriber},
# ),
# DEFAULT_FROM_EMAIL,
# [subscriber.email],
# connection=connection,
# )
#
# html = render_to_string(
# "courriers/newsletter_raw_detail.html",
# {
# "object": newsletter,
# "items": newsletter.items.all().prefetch_related("newsletter"),
# "subscriber": subscriber,
# },
# )
#
# for pre_processor in PRE_PROCESSORS:
# html = load_class(pre_processor)(html)
#
# email.attach_alternative(html, "text/html")
#
# emails.append(email)
#
# translation.activate(old_language)
#
# results = connection.send_messages(emails)
#
# newsletter.sent = True
# newsletter.save(update_fields=("sent",))
#
# return results
. Output only the next line. | if not DEFAULT_FROM_EMAIL: |
Here is a snippet: <|code_start|>
logger = logging.getLogger("courriers")
class CampaignBackend(SimpleBackend):
def send_mails(self, newsletter):
if not newsletter.is_online():
raise Exception("This newsletter is not online. You can't send it.")
nl_list = newsletter.newsletter_list
nl_segment = newsletter.newsletter_segment
self.send_campaign(newsletter, nl_list.list_id, nl_segment.segment_id)
def _format_slug(self, *args):
raise NotImplementedError
def send_campaign(self, newsletter, list_id, segment_id):
if not DEFAULT_FROM_EMAIL:
raise ImproperlyConfigured(
"You have to specify a DEFAULT_FROM_EMAIL in Django settings."
)
<|code_end|>
. Write the next line using the current file imports:
import logging
from courriers.settings import FAIL_SILENTLY, DEFAULT_FROM_EMAIL, DEFAULT_FROM_NAME
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.utils import translation
from .simple import SimpleBackend
and context from other files:
# Path: courriers/settings.py
# FAIL_SILENTLY = getattr(settings, "COURRIERS_FAIL_SILENTLY", False)
#
# DEFAULT_FROM_EMAIL = getattr(
# settings, "COURRIERS_DEFAULT_FROM_EMAIL", settings.DEFAULT_FROM_EMAIL
# )
#
# DEFAULT_FROM_NAME = getattr(settings, "COURRIERS_DEFAULT_FROM_NAME", "")
#
# Path: courriers/backends/simple.py
# class SimpleBackend(BaseBackend):
# def subscribe(self, list_id, email, lang=None, user=None):
# pass
#
# def unsubscribe(self, list_id, email, lang=None, user=None):
# pass
#
# def register(self, email, newsletter_list, lang=None, user=None):
# if not user:
# try:
# user = User.objects.get(email=email)
# except User.DoesNotExist:
# user = User.objects.create(email=email, username=email)
#
# user.subscribe(newsletter_list, lang=lang)
#
# def unregister(self, email, newsletter_list=None, user=None, lang=None):
# if not user:
# try:
# user = User.objects.get(email=email)
# except User.DoesNotExist:
# return
#
# user.unsubscribe(newsletter_list, lang=lang)
#
# def send_mails(self, newsletter, fail_silently=False, subscribers=None):
# connection = mail.get_connection(fail_silently=fail_silently)
#
# emails = []
#
# old_language = translation.get_language()
#
# for subscriber in subscribers:
# if (
# newsletter.newsletter_segment.lang
# and newsletter.newsletter_segment.lang != subscriber.lang
# ):
# continue
#
# translation.activate(subscriber.lang)
#
# email = EmailMultiAlternatives(
# newsletter.name,
# render_to_string(
# "courriers/newsletter_raw_detail.txt",
# {"object": newsletter, "subscriber": subscriber},
# ),
# DEFAULT_FROM_EMAIL,
# [subscriber.email],
# connection=connection,
# )
#
# html = render_to_string(
# "courriers/newsletter_raw_detail.html",
# {
# "object": newsletter,
# "items": newsletter.items.all().prefetch_related("newsletter"),
# "subscriber": subscriber,
# },
# )
#
# for pre_processor in PRE_PROCESSORS:
# html = load_class(pre_processor)(html)
#
# email.attach_alternative(html, "text/html")
#
# emails.append(email)
#
# translation.activate(old_language)
#
# results = connection.send_messages(emails)
#
# newsletter.sent = True
# newsletter.save(update_fields=("sent",))
#
# return results
, which may include functions, classes, or code. Output only the next line. | if not DEFAULT_FROM_NAME: |
Based on the snippet: <|code_start|> sorted(self._partition.keys())))
def automaton(self):
r"""
EXAMPLES::
sage: from slabbe.markov_transformation import markov_transformations
sage: T = markov_transformations.Selmer()
sage: T.automaton()
Automaton with 12 states
"""
states = list(self._partition.keys())
autom = Automaton(initial_states=states, final_states=states)
for key,values in self._transitions.items():
for v in values:
autom.add_transition(key, v, v)
return autom
def language(self):
r"""
EXAMPLES::
sage: from slabbe.markov_transformation import markov_transformations
sage: T = markov_transformations.Selmer()
sage: T.language()
Regular language over [-321, -312, -231, -213, -132, -123,
123, 132, 213, 231, 312, 321]
defined by: Automaton with 12 states
"""
alphabet = list(self._partition.keys())
<|code_end|>
, predict the immediate next line with the help of imports:
import itertools
from sage.misc.cachefunc import cached_method
from sage.misc.misc_c import prod
from sage.matrix.constructor import matrix
from sage.combinat.finite_state_machine import Automaton
from .language import RegularLanguage
from .matrices import projection_matrix
from sage.rings.finite_rings.integer_mod_ring import Integers
from sage.plot.graphics import Graphics
from sage.plot.polygon import polygon
from sage.plot.text import text
from slabbe import TikzPicture
and context (classes, functions, sometimes code) from other files:
# Path: slabbe/language.py
# class RegularLanguage(Language):
# r"""
# Regular language
#
# INPUT:
#
# - ``alphabet`` -- iterable of letters
# - ``automaton`` -- finite state automaton
#
# EXAMPLES::
#
# sage: from slabbe.language import RegularLanguage
# sage: alphabet = ['a', 'b']
# sage: trans = [(0, 1, 'a'), (1, 2, 'b'), (2, 3, 'b'), (3, 4, 'a')]
# sage: automaton = Automaton(trans, initial_states=[0], final_states=[4])
# sage: RegularLanguage(alphabet, automaton)
# Regular language over ['a', 'b']
# defined by: Automaton with 5 states
# """
# def __init__(self, alphabet, automaton):
# r"""
# EXAMPLES::
#
# sage: from slabbe.language import RegularLanguage
# sage: alphabet = ['a', 'b']
# sage: trans = [(0, 1, 'a'), (1, 2, 'b'), (2, 3, 'b'), (3, 4, 'a')]
# sage: automaton = Automaton(trans, initial_states=[0], final_states=[4])
# sage: R = RegularLanguage(alphabet, automaton)
# """
# Language.__init__(self, alphabet)
# self._automaton = automaton
#
#
# def __repr__(self):
# r"""
# EXAMPLES::
#
# sage: from slabbe.language import RegularLanguage
# sage: alphabet = ['a', 'b']
# sage: trans = [(0, 1, 'a'), (1, 2, 'b'), (2, 3, 'b'), (3, 4, 'a')]
# sage: automaton = Automaton(trans, initial_states=[0], final_states=[4])
# sage: RegularLanguage(alphabet, automaton)
# Regular language over ['a', 'b']
# defined by: Automaton with 5 states
# """
# s = "Regular language over {}\ndefined by: {}"
# return s.format(self._alphabet, self._automaton)
#
# def words_of_length_iterator(self, length):
# r"""
# Return an iterator over words of given length.
#
# INPUT:
#
# - ``length`` -- integer
#
# EXAMPLES::
#
# sage: from slabbe.language import RegularLanguage
# sage: alphabet = ['a', 'b']
# sage: trans = [(0, 1, 'a'), (1, 2, 'b'), (2, 3, 'b'), (3, 4, 'a')]
# sage: automaton = Automaton(trans, initial_states=[0], final_states=[4])
# sage: R = RegularLanguage(alphabet, automaton)
# sage: [list(R.words_of_length_iterator(i)) for i in range(6)]
# [[], [], [], [], [word: abba], []]
# """
# it = super(RegularLanguage, self).words_of_length_iterator(length)
# return [a for a in it if self._automaton(a)]
#
# Path: slabbe/matrices.py
# def projection_matrix(dim_from=3, dim_to=2):
# r"""
# Return a projection matrix from R^d to R^l.
#
# INPUT:
#
# - ``dim_from` -- integer (default: ``3``)
# - ``dim_to` -- integer (default: ``2``)
#
# OUTPUT:
#
# matrix
#
# EXAMPLES::
#
# sage: from slabbe.matrices import projection_matrix
# sage: projection_matrix(3,2)
# [-0.866025403784439 0.866025403784439 0.000000000000000]
# [-0.500000000000000 -0.500000000000000 1.00000000000000]
# sage: projection_matrix(2,3)
# [-0.577350269189626 -0.333333333333333]
# [ 0.577350269189626 -0.333333333333333]
# [ 0.000000000000000 0.666666666666667]
# """
# from math import sqrt
# from sage.rings.real_mpfr import RR
# sqrt3 = sqrt(3)
# if dim_from == 3 and dim_to == 2:
# return matrix(2,[-sqrt3,sqrt3,0,-1,-1,2],ring=RR)/2
# elif dim_from == 2 and dim_to == 3:
# return matrix(3,[-sqrt3,-1,sqrt3,-1,0,2],ring=RR)/3
# elif dim_from == 4 and dim_to == 2:
# return matrix(2,[-sqrt3,sqrt3,0,1,-1,-1,2,0],ring=RR)/2
# elif dim_from == 4 and dim_to == 3:
# sqrt2 = sqrt(2)
# return matrix([(1,-1,0,0),
# (0,0,1,-1),
# (-1/sqrt2,-1/sqrt2,1/sqrt2,1/sqrt2)],
# ring=RR)
# else:
# s = "for input dim_from={} and dim_to={}"
# raise NotImplementedError(s.format(dim_from, dim_to))
. Output only the next line. | return RegularLanguage(alphabet, self.automaton()) |
Given the code snippet: <|code_start|>
def n_cylinders_edges(self, n):
r"""
EXAMPLES::
sage: from slabbe.markov_transformation import markov_transformations
sage: T = markov_transformations.Selmer()
sage: E = T.n_cylinders_edges(1)
sage: len(E)
39
"""
edges = set()
for w,cyl in self.n_cylinders_iterator(n):
cols = cyl.columns()
indices = Integers(len(cols))
edges.update(frozenset((cols[i], cols[i+1])) for i in indices)
return edges
def plot_n_cylinders(self, n, labels=True):
r"""
EXAMPLES::
sage: from slabbe.markov_transformation import markov_transformations
sage: T = markov_transformations.Selmer()
sage: G = T.plot_n_cylinders(3)
TESTS::
sage: G = T.plot_n_cylinders(0)
"""
<|code_end|>
, generate the next line using the imports in this file:
import itertools
from sage.misc.cachefunc import cached_method
from sage.misc.misc_c import prod
from sage.matrix.constructor import matrix
from sage.combinat.finite_state_machine import Automaton
from .language import RegularLanguage
from .matrices import projection_matrix
from sage.rings.finite_rings.integer_mod_ring import Integers
from sage.plot.graphics import Graphics
from sage.plot.polygon import polygon
from sage.plot.text import text
from slabbe import TikzPicture
and context (functions, classes, or occasionally code) from other files:
# Path: slabbe/language.py
# class RegularLanguage(Language):
# r"""
# Regular language
#
# INPUT:
#
# - ``alphabet`` -- iterable of letters
# - ``automaton`` -- finite state automaton
#
# EXAMPLES::
#
# sage: from slabbe.language import RegularLanguage
# sage: alphabet = ['a', 'b']
# sage: trans = [(0, 1, 'a'), (1, 2, 'b'), (2, 3, 'b'), (3, 4, 'a')]
# sage: automaton = Automaton(trans, initial_states=[0], final_states=[4])
# sage: RegularLanguage(alphabet, automaton)
# Regular language over ['a', 'b']
# defined by: Automaton with 5 states
# """
# def __init__(self, alphabet, automaton):
# r"""
# EXAMPLES::
#
# sage: from slabbe.language import RegularLanguage
# sage: alphabet = ['a', 'b']
# sage: trans = [(0, 1, 'a'), (1, 2, 'b'), (2, 3, 'b'), (3, 4, 'a')]
# sage: automaton = Automaton(trans, initial_states=[0], final_states=[4])
# sage: R = RegularLanguage(alphabet, automaton)
# """
# Language.__init__(self, alphabet)
# self._automaton = automaton
#
#
# def __repr__(self):
# r"""
# EXAMPLES::
#
# sage: from slabbe.language import RegularLanguage
# sage: alphabet = ['a', 'b']
# sage: trans = [(0, 1, 'a'), (1, 2, 'b'), (2, 3, 'b'), (3, 4, 'a')]
# sage: automaton = Automaton(trans, initial_states=[0], final_states=[4])
# sage: RegularLanguage(alphabet, automaton)
# Regular language over ['a', 'b']
# defined by: Automaton with 5 states
# """
# s = "Regular language over {}\ndefined by: {}"
# return s.format(self._alphabet, self._automaton)
#
# def words_of_length_iterator(self, length):
# r"""
# Return an iterator over words of given length.
#
# INPUT:
#
# - ``length`` -- integer
#
# EXAMPLES::
#
# sage: from slabbe.language import RegularLanguage
# sage: alphabet = ['a', 'b']
# sage: trans = [(0, 1, 'a'), (1, 2, 'b'), (2, 3, 'b'), (3, 4, 'a')]
# sage: automaton = Automaton(trans, initial_states=[0], final_states=[4])
# sage: R = RegularLanguage(alphabet, automaton)
# sage: [list(R.words_of_length_iterator(i)) for i in range(6)]
# [[], [], [], [], [word: abba], []]
# """
# it = super(RegularLanguage, self).words_of_length_iterator(length)
# return [a for a in it if self._automaton(a)]
#
# Path: slabbe/matrices.py
# def projection_matrix(dim_from=3, dim_to=2):
# r"""
# Return a projection matrix from R^d to R^l.
#
# INPUT:
#
# - ``dim_from` -- integer (default: ``3``)
# - ``dim_to` -- integer (default: ``2``)
#
# OUTPUT:
#
# matrix
#
# EXAMPLES::
#
# sage: from slabbe.matrices import projection_matrix
# sage: projection_matrix(3,2)
# [-0.866025403784439 0.866025403784439 0.000000000000000]
# [-0.500000000000000 -0.500000000000000 1.00000000000000]
# sage: projection_matrix(2,3)
# [-0.577350269189626 -0.333333333333333]
# [ 0.577350269189626 -0.333333333333333]
# [ 0.000000000000000 0.666666666666667]
# """
# from math import sqrt
# from sage.rings.real_mpfr import RR
# sqrt3 = sqrt(3)
# if dim_from == 3 and dim_to == 2:
# return matrix(2,[-sqrt3,sqrt3,0,-1,-1,2],ring=RR)/2
# elif dim_from == 2 and dim_to == 3:
# return matrix(3,[-sqrt3,-1,sqrt3,-1,0,2],ring=RR)/3
# elif dim_from == 4 and dim_to == 2:
# return matrix(2,[-sqrt3,sqrt3,0,1,-1,-1,2,0],ring=RR)/2
# elif dim_from == 4 and dim_to == 3:
# sqrt2 = sqrt(2)
# return matrix([(1,-1,0,0),
# (0,0,1,-1),
# (-1/sqrt2,-1/sqrt2,1/sqrt2,1/sqrt2)],
# ring=RR)
# else:
# s = "for input dim_from={} and dim_to={}"
# raise NotImplementedError(s.format(dim_from, dim_to))
. Output only the next line. | M3to2 = projection_matrix(3, 2) |
Given the code snippet: <|code_start|> response.processed_question = PROCESSED1
response = GOOD_RESPONSE.responses.add()
response.id = DOCID2
answer = response.answers.add()
answer.text = ANSWER2
answer.scores['environment_confidence'] = SCORE2
answer.scores['f1'] = F1_SCORE2
response.question = QUESTION2
response.processed_question = PROCESSED2
response = DUPLICATE_IDS_RESPONSE.responses.add()
response.id = DOCID1
answer = response.answers.add()
answer.text = ANSWER1
answer.scores['environment_confidence'] = SCORE1
answer.scores['f1'] = F1_SCORE1
response.question = QUESTION1
response.processed_question = PROCESSED1
response = DUPLICATE_IDS_RESPONSE.responses.add()
response.id = DOCID1 # Same docid.
answer = response.answers.add()
answer.text = ANSWER2
answer.scores['environment_confidence'] = SCORE2
answer.scores['f1'] = F1_SCORE2
response.question = QUESTION2
response.processed_question = PROCESSED2
<|code_end|>
, generate the next line using the imports in this file:
import collections
import grpc
import mock
import portpicker
import unittest
from absl import logging
from grpc.framework.foundation import logging_pool
from tensorflow.python.util.protobuf import compare
from px.environments import bidaf
from px.environments import bidaf_server
from px.proto import aqa_pb2
from px.proto import aqa_pb2_grpc
and context (functions, classes, or occasionally code) from other files:
# Path: px/environments/bidaf.py
# class BidafEnvironment(object):
# def __init__(self,
# data_dir,
# shared_path,
# model_dir,
# docid_separator='###',
# debug_mode=False,
# load_test=False,
# load_impossible_questions=False):
# def _ReadImpossiblities(self, dataset, data_dir):
# def _WordTokenize(self, text):
# def _PreprocessQaData(self, questions, document_ids):
# def IsImpossible(self, document_id):
# def GetAnswers(self, questions, document_ids):
#
# Path: px/environments/bidaf_server.py
# FLAGS = flags.FLAGS
# DOCID_SEPARATOR = '###'
# class BidafServer(aqa_pb2_grpc.EnvironmentServerServicer):
# def __init__(self, *args, **kwargs):
# def _InitializeEnvironment(self, data_dir, shared_file, model_dir, load_test,
# load_impossible_questions, debug_mode):
# def GetObservations(self, request, context):
# def main(unused_argv):
. Output only the next line. | class MockBidafEnvironment(bidaf.BidafEnvironment): |
Given snippet: <|code_start|> document_ids[1] == expected_id1_1):
answers_dict.update([
('scores', {
document_ids[0]: SCORE1,
document_ids[1]: SCORE2
}),
('f1_scores', {
document_ids[0]: F1_SCORE1,
document_ids[1]: F1_SCORE2
}),
(document_ids[0], ANSWER1),
(document_ids[1], ANSWER2)
])
questions_dict = {
document_ids[0]: {
'rewrite': PROCESSED1,
'raw_rewrite': QUESTION1
},
document_ids[1]: {
'rewrite': PROCESSED2,
'raw_rewrite': QUESTION2
}
}
return answers_dict, questions_dict, 0
class BidafServerTest(unittest.TestCase):
def setUp(self):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import collections
import grpc
import mock
import portpicker
import unittest
from absl import logging
from grpc.framework.foundation import logging_pool
from tensorflow.python.util.protobuf import compare
from px.environments import bidaf
from px.environments import bidaf_server
from px.proto import aqa_pb2
from px.proto import aqa_pb2_grpc
and context:
# Path: px/environments/bidaf.py
# class BidafEnvironment(object):
# def __init__(self,
# data_dir,
# shared_path,
# model_dir,
# docid_separator='###',
# debug_mode=False,
# load_test=False,
# load_impossible_questions=False):
# def _ReadImpossiblities(self, dataset, data_dir):
# def _WordTokenize(self, text):
# def _PreprocessQaData(self, questions, document_ids):
# def IsImpossible(self, document_id):
# def GetAnswers(self, questions, document_ids):
#
# Path: px/environments/bidaf_server.py
# FLAGS = flags.FLAGS
# DOCID_SEPARATOR = '###'
# class BidafServer(aqa_pb2_grpc.EnvironmentServerServicer):
# def __init__(self, *args, **kwargs):
# def _InitializeEnvironment(self, data_dir, shared_file, model_dir, load_test,
# load_impossible_questions, debug_mode):
# def GetObservations(self, request, context):
# def main(unused_argv):
which might include code, classes, or functions. Output only the next line. | with mock.patch.object(bidaf_server.BidafServer, |
Next line prediction: <|code_start|> tgt_eos=tgt_eos,
subword_option=subword_option)
trans_f.write((translation + "\n").decode("utf-8"))
if step % hparams.steps_per_stats == 0:
# print_time does not print decimal places for time.
utils.print_out(" external evaluation, step %d, time %.2f" %
(step, time.time() - start_time_step))
step += 1
start_time_step = time.time()
except tf.errors.OutOfRangeError:
utils.print_time(
" done, num sentences %d, num translations per input %d" %
(num_sentences, num_translations_per_input), start_time)
break
# Evaluation
evaluation_scores = {}
# We treat F1 scores differently because they don't need ground truth
# sentences and they are expensive to compute due to environment calls.
if "f1" in metrics:
f1_score = np.mean(all_rewards)
evaluation_scores["f1"] = f1_score
utils.print_out(" f1 %s: %.1f" % (name, f1_score))
for metric in metrics:
if metric != "f1" and ref_file:
if not tf.gfile.Exists(trans_file):
raise IOException("%s: translation file not found" % trans_file)
<|code_end|>
. Use current file imports:
(import time
import numpy as np
import tensorflow as tf
from third_party.nmt.utils import evaluation_utils
from third_party.nmt.utils import misc_utils as utils)
and context including class names, function names, or small code snippets from other files:
# Path: third_party/nmt/utils/evaluation_utils.py
# def evaluate(ref_file, trans_file, metric, subword_option=None):
# def _clean(sentence, subword_option):
# def _bleu(ref_file, trans_file, subword_option=None):
# def _rouge(ref_file, summarization_file, subword_option=None):
# def _accuracy(label_file, pred_file):
# def _word_accuracy(label_file, pred_file):
# def _moses_bleu(multi_bleu_script, tgt_test, trans_file, subword_option=None):
#
# Path: third_party/nmt/utils/misc_utils.py
# def check_tensorflow_version():
# def safe_exp(value):
# def print_time(s, start_time):
# def print_out(s, f=None, new_line=True):
# def print_hparams(hparams, skip_patterns=None, header=None):
# def load_hparams(model_dir):
# def maybe_parse_standard_hparams(hparams, hparams_path):
# def save_hparams(out_dir, hparams):
# def debug_tensor(s, msg=None, summarize=10):
# def add_summary(summary_writer, global_step, tag, value):
# def get_config_proto(log_device_placement=False, allow_soft_placement=True,
# num_intra_threads=0, num_inter_threads=0):
# def format_text(words):
# def format_bpe_text(symbols, delimiter=b"@@"):
# def format_spm_text(symbols):
. Output only the next line. | score = evaluation_utils.evaluate( |
Based on the snippet: <|code_start|> reference = _clean(reference, subword_option)
reference_list.append(reference.split(" "))
per_segment_references.append(reference_list)
translations = []
with codecs.getreader("utf-8")(tf.gfile.GFile(trans_file, "rb")) as fh:
for line in fh:
line = _clean(line, subword_option=None)
translations.append(line.split(" "))
# bleu_score, precisions, bp, ratio, translation_length, reference_length
bleu_score, _, _, _, _, _ = bleu.compute_bleu(
per_segment_references, translations, max_order, smooth)
return 100 * bleu_score
def _rouge(ref_file, summarization_file, subword_option=None):
"""Compute ROUGE scores and handling BPE."""
references = []
with codecs.getreader("utf-8")(tf.gfile.GFile(ref_file, "rb")) as fh:
for line in fh:
references.append(_clean(line, subword_option))
hypotheses = []
with codecs.getreader("utf-8")(
tf.gfile.GFile(summarization_file, "rb")) as fh:
for line in fh:
hypotheses.append(_clean(line, subword_option=None))
<|code_end|>
, predict the immediate next line with the help of imports:
import codecs
import os
import re
import subprocess
import tensorflow as tf
from third_party.nmt.scripts import bleu
from third_party.nmt.scripts import rouge
and context (classes, functions, sometimes code) from other files:
# Path: third_party/nmt/scripts/rouge.py
# def rouge(hypotheses, references):
# """Calculates average rouge scores for a list of hypotheses and
# references"""
#
# # Filter out hyps that are of 0 length
# # hyps_and_refs = zip(hypotheses, references)
# # hyps_and_refs = [_ for _ in hyps_and_refs if len(_[0]) > 0]
# # hypotheses, references = zip(*hyps_and_refs)
#
# # Calculate ROUGE-1 F1, precision, recall scores
# rouge_1 = [
# rouge_n([hyp], [ref], 1) for hyp, ref in zip(hypotheses, references)
# ]
# rouge_1_f, rouge_1_p, rouge_1_r = map(np.mean, zip(*rouge_1))
#
# # Calculate ROUGE-2 F1, precision, recall scores
# rouge_2 = [
# rouge_n([hyp], [ref], 2) for hyp, ref in zip(hypotheses, references)
# ]
# rouge_2_f, rouge_2_p, rouge_2_r = map(np.mean, zip(*rouge_2))
#
# # Calculate ROUGE-L F1, precision, recall scores
# rouge_l = [
# rouge_l_sentence_level([hyp], [ref])
# for hyp, ref in zip(hypotheses, references)
# ]
# rouge_l_f, rouge_l_p, rouge_l_r = map(np.mean, zip(*rouge_l))
#
# return {
# "rouge_1/f_score": rouge_1_f,
# "rouge_1/r_score": rouge_1_r,
# "rouge_1/p_score": rouge_1_p,
# "rouge_2/f_score": rouge_2_f,
# "rouge_2/r_score": rouge_2_r,
# "rouge_2/p_score": rouge_2_p,
# "rouge_l/f_score": rouge_l_f,
# "rouge_l/r_score": rouge_l_r,
# "rouge_l/p_score": rouge_l_p,
# }
. Output only the next line. | rouge_score_map = rouge.rouge(hypotheses, references) |
Given the code snippet: <|code_start|> use_rl=False,
entropy_regularization_weight=0.0,
server_mode=False,
optimize_ngrams_len=0)
def create_test_iterator(hparams, mode, trie_excludes=None):
"""Create test iterator."""
src_vocab_table = lookup_ops.index_table_from_tensor(
tf.constant([hparams.eos, "a", "b", "c", "d"]))
tgt_vocab_mapping = tf.constant([hparams.sos, hparams.eos, "a", "b", "c"])
tgt_vocab_table = lookup_ops.index_table_from_tensor(tgt_vocab_mapping)
reverse_tgt_vocab_table = lookup_ops.index_to_string_table_from_tensor(
tgt_vocab_mapping)
src_dataset = tf.data.Dataset.from_tensor_slices(
tf.constant(["a a b b c", "a b b"]))
ctx_dataset = tf.data.Dataset.from_tensor_slices(
tf.constant(["c b c b a", "b c b a"]))
trie_excludes = trie_excludes or []
trie_excludes = " {} ".format(hparams.eos).join(trie_excludes)
tex_dataset = tf.data.Dataset.from_tensor_slices(
tf.constant([trie_excludes, trie_excludes]))
if mode != tf.contrib.learn.ModeKeys.INFER:
tgt_dataset = tf.data.Dataset.from_tensor_slices(
tf.constant(["a b c b c", "a b c b"]))
<|code_end|>
, generate the next line using the imports in this file:
import tensorflow as tf
from tensorflow.python.ops import lookup_ops
from px.nmt.utils import iterator_utils
and context (functions, classes, or occasionally code) from other files:
# Path: px/nmt/utils/iterator_utils.py
# class BatchedInput(
# collections.namedtuple(
# "BatchedInput", ("initializer", "source_string", "source",
# "target_input", "target_output", "weights", "context",
# "annotation", "trie_exclude", "source_sequence_length",
# "target_sequence_length", "context_sequence_length"))):
# def get_infer_iterator(hparams,
# src_dataset,
# src_vocab_table,
# batch_size,
# eos,
# ctx_dataset=None,
# annot_dataset=None,
# trie_exclude_dataset=None,
# src_max_len=None,
# tgt_vocab_table=None):
# def batching_func(x):
# def get_iterator(hparams,
# src_dataset,
# tgt_dataset,
# src_vocab_table,
# tgt_vocab_table,
# batch_size,
# sos,
# eos,
# random_seed,
# num_buckets,
# wgt_dataset=None,
# ctx_dataset=None,
# annot_dataset=None,
# src_max_len=None,
# tgt_max_len=None,
# num_parallel_calls=4,
# output_buffer_size=None,
# skip_count=None,
# num_shards=1,
# shard_index=0,
# reshuffle_each_iteration=True):
# def batching_func(x):
# def key_func(unused_1, unused_2, unused_3, unused_4, unused_5, unused_6,
# unused_7, unused_8, src_len, tgt_len, unused_9):
# def reduce_func(unused_key, windowed_data):
. Output only the next line. | return (iterator_utils.get_iterator( |
Continue the code snippet: <|code_start|>from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
def dynamic_rnn(cell,
inputs,
sequence_length=None,
initial_state=None,
dtype=None,
parallel_iterations=None,
swap_memory=False,
time_major=False,
scope=None):
assert not time_major # TODO : to be implemented later!
<|code_end|>
. Use current file imports:
from tensorflow.python.ops.rnn import dynamic_rnn as _dynamic_rnn
from tensorflow.python.ops.rnn import bidirectional_dynamic_rnn as _bidirectional_dynamic_rnn
from tensorflow.contrib.learn.python.learn.models import bidirectional_rnn as _bidirectional_rnn
from third_party.bi_att_flow.my.tensorflow.general import flatten, reconstruct
import tensorflow as tf
and context (classes, functions, or code) from other files:
# Path: third_party/bi_att_flow/my/tensorflow/general.py
# def flatten(tensor, keep):
# fixed_shape = tensor.get_shape().as_list()
# start = len(fixed_shape) - keep
# left = reduce(mul,
# [fixed_shape[i] or tf.shape(tensor)[i] for i in range(start)])
# out_shape = [left] + [
# fixed_shape[i] or tf.shape(tensor)[i]
# for i in range(start, len(fixed_shape))
# ]
# flat = tf.reshape(tensor, out_shape)
# return flat
#
# def reconstruct(tensor, ref, keep):
# ref_shape = ref.get_shape().as_list()
# tensor_shape = tensor.get_shape().as_list()
# ref_stop = len(ref_shape) - keep
# tensor_start = len(tensor_shape) - keep
# pre_shape = [ref_shape[i] or tf.shape(ref)[i] for i in range(ref_stop)]
# keep_shape = [
# tensor_shape[i] or tf.shape(tensor)[i]
# for i in range(tensor_start, len(tensor_shape))
# ]
# # pre_shape = [tf.shape(ref)[i] for i in range(len(ref.get_shape().as_list()[:-keep]))]
# # keep_shape = tensor.get_shape().as_list()[-keep:]
# target_shape = pre_shape + keep_shape
# out = tf.reshape(tensor, target_shape)
# return out
. Output only the next line. | flat_inputs = flatten(inputs, 2) # [-1, J, d] |
Using the snippet: <|code_start|>
def dynamic_rnn(cell,
inputs,
sequence_length=None,
initial_state=None,
dtype=None,
parallel_iterations=None,
swap_memory=False,
time_major=False,
scope=None):
assert not time_major # TODO : to be implemented later!
flat_inputs = flatten(inputs, 2) # [-1, J, d]
flat_len = None if sequence_length is None else tf.cast(
flatten(sequence_length, 0), 'int64')
flat_outputs, final_state = _dynamic_rnn(
cell,
flat_inputs,
sequence_length=flat_len,
initial_state=initial_state,
dtype=dtype,
parallel_iterations=parallel_iterations,
swap_memory=swap_memory,
time_major=time_major,
scope=scope)
<|code_end|>
, determine the next line of code. You have imports:
from tensorflow.python.ops.rnn import dynamic_rnn as _dynamic_rnn
from tensorflow.python.ops.rnn import bidirectional_dynamic_rnn as _bidirectional_dynamic_rnn
from tensorflow.contrib.learn.python.learn.models import bidirectional_rnn as _bidirectional_rnn
from third_party.bi_att_flow.my.tensorflow.general import flatten, reconstruct
import tensorflow as tf
and context (class names, function names, or code) available:
# Path: third_party/bi_att_flow/my/tensorflow/general.py
# def flatten(tensor, keep):
# fixed_shape = tensor.get_shape().as_list()
# start = len(fixed_shape) - keep
# left = reduce(mul,
# [fixed_shape[i] or tf.shape(tensor)[i] for i in range(start)])
# out_shape = [left] + [
# fixed_shape[i] or tf.shape(tensor)[i]
# for i in range(start, len(fixed_shape))
# ]
# flat = tf.reshape(tensor, out_shape)
# return flat
#
# def reconstruct(tensor, ref, keep):
# ref_shape = ref.get_shape().as_list()
# tensor_shape = tensor.get_shape().as_list()
# ref_stop = len(ref_shape) - keep
# tensor_start = len(tensor_shape) - keep
# pre_shape = [ref_shape[i] or tf.shape(ref)[i] for i in range(ref_stop)]
# keep_shape = [
# tensor_shape[i] or tf.shape(tensor)[i]
# for i in range(tensor_start, len(tensor_shape))
# ]
# # pre_shape = [tf.shape(ref)[i] for i in range(len(ref.get_shape().as_list()[:-keep]))]
# # keep_shape = tensor.get_shape().as_list()[-keep:]
# target_shape = pre_shape + keep_shape
# out = tf.reshape(tensor, target_shape)
# return out
. Output only the next line. | outputs = reconstruct(flat_outputs, inputs, 2) |
Given the following code snippet before the placeholder: <|code_start|> cls.tmpdir = tempfile.mkdtemp()
cls.vocab_path = os.path.join(cls.tmpdir, 'test.vocab')
cls.save_path = os.path.join(cls.tmpdir, 'trie.pkl')
cls.test_vocab = """
<unk>
<s>
</s>
a
b
c
""".strip().split()
cls.test_trie_entries = [
('a b c b a', 'x'),
('a b c b a c', 'y'),
('a c c b', 'z'),
]
with open(cls.vocab_path, 'w') as f:
f.write('\n'.join(cls.test_vocab))
@classmethod
def tearDownClass(cls):
shutil.rmtree(cls.tmpdir)
def testSaveLoadTrie(self):
<|code_end|>
, predict the next line using imports from the current file:
import os.path
import shutil
import tempfile
import tensorflow as tf
from px.nmt.utils import trie_decoder_utils
from px.proto import aqa_pb2
and context including class names, function names, and sometimes code from other files:
# Path: px/nmt/utils/trie_decoder_utils.py
# class TrieSamplerState(
# collections.namedtuple('TrieSamplerState',
# ('cell_state', 'trie_keys', 'trie_exclude'))):
# class TrieSamplerAttentionState(
# collections.namedtuple(
# 'TrieSamplerAttentionState',
# ('cell_state', 'attention', 'time', 'alignments', 'alignment_history',
# 'attention_state', 'trie_keys', 'trie_exclude')),
# attention_wrapper.AttentionWrapperState):
# class TrieBeamSearchDecoderState(
# collections.namedtuple('TrieBeamSearchDecoderState',
# ('cell_state', 'log_probs', 'finished', 'lengths',
# 'trie_keys', 'trie_exclude'))):
# class DecoderTrie(pygtrie.StringTrie):
# class TrieSamplerDecoder(basic_decoder.BasicDecoder):
# class TrieBeamSearchDecoder(beam_search_decoder.BeamSearchDecoder):
# def __init__(self,
# vocab_path,
# eos_token='</s>',
# unk_token='<unk>',
# subword_option='',
# subword_model=None,
# prefix='',
# optimize_ngrams_len=0):
# def _create_vocab(self):
# def _add_to_start_words(self, key):
# def _create_start_words(self):
# def _create_sentencepiece_processor(self):
# def __getstate__(self):
# def __setstate__(self, state):
# def insert_question(self, question, answers):
# def save_to_file(self, file_path):
# def load_from_file(cls, file_path):
# def populate_from_text_file(self, text_file_path):
# def _is_attention_state(state):
# def _is_gnmt_state(state):
# def __init__(self, trie, trie_exclude, *args, **kwargs):
# def initialize(self, name=None):
# def step(self, time, inputs, state, name=None):
# def __init__(self, trie, trie_exclude, *args, **kwargs):
# def initialize(self, name=None):
# def step(self, time, inputs, state, name=None):
# def _trie_beam_search_step(time, logits, next_cell_state, beam_state,
# batch_size, beam_width, end_token,
# length_penalty_weight, trie):
# def _init_trie_keys_py_func(beam_search=False):
# def _py_func(batch_size, beam_size):
# def _py_func(batch_size):
# def _amend_trie_keys_py_func(beam_search=False):
# def _py_func(trie_keys, next_word_ids, next_beam_ids):
# def _py_func(trie_keys, next_word_ids):
# def _clean_trie_key(trie, trie_key):
# def _trie_scores_py_func(trie, beam_search=False):
# def _py_func(log_probs, sequence_lengths, scores, trie_keys, trie_exclude):
# def _py_func(logits, trie_keys, trie_exclude):
# def _py_func_inner(batch_idx):
# def _get_valid_continuation_idxs(trie, trie_exclude_batch_set, trie_key):
# def _create_trie_exclude_batch_set(trie, trie_exclude_batch):
# def _get_scores(log_probs, sequence_lengths, length_penalty_weight):
# def _length_penalty(sequence_lengths, penalty_factor):
# def _get_trie_scores(log_probs, sequence_lengths, length_penalty_weight,
# trie_keys, trie_exclude, trie):
# def _mask_probs(probs, eos_token, finished):
# def _check_maybe(t):
# def _maybe_tensor_gather_helper(gather_indices, gather_from, batch_size,
# range_size, gather_shape):
# def _tensor_gather_helper(gather_indices,
# gather_from,
# batch_size,
# range_size,
# gather_shape,
# name=None):
. Output only the next line. | trie = trie_decoder_utils.DecoderTrie(TrieDecoderUtilsTest.vocab_path) |
Predict the next line for this snippet: <|code_start|># Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Convert the context string into a vector."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
<|code_end|>
with the help of current file imports:
import tensorflow as tf
from third_party.nmt.utils import misc_utils as utils
from px.nmt import model_helper
and context from other files:
# Path: third_party/nmt/utils/misc_utils.py
# def check_tensorflow_version():
# def safe_exp(value):
# def print_time(s, start_time):
# def print_out(s, f=None, new_line=True):
# def print_hparams(hparams, skip_patterns=None, header=None):
# def load_hparams(model_dir):
# def maybe_parse_standard_hparams(hparams, hparams_path):
# def save_hparams(out_dir, hparams):
# def debug_tensor(s, msg=None, summarize=10):
# def add_summary(summary_writer, global_step, tag, value):
# def get_config_proto(log_device_placement=False, allow_soft_placement=True,
# num_intra_threads=0, num_inter_threads=0):
# def format_text(words):
# def format_bpe_text(symbols, delimiter=b"@@"):
# def format_spm_text(symbols):
#
# Path: px/nmt/model_helper.py
# VOCAB_SIZE_THRESHOLD_CPU = 50000
# def get_initializer(init_op, seed=None, init_weight=None):
# def get_device_str(device_id, num_gpus):
# def create_train_model(model_creator,
# hparams,
# scope=None,
# num_workers=1,
# jobid=0,
# graph=None,
# extra_args=None,
# trie=None,
# use_placeholders=False):
# def create_train_model_for_server(model_creator,
# hparams,
# scope=None,
# num_workers=1,
# jobid=0,
# graph=None,
# extra_args=None,
# trie=None):
# def create_eval_model(model_creator,
# hparams,
# scope=None,
# graph=None,
# extra_args=None,
# trie=None):
# def create_infer_model(model_creator,
# hparams,
# scope=None,
# graph=None,
# extra_args=None,
# trie=None):
# def _get_embed_device(vocab_size):
# def _create_pretrained_emb_from_txt(vocab_file,
# embed_file,
# num_trainable_tokens=3,
# dtype=tf.float32,
# scope=None):
# def _create_or_load_embed(embed_name, vocab_file, embed_file, vocab_size,
# embed_size, dtype):
# def create_emb_for_encoder_and_decoder(share_vocab,
# src_vocab_size,
# tgt_vocab_size,
# src_embed_size,
# tgt_embed_size,
# dtype=tf.float32,
# num_partitions=0,
# src_vocab_file=None,
# tgt_vocab_file=None,
# src_embed_file=None,
# tgt_embed_file=None,
# scope=None):
# def _single_cell(unit_type,
# num_units,
# forget_bias,
# dropout,
# mode,
# residual_connection=False,
# device_str=None,
# residual_fn=None):
# def _cell_list(unit_type,
# num_units,
# num_layers,
# num_residual_layers,
# forget_bias,
# dropout,
# mode,
# num_gpus,
# base_gpu=0,
# single_cell_fn=None,
# residual_fn=None):
# def create_rnn_cell(unit_type,
# num_units,
# num_layers,
# num_residual_layers,
# forget_bias,
# dropout,
# mode,
# num_gpus,
# base_gpu=0,
# single_cell_fn=None):
# def gradient_clip(gradients, max_gradient_norm):
# def load_model(model, ckpt, session, name):
# def avg_checkpoints(model_dir, num_last_checkpoints, global_step,
# global_step_name):
# def get_global_step(model, session):
# def create_or_load_model(model, model_dir, session, name):
# def compute_perplexity(hparams, model, sess, name):
# class ExtraArgs(
# collections.namedtuple(
# "ExtraArgs",
# ("single_cell_fn", "model_device_fn", "attention_mechanism_fn"))):
# class TrainModel(
# collections.namedtuple(
# "TrainModel",
# ("graph", "model", "iterator", "src_placeholder", "tgt_placeholder",
# "annot_placeholder", "skip_count_placeholder"))):
# class TrainModelForServer(
# collections.namedtuple(
# "TrainModelForServer",
# ("graph", "model", "iterator", "src_placeholder", "tgt_placeholder",
# "wgt_placeholder", "batch_size_placeholder", "skip_count_placeholder"))
# ):
# class EvalModel(
# collections.namedtuple(
# "EvalModel",
# ("graph", "model", "src_file_placeholder", "tgt_file_placeholder",
# "ctx_file_placeholder", "annot_file_placeholder", "iterator"))):
# class InferModel(
# collections.namedtuple(
# "InferModel", ("graph", "model", "src_placeholder", "annot_placeholder",
# "ctx_placeholder", "trie_exclude_placeholder",
# "batch_size_placeholder", "iterator"))):
, which may contain function names, class names, or code. Output only the next line. | from third_party.nmt.utils import misc_utils as utils |
Given the following code snippet before the placeholder: <|code_start|># Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Utility to handle vocabularies."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
<|code_end|>
, predict the next line using imports from the current file:
import codecs
import os
import tensorflow as tf
from tensorflow.python.ops import lookup_ops
from third_party.nmt.utils import misc_utils as utils
and context including class names, function names, and sometimes code from other files:
# Path: third_party/nmt/utils/misc_utils.py
# def check_tensorflow_version():
# def safe_exp(value):
# def print_time(s, start_time):
# def print_out(s, f=None, new_line=True):
# def print_hparams(hparams, skip_patterns=None, header=None):
# def load_hparams(model_dir):
# def maybe_parse_standard_hparams(hparams, hparams_path):
# def save_hparams(out_dir, hparams):
# def debug_tensor(s, msg=None, summarize=10):
# def add_summary(summary_writer, global_step, tag, value):
# def get_config_proto(log_device_placement=False, allow_soft_placement=True,
# num_intra_threads=0, num_inter_threads=0):
# def format_text(words):
# def format_bpe_text(symbols, delimiter=b"@@"):
# def format_spm_text(symbols):
. Output only the next line. | from third_party.nmt.utils import misc_utils as utils |
Given the code snippet: <|code_start|> new_state = tf.cond(self.is_train, lambda: new_state_do,
lambda: new_state)
return outputs, new_state
class TreeRNNCell(tf.nn.rnn_cell.RNNCell):
def __init__(self, cell, input_size, reduce_func):
self._cell = cell
self._input_size = input_size
self._reduce_func = reduce_func
def __call__(self, inputs, state, scope=None):
"""
:param inputs: [N*B, I + B]
:param state: [N*B, d]
:param scope:
:return: [N*B, d]
"""
with tf.variable_scope(scope or self.__class__.__name__):
d = self.state_size
x = tf.slice(inputs, [0, 0], [-1, self._input_size]) # [N*B, I]
mask = tf.slice(inputs, [0, self._input_size], [-1, -1]) # [N*B, B]
B = tf.shape(mask)[1]
prev_state = tf.expand_dims(tf.reshape(state, [-1, B, d]),
1) # [N, B, d] -> [N, 1, B, d]
mask = tf.tile(
tf.expand_dims(tf.reshape(mask, [-1, B, B]), -1), [1, 1, 1,
d]) # [N, B, B, d]
# prev_state = self._reduce_func(tf.tile(prev_state, [1, B, 1, 1]), 2)
<|code_end|>
, generate the next line using the imports in this file:
import tensorflow as tf
from third_party.bi_att_flow.my.tensorflow.general import exp_mask, flatten
from third_party.bi_att_flow.my.tensorflow.nn import linear, softsel, double_linear_logits
and context (functions, classes, or occasionally code) from other files:
# Path: third_party/bi_att_flow/my/tensorflow/general.py
# def exp_mask(val, mask, name=None):
# """Give very negative number to unmasked elements in val.
#
# For example, [-3, -2, 10], [True, True, False] -> [-3, -2, -1e9].
# Typically, this effectively masks in exponential space (e.g. softmax)
# Args:
# val: values to be masked
# mask: masking boolean tensor, same shape as tensor
# name: name for output tensor
#
# Returns:
# Same shape as val, where some elements are very small (exponentially
# zero)
# """
# if name is None:
# name = 'exp_mask'
# return tf.add(
# val, (1 - tf.cast(mask, 'float')) * VERY_NEGATIVE_NUMBER, name=name)
#
# def flatten(tensor, keep):
# fixed_shape = tensor.get_shape().as_list()
# start = len(fixed_shape) - keep
# left = reduce(mul,
# [fixed_shape[i] or tf.shape(tensor)[i] for i in range(start)])
# out_shape = [left] + [
# fixed_shape[i] or tf.shape(tensor)[i]
# for i in range(start, len(fixed_shape))
# ]
# flat = tf.reshape(tensor, out_shape)
# return flat
#
# Path: third_party/bi_att_flow/my/tensorflow/nn.py
# def linear(args,
# output_size,
# bias,
# bias_start=0.0,
# scope=None,
# squeeze=False,
# wd=0.0,
# input_keep_prob=1.0,
# is_train=None):
# if args is None or (nest.is_sequence(args) and not args):
# raise ValueError("`args` must be specified")
# if not nest.is_sequence(args):
# args = [args]
#
# flat_args = [flatten(arg, 1) for arg in args]
# if input_keep_prob < 1.0:
# assert is_train is not None
# flat_args = [
# tf.cond(is_train, lambda: tf.nn.dropout(arg, input_keep_prob),
# lambda: arg) for arg in flat_args
# ]
#
# flat_out = _linear(
# flat_args, output_size, bias, bias_start=bias_start, scope=scope)
# out = reconstruct(flat_out, args[0], 1)
# if squeeze:
# out = tf.squeeze(out, [len(args[0].get_shape().as_list()) - 1])
# if wd:
# add_wd(wd)
#
# return out
#
# def softsel(target, logits, mask=None, scope=None):
# """
#
# :param target: [ ..., J, d] dtype=float
# :param logits: [ ..., J], dtype=float
# :param mask: [ ..., J], dtype=bool
# :param scope:
# :return: [..., d], dtype=float
# """
# with tf.name_scope(scope or "Softsel"):
# a = softmax(logits, mask=mask)
# target_rank = len(target.get_shape().as_list())
# out = tf.reduce_sum(tf.expand_dims(a, -1) * target, target_rank - 2)
# return out
#
# def double_linear_logits(args,
# size,
# bias,
# bias_start=0.0,
# scope=None,
# mask=None,
# wd=0.0,
# input_keep_prob=1.0,
# is_train=None):
# with tf.variable_scope(scope or "Double_Linear_Logits"):
# first = tf.tanh(
# linear(
# args,
# size,
# bias,
# bias_start=bias_start,
# scope="first",
# wd=wd,
# input_keep_prob=input_keep_prob,
# is_train=is_train))
# second = linear(
# first,
# 1,
# bias,
# bias_start=bias_start,
# squeeze=True,
# scope="second",
# wd=wd,
# input_keep_prob=input_keep_prob,
# is_train=is_train)
# if mask is not None:
# second = exp_mask(second, mask)
# return second
. Output only the next line. | prev_state = self._reduce_func(exp_mask(prev_state, mask), 2) # [N, B, d] |
Next line prediction: <|code_start|> a = tf.nn.softmax(
exp_mask(linear(f, 1, True, squeeze=True, scope='a'),
q_mask)) # [N, JQ]
q = tf.reduce_sum(qs * tf.expand_dims(a, -1), 1)
z = tf.concat(1, [x, q]) # [N, 2d]
return self._cell(z, state)
class AttentionCell(tf.nn.rnn_cell.RNNCell):
def __init__(self,
cell,
memory,
mask=None,
controller=None,
mapper=None,
input_keep_prob=1.0,
is_train=None):
"""
Early fusion attention cell: uses the (inputs, state) to control the
current attention.
:param cell:
:param memory: [N, M, m]
:param mask:
:param controller: (inputs, prev_state, memory) -> memory_logits
"""
self._cell = cell
self._memory = memory
self._mask = mask
<|code_end|>
. Use current file imports:
(import tensorflow as tf
from third_party.bi_att_flow.my.tensorflow.general import exp_mask, flatten
from third_party.bi_att_flow.my.tensorflow.nn import linear, softsel, double_linear_logits)
and context including class names, function names, or small code snippets from other files:
# Path: third_party/bi_att_flow/my/tensorflow/general.py
# def exp_mask(val, mask, name=None):
# """Give very negative number to unmasked elements in val.
#
# For example, [-3, -2, 10], [True, True, False] -> [-3, -2, -1e9].
# Typically, this effectively masks in exponential space (e.g. softmax)
# Args:
# val: values to be masked
# mask: masking boolean tensor, same shape as tensor
# name: name for output tensor
#
# Returns:
# Same shape as val, where some elements are very small (exponentially
# zero)
# """
# if name is None:
# name = 'exp_mask'
# return tf.add(
# val, (1 - tf.cast(mask, 'float')) * VERY_NEGATIVE_NUMBER, name=name)
#
# def flatten(tensor, keep):
# fixed_shape = tensor.get_shape().as_list()
# start = len(fixed_shape) - keep
# left = reduce(mul,
# [fixed_shape[i] or tf.shape(tensor)[i] for i in range(start)])
# out_shape = [left] + [
# fixed_shape[i] or tf.shape(tensor)[i]
# for i in range(start, len(fixed_shape))
# ]
# flat = tf.reshape(tensor, out_shape)
# return flat
#
# Path: third_party/bi_att_flow/my/tensorflow/nn.py
# def linear(args,
# output_size,
# bias,
# bias_start=0.0,
# scope=None,
# squeeze=False,
# wd=0.0,
# input_keep_prob=1.0,
# is_train=None):
# if args is None or (nest.is_sequence(args) and not args):
# raise ValueError("`args` must be specified")
# if not nest.is_sequence(args):
# args = [args]
#
# flat_args = [flatten(arg, 1) for arg in args]
# if input_keep_prob < 1.0:
# assert is_train is not None
# flat_args = [
# tf.cond(is_train, lambda: tf.nn.dropout(arg, input_keep_prob),
# lambda: arg) for arg in flat_args
# ]
#
# flat_out = _linear(
# flat_args, output_size, bias, bias_start=bias_start, scope=scope)
# out = reconstruct(flat_out, args[0], 1)
# if squeeze:
# out = tf.squeeze(out, [len(args[0].get_shape().as_list()) - 1])
# if wd:
# add_wd(wd)
#
# return out
#
# def softsel(target, logits, mask=None, scope=None):
# """
#
# :param target: [ ..., J, d] dtype=float
# :param logits: [ ..., J], dtype=float
# :param mask: [ ..., J], dtype=bool
# :param scope:
# :return: [..., d], dtype=float
# """
# with tf.name_scope(scope or "Softsel"):
# a = softmax(logits, mask=mask)
# target_rank = len(target.get_shape().as_list())
# out = tf.reduce_sum(tf.expand_dims(a, -1) * target, target_rank - 2)
# return out
#
# def double_linear_logits(args,
# size,
# bias,
# bias_start=0.0,
# scope=None,
# mask=None,
# wd=0.0,
# input_keep_prob=1.0,
# is_train=None):
# with tf.variable_scope(scope or "Double_Linear_Logits"):
# first = tf.tanh(
# linear(
# args,
# size,
# bias,
# bias_start=bias_start,
# scope="first",
# wd=wd,
# input_keep_prob=input_keep_prob,
# is_train=is_train))
# second = linear(
# first,
# 1,
# bias,
# bias_start=bias_start,
# squeeze=True,
# scope="second",
# wd=wd,
# input_keep_prob=input_keep_prob,
# is_train=is_train)
# if mask is not None:
# second = exp_mask(second, mask)
# return second
. Output only the next line. | self._flat_memory = flatten(memory, 2) |
Based on the snippet: <|code_start|> # FIXME : This won't be needed with good shape guessing
self._q_len = q_len
@property
def state_size(self):
return self._cell.state_size
@property
def output_size(self):
return self._cell.output_size
def __call__(self, inputs, state, scope=None):
"""
:param inputs: [N, d + JQ + JQ * d]
:param state: [N, d]
:param scope:
:return:
"""
with tf.variable_scope(scope or self.__class__.__name__):
c_prev, h_prev = state
x = tf.slice(inputs, [0, 0], [-1, self._input_size])
q_mask = tf.slice(inputs, [0, self._input_size], [-1,
self._q_len]) # [N, JQ]
qs = tf.slice(inputs, [0, self._input_size + self._q_len], [-1, -1])
qs = tf.reshape(qs, [-1, self._q_len, self._input_size]) # [N, JQ, d]
x_tiled = tf.tile(tf.expand_dims(x, 1), [1, self._q_len, 1]) # [N, JQ, d]
h_prev_tiled = tf.tile(tf.expand_dims(h_prev, 1), [1, self._q_len,
1]) # [N, JQ, d]
f = tf.tanh(
<|code_end|>
, predict the immediate next line with the help of imports:
import tensorflow as tf
from third_party.bi_att_flow.my.tensorflow.general import exp_mask, flatten
from third_party.bi_att_flow.my.tensorflow.nn import linear, softsel, double_linear_logits
and context (classes, functions, sometimes code) from other files:
# Path: third_party/bi_att_flow/my/tensorflow/general.py
# def exp_mask(val, mask, name=None):
# """Give very negative number to unmasked elements in val.
#
# For example, [-3, -2, 10], [True, True, False] -> [-3, -2, -1e9].
# Typically, this effectively masks in exponential space (e.g. softmax)
# Args:
# val: values to be masked
# mask: masking boolean tensor, same shape as tensor
# name: name for output tensor
#
# Returns:
# Same shape as val, where some elements are very small (exponentially
# zero)
# """
# if name is None:
# name = 'exp_mask'
# return tf.add(
# val, (1 - tf.cast(mask, 'float')) * VERY_NEGATIVE_NUMBER, name=name)
#
# def flatten(tensor, keep):
# fixed_shape = tensor.get_shape().as_list()
# start = len(fixed_shape) - keep
# left = reduce(mul,
# [fixed_shape[i] or tf.shape(tensor)[i] for i in range(start)])
# out_shape = [left] + [
# fixed_shape[i] or tf.shape(tensor)[i]
# for i in range(start, len(fixed_shape))
# ]
# flat = tf.reshape(tensor, out_shape)
# return flat
#
# Path: third_party/bi_att_flow/my/tensorflow/nn.py
# def linear(args,
# output_size,
# bias,
# bias_start=0.0,
# scope=None,
# squeeze=False,
# wd=0.0,
# input_keep_prob=1.0,
# is_train=None):
# if args is None or (nest.is_sequence(args) and not args):
# raise ValueError("`args` must be specified")
# if not nest.is_sequence(args):
# args = [args]
#
# flat_args = [flatten(arg, 1) for arg in args]
# if input_keep_prob < 1.0:
# assert is_train is not None
# flat_args = [
# tf.cond(is_train, lambda: tf.nn.dropout(arg, input_keep_prob),
# lambda: arg) for arg in flat_args
# ]
#
# flat_out = _linear(
# flat_args, output_size, bias, bias_start=bias_start, scope=scope)
# out = reconstruct(flat_out, args[0], 1)
# if squeeze:
# out = tf.squeeze(out, [len(args[0].get_shape().as_list()) - 1])
# if wd:
# add_wd(wd)
#
# return out
#
# def softsel(target, logits, mask=None, scope=None):
# """
#
# :param target: [ ..., J, d] dtype=float
# :param logits: [ ..., J], dtype=float
# :param mask: [ ..., J], dtype=bool
# :param scope:
# :return: [..., d], dtype=float
# """
# with tf.name_scope(scope or "Softsel"):
# a = softmax(logits, mask=mask)
# target_rank = len(target.get_shape().as_list())
# out = tf.reduce_sum(tf.expand_dims(a, -1) * target, target_rank - 2)
# return out
#
# def double_linear_logits(args,
# size,
# bias,
# bias_start=0.0,
# scope=None,
# mask=None,
# wd=0.0,
# input_keep_prob=1.0,
# is_train=None):
# with tf.variable_scope(scope or "Double_Linear_Logits"):
# first = tf.tanh(
# linear(
# args,
# size,
# bias,
# bias_start=bias_start,
# scope="first",
# wd=wd,
# input_keep_prob=input_keep_prob,
# is_train=is_train))
# second = linear(
# first,
# 1,
# bias,
# bias_start=bias_start,
# squeeze=True,
# scope="second",
# wd=wd,
# input_keep_prob=input_keep_prob,
# is_train=is_train)
# if mask is not None:
# second = exp_mask(second, mask)
# return second
. Output only the next line. | linear( |
Given snippet: <|code_start|> :param cell:
:param memory: [N, M, m]
:param mask:
:param controller: (inputs, prev_state, memory) -> memory_logits
"""
self._cell = cell
self._memory = memory
self._mask = mask
self._flat_memory = flatten(memory, 2)
self._flat_mask = flatten(mask, 1)
if controller is None:
controller = AttentionCell.get_linear_controller(True, is_train=is_train)
self._controller = controller
if mapper is None:
mapper = AttentionCell.get_concat_mapper()
elif mapper == 'sim':
mapper = AttentionCell.get_sim_mapper()
self._mapper = mapper
@property
def state_size(self):
return self._cell.state_size
@property
def output_size(self):
return self._cell.output_size
def __call__(self, inputs, state, scope=None):
with tf.variable_scope(scope or 'AttentionCell'):
memory_logits = self._controller(inputs, state, self._flat_memory)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import tensorflow as tf
from third_party.bi_att_flow.my.tensorflow.general import exp_mask, flatten
from third_party.bi_att_flow.my.tensorflow.nn import linear, softsel, double_linear_logits
and context:
# Path: third_party/bi_att_flow/my/tensorflow/general.py
# def exp_mask(val, mask, name=None):
# """Give very negative number to unmasked elements in val.
#
# For example, [-3, -2, 10], [True, True, False] -> [-3, -2, -1e9].
# Typically, this effectively masks in exponential space (e.g. softmax)
# Args:
# val: values to be masked
# mask: masking boolean tensor, same shape as tensor
# name: name for output tensor
#
# Returns:
# Same shape as val, where some elements are very small (exponentially
# zero)
# """
# if name is None:
# name = 'exp_mask'
# return tf.add(
# val, (1 - tf.cast(mask, 'float')) * VERY_NEGATIVE_NUMBER, name=name)
#
# def flatten(tensor, keep):
# fixed_shape = tensor.get_shape().as_list()
# start = len(fixed_shape) - keep
# left = reduce(mul,
# [fixed_shape[i] or tf.shape(tensor)[i] for i in range(start)])
# out_shape = [left] + [
# fixed_shape[i] or tf.shape(tensor)[i]
# for i in range(start, len(fixed_shape))
# ]
# flat = tf.reshape(tensor, out_shape)
# return flat
#
# Path: third_party/bi_att_flow/my/tensorflow/nn.py
# def linear(args,
# output_size,
# bias,
# bias_start=0.0,
# scope=None,
# squeeze=False,
# wd=0.0,
# input_keep_prob=1.0,
# is_train=None):
# if args is None or (nest.is_sequence(args) and not args):
# raise ValueError("`args` must be specified")
# if not nest.is_sequence(args):
# args = [args]
#
# flat_args = [flatten(arg, 1) for arg in args]
# if input_keep_prob < 1.0:
# assert is_train is not None
# flat_args = [
# tf.cond(is_train, lambda: tf.nn.dropout(arg, input_keep_prob),
# lambda: arg) for arg in flat_args
# ]
#
# flat_out = _linear(
# flat_args, output_size, bias, bias_start=bias_start, scope=scope)
# out = reconstruct(flat_out, args[0], 1)
# if squeeze:
# out = tf.squeeze(out, [len(args[0].get_shape().as_list()) - 1])
# if wd:
# add_wd(wd)
#
# return out
#
# def softsel(target, logits, mask=None, scope=None):
# """
#
# :param target: [ ..., J, d] dtype=float
# :param logits: [ ..., J], dtype=float
# :param mask: [ ..., J], dtype=bool
# :param scope:
# :return: [..., d], dtype=float
# """
# with tf.name_scope(scope or "Softsel"):
# a = softmax(logits, mask=mask)
# target_rank = len(target.get_shape().as_list())
# out = tf.reduce_sum(tf.expand_dims(a, -1) * target, target_rank - 2)
# return out
#
# def double_linear_logits(args,
# size,
# bias,
# bias_start=0.0,
# scope=None,
# mask=None,
# wd=0.0,
# input_keep_prob=1.0,
# is_train=None):
# with tf.variable_scope(scope or "Double_Linear_Logits"):
# first = tf.tanh(
# linear(
# args,
# size,
# bias,
# bias_start=bias_start,
# scope="first",
# wd=wd,
# input_keep_prob=input_keep_prob,
# is_train=is_train))
# second = linear(
# first,
# 1,
# bias,
# bias_start=bias_start,
# squeeze=True,
# scope="second",
# wd=wd,
# input_keep_prob=input_keep_prob,
# is_train=is_train)
# if mask is not None:
# second = exp_mask(second, mask)
# return second
which might include code, classes, or functions. Output only the next line. | sel_mem = softsel( |
Predict the next line for this snippet: <|code_start|> new_inputs, new_state = self._mapper(inputs, state, sel_mem)
return self._cell(new_inputs, state)
@staticmethod
def get_double_linear_controller(size,
bias,
input_keep_prob=1.0,
is_train=None):
def double_linear_controller(inputs, state, memory):
"""
:param inputs: [N, i]
:param state: [N, d]
:param memory: [N, M, m]
:return: [N, M]
"""
rank = len(memory.get_shape())
_memory_size = tf.shape(memory)[rank - 2]
tiled_inputs = tf.tile(tf.expand_dims(inputs, 1), [1, _memory_size, 1])
if isinstance(state, tuple):
tiled_states = [
tf.tile(tf.expand_dims(each, 1), [1, _memory_size, 1])
for each in state
]
else:
tiled_states = [tf.tile(tf.expand_dims(state, 1), [1, _memory_size, 1])]
# [N, M, d]
in_ = tf.concat(2, [tiled_inputs] + tiled_states + [memory])
<|code_end|>
with the help of current file imports:
import tensorflow as tf
from third_party.bi_att_flow.my.tensorflow.general import exp_mask, flatten
from third_party.bi_att_flow.my.tensorflow.nn import linear, softsel, double_linear_logits
and context from other files:
# Path: third_party/bi_att_flow/my/tensorflow/general.py
# def exp_mask(val, mask, name=None):
# """Give very negative number to unmasked elements in val.
#
# For example, [-3, -2, 10], [True, True, False] -> [-3, -2, -1e9].
# Typically, this effectively masks in exponential space (e.g. softmax)
# Args:
# val: values to be masked
# mask: masking boolean tensor, same shape as tensor
# name: name for output tensor
#
# Returns:
# Same shape as val, where some elements are very small (exponentially
# zero)
# """
# if name is None:
# name = 'exp_mask'
# return tf.add(
# val, (1 - tf.cast(mask, 'float')) * VERY_NEGATIVE_NUMBER, name=name)
#
# def flatten(tensor, keep):
# fixed_shape = tensor.get_shape().as_list()
# start = len(fixed_shape) - keep
# left = reduce(mul,
# [fixed_shape[i] or tf.shape(tensor)[i] for i in range(start)])
# out_shape = [left] + [
# fixed_shape[i] or tf.shape(tensor)[i]
# for i in range(start, len(fixed_shape))
# ]
# flat = tf.reshape(tensor, out_shape)
# return flat
#
# Path: third_party/bi_att_flow/my/tensorflow/nn.py
# def linear(args,
# output_size,
# bias,
# bias_start=0.0,
# scope=None,
# squeeze=False,
# wd=0.0,
# input_keep_prob=1.0,
# is_train=None):
# if args is None or (nest.is_sequence(args) and not args):
# raise ValueError("`args` must be specified")
# if not nest.is_sequence(args):
# args = [args]
#
# flat_args = [flatten(arg, 1) for arg in args]
# if input_keep_prob < 1.0:
# assert is_train is not None
# flat_args = [
# tf.cond(is_train, lambda: tf.nn.dropout(arg, input_keep_prob),
# lambda: arg) for arg in flat_args
# ]
#
# flat_out = _linear(
# flat_args, output_size, bias, bias_start=bias_start, scope=scope)
# out = reconstruct(flat_out, args[0], 1)
# if squeeze:
# out = tf.squeeze(out, [len(args[0].get_shape().as_list()) - 1])
# if wd:
# add_wd(wd)
#
# return out
#
# def softsel(target, logits, mask=None, scope=None):
# """
#
# :param target: [ ..., J, d] dtype=float
# :param logits: [ ..., J], dtype=float
# :param mask: [ ..., J], dtype=bool
# :param scope:
# :return: [..., d], dtype=float
# """
# with tf.name_scope(scope or "Softsel"):
# a = softmax(logits, mask=mask)
# target_rank = len(target.get_shape().as_list())
# out = tf.reduce_sum(tf.expand_dims(a, -1) * target, target_rank - 2)
# return out
#
# def double_linear_logits(args,
# size,
# bias,
# bias_start=0.0,
# scope=None,
# mask=None,
# wd=0.0,
# input_keep_prob=1.0,
# is_train=None):
# with tf.variable_scope(scope or "Double_Linear_Logits"):
# first = tf.tanh(
# linear(
# args,
# size,
# bias,
# bias_start=bias_start,
# scope="first",
# wd=wd,
# input_keep_prob=input_keep_prob,
# is_train=is_train))
# second = linear(
# first,
# 1,
# bias,
# bias_start=bias_start,
# squeeze=True,
# scope="second",
# wd=wd,
# input_keep_prob=input_keep_prob,
# is_train=is_train)
# if mask is not None:
# second = exp_mask(second, mask)
# return second
, which may contain function names, class names, or code. Output only the next line. | out = double_linear_logits( |
Based on the snippet: <|code_start|> self.debug_mode = debug_mode
if model_type == 'triviaqa':
self._InitializeEnvironment(
precomputed_data_path=precomputed_data_path,
corpus_dir=corpus_dir,
model_dir=model_dir,
nltk_dir=nltk_dir,
load_test=load_test,
debug_mode=debug_mode)
elif model_type == 'squad':
self._InitializeSquadEnvironment(
corpus_dir=corpus_dir,
corpus_name=corpus_name,
corpus_part=corpus_part,
model_dir=model_dir,
nltk_dir=nltk_dir)
def _InitializeEnvironment(self, precomputed_data_path, corpus_dir, model_dir,
nltk_dir, load_test, debug_mode):
"""Initilizes the DocQA model environment.
Args:
precomputed_data_path: Path to the precomputed data stored in a pickle
file.
corpus_dir: Path to corpus directory.
model_dir: Directory containing parameters of a pre-trained DocQA model.
nltk_dir: Folder containing the nltk package.
load_test: If True, loads the test set as well.
debug_mode: If true, logs additional debug information.
"""
<|code_end|>
, predict the immediate next line with the help of imports:
from concurrent import futures
from absl import app
from absl import flags
from absl import logging
from px.environments import docqa
from px.environments import docqa_squad
from px.proto import aqa_pb2
from px.proto import aqa_pb2_grpc
import time
import grpc
and context (classes, functions, sometimes code) from other files:
# Path: px/environments/docqa.py
# class DocqaEnvironment(object):
# def __init__(self,
# precomputed_data_path,
# corpus_dir,
# model_dir,
# nltk_dir,
# async=0,
# batch_size=32,
# corpus_name="wiki",
# debug_mode=False,
# filter_name=None,
# load_test=False,
# max_answer_len=8,
# max_tokens=400,
# n_paragraphs=5,
# n_processes=12,
# step="latest"):
# def GetAnswers(self, questions, document_ids):
# def best_answers(self, dataframe):
# def load_data(self, precomputed_data_path, corpus_name, corpus_dir, nltk_dir,
# datasets, filter_name, n_paragraphs, n_processes):
. Output only the next line. | self._environment = docqa.DocqaEnvironment( |
Here is a snippet: <|code_start|># ==============================================================================
"""Tests for iterator_utils.py"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
class IteratorUtilsTest(tf.test.TestCase):
def testGetIterator(self):
tf.set_random_seed(1)
tgt_vocab_table = src_vocab_table = lookup_ops.index_table_from_tensor(
tf.constant(["a", "b", "c", "eos", "sos"]))
src_dataset = tf.data.Dataset.from_tensor_slices(
tf.constant(["f e a g", "c c a", "d", "c a"]))
tgt_dataset = tf.data.Dataset.from_tensor_slices(
tf.constant(["c c", "a b", "", "b c"]))
hparams = tf.contrib.training.HParams(
random_seed=3,
num_buckets=5,
eos="eos",
sos="sos",
context_feed="",
server_mode=False)
batch_size = 2
src_max_len = 3
<|code_end|>
. Write the next line using the current file imports:
import tensorflow as tf
from tensorflow.python.ops import lookup_ops
from px.nmt.utils import iterator_utils
and context from other files:
# Path: px/nmt/utils/iterator_utils.py
# class BatchedInput(
# collections.namedtuple(
# "BatchedInput", ("initializer", "source_string", "source",
# "target_input", "target_output", "weights", "context",
# "annotation", "trie_exclude", "source_sequence_length",
# "target_sequence_length", "context_sequence_length"))):
# def get_infer_iterator(hparams,
# src_dataset,
# src_vocab_table,
# batch_size,
# eos,
# ctx_dataset=None,
# annot_dataset=None,
# trie_exclude_dataset=None,
# src_max_len=None,
# tgt_vocab_table=None):
# def batching_func(x):
# def get_iterator(hparams,
# src_dataset,
# tgt_dataset,
# src_vocab_table,
# tgt_vocab_table,
# batch_size,
# sos,
# eos,
# random_seed,
# num_buckets,
# wgt_dataset=None,
# ctx_dataset=None,
# annot_dataset=None,
# src_max_len=None,
# tgt_max_len=None,
# num_parallel_calls=4,
# output_buffer_size=None,
# skip_count=None,
# num_shards=1,
# shard_index=0,
# reshuffle_each_iteration=True):
# def batching_func(x):
# def key_func(unused_1, unused_2, unused_3, unused_4, unused_5, unused_6,
# unused_7, unused_8, src_len, tgt_len, unused_9):
# def reduce_func(unused_key, windowed_data):
, which may include functions, classes, or code. Output only the next line. | iterator = iterator_utils.get_iterator( |
Here is a snippet: <|code_start|>
def linear(args,
output_size,
bias,
bias_start=0.0,
scope=None,
squeeze=False,
wd=0.0,
input_keep_prob=1.0,
is_train=None):
if args is None or (nest.is_sequence(args) and not args):
raise ValueError("`args` must be specified")
if not nest.is_sequence(args):
args = [args]
flat_args = [flatten(arg, 1) for arg in args]
if input_keep_prob < 1.0:
assert is_train is not None
flat_args = [
tf.cond(is_train, lambda: tf.nn.dropout(arg, input_keep_prob),
lambda: arg) for arg in flat_args
]
flat_out = _linear(
flat_args, output_size, bias, bias_start=bias_start, scope=scope)
out = reconstruct(flat_out, args[0], 1)
if squeeze:
out = tf.squeeze(out, [len(args[0].get_shape().as_list()) - 1])
if wd:
<|code_end|>
. Write the next line using the current file imports:
import tensorflow as tf
from third_party.bi_att_flow.my.tensorflow.general import add_wd
from third_party.bi_att_flow.my.tensorflow.general import exp_mask
from third_party.bi_att_flow.my.tensorflow.general import flatten
from third_party.bi_att_flow.my.tensorflow.general import reconstruct
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import init_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import variable_scope as vs
from tensorflow.python.util import nest
and context from other files:
# Path: third_party/bi_att_flow/my/tensorflow/general.py
# def add_wd(wd, scope=None):
# scope = scope or tf.get_variable_scope().name
# variables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=scope)
# with tf.name_scope('weight_decay'):
# for var in variables:
# weight_decay = tf.mul(
# tf.nn.l2_loss(var), wd, name='{}/wd'.format(var.op.name))
# tf.add_to_collection('losses', weight_decay)
#
# Path: third_party/bi_att_flow/my/tensorflow/general.py
# def exp_mask(val, mask, name=None):
# """Give very negative number to unmasked elements in val.
#
# For example, [-3, -2, 10], [True, True, False] -> [-3, -2, -1e9].
# Typically, this effectively masks in exponential space (e.g. softmax)
# Args:
# val: values to be masked
# mask: masking boolean tensor, same shape as tensor
# name: name for output tensor
#
# Returns:
# Same shape as val, where some elements are very small (exponentially
# zero)
# """
# if name is None:
# name = 'exp_mask'
# return tf.add(
# val, (1 - tf.cast(mask, 'float')) * VERY_NEGATIVE_NUMBER, name=name)
#
# Path: third_party/bi_att_flow/my/tensorflow/general.py
# def flatten(tensor, keep):
# fixed_shape = tensor.get_shape().as_list()
# start = len(fixed_shape) - keep
# left = reduce(mul,
# [fixed_shape[i] or tf.shape(tensor)[i] for i in range(start)])
# out_shape = [left] + [
# fixed_shape[i] or tf.shape(tensor)[i]
# for i in range(start, len(fixed_shape))
# ]
# flat = tf.reshape(tensor, out_shape)
# return flat
#
# Path: third_party/bi_att_flow/my/tensorflow/general.py
# def reconstruct(tensor, ref, keep):
# ref_shape = ref.get_shape().as_list()
# tensor_shape = tensor.get_shape().as_list()
# ref_stop = len(ref_shape) - keep
# tensor_start = len(tensor_shape) - keep
# pre_shape = [ref_shape[i] or tf.shape(ref)[i] for i in range(ref_stop)]
# keep_shape = [
# tensor_shape[i] or tf.shape(tensor)[i]
# for i in range(tensor_start, len(tensor_shape))
# ]
# # pre_shape = [tf.shape(ref)[i] for i in range(len(ref.get_shape().as_list()[:-keep]))]
# # keep_shape = tensor.get_shape().as_list()[-keep:]
# target_shape = pre_shape + keep_shape
# out = tf.reshape(tensor, target_shape)
# return out
, which may include functions, classes, or code. Output only the next line. | add_wd(wd) |
Predict the next line after this snippet: <|code_start|> if input_keep_prob < 1.0:
assert is_train is not None
flat_args = [
tf.cond(is_train, lambda: tf.nn.dropout(arg, input_keep_prob),
lambda: arg) for arg in flat_args
]
flat_out = _linear(
flat_args, output_size, bias, bias_start=bias_start, scope=scope)
out = reconstruct(flat_out, args[0], 1)
if squeeze:
out = tf.squeeze(out, [len(args[0].get_shape().as_list()) - 1])
if wd:
add_wd(wd)
return out
def dropout(x, keep_prob, is_train, noise_shape=None, seed=None, name=None):
with tf.name_scope(name or "dropout"):
if keep_prob < 1.0:
d = tf.nn.dropout(x, keep_prob, noise_shape=noise_shape, seed=seed)
out = tf.cond(is_train, lambda: d, lambda: x)
return out
return x
def softmax(logits, mask=None, scope=None):
with tf.name_scope(scope or "Softmax"):
if mask is not None:
<|code_end|>
using the current file's imports:
import tensorflow as tf
from third_party.bi_att_flow.my.tensorflow.general import add_wd
from third_party.bi_att_flow.my.tensorflow.general import exp_mask
from third_party.bi_att_flow.my.tensorflow.general import flatten
from third_party.bi_att_flow.my.tensorflow.general import reconstruct
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import init_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import variable_scope as vs
from tensorflow.python.util import nest
and any relevant context from other files:
# Path: third_party/bi_att_flow/my/tensorflow/general.py
# def add_wd(wd, scope=None):
# scope = scope or tf.get_variable_scope().name
# variables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=scope)
# with tf.name_scope('weight_decay'):
# for var in variables:
# weight_decay = tf.mul(
# tf.nn.l2_loss(var), wd, name='{}/wd'.format(var.op.name))
# tf.add_to_collection('losses', weight_decay)
#
# Path: third_party/bi_att_flow/my/tensorflow/general.py
# def exp_mask(val, mask, name=None):
# """Give very negative number to unmasked elements in val.
#
# For example, [-3, -2, 10], [True, True, False] -> [-3, -2, -1e9].
# Typically, this effectively masks in exponential space (e.g. softmax)
# Args:
# val: values to be masked
# mask: masking boolean tensor, same shape as tensor
# name: name for output tensor
#
# Returns:
# Same shape as val, where some elements are very small (exponentially
# zero)
# """
# if name is None:
# name = 'exp_mask'
# return tf.add(
# val, (1 - tf.cast(mask, 'float')) * VERY_NEGATIVE_NUMBER, name=name)
#
# Path: third_party/bi_att_flow/my/tensorflow/general.py
# def flatten(tensor, keep):
# fixed_shape = tensor.get_shape().as_list()
# start = len(fixed_shape) - keep
# left = reduce(mul,
# [fixed_shape[i] or tf.shape(tensor)[i] for i in range(start)])
# out_shape = [left] + [
# fixed_shape[i] or tf.shape(tensor)[i]
# for i in range(start, len(fixed_shape))
# ]
# flat = tf.reshape(tensor, out_shape)
# return flat
#
# Path: third_party/bi_att_flow/my/tensorflow/general.py
# def reconstruct(tensor, ref, keep):
# ref_shape = ref.get_shape().as_list()
# tensor_shape = tensor.get_shape().as_list()
# ref_stop = len(ref_shape) - keep
# tensor_start = len(tensor_shape) - keep
# pre_shape = [ref_shape[i] or tf.shape(ref)[i] for i in range(ref_stop)]
# keep_shape = [
# tensor_shape[i] or tf.shape(tensor)[i]
# for i in range(tensor_start, len(tensor_shape))
# ]
# # pre_shape = [tf.shape(ref)[i] for i in range(len(ref.get_shape().as_list()[:-keep]))]
# # keep_shape = tensor.get_shape().as_list()[-keep:]
# target_shape = pre_shape + keep_shape
# out = tf.reshape(tensor, target_shape)
# return out
. Output only the next line. | logits = exp_mask(logits, mask) |
Given the following code snippet before the placeholder: <|code_start|> matrix = vs.get_variable(
"Matrix", [total_arg_size, output_size], dtype=dtype)
if len(args) == 1:
res = math_ops.matmul(args[0], matrix)
else:
res = math_ops.matmul(array_ops.concat(args, 1), matrix)
if not bias:
return res
bias_term = vs.get_variable(
"Bias", [output_size],
dtype=dtype,
initializer=init_ops.constant_initializer(
bias_start, dtype=dtype))
return res + bias_term
def linear(args,
output_size,
bias,
bias_start=0.0,
scope=None,
squeeze=False,
wd=0.0,
input_keep_prob=1.0,
is_train=None):
if args is None or (nest.is_sequence(args) and not args):
raise ValueError("`args` must be specified")
if not nest.is_sequence(args):
args = [args]
<|code_end|>
, predict the next line using imports from the current file:
import tensorflow as tf
from third_party.bi_att_flow.my.tensorflow.general import add_wd
from third_party.bi_att_flow.my.tensorflow.general import exp_mask
from third_party.bi_att_flow.my.tensorflow.general import flatten
from third_party.bi_att_flow.my.tensorflow.general import reconstruct
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import init_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import variable_scope as vs
from tensorflow.python.util import nest
and context including class names, function names, and sometimes code from other files:
# Path: third_party/bi_att_flow/my/tensorflow/general.py
# def add_wd(wd, scope=None):
# scope = scope or tf.get_variable_scope().name
# variables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=scope)
# with tf.name_scope('weight_decay'):
# for var in variables:
# weight_decay = tf.mul(
# tf.nn.l2_loss(var), wd, name='{}/wd'.format(var.op.name))
# tf.add_to_collection('losses', weight_decay)
#
# Path: third_party/bi_att_flow/my/tensorflow/general.py
# def exp_mask(val, mask, name=None):
# """Give very negative number to unmasked elements in val.
#
# For example, [-3, -2, 10], [True, True, False] -> [-3, -2, -1e9].
# Typically, this effectively masks in exponential space (e.g. softmax)
# Args:
# val: values to be masked
# mask: masking boolean tensor, same shape as tensor
# name: name for output tensor
#
# Returns:
# Same shape as val, where some elements are very small (exponentially
# zero)
# """
# if name is None:
# name = 'exp_mask'
# return tf.add(
# val, (1 - tf.cast(mask, 'float')) * VERY_NEGATIVE_NUMBER, name=name)
#
# Path: third_party/bi_att_flow/my/tensorflow/general.py
# def flatten(tensor, keep):
# fixed_shape = tensor.get_shape().as_list()
# start = len(fixed_shape) - keep
# left = reduce(mul,
# [fixed_shape[i] or tf.shape(tensor)[i] for i in range(start)])
# out_shape = [left] + [
# fixed_shape[i] or tf.shape(tensor)[i]
# for i in range(start, len(fixed_shape))
# ]
# flat = tf.reshape(tensor, out_shape)
# return flat
#
# Path: third_party/bi_att_flow/my/tensorflow/general.py
# def reconstruct(tensor, ref, keep):
# ref_shape = ref.get_shape().as_list()
# tensor_shape = tensor.get_shape().as_list()
# ref_stop = len(ref_shape) - keep
# tensor_start = len(tensor_shape) - keep
# pre_shape = [ref_shape[i] or tf.shape(ref)[i] for i in range(ref_stop)]
# keep_shape = [
# tensor_shape[i] or tf.shape(tensor)[i]
# for i in range(tensor_start, len(tensor_shape))
# ]
# # pre_shape = [tf.shape(ref)[i] for i in range(len(ref.get_shape().as_list()[:-keep]))]
# # keep_shape = tensor.get_shape().as_list()[-keep:]
# target_shape = pre_shape + keep_shape
# out = tf.reshape(tensor, target_shape)
# return out
. Output only the next line. | flat_args = [flatten(arg, 1) for arg in args] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.