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 ...
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 ...
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) # ...
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_a...
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...
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...
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...
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 = () ...
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 s...
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 ...
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...
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...
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.g...
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 ...
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...
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='Num...
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_...
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' )...
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 = s...
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): <...
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 ...
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)...
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: ...
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]'...
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...
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' ] ) ...
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 ...
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) ...
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 ru...
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',...
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__() ad...
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 # Signa...
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.com...
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 ...
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, ...
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 ad...
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 ...
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 != ge...
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...
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...
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 co...
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 impor...
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,...
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(se...
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() ...
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): ...
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") ...
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 = [] ...
fh = FuncHeuristic(None, None, "")
Predict the next line for this snippet: <|code_start|> | |-- | | |-- ! | | | |-- isalnum | | | `-- isgraph | | -- \\x00 | | |-- isascii | | `-- isprint | `-- A | |-- isalpha | `-- islower `-- \\t ...
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_WRI...
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_a...
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, ...
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, ContainerUnk...
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, chec...
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 ...
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 r...
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...
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, se...
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): ...
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) e...
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.act...
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 Improperly...
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" ...
"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" ) ...
"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 se...
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 ...
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_i...
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/$", Ne...
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, New...
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....
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...
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(), ...
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", ...
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", ...
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_l...
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....
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 = new...
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...
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.auto...
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) ...
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 = QUESTIO...
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_S...
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....
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 = _cle...
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(...
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, p...
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=N...
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() ...
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 # # Unles...
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/LICE...
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 = ...
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....
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): """ ...
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_mas...
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, ...
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, ...
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 testGet...
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 Val...
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, ...
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:...
flat_args = [flatten(arg, 1) for arg in args]