Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Using the snippet: <|code_start|> <span> 42 </span> </div>""", tmpl.generate(foo={'bar': 42}).render(encoding=None)) def test_unicode_expr(self): tmpl = MarkupTemplate(u"""<div xmlns:py="http://genshi.edgewall.org/"> <span py:with="weeks=(u'一', u'二', u'三', u'四', u'五', u'六', u'日')"> $weeks </span> </div>""") self.assertEqual(u"""<div> <span> 一二三四五六日 </span> </div>""", tmpl.generate().render(encoding=None)) def test_with_empty_value(self): """ Verify that an empty py:with works (useless, but legal) """ tmpl = MarkupTemplate("""<div xmlns:py="http://genshi.edgewall.org/"> <span py:with="">Text</span></div>""") self.assertEqual("""<div> <span>Text</span></div>""", tmpl.generate().render(encoding=None)) def suite(): suite = unittest.TestSuite() <|code_end|> , determine the next line of code. You have imports: import doctest import re import sys import unittest from genshi.template import directives, MarkupTemplate, TextTemplate, \ TemplateRuntimeError, TemplateSyntaxError and context (class names, function names, or code) available: # Path: genshi/template/directives.py # class DirectiveMeta(type): # class Directive(object): # class AttrsDirective(Directive): # class ContentDirective(Directive): # class DefDirective(Directive): # class ForDirective(Directive): # class IfDirective(Directive): # class MatchDirective(Directive): # class ReplaceDirective(Directive): # class StripDirective(Directive): # class ChooseDirective(Directive): # class WhenDirective(Directive): # class OtherwiseDirective(Directive): # class WithDirective(Directive): # def __new__(cls, name, bases, d): # def __init__(self, value, template=None, namespaces=None, lineno=-1, # offset=-1): # def attach(cls, template, stream, value, namespaces, pos): # def __call__(self, stream, directives, ctxt, **vars): # def __repr__(self): # def _parse_expr(cls, expr, template, lineno=-1, offset=-1): # def _assignment(ast): # def _names(node): # def _assign(data, value, names=_names(ast)): # def __call__(self, stream, directives, ctxt, **vars): # def _generate(): # def attach(cls, template, stream, value, namespaces, pos): # def __init__(self, args, template, namespaces=None, lineno=-1, offset=-1): # def attach(cls, template, stream, value, namespaces, pos): # def __call__(self, stream, directives, ctxt, **vars): # def function(*args, **kwargs): # def __repr__(self): # def __init__(self, value, template, namespaces=None, lineno=-1, offset=-1): # def attach(cls, template, stream, value, namespaces, pos): # def __call__(self, stream, directives, ctxt, **vars): # def __repr__(self): # def attach(cls, template, stream, value, namespaces, pos): # def __call__(self, stream, directives, ctxt, **vars): # def __init__(self, value, template, hints=None, namespaces=None, # lineno=-1, offset=-1): # def attach(cls, template, stream, value, namespaces, pos): # def __call__(self, stream, directives, ctxt, **vars): # def __repr__(self): # def attach(cls, template, stream, value, namespaces, pos): # def __call__(self, stream, directives, ctxt, **vars): # def _generate(): # def attach(cls, template, stream, value, namespaces, pos): # def __call__(self, stream, directives, ctxt, **vars): # def __init__(self, value, template, namespaces=None, lineno=-1, offset=-1): # def attach(cls, template, stream, value, namespaces, pos): # def __call__(self, stream, directives, ctxt, **vars): # def __init__(self, value, template, namespaces=None, lineno=-1, offset=-1): # def __call__(self, stream, directives, ctxt, **vars): # def __init__(self, value, template, namespaces=None, lineno=-1, offset=-1): # def attach(cls, template, stream, value, namespaces, pos): # def __call__(self, stream, directives, ctxt, **vars): # def __repr__(self): . Output only the next line.
suite.addTest(doctest.DocTestSuite(directives))
Predict the next line for this snippet: <|code_start|>#=========================================================================== # # Config parsing # #=========================================================================== __doc__ = """Config parsing. """ #=========================================================================== def parse( configDir ): # Parse the files. Default xform makes all keys lower case so set # it to str to stop that behavior. p = ConfigParser.ConfigParser() p.optionxform = str files = glob.glob( os.path.join( configDir, "*.conf" ) ) for f in files: p.read( f ) <|code_end|> with the help of current file imports: from .util import Data import ConfigParser import glob import os.path and context from other files: # Path: python/tHome/util/Data.py # class Data: # def __init__( self, dict=None, **kwargs ): # if dict: # self.__dict__.update( dict ) # if kwargs: # self.__dict__.update( kwargs ) # # #-------------------------------------------------------------------------- # def keys( self ): # return self.__dict__.keys() # # #-------------------------------------------------------------------------- # def update( self, rhs ): # return self.__dict__.update( rhs.__dict__ ) # # #-------------------------------------------------------------------------- # def __setitem__( self, key, value ): # self.__dict__[key] = value # # #-------------------------------------------------------------------------- # def __getitem__( self, key ): # return self.__dict__[key] # # #-------------------------------------------------------------------------- # def __contains__( self, key ): # return key in self.__dict__ # # #-------------------------------------------------------------------------- # def __str__( self ): # out = StringIO.StringIO() # self._formatValue( self, out, 3 ) # return out.getvalue() # # #-------------------------------------------------------------------------- # def __repr__( self ): # return self.__str__() # # #-------------------------------------------------------------------------- # def _formatValue( self, value, out, indent ): # if isinstance( value, Data ): # out.write( "%s(\n" % self.__class__.__name__ ) # for k, v in sorted( value.__dict__.iteritems() ): # if k[0] == "_": # continue # # out.write( "%*s%s" % ( indent, '', k ) ) # out.write( " = " ) # self._formatValue( v, out, indent+3 ) # out.write( ",\n" ) # # out.write( "%*s)" % ( indent, '' ) ) # # elif isinstance( value, dict ): # out.write( "{\n" ) # for k, v in sorted( value.iteritems() ): # if k[0] == "_": # continue # # out.write( "%*s" % ( indent, '' ) ) # self._formatValue( k, out, 0 ) # out.write( " : " ) # self._formatValue( v, out, indent+3 ) # out.write( ",\n" ) # # out.write( "%*s}" % ( indent, '' ) ) # # elif isinstance( value, list ): # out.write( "[\n" ) # for i in value: # out.write( "%*s" % ( indent, '' ) ) # self._formatValue( i, out, indent+3 ) # out.write( ",\n" ) # # out.write( "%*s]" % ( indent, '' ) ) # # elif isinstance( value, str ): # out.write( "'%s'" % ( value ) ) # # else: # out.write( "%s" % ( value ) ) , which may contain function names, class names, or code. Output only the next line.
cfg = Data( _config = p )
Given the following code snippet before the placeholder: <|code_start|>batteryMap = { "normal" : 1.0, "low" : 0.1, } #=========================================================================== def decode( text, sensorMap ): """Decode a sensor post from the Acurite bridge. Input is a line of text sent by the bridge to the Acurite server. Return valeue is a tHome.util.Data object (dict) with the parsed values. """ # Skip lines that aren't the sensor information. idx = text.find( "id=" ) if idx == -1: return text = text[idx:] # Split the input into fields. elems = text.split( "&" ) # Get the key/value pairs for each element. items = {} for e in elems: k, v = e.split( "=" ) items[k] = v # Create an empty data object (dict) to store the results. <|code_end|> , predict the next line using imports from the current file: import StringIO import time from ..util import Data and context including class names, function names, and sometimes code from other files: # Path: python/tHome/util/Data.py # class Data: # def __init__( self, dict=None, **kwargs ): # if dict: # self.__dict__.update( dict ) # if kwargs: # self.__dict__.update( kwargs ) # # #-------------------------------------------------------------------------- # def keys( self ): # return self.__dict__.keys() # # #-------------------------------------------------------------------------- # def update( self, rhs ): # return self.__dict__.update( rhs.__dict__ ) # # #-------------------------------------------------------------------------- # def __setitem__( self, key, value ): # self.__dict__[key] = value # # #-------------------------------------------------------------------------- # def __getitem__( self, key ): # return self.__dict__[key] # # #-------------------------------------------------------------------------- # def __contains__( self, key ): # return key in self.__dict__ # # #-------------------------------------------------------------------------- # def __str__( self ): # out = StringIO.StringIO() # self._formatValue( self, out, 3 ) # return out.getvalue() # # #-------------------------------------------------------------------------- # def __repr__( self ): # return self.__str__() # # #-------------------------------------------------------------------------- # def _formatValue( self, value, out, indent ): # if isinstance( value, Data ): # out.write( "%s(\n" % self.__class__.__name__ ) # for k, v in sorted( value.__dict__.iteritems() ): # if k[0] == "_": # continue # # out.write( "%*s%s" % ( indent, '', k ) ) # out.write( " = " ) # self._formatValue( v, out, indent+3 ) # out.write( ",\n" ) # # out.write( "%*s)" % ( indent, '' ) ) # # elif isinstance( value, dict ): # out.write( "{\n" ) # for k, v in sorted( value.iteritems() ): # if k[0] == "_": # continue # # out.write( "%*s" % ( indent, '' ) ) # self._formatValue( k, out, 0 ) # out.write( " : " ) # self._formatValue( v, out, indent+3 ) # out.write( ",\n" ) # # out.write( "%*s}" % ( indent, '' ) ) # # elif isinstance( value, list ): # out.write( "[\n" ) # for i in value: # out.write( "%*s" % ( indent, '' ) ) # self._formatValue( i, out, indent+3 ) # out.write( ",\n" ) # # out.write( "%*s]" % ( indent, '' ) ) # # elif isinstance( value, str ): # out.write( "'%s'" % ( value ) ) # # else: # out.write( "%s" % ( value ) ) . Output only the next line.
data = Data()
Given the code snippet: <|code_start|>#=========================================================================== # # File and directory utilities. # #=========================================================================== #=========================================================================== def makeDirs( fileName ): """TODO: docs """ try: d = os.path.dirname( fileName ) if d and not os.path.exists( d ): os.makedirs( d ) except ( IOError, OSError ) as e: msg = "Error trying to create intermediate directories for the file: " \ "'%s'" % ( fileName ) <|code_end|> , generate the next line using the imports in this file: import os import os.path from .Error import Error and context (functions, classes, or occasionally code) from other files: # Path: python/tHome/util/Error.py # class Error ( Exception ): # """: Stack based error message exception class. # """ # # #----------------------------------------------------------------------- # @staticmethod # def raiseException( exception, msg ): # excType, excValue, trace = sys.exc_info() # # if not isinstance( exception, Error ): # exception = Error( str( exception ) ) # # exception.add( msg ) # # raise exception, None, trace # # #----------------------------------------------------------------------- # @staticmethod # def fromException( exception, msg ): # excType, excValue, trace = sys.exc_info() # # newError = Error( str( exception ) ) # newError.add( msg ) # # raise newError, None, trace # # #----------------------------------------------------------------------- # def __init__( self, msg ): # """: Constructor # """ # self._msg = [ msg ] # # Exception.__init__( self ) # # #----------------------------------------------------------------------- # def add( self, msg ): # self._msg.append( msg ) # # #----------------------------------------------------------------------- # def __str__( self ): # s = "\n" # for msg in reversed( self._msg ): # s += "- %s\n" % msg # # return s # # #----------------------------------------------------------------------- . Output only the next line.
Error.raiseException( e, msg )
Next line prediction: <|code_start|> def __init__( self, endian, elems ): """Constructr endian == BIG_ENDIAN or LITTLE_ENDIAN elems = [ ( struct_format_code, name ), ... ] """ assert( endian == "BIG_ENDIAN" or endian == "LITTLE_ENDIAN" ) if endian == "BIG_ENDIAN": self.format = ">" elif endian == "LITTLE_ENDIAN": self.format = "<" self.format += "".join( [ i[0] for i in elems ] ) self.names = [ i[1] for i in elems ] self.struct = struct.Struct( self.format ) #--------------------------------------------------------------------------- def __len__( self ): return self.struct.size #--------------------------------------------------------------------------- def pack( self, obj ): data = [ getattr( obj, i ) for i in self.names ] return self.struct.pack( *data ) #--------------------------------------------------------------------------- def unpack( self, obj, bytes, offset=0 ): if obj is None: <|code_end|> . Use current file imports: (import struct from .Data import Data) and context including class names, function names, or small code snippets from other files: # Path: python/tHome/util/Data.py # class Data: # def __init__( self, dict=None, **kwargs ): # if dict: # self.__dict__.update( dict ) # if kwargs: # self.__dict__.update( kwargs ) # # #-------------------------------------------------------------------------- # def keys( self ): # return self.__dict__.keys() # # #-------------------------------------------------------------------------- # def update( self, rhs ): # return self.__dict__.update( rhs.__dict__ ) # # #-------------------------------------------------------------------------- # def __setitem__( self, key, value ): # self.__dict__[key] = value # # #-------------------------------------------------------------------------- # def __getitem__( self, key ): # return self.__dict__[key] # # #-------------------------------------------------------------------------- # def __contains__( self, key ): # return key in self.__dict__ # # #-------------------------------------------------------------------------- # def __str__( self ): # out = StringIO.StringIO() # self._formatValue( self, out, 3 ) # return out.getvalue() # # #-------------------------------------------------------------------------- # def __repr__( self ): # return self.__str__() # # #-------------------------------------------------------------------------- # def _formatValue( self, value, out, indent ): # if isinstance( value, Data ): # out.write( "%s(\n" % self.__class__.__name__ ) # for k, v in sorted( value.__dict__.iteritems() ): # if k[0] == "_": # continue # # out.write( "%*s%s" % ( indent, '', k ) ) # out.write( " = " ) # self._formatValue( v, out, indent+3 ) # out.write( ",\n" ) # # out.write( "%*s)" % ( indent, '' ) ) # # elif isinstance( value, dict ): # out.write( "{\n" ) # for k, v in sorted( value.iteritems() ): # if k[0] == "_": # continue # # out.write( "%*s" % ( indent, '' ) ) # self._formatValue( k, out, 0 ) # out.write( " : " ) # self._formatValue( v, out, indent+3 ) # out.write( ",\n" ) # # out.write( "%*s}" % ( indent, '' ) ) # # elif isinstance( value, list ): # out.write( "[\n" ) # for i in value: # out.write( "%*s" % ( indent, '' ) ) # self._formatValue( i, out, indent+3 ) # out.write( ",\n" ) # # out.write( "%*s]" % ( indent, '' ) ) # # elif isinstance( value, str ): # out.write( "'%s'" % ( value ) ) # # else: # out.write( "%s" % ( value ) ) . Output only the next line.
obj = Data()
Here is a snippet: <|code_start|>sys.path.insert(1,"./COMTool/") if sys.version_info < (3, 8): print("only support python >= 3.8, but now is {}".format(sys.version_info)) sys.exit(1) <|code_end|> . Write the next line using the current file imports: import os, sys, shutil import zipfile import shutil import re from COMTool import version, i18n and context from other files: # Path: COMTool/version.py # class Version: # def __init__(self, major=major, minor=minor, dev=dev, name="", desc=""): # def dump_dict(self): # def load_dict(self, obj): # def int(self): # def __str__(self): # # Path: COMTool/i18n.py # def _(text): # def set_locale(locale_in): # def get_languages(): # def extract(src_path, config_file_path, out_path): # def init(template_path, out_dir, locale, domain="messages"): # def update(template_path, out_dir, locale, domain="messages"): # def compile(translate_dir, locale, domain="messages"): # def main(cmd): , which may include functions, classes, or code. Output only the next line.
linux_out = "comtool_ubuntu_v{}.tar.xz".format(version.__version__)
Here is a snippet: <|code_start|> if type(v) == str: bundle_str_args += f'{k}="{v}",\n' else: bundle_str_args += f'{k}={v},\n' return bundle_str_args match = re.findall(r'BUNDLE\((.*?)\)', spec, flags=re.MULTILINE|re.DOTALL) if len(match) <= 0: raise Exception("no BUNDLE found in spec, please check code") code =f'app = BUNDLE({match[0]})' vars = { "BUNDLE": BUNDLE, "exe": "exe", "coll": "coll" } exec(code, vars) final_str = vars["app"] def re_replace(c): print(c[0]) return f'BUNDLE({final_str})' final_str = re.sub(r'BUNDLE\((.*)\)', re_replace, spec, flags=re.I|re.MULTILINE|re.DOTALL) print(final_str) with open(spec_path, "w") as f: f.write(spec) def pack(): # update translate <|code_end|> . Write the next line using the current file imports: import os, sys, shutil import zipfile import shutil import re from COMTool import version, i18n and context from other files: # Path: COMTool/version.py # class Version: # def __init__(self, major=major, minor=minor, dev=dev, name="", desc=""): # def dump_dict(self): # def load_dict(self, obj): # def int(self): # def __str__(self): # # Path: COMTool/i18n.py # def _(text): # def set_locale(locale_in): # def get_languages(): # def extract(src_path, config_file_path, out_path): # def init(template_path, out_dir, locale, domain="messages"): # def update(template_path, out_dir, locale, domain="messages"): # def compile(translate_dir, locale, domain="messages"): # def main(cmd): , which may include functions, classes, or code. Output only the next line.
i18n.main("finish")
Based on the snippet: <|code_start|>here = path.abspath(path.dirname(__file__)) # update translate i18n.main("finish") # Get the long description from the README file with open(path.join(here, 'README.MD'), encoding='utf-8') as f: long_description = f.read() systemPlatform = platform.platform() if "Linux" in systemPlatform and "arm" in systemPlatform : print("platform is arm linux: will install lib first") os.system("sudo apt install python3 python3-pip python3-pyqt5") os.system("sudo pip3 install --upgrade pyserial") installRequires = [] else: installRequires = ['pyqt5>=5', 'pyserial>=3.4', 'requests', 'Babel', 'qtawesome' ] setup( name='COMTool', # Versions should comply with PEP440. For a discussion on single-sourcing # the version across setup.py and the project code, see # https://packaging.python.org/en/latest/single_source_version.html <|code_end|> , predict the immediate next line with the help of imports: from setuptools import setup,find_packages from codecs import open from os import path from COMTool import helpAbout, parameters, i18n, version import os import platform and context (classes, functions, sometimes code) from other files: # Path: COMTool/helpAbout.py # def strAbout(): # # Path: COMTool/parameters.py # class Strings: # class Parameters: # def __init__(self, locale): # def get_config_path(configFileName): # def save(self, path): # def load(self, path): # def __str__(self) -> str: # # Path: COMTool/i18n.py # def _(text): # def set_locale(locale_in): # def get_languages(): # def extract(src_path, config_file_path, out_path): # def init(template_path, out_dir, locale, domain="messages"): # def update(template_path, out_dir, locale, domain="messages"): # def compile(translate_dir, locale, domain="messages"): # def main(cmd): # # Path: COMTool/version.py # class Version: # def __init__(self, major=major, minor=minor, dev=dev, name="", desc=""): # def dump_dict(self): # def load_dict(self, obj): # def int(self): # def __str__(self): . Output only the next line.
version=version.__version__,
Given the code snippet: <|code_start|> here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() # Dependencies are automatically detected, but it might need fine tuning. #中文需要显式用gbk方式编码 <|code_end|> , generate the next line using the imports in this file: from cx_Freeze import setup,Executable from codecs import open from os import path from COMTool import parameters,helpAbout import sys import traceback import msilib and context (functions, classes, or occasionally code) from other files: # Path: COMTool/parameters.py # class Strings: # class Parameters: # def __init__(self, locale): # def get_config_path(configFileName): # def save(self, path): # def load(self, path): # def __str__(self) -> str: # # Path: COMTool/helpAbout.py # def strAbout(): . Output only the next line.
product_name = parameters.appName.encode('gbk')
Given the code snippet: <|code_start|> here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() # Dependencies are automatically detected, but it might need fine tuning. #中文需要显式用gbk方式编码 product_name = parameters.appName.encode('gbk') unproduct_name = (parameters.strUninstallApp).encode('gbk') <|code_end|> , generate the next line using the imports in this file: from cx_Freeze import setup,Executable from codecs import open from os import path from COMTool import parameters,helpAbout import sys import traceback import msilib and context (functions, classes, or occasionally code) from other files: # Path: COMTool/parameters.py # class Strings: # class Parameters: # def __init__(self, locale): # def get_config_path(configFileName): # def save(self, path): # def load(self, path): # def __str__(self) -> str: # # Path: COMTool/helpAbout.py # def strAbout(): . Output only the next line.
product_desc = (parameters.appName+" V"+str(helpAbout.versionMajor)+"."+str(helpAbout.versionMinor)).encode("gbk")
Predict the next line for this snippet: <|code_start|> self._ready = asyncio.Event() self._log = loggers[__name__] def append(self, state): self._deque.append(state) self._ready.set() def extend(self, states): self._deque.extend(states) self._ready.set() async def get(self): """ Returns (batch, data) if one or more items could be retrieved. If the cancellation occurs or only invalid items were in the queue, (None, None) will be returned instead. """ if not self._deque: self._ready.clear() await self._ready.wait() buffer = io.BytesIO() batch = [] size = 0 # Fill a new batch to return while the size is small enough, # as long as we don't exceed the maximum length of messages. while self._deque and len(batch) <= MessageContainer.MAXIMUM_LENGTH: state = self._deque.popleft() <|code_end|> with the help of current file imports: import asyncio import collections import io import struct from .._tl import TLRequest from ..types._core import MessageContainer, TLMessage and context from other files: # Path: telethon/types/_core/tlmessage.py # class TLMessage(tlobject.TLObject): # """ # https://core.telegram.org/mtproto/service_messages#simple-container. # # Messages are what's ultimately sent to Telegram: # message msg_id:long seqno:int bytes:int body:bytes = Message; # # Each message has its own unique identifier, and the body is simply # the serialized request that should be executed on the server, or # the response object from Telegram. Since the body is always a valid # object, it makes sense to store the object and not the bytes to # ease working with them. # # There is no need to add serializing logic here since that can be # inlined and is unlikely to change. Thus these are only needed to # encapsulate responses. # """ # SIZE_OVERHEAD = 12 # # def __init__(self, msg_id, seq_no, obj): # self.msg_id = msg_id # self.seq_no = seq_no # self.obj = obj # # def to_dict(self): # return { # '_': 'TLMessage', # 'msg_id': self.msg_id, # 'seq_no': self.seq_no, # 'obj': self.obj # } # # Path: telethon/types/_core/messagecontainer.py # class MessageContainer(TLObject): # CONSTRUCTOR_ID = 0x73f1f8dc # # # Maximum size in bytes for the inner payload of the container. # # Telegram will close the connection if the payload is bigger. # # The overhead of the container itself is subtracted. # MAXIMUM_SIZE = 1044456 - 8 # # # Maximum amount of messages that can't be sent inside a single # # container, inclusive. Beyond this limit Telegram will respond # # with BAD_MESSAGE 64 (invalid container). # # # # This limit is not 100% accurate and may in some cases be higher. # # However, sending up to 100 requests at once in a single container # # is a reasonable conservative value, since it could also depend on # # other factors like size per request, but we cannot know this. # MAXIMUM_LENGTH = 100 # # def __init__(self, messages): # self.messages = messages # # def to_dict(self): # return { # '_': 'MessageContainer', # 'messages': # [] if self.messages is None else [ # None if x is None else x.to_dict() for x in self.messages # ], # } # # @classmethod # def _from_reader(cls, reader): # # This assumes that .read_* calls are done in the order they appear # messages = [] # for _ in range(reader.read_int()): # msg_id = reader.read_long() # seq_no = reader.read_int() # length = reader.read_int() # before = reader.tell_position() # obj = reader.tgread_object() # May over-read e.g. RpcResult # reader.set_position(before + length) # messages.append(TLMessage(msg_id, seq_no, obj)) # return MessageContainer(messages) , which may contain function names, class names, or code. Output only the next line.
size += len(state.data) + TLMessage.SIZE_OVERHEAD
Predict the next line after this snippet: <|code_start|> self._state = state self._deque = collections.deque() self._ready = asyncio.Event() self._log = loggers[__name__] def append(self, state): self._deque.append(state) self._ready.set() def extend(self, states): self._deque.extend(states) self._ready.set() async def get(self): """ Returns (batch, data) if one or more items could be retrieved. If the cancellation occurs or only invalid items were in the queue, (None, None) will be returned instead. """ if not self._deque: self._ready.clear() await self._ready.wait() buffer = io.BytesIO() batch = [] size = 0 # Fill a new batch to return while the size is small enough, # as long as we don't exceed the maximum length of messages. <|code_end|> using the current file's imports: import asyncio import collections import io import struct from .._tl import TLRequest from ..types._core import MessageContainer, TLMessage and any relevant context from other files: # Path: telethon/types/_core/tlmessage.py # class TLMessage(tlobject.TLObject): # """ # https://core.telegram.org/mtproto/service_messages#simple-container. # # Messages are what's ultimately sent to Telegram: # message msg_id:long seqno:int bytes:int body:bytes = Message; # # Each message has its own unique identifier, and the body is simply # the serialized request that should be executed on the server, or # the response object from Telegram. Since the body is always a valid # object, it makes sense to store the object and not the bytes to # ease working with them. # # There is no need to add serializing logic here since that can be # inlined and is unlikely to change. Thus these are only needed to # encapsulate responses. # """ # SIZE_OVERHEAD = 12 # # def __init__(self, msg_id, seq_no, obj): # self.msg_id = msg_id # self.seq_no = seq_no # self.obj = obj # # def to_dict(self): # return { # '_': 'TLMessage', # 'msg_id': self.msg_id, # 'seq_no': self.seq_no, # 'obj': self.obj # } # # Path: telethon/types/_core/messagecontainer.py # class MessageContainer(TLObject): # CONSTRUCTOR_ID = 0x73f1f8dc # # # Maximum size in bytes for the inner payload of the container. # # Telegram will close the connection if the payload is bigger. # # The overhead of the container itself is subtracted. # MAXIMUM_SIZE = 1044456 - 8 # # # Maximum amount of messages that can't be sent inside a single # # container, inclusive. Beyond this limit Telegram will respond # # with BAD_MESSAGE 64 (invalid container). # # # # This limit is not 100% accurate and may in some cases be higher. # # However, sending up to 100 requests at once in a single container # # is a reasonable conservative value, since it could also depend on # # other factors like size per request, but we cannot know this. # MAXIMUM_LENGTH = 100 # # def __init__(self, messages): # self.messages = messages # # def to_dict(self): # return { # '_': 'MessageContainer', # 'messages': # [] if self.messages is None else [ # None if x is None else x.to_dict() for x in self.messages # ], # } # # @classmethod # def _from_reader(cls, reader): # # This assumes that .read_* calls are done in the order they appear # messages = [] # for _ in range(reader.read_int()): # msg_id = reader.read_long() # seq_no = reader.read_int() # length = reader.read_int() # before = reader.tell_position() # obj = reader.tgread_object() # May over-read e.g. RpcResult # reader.set_position(before + length) # messages.append(TLMessage(msg_id, seq_no, obj)) # return MessageContainer(messages) . Output only the next line.
while self._deque and len(batch) <= MessageContainer.MAXIMUM_LENGTH:
Here is a snippet: <|code_start|> :param result: The result type of the TL object :param is_function: Is the object a function or a type? :param usability: The usability for this method. :param friendly: A tuple (namespace, friendly method name) if known. :param layer: The layer this TLObject belongs to. """ # The name can or not have a namespace self.fullname = fullname if '.' in fullname: self.namespace, self.name = fullname.split('.', maxsplit=1) else: self.namespace, self.name = None, fullname self.args = args self.result = result self.is_function = is_function self.usability = usability self.friendly = friendly self.id = None if object_id is None: self.id = self.infer_id() else: self.id = int(object_id, base=16) whitelist = WHITELISTED_MISMATCHING_IDS[0] |\ WHITELISTED_MISMATCHING_IDS.get(layer, set()) if self.fullname not in whitelist: assert self.id == self.infer_id(),\ 'Invalid inferred ID for ' + repr(self) <|code_end|> . Write the next line using the current file imports: import re import struct import zlib from ...utils import snake_to_camel_case and context from other files: # Path: telethon_generator/utils.py # def snake_to_camel_case(name, suffix=None): # # Courtesy of http://stackoverflow.com/a/31531797/4759433 # result = re.sub(r'_([a-z])', lambda m: m.group(1).upper(), name) # result = result[:1].upper() + result[1:].replace('_', '') # return result + suffix if suffix else result , which may include functions, classes, or code. Output only the next line.
self.class_name = snake_to_camel_case(self.name)
Predict the next line for this snippet: <|code_start|> 'InputChatPhoto': 'utils.get_input_chat_photo({})', 'InputGroupCall': 'utils.get_input_group_call({})', } NAMED_AUTO_CASTS = { ('chat_id', 'int'): 'await client._get_peer_id({})' } # Secret chats have a chat_id which may be negative. # With the named auto-cast above, we would break it. # However there are plenty of other legit requests # with `chat_id:int` where it is useful. # # NOTE: This works because the auto-cast is not recursive. # There are plenty of types that would break if we # did recurse into them to resolve them. NAMED_BLACKLIST = { 'messages.discardEncryption' } BASE_TYPES = ('string', 'bytes', 'int', 'long', 'int128', 'int256', 'double', 'Bool', 'true', 'date') def _write_modules( out_dir, in_mod, kind, namespace_tlobjects, type_constructors, layer, all_tlobjects): # namespace_tlobjects: {'namespace', [TLObject]} out_dir.mkdir(parents=True, exist_ok=True) for ns, tlobjects in namespace_tlobjects.items(): file = out_dir / '{}.py'.format(ns or '__init__') <|code_end|> with the help of current file imports: import builtins import functools import os import re import shutil import struct from collections import defaultdict from zlib import crc32 from ..sourcebuilder import SourceBuilder from ..utils import snake_to_camel_case and context from other files: # Path: telethon_generator/sourcebuilder.py # class SourceBuilder: # """This class should be used to build .py source files""" # # def __init__(self, out_stream, indent_size=4): # self.current_indent = 0 # self.on_new_line = False # self.indent_size = indent_size # self.out_stream = out_stream # # # Was a new line added automatically before? If so, avoid it # self.auto_added_line = False # # def indent(self): # """Indents the current source code line # by the current indentation level # """ # self.write(' ' * (self.current_indent * self.indent_size)) # # def write(self, string, *args, **kwargs): # """Writes a string into the source code, # applying indentation if required # """ # if self.on_new_line: # self.on_new_line = False # We're not on a new line anymore # # If the string was not empty, indent; Else probably a new line # if string.strip(): # self.indent() # # if args or kwargs: # self.out_stream.write(string.format(*args, **kwargs)) # else: # self.out_stream.write(string) # # def writeln(self, string='', *args, **kwargs): # """Writes a string into the source code _and_ appends a new line, # applying indentation if required # """ # self.write(string + '\n', *args, **kwargs) # self.on_new_line = True # # # If we're writing a block, increment indent for the next time # if string and string[-1] == ':': # self.current_indent += 1 # # # Clear state after the user adds a new line # self.auto_added_line = False # # def end_block(self): # """Ends an indentation block, leaving an empty line afterwards""" # self.current_indent -= 1 # # # If we did not add a new line automatically yet, now it's the time! # if not self.auto_added_line: # self.writeln() # self.auto_added_line = True # # def __str__(self): # self.out_stream.seek(0) # return self.out_stream.read() # # def __enter__(self): # return self # # def __exit__(self, exc_type, exc_val, exc_tb): # self.out_stream.close() # # Path: telethon_generator/utils.py # def snake_to_camel_case(name, suffix=None): # # Courtesy of http://stackoverflow.com/a/31531797/4759433 # result = re.sub(r'_([a-z])', lambda m: m.group(1).upper(), name) # result = result[:1].upper() + result[1:].replace('_', '') # return result + suffix if suffix else result , which may contain function names, class names, or code. Output only the next line.
with file.open('w') as f, SourceBuilder(f) as builder:
Given snippet: <|code_start|> elif 'string' == arg.type: builder.writeln('{} = reader.tgread_string()', name) elif 'Bool' == arg.type: builder.writeln('{} = reader.tgread_bool()', name) elif 'true' == arg.type: # Arbitrary not-None value, don't actually read "true" flags builder.writeln('{} = True', name) elif 'bytes' == arg.type: builder.writeln('{} = reader.tgread_bytes()', name) elif 'date' == arg.type: # Custom format builder.writeln('{} = reader.tgread_date()', name) else: # Else it may be a custom type if not arg.skip_constructor_id: builder.writeln('{} = reader.tgread_object()', name) else: # Import the correct type inline to avoid cyclic imports. # There may be better solutions so that we can just access # all the types before the files have been parsed, but I # don't know of any. sep_index = arg.type.find('.') if sep_index == -1: ns, t = '.', arg.type else: ns, t = '.' + arg.type[:sep_index], arg.type[sep_index+1:] <|code_end|> , continue by predicting the next line. Consider current file imports: import builtins import functools import os import re import shutil import struct from collections import defaultdict from zlib import crc32 from ..sourcebuilder import SourceBuilder from ..utils import snake_to_camel_case and context: # Path: telethon_generator/sourcebuilder.py # class SourceBuilder: # """This class should be used to build .py source files""" # # def __init__(self, out_stream, indent_size=4): # self.current_indent = 0 # self.on_new_line = False # self.indent_size = indent_size # self.out_stream = out_stream # # # Was a new line added automatically before? If so, avoid it # self.auto_added_line = False # # def indent(self): # """Indents the current source code line # by the current indentation level # """ # self.write(' ' * (self.current_indent * self.indent_size)) # # def write(self, string, *args, **kwargs): # """Writes a string into the source code, # applying indentation if required # """ # if self.on_new_line: # self.on_new_line = False # We're not on a new line anymore # # If the string was not empty, indent; Else probably a new line # if string.strip(): # self.indent() # # if args or kwargs: # self.out_stream.write(string.format(*args, **kwargs)) # else: # self.out_stream.write(string) # # def writeln(self, string='', *args, **kwargs): # """Writes a string into the source code _and_ appends a new line, # applying indentation if required # """ # self.write(string + '\n', *args, **kwargs) # self.on_new_line = True # # # If we're writing a block, increment indent for the next time # if string and string[-1] == ':': # self.current_indent += 1 # # # Clear state after the user adds a new line # self.auto_added_line = False # # def end_block(self): # """Ends an indentation block, leaving an empty line afterwards""" # self.current_indent -= 1 # # # If we did not add a new line automatically yet, now it's the time! # if not self.auto_added_line: # self.writeln() # self.auto_added_line = True # # def __str__(self): # self.out_stream.seek(0) # return self.out_stream.read() # # def __enter__(self): # return self # # def __exit__(self, exc_type, exc_val, exc_tb): # self.out_stream.close() # # Path: telethon_generator/utils.py # def snake_to_camel_case(name, suffix=None): # # Courtesy of http://stackoverflow.com/a/31531797/4759433 # result = re.sub(r'_([a-z])', lambda m: m.group(1).upper(), name) # result = result[:1].upper() + result[1:].replace('_', '') # return result + suffix if suffix else result which might include code, classes, or functions. Output only the next line.
class_name = snake_to_camel_case(t)
Given snippet: <|code_start|> ... await event.delete() ... # No other event handler will have a chance to handle this event ... raise StopPropagation ... >>> @client.on(events.NewMessage) ... async def _(event): ... # Will never be reached, because it is the second handler ... pass """ # For some reason Sphinx wants the silly >>> or # it will show warnings and look bad when generated. pass class EventBuilder(abc.ABC): @classmethod @abc.abstractmethod def _build(cls, client, update, entities): """ Builds an event for the given update if possible, or returns None. `entities` must have `get(Peer) -> User|Chat` and `self_id`, which must be the current user's ID. """ @functools.total_ordering class EventHandler: __slots__ = ('_event', '_callback', '_priority', '_filter') <|code_end|> , continue by predicting the next line. Consider current file imports: import abc import functools from .filters import Filter and context: # Path: telethon/_events/filters/base.py # class Filter(abc.ABC): # @abc.abstractmethod # def __call__(self, event): # return True # # def __and__(self, other): # return And(self, other) # # def __or__(self, other): # return Or(self, other) # # def __invert__(self): # return Not(self) which might include code, classes, or functions. Output only the next line.
def __init__(self, event: EventBuilder, callback: callable, priority: int, filter: Filter):
Using the snippet: <|code_start|> # {fingerprint: (Crypto.PublicKey.RSA._RSAobj, old)} dictionary _server_keys = {} def get_byte_array(integer): """Return the variable length bytes corresponding to the given int""" # Operate in big endian (unlike most of Telegram API) since: # > "...pq is a representation of a natural number # (in binary *big endian* format)..." # > "...current value of dh_prime equals # (in *big-endian* byte order)..." # Reference: https://core.telegram.org/mtproto/auth_key return int.to_bytes( integer, (integer.bit_length() + 8 - 1) // 8, # 8 bits per byte, byteorder='big', signed=False ) def _compute_fingerprint(key): """ Given a RSA key, computes its fingerprint like Telegram does. :param key: the Crypto.RSA key. :return: its 8-bytes-long fingerprint. """ <|code_end|> , determine the next line of code. You have imports: import os import struct import rsa import rsa.core from hashlib import sha1 from .._misc import tlobject and context (class names, function names, or code) available: # Path: telethon/_misc/tlobject.py # _EPOCH_NAIVE = datetime(*time.gmtime(0)[:6]) # _EPOCH_NAIVE_LOCAL = datetime(*time.localtime(0)[:6]) # _EPOCH = _EPOCH_NAIVE.replace(tzinfo=timezone.utc) # CONSTRUCTOR_ID = None # SUBCLASS_OF_ID = None # def _datetime_to_timestamp(dt): # def _json_default(value): # def _serialize_bytes(data): # def _serialize_datetime(dt): # def __eq__(self, o): # def __ne__(self, o): # def __repr__(self): # def __str__(self): # def stringify(self): # def to_dict(self): # def __bytes__(self): # def _bytes(self): # def _from_reader(cls, reader): # def _read_result(reader): # async def _resolve(self, client, utils): # class TLObject: # class TLRequest(TLObject): . Output only the next line.
n = tlobject.TLObject._serialize_bytes(get_byte_array(key.n))
Predict the next line after this snippet: <|code_start|> r.append(bytes(padding)) return b''.join(r) @staticmethod def _serialize_datetime(dt): if not dt and not isinstance(dt, timedelta): return b'\0\0\0\0' if isinstance(dt, datetime): dt = _datetime_to_timestamp(dt) elif isinstance(dt, date): dt = _datetime_to_timestamp(datetime(dt.year, dt.month, dt.day)) elif isinstance(dt, float): dt = int(dt) elif isinstance(dt, timedelta): # Timezones are tricky. datetime.utcnow() + ... timestamp() works dt = _datetime_to_timestamp(datetime.utcnow() + dt) if isinstance(dt, int): return struct.pack('<i', dt) raise TypeError('Cannot interpret "{}" as a date.'.format(dt)) def __eq__(self, o): return isinstance(o, type(self)) and self.to_dict() == o.to_dict() def __ne__(self, o): return not isinstance(o, type(self)) or self.to_dict() != o.to_dict() def __repr__(self): <|code_end|> using the current file's imports: import base64 import json import struct import time from datetime import datetime, date, timedelta, timezone from .helpers import pretty_print and any relevant context from other files: # Path: telethon/_misc/helpers.py # def pretty_print(obj, indent=None, max_depth=float('inf')): # max_depth -= 1 # if max_depth < 0: # return '...' # # to_d = getattr(obj, 'to_dict', None) # if callable(to_d): # obj = to_d() # # if indent is None: # if isinstance(obj, dict): # return '{}({})'.format(obj.get('_', 'dict'), ', '.join( # '{}={}'.format(k, pretty_print(v, indent, max_depth)) # for k, v in obj.items() if k != '_' # )) # elif isinstance(obj, str) or isinstance(obj, bytes): # return repr(obj) # elif hasattr(obj, '__iter__'): # return '[{}]'.format( # ', '.join(pretty_print(x, indent, max_depth) for x in obj) # ) # else: # return repr(obj) # else: # result = [] # # if isinstance(obj, dict): # result.append(obj.get('_', 'dict')) # result.append('(') # if obj: # result.append('\n') # indent += 1 # for k, v in obj.items(): # if k == '_': # continue # result.append('\t' * indent) # result.append(k) # result.append('=') # result.append(pretty_print(v, indent, max_depth)) # result.append(',\n') # result.pop() # last ',\n' # indent -= 1 # result.append('\n') # result.append('\t' * indent) # result.append(')') # # elif isinstance(obj, str) or isinstance(obj, bytes): # result.append(repr(obj)) # # elif hasattr(obj, '__iter__'): # result.append('[\n') # indent += 1 # for x in obj: # result.append('\t' * indent) # result.append(pretty_print(x, indent, max_depth)) # result.append(',\n') # indent -= 1 # result.append('\t' * indent) # result.append(']') # # else: # result.append(repr(obj)) # # return ''.join(result) . Output only the next line.
return pretty_print(self)
Using the snippet: <|code_start|> else: docs.write(' print(result') if tlobject.result != 'Bool' \ and not tlobject.result.startswith('Vector'): docs.write('.stringify()') docs.write(')</pre>') if tlobject.friendly: docs.write('</details>') depth = '../' * (2 if tlobject.namespace else 1) docs.add_script(src='prependPath = "{}";'.format(depth)) docs.add_script(path=paths['search.js']) docs.end_body() # Find all the available types (which are not the same as the constructors) # Each type has a list of constructors associated to it, hence is a map for t, cs in type_to_constructors.items(): filename = _get_path_for_type(t) out_dir = filename.parent if out_dir: out_dir.mkdir(parents=True, exist_ok=True) # Since we don't have access to the full TLObject, split the type if '.' in t: namespace, name = t.split('.') else: namespace, name = None, t with DocsWriter(filename, _get_path_for_type) as docs: <|code_end|> , determine the next line of code. You have imports: import functools import os import pathlib import re import shutil from collections import defaultdict from pathlib import Path from ..docswriter import DocsWriter from ..parsers import TLObject, Usability from ..utils import snake_to_camel_case and context (class names, function names, or code) available: # Path: telethon_generator/utils.py # def snake_to_camel_case(name, suffix=None): # # Courtesy of http://stackoverflow.com/a/31531797/4759433 # result = re.sub(r'_([a-z])', lambda m: m.group(1).upper(), name) # result = result[:1].upper() + result[1:].replace('_', '') # return result + suffix if suffix else result . Output only the next line.
docs.write_head(title=snake_to_camel_case(name),
Predict the next line after this snippet: <|code_start|> class RDPFile(DPAPIProbe): def parse(self, data): self.cleartext = None self.dpapiblob = None self.entropy = None self.values = defaultdict(lambda: None) def preprocess(self, **k): s = [] if k.get('file') != None: f = open(k['file'], "r") s = f.read().split("\n") f.close() elif k.get('content') != None: s = k['content'].split("\n") for l in s: (n,t,v) = l.split(":", 3) v = v.rstrip() if t == 'i': v = int(v) elif t == 'b': if len(v) & 1 == 1: ## if odd length, strip the last quartet which should be a ## useless "0" v = v[:-1] v = v.decode('hex') self.values[n] = v if self.values['password 51'] != None: <|code_end|> using the current file's imports: from DPAPI.probe import DPAPIProbe from DPAPI.Core import blob from collections import defaultdict and any relevant context from other files: # Path: DPAPI/Core/blob.py # class DPAPIBlob(eater.DataStruct): # def __init__(self, raw=None): # def parse(self, data): # def decrypt(self, masterkey, entropy=None, strongPassword=None): # def __repr__(self): . Output only the next line.
self.dpapiblob = blob.DPAPIBlob(self.values['password 51'])
Based on the snippet: <|code_start|>## circulated without prior licence ## ## ## ## Author: Jean-Michel Picod <jmichel.p@gmail.com> ## ## ## ## This program is distributed under GPLv3 licence (see LICENCE.txt) ## ## ## ############################################################################# class BlobXPSimpleTest(unittest.TestCase): def setUp(self): self.raw = ("01000000d08c9ddf0115d1118c7a00c0" "4fc297eb010000002f44b69f6a628049" "9c85d238be955b3c000000003c000000" "4400500041005000490063006b002000" "730069006d0070006c00650020006200" "6c006f0062002000670065006e006500" "7200610074006f007200000003660000" "a80000001000000055d9d46709e463db" "53c783ec1edd69dc0000000004800000" "a00000001000000038d39c66910558b6" "a4e961b5de40e84918000000eae8acdd" "f984a8efae7701754baf9f844c9f1cbd" "df818a9f14000000be5c65c109be3c7f" "d4787df81e923b596f635d0f").decode("hex") self.mkey = ("f1cd9c3915428d12c0e9bf5ac0c44dda" "647e6e387118c09eb00a294e485a3f6e" "fe47f16686ad5f60fbd740164de87711" "6eb70d35445b22ddebdb02b0d55ee613").decode("hex") <|code_end|> , predict the immediate next line with the help of imports: import unittest from DPAPI.Core import masterkey from DPAPI.Core import crypto from DPAPI.Core import blob and context (classes, functions, sometimes code) from other files: # Path: DPAPI/Core/masterkey.py # class MasterKey(eater.DataStruct): # class CredHist(eater.DataStruct): # class DomainKey(eater.DataStruct): # class MasterKeyFile(eater.DataStruct): # class MasterKeyPool(object): # def __init__(self, raw=None): # def __getstate__(self): # def __setstate__(self, d): # def parse(self, data): # def decryptWithHash(self, userSID, pwdhash): # def decryptWithPassword(self, userSID, pwd): # def setKeyHash(self, h): # def setDecryptedKey(self, data): # def decryptWithKey(self, pwdhash): # def __repr__(self): # def __init__(self, raw=None): # def parse(self, data): # def __repr__(self): # def __init__(self, raw=None): # def parse(self, data): # def __repr__(self): # def __init__(self, raw=None): # def parse(self, data): # def decryptWithHash(self, userSID, h): # def decryptWithPassword(self, userSID, pwd): # def decryptWithKey(self, pwdhash): # def addKeyHash(self, guid, h): # def addDecryptedKey(self, guid, data): # def get_key(self): # def __repr__(self): # def __init__(self): # def addMasterKey(self, mkey): # def addMasterKeyHash(self, guid, h): # def getMasterKeys(self, guid): # def addSystemCredential(self, blob): # def addCredhist(self, sid, cred): # def addCredhistFile(self, sid, credfile): # def loadDirectory(self, directory): # def pickle(self, filename=None): # def __getstate__(self): # def __setstate__(self, d): # def unpickle(data=None, filename=None): # def try_credential_hash(self, userSID, pwdhash): # def try_credential(self, userSID, password): # def __repr__(self): # # Path: DPAPI/Core/crypto.py # class CryptoAlgo(object): # class Algo(object): # def __init__(self, data): # def __getattr__(self, attr): # def add_algo(cls, algnum, **kargs): # def get_algo(cls, algnum): # def __init__(self, i): # def do_fixup_key(self, key): # def __repr__(self): # def des_set_odd_parity(key): # def CryptSessionKeyXP(masterkey, nonce, hashAlgo, entropy=None, strongPassword=None, verifBlob=None): # def CryptSessionKeyWin7(masterkey, nonce, hashAlgo, entropy=None, strongPassword=None, verifBlob=None): # def CryptDeriveKey(h, cipherAlgo, hashAlgo): # def decrypt_lsa_key_nt5(lsakey, syskey): # def decrypt_lsa_key_nt6(lsakey, syskey): # def SystemFunction005(secret, key): # def decrypt_lsa_secret(secret, lsa_keys): # def pbkdf2(passphrase, salt, keylen, iterations, digest='sha1'): # def derivePwdHash(pwdhash, userSID, digest='sha1'): # def dataDecrypt(cipherAlgo, hashAlgo, raw, encKey, iv, rounds): # def DPAPIHmac(hashAlgo, pwdhash, hmacSalt, value): # U = salt + struct.pack("!L", i) # # Path: DPAPI/Core/blob.py # class DPAPIBlob(eater.DataStruct): # def __init__(self, raw=None): # def parse(self, data): # def decrypt(self, masterkey, entropy=None, strongPassword=None): # def __repr__(self): . Output only the next line.
self.blob = blob.DPAPIBlob(self.raw)
Given snippet: <|code_start|># Copyright 2019 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 # # http://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. from __future__ import absolute_import from __future__ import division from __future__ import print_function flags.DEFINE_string('model', 'w2v', 'Word embedding model') flags.DEFINE_float('noise_multiplier', 0., 'Ratio of the standard deviation to the clipping norm') flags.DEFINE_float('l2_norm_clip', 0., 'Clipping norm') flags.DEFINE_integer('epoch', 4, 'Load model trained this epoch') flags.DEFINE_integer('microbatches', 128, 'microbatches') flags.DEFINE_integer('exp_id', 0, 'Experiment trial number') <|code_end|> , continue by predicting the next line. Consider current file imports: from absl import flags from absl import app from data.common import MODEL_DIR from gensim.models import Word2Vec, FastText from utils.word_utils import load_glove_model, load_tf_embedding import os and context: # Path: data/common.py # MODEL_DIR = '/path/to/model/' # # Path: utils/word_utils.py # def load_glove_model(model_path): # glove_model = Glove.load(model_path) # word2vec_model = Word2Vec.load(model_path.replace('glove', 'w2v')) # vocab = word2vec_model.wv.vocab # # for word in vocab: # glove_index = glove_model.dictionary[word] # word2vec_model.wv.vectors[vocab[word].index] = \ # glove_model.word_vectors[glove_index] # # return word2vec_model # # def load_tf_embedding(exp_id, save_dir, epoch=0, noise_multiplier=0., # l2_norm_clip=0., microbatches=128): # model_name = 'tfw2v_{}'.format(exp_id) # vocab_path = os.path.join(save_dir, model_name, 'vocab.txt') # # if epoch > 0: # model_name += '{}_n{}_l{}_mb{}'.format(epoch, noise_multiplier, # l2_norm_clip, microbatches) # save_path = os.path.join(save_dir, model_name) # np_path = os.path.join(save_path, 'word_emb.npz') # # if os.path.exists(np_path): # with np.load(np_path) as f: # word_emb = f['arr_0'] # else: # word_emb = load_trained_variable(os.path.abspath(save_path), 'emb') # np.savez(np_path, word_emb) # # dictionary = dict() # with open(vocab_path) as f: # i = 0 # for line in f: # word = line.split(' ')[0] # dictionary[word] = i # i += 1 # # model_path = './models/w2v/wiki9_w2v_{}.model'.format(exp_id) # word2vec_model = Word2Vec.load(model_path) # vocab = word2vec_model.wv.vocab # # word2vec_model.wv.vectors = np.zeros((len(vocab), word_emb.shape[1])) # for word in vocab: # tf_index = dictionary[word.encode("utf-8")] # word2vec_model.wv.vectors[vocab[word].index] = word_emb[tf_index] # # return word2vec_model which might include code, classes, or functions. Output only the next line.
flags.DEFINE_string('save_dir', os.path.join(MODEL_DIR, 'w2v'),
Given the code snippet: <|code_start|>from __future__ import division from __future__ import print_function flags.DEFINE_string('model', 'w2v', 'Word embedding model') flags.DEFINE_float('noise_multiplier', 0., 'Ratio of the standard deviation to the clipping norm') flags.DEFINE_float('l2_norm_clip', 0., 'Clipping norm') flags.DEFINE_integer('epoch', 4, 'Load model trained this epoch') flags.DEFINE_integer('microbatches', 128, 'microbatches') flags.DEFINE_integer('exp_id', 0, 'Experiment trial number') flags.DEFINE_string('save_dir', os.path.join(MODEL_DIR, 'w2v'), 'Model directory for embedding model') FLAGS = flags.FLAGS def main(_): emb_model = FLAGS.model save_dir = FLAGS.save_dir model_name = 'wiki9_{}_{}.model'.format(emb_model, FLAGS.exp_id) model_path = os.path.join(save_dir, model_name) if emb_model == 'ft': model = FastText.load(model_path) elif emb_model == 'w2v': model = Word2Vec.load(model_path) elif emb_model == 'glove': <|code_end|> , generate the next line using the imports in this file: from absl import flags from absl import app from data.common import MODEL_DIR from gensim.models import Word2Vec, FastText from utils.word_utils import load_glove_model, load_tf_embedding import os and context (functions, classes, or occasionally code) from other files: # Path: data/common.py # MODEL_DIR = '/path/to/model/' # # Path: utils/word_utils.py # def load_glove_model(model_path): # glove_model = Glove.load(model_path) # word2vec_model = Word2Vec.load(model_path.replace('glove', 'w2v')) # vocab = word2vec_model.wv.vocab # # for word in vocab: # glove_index = glove_model.dictionary[word] # word2vec_model.wv.vectors[vocab[word].index] = \ # glove_model.word_vectors[glove_index] # # return word2vec_model # # def load_tf_embedding(exp_id, save_dir, epoch=0, noise_multiplier=0., # l2_norm_clip=0., microbatches=128): # model_name = 'tfw2v_{}'.format(exp_id) # vocab_path = os.path.join(save_dir, model_name, 'vocab.txt') # # if epoch > 0: # model_name += '{}_n{}_l{}_mb{}'.format(epoch, noise_multiplier, # l2_norm_clip, microbatches) # save_path = os.path.join(save_dir, model_name) # np_path = os.path.join(save_path, 'word_emb.npz') # # if os.path.exists(np_path): # with np.load(np_path) as f: # word_emb = f['arr_0'] # else: # word_emb = load_trained_variable(os.path.abspath(save_path), 'emb') # np.savez(np_path, word_emb) # # dictionary = dict() # with open(vocab_path) as f: # i = 0 # for line in f: # word = line.split(' ')[0] # dictionary[word] = i # i += 1 # # model_path = './models/w2v/wiki9_w2v_{}.model'.format(exp_id) # word2vec_model = Word2Vec.load(model_path) # vocab = word2vec_model.wv.vocab # # word2vec_model.wv.vectors = np.zeros((len(vocab), word_emb.shape[1])) # for word in vocab: # tf_index = dictionary[word.encode("utf-8")] # word2vec_model.wv.vectors[vocab[word].index] = word_emb[tf_index] # # return word2vec_model . Output only the next line.
model = load_glove_model(model_path)
Given the following code snippet before the placeholder: <|code_start|> flags.DEFINE_string('model', 'w2v', 'Word embedding model') flags.DEFINE_float('noise_multiplier', 0., 'Ratio of the standard deviation to the clipping norm') flags.DEFINE_float('l2_norm_clip', 0., 'Clipping norm') flags.DEFINE_integer('epoch', 4, 'Load model trained this epoch') flags.DEFINE_integer('microbatches', 128, 'microbatches') flags.DEFINE_integer('exp_id', 0, 'Experiment trial number') flags.DEFINE_string('save_dir', os.path.join(MODEL_DIR, 'w2v'), 'Model directory for embedding model') FLAGS = flags.FLAGS def main(_): emb_model = FLAGS.model save_dir = FLAGS.save_dir model_name = 'wiki9_{}_{}.model'.format(emb_model, FLAGS.exp_id) model_path = os.path.join(save_dir, model_name) if emb_model == 'ft': model = FastText.load(model_path) elif emb_model == 'w2v': model = Word2Vec.load(model_path) elif emb_model == 'glove': model = load_glove_model(model_path) elif emb_model == 'tfw2v': <|code_end|> , predict the next line using imports from the current file: from absl import flags from absl import app from data.common import MODEL_DIR from gensim.models import Word2Vec, FastText from utils.word_utils import load_glove_model, load_tf_embedding import os and context including class names, function names, and sometimes code from other files: # Path: data/common.py # MODEL_DIR = '/path/to/model/' # # Path: utils/word_utils.py # def load_glove_model(model_path): # glove_model = Glove.load(model_path) # word2vec_model = Word2Vec.load(model_path.replace('glove', 'w2v')) # vocab = word2vec_model.wv.vocab # # for word in vocab: # glove_index = glove_model.dictionary[word] # word2vec_model.wv.vectors[vocab[word].index] = \ # glove_model.word_vectors[glove_index] # # return word2vec_model # # def load_tf_embedding(exp_id, save_dir, epoch=0, noise_multiplier=0., # l2_norm_clip=0., microbatches=128): # model_name = 'tfw2v_{}'.format(exp_id) # vocab_path = os.path.join(save_dir, model_name, 'vocab.txt') # # if epoch > 0: # model_name += '{}_n{}_l{}_mb{}'.format(epoch, noise_multiplier, # l2_norm_clip, microbatches) # save_path = os.path.join(save_dir, model_name) # np_path = os.path.join(save_path, 'word_emb.npz') # # if os.path.exists(np_path): # with np.load(np_path) as f: # word_emb = f['arr_0'] # else: # word_emb = load_trained_variable(os.path.abspath(save_path), 'emb') # np.savez(np_path, word_emb) # # dictionary = dict() # with open(vocab_path) as f: # i = 0 # for line in f: # word = line.split(' ')[0] # dictionary[word] = i # i += 1 # # model_path = './models/w2v/wiki9_w2v_{}.model'.format(exp_id) # word2vec_model = Word2Vec.load(model_path) # vocab = word2vec_model.wv.vocab # # word2vec_model.wv.vectors = np.zeros((len(vocab), word_emb.shape[1])) # for word in vocab: # tf_index = dictionary[word.encode("utf-8")] # word2vec_model.wv.vectors[vocab[word].index] = word_emb[tf_index] # # return word2vec_model . Output only the next line.
model = load_tf_embedding(FLAGS.exp_id, save_dir=save_dir,
Predict the next line after this snippet: <|code_start|> self.gen_params = [v for v in t_vars if v.name.startswith('gen')] self.gen_optimizer = tf.train.AdamOptimizer(lr, beta1=beta1) self.gen_loss = -tf.reduce_mean(self.fake_score) self.gen_train_ops = self.gen_optimizer.minimize( self.gen_loss + gamma * self.l2_loss, var_list=self.gen_params) def generate(self, sess, x): return sess.run(self.fake_y, {self.input_x: x}) def train_disc_one_batch(self, sess, x, y): d_err, _ = sess.run([self.disc_loss, self.disc_train_ops], {self.input_x: x, self.input_y: y}) return d_err def train_gen_one_batch(self, sess, x, y): g_err, l2_err, _ = sess.run([-self.gen_loss, self.l2_loss, self.gen_train_ops], {self.input_x: x, self.input_y: y}) return g_err, l2_err def gan_mapping(x, y, lr=1e-4, lmbda=10., gamma=0., beta1=0.5, activation=tf.nn.relu, epoch=30, disc_iters=10, batch_size=128): n_data, x_dim = x.shape y_dim = y.shape[1] model = WGANGP(x_dim, y_dim, lr=lr, lmbda=lmbda, gamma=gamma, beta1=beta1, activation=activation) <|code_end|> using the current file's imports: from utils.sent_utils import inf_batch_iterator, iterate_minibatches_indices from utils.common_utils import log import sklearn.linear_model as linear_model import tensorflow as tf import numpy as np and any relevant context from other files: # Path: utils/sent_utils.py # def inf_batch_iterator(n, batch_size, shuffle=True, include_last=False): # while True: # for indices in iterate_minibatches_indices(n, batch_size, # shuffle, include_last): # yield indices # # def iterate_minibatches_indices(n, batch_size, shuffle=False, # include_last=True): # indices = np.arange(n) # # num_batches = n // batch_size # if include_last: # num_batches += (n % batch_size != 0) # # if num_batches == 0: # num_batches = 1 # # if shuffle: # np.random.shuffle(indices) # # for batch_idx in range(num_batches): # batch_indices = indices[batch_idx * batch_size: # (batch_idx + 1) * batch_size] # yield batch_indices # # Path: utils/common_utils.py # def log(msg): # if msg[-1] != '\n': # msg += '\n' # sys.stderr.write(msg) # sys.stderr.flush() . Output only the next line.
gen_sampler = inf_batch_iterator(n_data, batch_size)
Given the code snippet: <|code_start|> sess = tf.Session() sess.run(tf.global_variables_initializer()) for e in range(epoch): train_d_loss = [] train_g_loss = [] train_l2_loss = [] for _ in range(num_batch_per_epoch): # train disc first for _ in range(disc_iters): disc_idx = next(disc_sampler) disc_x, disc_y = x[disc_idx], y[disc_idx] d_err = model.train_disc_one_batch(sess, disc_x, disc_y) train_d_loss.append(d_err) gen_idx = next(gen_sampler) gen_x, gen_y = x[gen_idx], y[gen_idx] g_err, l2_err = model.train_gen_one_batch(sess, gen_x, gen_y) train_g_loss.append(g_err) train_l2_loss.append(l2_err) train_d_loss = np.mean(train_d_loss) train_g_loss = np.mean(train_g_loss) train_l2_loss = np.mean(train_l2_loss) log('Epoch: {}, disc loss: {:.4f}, gen loss: {:.4f},' ' l2 loss: {:.4f}'.format( e + 1, train_d_loss, train_g_loss, train_l2_loss)) def mapping(z): mapped = [] <|code_end|> , generate the next line using the imports in this file: from utils.sent_utils import inf_batch_iterator, iterate_minibatches_indices from utils.common_utils import log import sklearn.linear_model as linear_model import tensorflow as tf import numpy as np and context (functions, classes, or occasionally code) from other files: # Path: utils/sent_utils.py # def inf_batch_iterator(n, batch_size, shuffle=True, include_last=False): # while True: # for indices in iterate_minibatches_indices(n, batch_size, # shuffle, include_last): # yield indices # # def iterate_minibatches_indices(n, batch_size, shuffle=False, # include_last=True): # indices = np.arange(n) # # num_batches = n // batch_size # if include_last: # num_batches += (n % batch_size != 0) # # if num_batches == 0: # num_batches = 1 # # if shuffle: # np.random.shuffle(indices) # # for batch_idx in range(num_batches): # batch_indices = indices[batch_idx * batch_size: # (batch_idx + 1) * batch_size] # yield batch_indices # # Path: utils/common_utils.py # def log(msg): # if msg[-1] != '\n': # msg += '\n' # sys.stderr.write(msg) # sys.stderr.flush() . Output only the next line.
for idx in iterate_minibatches_indices(len(z), batch_size=2048):
Continue the code snippet: <|code_start|> model = WGANGP(x_dim, y_dim, lr=lr, lmbda=lmbda, gamma=gamma, beta1=beta1, activation=activation) gen_sampler = inf_batch_iterator(n_data, batch_size) disc_sampler = inf_batch_iterator(n_data, batch_size) num_batch_per_epoch = n_data // batch_size + (n_data % batch_size) != 0 sess = tf.Session() sess.run(tf.global_variables_initializer()) for e in range(epoch): train_d_loss = [] train_g_loss = [] train_l2_loss = [] for _ in range(num_batch_per_epoch): # train disc first for _ in range(disc_iters): disc_idx = next(disc_sampler) disc_x, disc_y = x[disc_idx], y[disc_idx] d_err = model.train_disc_one_batch(sess, disc_x, disc_y) train_d_loss.append(d_err) gen_idx = next(gen_sampler) gen_x, gen_y = x[gen_idx], y[gen_idx] g_err, l2_err = model.train_gen_one_batch(sess, gen_x, gen_y) train_g_loss.append(g_err) train_l2_loss.append(l2_err) train_d_loss = np.mean(train_d_loss) train_g_loss = np.mean(train_g_loss) train_l2_loss = np.mean(train_l2_loss) <|code_end|> . Use current file imports: from utils.sent_utils import inf_batch_iterator, iterate_minibatches_indices from utils.common_utils import log import sklearn.linear_model as linear_model import tensorflow as tf import numpy as np and context (classes, functions, or code) from other files: # Path: utils/sent_utils.py # def inf_batch_iterator(n, batch_size, shuffle=True, include_last=False): # while True: # for indices in iterate_minibatches_indices(n, batch_size, # shuffle, include_last): # yield indices # # def iterate_minibatches_indices(n, batch_size, shuffle=False, # include_last=True): # indices = np.arange(n) # # num_batches = n // batch_size # if include_last: # num_batches += (n % batch_size != 0) # # if num_batches == 0: # num_batches = 1 # # if shuffle: # np.random.shuffle(indices) # # for batch_idx in range(num_batches): # batch_indices = indices[batch_idx * batch_size: # (batch_idx + 1) * batch_size] # yield batch_indices # # Path: utils/common_utils.py # def log(msg): # if msg[-1] != '\n': # msg += '\n' # sys.stderr.write(msg) # sys.stderr.flush() . Output only the next line.
log('Epoch: {}, disc loss: {:.4f}, gen loss: {:.4f},'
Given the code snippet: <|code_start|># Copyright 2019 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 # # http://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. from __future__ import absolute_import from __future__ import division from __future__ import print_function <|code_end|> , generate the next line using the imports in this file: from gensim.models import KeyedVectors from data.common import WORD_EMB_PATH from data.bookcorpus import VOCAB_PATH import collections import os import tqdm import numpy as np import sklearn.linear_model import tensorflow as tf and context (functions, classes, or occasionally code) from other files: # Path: data/common.py # WORD_EMB_PATH = '/path/to/word/embedding/' # # Path: data/bookcorpus.py # VOCAB_PATH = os.path.join(BOOKCORPUS_DATA_DIR, 'word_count{}') . Output only the next line.
GLOVE_EMBEDDING_PATH = WORD_EMB_PATH + 'glove.840B.300d_gensim.txt'
Predict the next line after this snippet: <|code_start|># Copyright 2019 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 # # http://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. from __future__ import absolute_import from __future__ import division from __future__ import print_function GLOVE_EMBEDDING_PATH = WORD_EMB_PATH + 'glove.840B.300d_gensim.txt' W2V_EMBEDDING_PATH = WORD_EMB_PATH + 'GoogleNews-vectors-negative300.bin' <|code_end|> using the current file's imports: from gensim.models import KeyedVectors from data.common import WORD_EMB_PATH from data.bookcorpus import VOCAB_PATH import collections import os import tqdm import numpy as np import sklearn.linear_model import tensorflow as tf and any relevant context from other files: # Path: data/common.py # WORD_EMB_PATH = '/path/to/word/embedding/' # # Path: data/bookcorpus.py # VOCAB_PATH = os.path.join(BOOKCORPUS_DATA_DIR, 'word_count{}') . Output only the next line.
VOCAB_PATH = VOCAB_PATH.format(0)
Next line prediction: <|code_start|>def main(_): assert FLAGS.dpsgd exp_id = FLAGS.exp_id num_gpu = FLAGS.num_gpu train_words, unigrams, word_sample_int = preprocess_texts(exp_id) n_vocab = len(unigrams) n_sampled = FLAGS.n_sampled n_embedding = FLAGS.hidden_size init_width = 0.5 / n_embedding epochs = FLAGS.epochs window_size = 5 batch_size = FLAGS.batch_size learning_rate = FLAGS.learning_rate delta = 1 / len(train_words) cumtable = tf.constant(np.cumsum(unigrams)) inputs = tf.placeholder(tf.int64, [None], name='inputs') labels = tf.placeholder(tf.int64, [None, 1], name='labels') embedding = tf.Variable(tf.random_uniform( (n_vocab, n_embedding), -init_width, init_width), name="emb") sm_w_t = embedding sm_b = tf.Variable(tf.zeros(n_vocab), name="sm_b") curr_words = tf.Variable(0, trainable=False) update_curr_words = curr_words.assign_add(batch_size) lr = learning_rate * tf.maximum( 0.0001, 1.0 - tf.cast(curr_words, tf.float32) / len(train_words) / epochs) num_microbatches = FLAGS.microbatches if FLAGS.dpsgd: <|code_end|> . Use current file imports: (from absl import flags from absl import app from dp_optimizer.dp_optimizer_sparse import SparseDPAdamGaussianOptimizer from privacy.analysis.rdp_accountant import compute_rdp, get_privacy_spent from utils.common_utils import rigid_op_sequence from data.wiki9 import read_wiki9_train_split from data.common import MODEL_DIR from utils.common_utils import log from collections import Counter import tensorflow as tf import numpy as np import time import smart_open import os) and context including class names, function names, or small code snippets from other files: # Path: dp_optimizer/dp_optimizer_sparse.py # class SparseGaussianSumQuery(gaussian_query.GaussianSumQuery): # class DPOptimizerClass(cls): # class SparseDPGaussianOptimizerClass(make_optimizer_class(cls)): # def get_noised_result(self, sample_state, global_state): # def add_noise(v): # def add_noise(v): # def make_optimizer_class(cls): # def __init__( # self, # dp_sum_query, # num_microbatches=None, # unroll_microbatches=False, # *args, # pylint: disable=keyword-arg-before-vararg, g-doc-args # **kwargs): # def compute_gradients(self, # loss, # var_list, # gate_gradients=GATE_OP, # aggregation_method=None, # colocate_gradients_with_ops=False, # grad_loss=None, # gradient_tape=None): # def process_microbatch(i, sample_state): # def normalize(v): # def make_gaussian_optimizer_class(cls): # def __init__( # self, # l2_norm_clip, # noise_multiplier, # num_microbatches=None, # ledger=None, # unroll_microbatches=False, # *args, # pylint: disable=keyword-arg-before-vararg # **kwargs): # def ledger(self): # GATE_OP = tf.train.Optimizer.GATE_OP # pylint: disable=invalid-name # GATE_OP = None # pylint: disable=invalid-name # # Path: utils/common_utils.py # def rigid_op_sequence(op_lambdas): # with ExitStack() as stack: # for op_func in op_lambdas: # op = op_func() # context = tf.control_dependencies([op]) # stack.enter_context(context) # return op # # Path: data/wiki9.py # def read_wiki9_train_split(exp_id=0): # split_path = os.path.join(WIKI9_SPLIT_DIR, 'split{}.train'.format(exp_id)) # if not os.path.exists(split_path): # train_docs, _ = split_wiki9_articles() # with open(split_path, 'wb') as f: # for doc in tqdm.tqdm(train_docs): # with open(os.path.join(WIKI9_DIR, doc)) as fd: # f.write(fd.read()) # f.write(' ') # # return split_path # # Path: data/common.py # MODEL_DIR = '/path/to/model/' # # Path: utils/common_utils.py # def log(msg): # if msg[-1] != '\n': # msg += '\n' # sys.stderr.write(msg) # sys.stderr.flush() . Output only the next line.
optimizer = SparseDPAdamGaussianOptimizer(
Predict the next line after this snippet: <|code_start|> sampled_w_mat = tf.reshape(sampled_w, [nb, n_sampled, n_embedding]) sampled_b_vec = tf.reshape(sampled_b, [nb, n_sampled]) example_emb_mat = tf.reshape(example_emb, [nb, n_embedding, 1]) sampled_logits = tf.squeeze( tf.matmul(sampled_w_mat, example_emb_mat)) + sampled_b_vec # Calculate the loss using negative sampling true_xent = tf.nn.sigmoid_cross_entropy_with_logits( labels=tf.ones_like(true_logits), logits=true_logits) sampled_xent = tf.nn.sigmoid_cross_entropy_with_logits( labels=tf.zeros_like(sampled_logits), logits=sampled_logits) sampled_mask = 1 - tf.cast( tf.equal(y, tf.reshape(sampled_ids, [nb, n_sampled])), tf.float32) vector_loss = true_xent + tf.reduce_sum(sampled_xent * sampled_mask, axis=1) scalar_loss = tf.reduce_mean(vector_loss) if FLAGS.dpsgd: grads = optimizer.compute_gradients( vector_loss, t_vars, colocate_gradients_with_ops=num_gpu > 1) else: grads = optimizer.compute_gradients( scalar_loss, t_vars, colocate_gradients_with_ops=num_gpu > 1) return grads, scalar_loss if num_gpu > 1: tower_grads, scalar_loss = make_parallel(model, optimizer, num_gpu, x=inputs, y=labels) <|code_end|> using the current file's imports: from absl import flags from absl import app from dp_optimizer.dp_optimizer_sparse import SparseDPAdamGaussianOptimizer from privacy.analysis.rdp_accountant import compute_rdp, get_privacy_spent from utils.common_utils import rigid_op_sequence from data.wiki9 import read_wiki9_train_split from data.common import MODEL_DIR from utils.common_utils import log from collections import Counter import tensorflow as tf import numpy as np import time import smart_open import os and any relevant context from other files: # Path: dp_optimizer/dp_optimizer_sparse.py # class SparseGaussianSumQuery(gaussian_query.GaussianSumQuery): # class DPOptimizerClass(cls): # class SparseDPGaussianOptimizerClass(make_optimizer_class(cls)): # def get_noised_result(self, sample_state, global_state): # def add_noise(v): # def add_noise(v): # def make_optimizer_class(cls): # def __init__( # self, # dp_sum_query, # num_microbatches=None, # unroll_microbatches=False, # *args, # pylint: disable=keyword-arg-before-vararg, g-doc-args # **kwargs): # def compute_gradients(self, # loss, # var_list, # gate_gradients=GATE_OP, # aggregation_method=None, # colocate_gradients_with_ops=False, # grad_loss=None, # gradient_tape=None): # def process_microbatch(i, sample_state): # def normalize(v): # def make_gaussian_optimizer_class(cls): # def __init__( # self, # l2_norm_clip, # noise_multiplier, # num_microbatches=None, # ledger=None, # unroll_microbatches=False, # *args, # pylint: disable=keyword-arg-before-vararg # **kwargs): # def ledger(self): # GATE_OP = tf.train.Optimizer.GATE_OP # pylint: disable=invalid-name # GATE_OP = None # pylint: disable=invalid-name # # Path: utils/common_utils.py # def rigid_op_sequence(op_lambdas): # with ExitStack() as stack: # for op_func in op_lambdas: # op = op_func() # context = tf.control_dependencies([op]) # stack.enter_context(context) # return op # # Path: data/wiki9.py # def read_wiki9_train_split(exp_id=0): # split_path = os.path.join(WIKI9_SPLIT_DIR, 'split{}.train'.format(exp_id)) # if not os.path.exists(split_path): # train_docs, _ = split_wiki9_articles() # with open(split_path, 'wb') as f: # for doc in tqdm.tqdm(train_docs): # with open(os.path.join(WIKI9_DIR, doc)) as fd: # f.write(fd.read()) # f.write(' ') # # return split_path # # Path: data/common.py # MODEL_DIR = '/path/to/model/' # # Path: utils/common_utils.py # def log(msg): # if msg[-1] != '\n': # msg += '\n' # sys.stderr.write(msg) # sys.stderr.flush() . Output only the next line.
train_ops = rigid_op_sequence(tower_grads)
Predict the next line after this snippet: <|code_start|> return vocab_to_int, int_to_vocab def get_target(words, idx, r): start = idx - r if (idx - r) > 0 else 0 stop = idx + r target_words = words[start:idx] + words[idx + 1:stop + 1] return target_words def get_batches(words, batch_size, word_sample_int, window_size=5): reduced_windows = np.random.randint(1, window_size + 1, size=len(words)) sampled_int = np.random.rand(len(words)) * 2 ** 32 for idx in range(0, len(words), batch_size): x, y = [], [] batch = words[idx:idx + batch_size] batch_sampled_int = sampled_int[idx: idx + batch_size] rs = reduced_windows[idx: idx + batch_size] for ii in range(len(batch)): batch_x = batch[ii] if batch_sampled_int[ii] >= word_sample_int[batch_x]: continue batch_y = get_target(batch, ii, rs[ii]) y.extend(batch_y) x.extend([batch_x] * len(batch_y)) yield x, y def preprocess_texts(exp_id=0, sample=1e-4): <|code_end|> using the current file's imports: from absl import flags from absl import app from dp_optimizer.dp_optimizer_sparse import SparseDPAdamGaussianOptimizer from privacy.analysis.rdp_accountant import compute_rdp, get_privacy_spent from utils.common_utils import rigid_op_sequence from data.wiki9 import read_wiki9_train_split from data.common import MODEL_DIR from utils.common_utils import log from collections import Counter import tensorflow as tf import numpy as np import time import smart_open import os and any relevant context from other files: # Path: dp_optimizer/dp_optimizer_sparse.py # class SparseGaussianSumQuery(gaussian_query.GaussianSumQuery): # class DPOptimizerClass(cls): # class SparseDPGaussianOptimizerClass(make_optimizer_class(cls)): # def get_noised_result(self, sample_state, global_state): # def add_noise(v): # def add_noise(v): # def make_optimizer_class(cls): # def __init__( # self, # dp_sum_query, # num_microbatches=None, # unroll_microbatches=False, # *args, # pylint: disable=keyword-arg-before-vararg, g-doc-args # **kwargs): # def compute_gradients(self, # loss, # var_list, # gate_gradients=GATE_OP, # aggregation_method=None, # colocate_gradients_with_ops=False, # grad_loss=None, # gradient_tape=None): # def process_microbatch(i, sample_state): # def normalize(v): # def make_gaussian_optimizer_class(cls): # def __init__( # self, # l2_norm_clip, # noise_multiplier, # num_microbatches=None, # ledger=None, # unroll_microbatches=False, # *args, # pylint: disable=keyword-arg-before-vararg # **kwargs): # def ledger(self): # GATE_OP = tf.train.Optimizer.GATE_OP # pylint: disable=invalid-name # GATE_OP = None # pylint: disable=invalid-name # # Path: utils/common_utils.py # def rigid_op_sequence(op_lambdas): # with ExitStack() as stack: # for op_func in op_lambdas: # op = op_func() # context = tf.control_dependencies([op]) # stack.enter_context(context) # return op # # Path: data/wiki9.py # def read_wiki9_train_split(exp_id=0): # split_path = os.path.join(WIKI9_SPLIT_DIR, 'split{}.train'.format(exp_id)) # if not os.path.exists(split_path): # train_docs, _ = split_wiki9_articles() # with open(split_path, 'wb') as f: # for doc in tqdm.tqdm(train_docs): # with open(os.path.join(WIKI9_DIR, doc)) as fd: # f.write(fd.read()) # f.write(' ') # # return split_path # # Path: data/common.py # MODEL_DIR = '/path/to/model/' # # Path: utils/common_utils.py # def log(msg): # if msg[-1] != '\n': # msg += '\n' # sys.stderr.write(msg) # sys.stderr.flush() . Output only the next line.
with smart_open.open(read_wiki9_train_split(exp_id), encoding='utf-8') as f:
Given the following code snippet before the placeholder: <|code_start|># http://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. from __future__ import absolute_import from __future__ import division from __future__ import print_function flags.DEFINE_float('learning_rate', 0.001, 'Learning rate for training') flags.DEFINE_float('noise_multiplier', 0.5, 'Ratio of the standard deviation to the clipping norm') flags.DEFINE_float('l2_norm_clip', 0.25, 'Clipping norm') flags.DEFINE_integer('exp_id', 0, 'Experiment trial number') flags.DEFINE_integer('num_gpu', 1, 'Number of GPU') flags.DEFINE_integer('batch_size', 512, 'Batch size') flags.DEFINE_integer('microbatches', 128, 'Number of microbatch') flags.DEFINE_integer('epochs', 5, 'Number of epochs') flags.DEFINE_integer('hidden_size', 100, 'Number of hidden units') flags.DEFINE_integer('n_sampled', 25, 'Number of hidden units') flags.DEFINE_integer('print_every', 1000, 'Number of hidden units') flags.DEFINE_boolean('dpsgd', True, 'If True, train with DP-SGD. ' 'If False, train with vanilla SGD.') <|code_end|> , predict the next line using imports from the current file: from absl import flags from absl import app from dp_optimizer.dp_optimizer_sparse import SparseDPAdamGaussianOptimizer from privacy.analysis.rdp_accountant import compute_rdp, get_privacy_spent from utils.common_utils import rigid_op_sequence from data.wiki9 import read_wiki9_train_split from data.common import MODEL_DIR from utils.common_utils import log from collections import Counter import tensorflow as tf import numpy as np import time import smart_open import os and context including class names, function names, and sometimes code from other files: # Path: dp_optimizer/dp_optimizer_sparse.py # class SparseGaussianSumQuery(gaussian_query.GaussianSumQuery): # class DPOptimizerClass(cls): # class SparseDPGaussianOptimizerClass(make_optimizer_class(cls)): # def get_noised_result(self, sample_state, global_state): # def add_noise(v): # def add_noise(v): # def make_optimizer_class(cls): # def __init__( # self, # dp_sum_query, # num_microbatches=None, # unroll_microbatches=False, # *args, # pylint: disable=keyword-arg-before-vararg, g-doc-args # **kwargs): # def compute_gradients(self, # loss, # var_list, # gate_gradients=GATE_OP, # aggregation_method=None, # colocate_gradients_with_ops=False, # grad_loss=None, # gradient_tape=None): # def process_microbatch(i, sample_state): # def normalize(v): # def make_gaussian_optimizer_class(cls): # def __init__( # self, # l2_norm_clip, # noise_multiplier, # num_microbatches=None, # ledger=None, # unroll_microbatches=False, # *args, # pylint: disable=keyword-arg-before-vararg # **kwargs): # def ledger(self): # GATE_OP = tf.train.Optimizer.GATE_OP # pylint: disable=invalid-name # GATE_OP = None # pylint: disable=invalid-name # # Path: utils/common_utils.py # def rigid_op_sequence(op_lambdas): # with ExitStack() as stack: # for op_func in op_lambdas: # op = op_func() # context = tf.control_dependencies([op]) # stack.enter_context(context) # return op # # Path: data/wiki9.py # def read_wiki9_train_split(exp_id=0): # split_path = os.path.join(WIKI9_SPLIT_DIR, 'split{}.train'.format(exp_id)) # if not os.path.exists(split_path): # train_docs, _ = split_wiki9_articles() # with open(split_path, 'wb') as f: # for doc in tqdm.tqdm(train_docs): # with open(os.path.join(WIKI9_DIR, doc)) as fd: # f.write(fd.read()) # f.write(' ') # # return split_path # # Path: data/common.py # MODEL_DIR = '/path/to/model/' # # Path: utils/common_utils.py # def log(msg): # if msg[-1] != '\n': # msg += '\n' # sys.stderr.write(msg) # sys.stderr.flush() . Output only the next line.
flags.DEFINE_string('save_dir', os.path.join(MODEL_DIR, 'w2v'),
Given the code snippet: <|code_start|> grads_and_vars, scalar_loss = model(inputs, labels) train_ops = optimizer.apply_gradients(grads_and_vars) saver = tf.train.Saver() iterations = epochs * len(train_words) // batch_size print_every = FLAGS.print_every with tf.Session() as sess: iteration = 0 train_loss = 0 sess.run(tf.global_variables_initializer()) for e in range(1, epochs + 1): start = time.time() for x, y in get_batches(train_words, batch_size, word_sample_int, window_size): b = len(x) if num_microbatches > 0: offset = b - b % num_microbatches x, y = x[:offset], y[:offset] feed = {inputs: x, labels: np.array(y)[:, None]} err, _, _ = sess.run([scalar_loss, train_ops, update_curr_words], feed_dict=feed) train_loss += err iteration += 1 if iteration % print_every == 0: end = time.time() <|code_end|> , generate the next line using the imports in this file: from absl import flags from absl import app from dp_optimizer.dp_optimizer_sparse import SparseDPAdamGaussianOptimizer from privacy.analysis.rdp_accountant import compute_rdp, get_privacy_spent from utils.common_utils import rigid_op_sequence from data.wiki9 import read_wiki9_train_split from data.common import MODEL_DIR from utils.common_utils import log from collections import Counter import tensorflow as tf import numpy as np import time import smart_open import os and context (functions, classes, or occasionally code) from other files: # Path: dp_optimizer/dp_optimizer_sparse.py # class SparseGaussianSumQuery(gaussian_query.GaussianSumQuery): # class DPOptimizerClass(cls): # class SparseDPGaussianOptimizerClass(make_optimizer_class(cls)): # def get_noised_result(self, sample_state, global_state): # def add_noise(v): # def add_noise(v): # def make_optimizer_class(cls): # def __init__( # self, # dp_sum_query, # num_microbatches=None, # unroll_microbatches=False, # *args, # pylint: disable=keyword-arg-before-vararg, g-doc-args # **kwargs): # def compute_gradients(self, # loss, # var_list, # gate_gradients=GATE_OP, # aggregation_method=None, # colocate_gradients_with_ops=False, # grad_loss=None, # gradient_tape=None): # def process_microbatch(i, sample_state): # def normalize(v): # def make_gaussian_optimizer_class(cls): # def __init__( # self, # l2_norm_clip, # noise_multiplier, # num_microbatches=None, # ledger=None, # unroll_microbatches=False, # *args, # pylint: disable=keyword-arg-before-vararg # **kwargs): # def ledger(self): # GATE_OP = tf.train.Optimizer.GATE_OP # pylint: disable=invalid-name # GATE_OP = None # pylint: disable=invalid-name # # Path: utils/common_utils.py # def rigid_op_sequence(op_lambdas): # with ExitStack() as stack: # for op_func in op_lambdas: # op = op_func() # context = tf.control_dependencies([op]) # stack.enter_context(context) # return op # # Path: data/wiki9.py # def read_wiki9_train_split(exp_id=0): # split_path = os.path.join(WIKI9_SPLIT_DIR, 'split{}.train'.format(exp_id)) # if not os.path.exists(split_path): # train_docs, _ = split_wiki9_articles() # with open(split_path, 'wb') as f: # for doc in tqdm.tqdm(train_docs): # with open(os.path.join(WIKI9_DIR, doc)) as fd: # f.write(fd.read()) # f.write(' ') # # return split_path # # Path: data/common.py # MODEL_DIR = '/path/to/model/' # # Path: utils/common_utils.py # def log(msg): # if msg[-1] != '\n': # msg += '\n' # sys.stderr.write(msg) # sys.stderr.flush() . Output only the next line.
log("Iteration: {:.4f}%, Loss: {:.4f}, {:.4f} sec/batch".format(
Next line prediction: <|code_start|># Copyright 2019 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 # # http://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. from __future__ import absolute_import from __future__ import division from __future__ import print_function flags.DEFINE_integer('exp_id', 0, 'Experiment trial number') flags.DEFINE_string('model', 'w2v', 'Word embedding model') <|code_end|> . Use current file imports: (from absl import flags from absl import app from gensim.models import Word2Vec, FastText from glove import Corpus, Glove from data.common import MODEL_DIR from data.wiki9 import split_wiki9_articles, WIKI9Articles import logging import os) and context including class names, function names, or small code snippets from other files: # Path: data/common.py # MODEL_DIR = '/path/to/model/' # # Path: data/wiki9.py # def split_wiki9_articles(exp_id=0): # all_docs = list(os.listdir(WIKI9_DIR)) # # s = gen_seed(exp_id) # random.seed(s) # random.shuffle(all_docs) # random.seed() # # n = len(all_docs) // 2 # return all_docs[:n], all_docs[n:] # # class WIKI9Articles(object): # def __init__(self, docs, dirname=WIKI9_DIR, verbose=0): # self.docs = docs # self.dirname = dirname # self.verbose = verbose # # def __iter__(self): # for fname in tqdm.tqdm(self.docs) if self.verbose else self.docs: # for line in smart_open.open(os.path.join(self.dirname, fname), # 'r', encoding='utf-8'): # yield line.split() . Output only the next line.
flags.DEFINE_string('save_dir', os.path.join(MODEL_DIR, 'w2v'),
Given the code snippet: <|code_start|> else: corpus_model = Corpus(dictionary) corpus_model.fit(corpus, window=params['window'] * 2, ignore_missing=True) if save_dict: corpus_model.save(dict_path) print('Dict size: %s' % len(corpus_model.dictionary)) print('Collocations: %s' % corpus_model.matrix.nnz) glove = Glove(no_components=100, learning_rate=params['alpha']) glove.fit(corpus_model.matrix, epochs=50, no_threads=params['workers'], verbose=True) glove.add_dictionary(corpus_model.dictionary) return glove def train_word_embedding(exp_id=0, emb_model='w2v'): logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) params = { 'sg': 1, 'negative': 25, 'alpha': 0.05, 'sample': 1e-4, 'workers': 48, 'iter': 5, 'window': 5, } <|code_end|> , generate the next line using the imports in this file: from absl import flags from absl import app from gensim.models import Word2Vec, FastText from glove import Corpus, Glove from data.common import MODEL_DIR from data.wiki9 import split_wiki9_articles, WIKI9Articles import logging import os and context (functions, classes, or occasionally code) from other files: # Path: data/common.py # MODEL_DIR = '/path/to/model/' # # Path: data/wiki9.py # def split_wiki9_articles(exp_id=0): # all_docs = list(os.listdir(WIKI9_DIR)) # # s = gen_seed(exp_id) # random.seed(s) # random.shuffle(all_docs) # random.seed() # # n = len(all_docs) // 2 # return all_docs[:n], all_docs[n:] # # class WIKI9Articles(object): # def __init__(self, docs, dirname=WIKI9_DIR, verbose=0): # self.docs = docs # self.dirname = dirname # self.verbose = verbose # # def __iter__(self): # for fname in tqdm.tqdm(self.docs) if self.verbose else self.docs: # for line in smart_open.open(os.path.join(self.dirname, fname), # 'r', encoding='utf-8'): # yield line.split() . Output only the next line.
train_docs, test_docs = split_wiki9_articles(exp_id)
Next line prediction: <|code_start|> corpus_model.fit(corpus, window=params['window'] * 2, ignore_missing=True) if save_dict: corpus_model.save(dict_path) print('Dict size: %s' % len(corpus_model.dictionary)) print('Collocations: %s' % corpus_model.matrix.nnz) glove = Glove(no_components=100, learning_rate=params['alpha']) glove.fit(corpus_model.matrix, epochs=50, no_threads=params['workers'], verbose=True) glove.add_dictionary(corpus_model.dictionary) return glove def train_word_embedding(exp_id=0, emb_model='w2v'): logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) params = { 'sg': 1, 'negative': 25, 'alpha': 0.05, 'sample': 1e-4, 'workers': 48, 'iter': 5, 'window': 5, } train_docs, test_docs = split_wiki9_articles(exp_id) print(len(train_docs), len(test_docs)) <|code_end|> . Use current file imports: (from absl import flags from absl import app from gensim.models import Word2Vec, FastText from glove import Corpus, Glove from data.common import MODEL_DIR from data.wiki9 import split_wiki9_articles, WIKI9Articles import logging import os) and context including class names, function names, or small code snippets from other files: # Path: data/common.py # MODEL_DIR = '/path/to/model/' # # Path: data/wiki9.py # def split_wiki9_articles(exp_id=0): # all_docs = list(os.listdir(WIKI9_DIR)) # # s = gen_seed(exp_id) # random.seed(s) # random.shuffle(all_docs) # random.seed() # # n = len(all_docs) // 2 # return all_docs[:n], all_docs[n:] # # class WIKI9Articles(object): # def __init__(self, docs, dirname=WIKI9_DIR, verbose=0): # self.docs = docs # self.dirname = dirname # self.verbose = verbose # # def __iter__(self): # for fname in tqdm.tqdm(self.docs) if self.verbose else self.docs: # for line in smart_open.open(os.path.join(self.dirname, fname), # 'r', encoding='utf-8'): # yield line.split() . Output only the next line.
wiki9_articles = WIKI9Articles(train_docs)
Next line prediction: <|code_start|> @six.python_2_unicode_compatible class News(Node): """Represents a News on CrunchBase""" KNOWN_PROPERTIES = [ "title", "author", "posted_on", "url", "created_at", "updated_at", ] def _coerce_values(self): for attr in ['posted_on']: if getattr(self, attr, None): <|code_end|> . Use current file imports: (import six from .node import Node from .utils import parse_date) and context including class names, function names, or small code snippets from other files: # Path: src/pycrunchbase/resource/utils.py # def parse_date(datelike): # """Helper for parsing dates in Organization properties""" # try: # return datetime.strptime(datelike, "%Y-%m-%d") # except ValueError: # return datelike . Output only the next line.
setattr(self, attr, parse_date(getattr(self, attr)))
Given the following code snippet before the placeholder: <|code_start|> "videos", "news", ] KNOWN_PROPERTIES = [ "permalink", "api_path", "web_path", "last_name", "first_name", "also_known_as", "bio", "profile_image_url", "role_investor", "born_on", "born_on_trust_code", "is_deceased", "died_on", "died_on_trust_code", "created_at", "updated_at", ] def _coerce_values(self): """A delegate method to handle parsing all data and converting them into python values """ # special cases to convert strings to pythonic value for attr in ['born_on', 'died_on']: if getattr(self, attr, None): <|code_end|> , predict the next line using imports from the current file: import six from .node import Node from .utils import parse_date and context including class names, function names, and sometimes code from other files: # Path: src/pycrunchbase/resource/utils.py # def parse_date(datelike): # """Helper for parsing dates in Organization properties""" # try: # return datetime.strptime(datelike, "%Y-%m-%d") # except ValueError: # return datelike . Output only the next line.
setattr(self, attr, parse_date(getattr(self, attr)))
Predict the next line for this snippet: <|code_start|> @six.python_2_unicode_compatible class Job(Node): """Represents a Job on CrunchBase""" KNOWN_PROPERTIES = [ "title", "is_current", "started_on", "started_on_trust_code", "ended_on", "ended_on_trust_code", "created_at", "updated_at", ] KNOWN_RELATIONSHIPS = [ "person", "organization", ] def _coerce_values(self): for attr in ['started_on', 'ended_on']: if getattr(self, attr, None): <|code_end|> with the help of current file imports: import six from .node import Node from .utils import parse_date and context from other files: # Path: src/pycrunchbase/resource/utils.py # def parse_date(datelike): # """Helper for parsing dates in Organization properties""" # try: # return datetime.strptime(datelike, "%Y-%m-%d") # except ValueError: # return datelike , which may contain function names, class names, or code. Output only the next line.
setattr(self, attr, parse_date(getattr(self, attr)))
Here is a snippet: <|code_start|> "api_path", "web_path", "funding_type", "series", "series_qualifier", "announced_on", "announced_on_trust_code", "closed_on", "closed_on_trust_code", "money_raised", "money_raised_currency_code", "money_raised_usd", "target_money_raised", "target_money_raised_currency_code", "target_money_raised_usd", "created_at", "updated_at", ] KNOWN_RELATIONSHIPS = [ "investments", "funded_organization", "images", "videos", "news", ] def _coerce_values(self): for attr in ['announced_on']: if getattr(self, attr, None): <|code_end|> . Write the next line using the current file imports: import six from .node import Node from .utils import parse_date and context from other files: # Path: src/pycrunchbase/resource/utils.py # def parse_date(datelike): # """Helper for parsing dates in Organization properties""" # try: # return datetime.strptime(datelike, "%Y-%m-%d") # except ValueError: # return datelike , which may include functions, classes, or code. Output only the next line.
setattr(self, attr, parse_date(getattr(self, attr)))
Here is a snippet: <|code_start|> "name", "also_known_as", "lifecycle_stage", "profile_image_url", "launched_on", "launched_on_trust_code", "closed_on", "closed_on_trust_code", "homepage_url", "short_description", "description", "created_at", "updated_at", ] KNOWN_RELATIONSHIPS = [ "owner", "categories", "primary_image", "competitors", "customers", "websites", "images", "videos", "news", ] def _coerce_values(self): for attr in ['launched_on']: if getattr(self, attr, None): <|code_end|> . Write the next line using the current file imports: import six from .node import Node from .utils import parse_date and context from other files: # Path: src/pycrunchbase/resource/utils.py # def parse_date(datelike): # """Helper for parsing dates in Organization properties""" # try: # return datetime.strptime(datelike, "%Y-%m-%d") # except ValueError: # return datelike , which may include functions, classes, or code. Output only the next line.
setattr(self, attr, parse_date(getattr(self, attr)))
Based on the snippet: <|code_start|> The data that is used to initialize a Page looks like this:: "data": { "paging": { "items_per_page": 1000, "current_page": 1, "number_of_pages": 1, "next_page_url": null, "prev_page_url": null, "total_items": 1, "sort_order": "custom" }, "items": [ { "properties": { "path": "organization/example", "name": "Example", "updated_at": 1423666090, "created_at": 1371717055, }, "type": "Organization", "uuid": "uuid" } ] } """ def __init__(self, name, data): self.name = name paging = data.get('paging') <|code_end|> , predict the immediate next line with the help of imports: import six from .utils import safe_int from .pageitem import PageItem from .relationship import Relationship and context (classes, functions, sometimes code) from other files: # Path: src/pycrunchbase/resource/utils.py # def safe_int(int_like): # try: # return int(int_like) # except TypeError: # return None . Output only the next line.
self.total_items = safe_int(paging.get('total_items')) or 0
Given the following code snippet before the placeholder: <|code_start|> "role_company", "role_investor", "role_group", "role_school", "founded_on", "founded_on_trust_code", "is_closed", "closed_on", "closed_on_trust_code", "num_employees_min", "num_employees_max", "total_funding_usd", "number_of_investments", "homepage_url", "created_at", "updated_at", "stock_exchange", "stock_symbol", "contact_email", "phone_number", "rank" ] def _coerce_values(self): """A delegate method to handle parsing all data and converting them into python values """ # special cases to convert strings to pythonic value for attr in ['closed_on', 'founded_on']: if getattr(self, attr, None): <|code_end|> , predict the next line using imports from the current file: import six from .node import Node from .utils import parse_date and context including class names, function names, and sometimes code from other files: # Path: src/pycrunchbase/resource/utils.py # def parse_date(datelike): # """Helper for parsing dates in Organization properties""" # try: # return datetime.strptime(datelike, "%Y-%m-%d") # except ValueError: # return datelike . Output only the next line.
setattr(self, attr, parse_date(getattr(self, attr)))
Next line prediction: <|code_start|> KNOWN_RELATIONSHIPS = [ 'venture_firm', 'investor', 'images', 'videos', 'news', ] KNOWN_PROPERTIES = [ "api_path", "web_path", "permalink", "name", "announced_on", "announced_on_trust_code", "money_raised", "money_raised_currency_code", "money_raised_usd", "created_at", "updated_at", ] def _coerce_values(self): """A delegate method to handle parsing all data and converting them into python values """ # special cases to convert strings to pythonic value for attr in ['announced_on']: if getattr(self, attr, None): <|code_end|> . Use current file imports: (import six from .node import Node from .utils import parse_date) and context including class names, function names, or small code snippets from other files: # Path: src/pycrunchbase/resource/utils.py # def parse_date(datelike): # """Helper for parsing dates in Organization properties""" # try: # return datetime.strptime(datelike, "%Y-%m-%d") # except ValueError: # return datelike . Output only the next line.
setattr(self, attr, parse_date(getattr(self, attr)))
Based on the snippet: <|code_start|> @six.python_2_unicode_compatible class Degree(Node): """Represents a Degree on CrunchBase""" KNOWN_PROPERTIES = [ # 'type', # 'uuid', 'started_on', 'started_on_trust_code', 'is_completed', 'completed_on', 'completed_on_trust_code', 'degree_type_name', 'degree_subject', 'created_at', 'updated_at', ] KNOWN_RELATIONSHIPS = [ 'school', 'person', ] def _coerce_values(self): for attr in ['started_on', 'completed_on']: if getattr(self, attr, None): <|code_end|> , predict the immediate next line with the help of imports: import six from .node import Node from .utils import parse_date and context (classes, functions, sometimes code) from other files: # Path: src/pycrunchbase/resource/utils.py # def parse_date(datelike): # """Helper for parsing dates in Organization properties""" # try: # return datetime.strptime(datelike, "%Y-%m-%d") # except ValueError: # return datelike . Output only the next line.
setattr(self, attr, parse_date(getattr(self, attr)))
Based on the snippet: <|code_start|>class Acquisition(Node): """Represents a Acquisition on CrunchBase""" KNOWN_PROPERTIES = [ "api_path", "web_path", "price", "price_currency_code", "price_usd", "payment_type", "acquisition_type", "acquisition_status", "disposition_of_acquired", "announced_on", "announced_on_trust_code", "completed_on", "completed_on_trust_code", "created_at", "updated_at", "permalink", ] KNOWN_RELATIONSHIPS = [ "acquirer", "acquiree", ] def _coerce_values(self): for attr in ['announced_on', 'completed_on']: if getattr(self, attr, None): <|code_end|> , predict the immediate next line with the help of imports: import six from .node import Node from .utils import parse_date and context (classes, functions, sometimes code) from other files: # Path: src/pycrunchbase/resource/utils.py # def parse_date(datelike): # """Helper for parsing dates in Organization properties""" # try: # return datetime.strptime(datelike, "%Y-%m-%d") # except ValueError: # return datelike . Output only the next line.
setattr(self, attr, parse_date(getattr(self, attr)))
Next line prediction: <|code_start|> HIDDEN_INPUT = forms.widgets.HiddenInput class PartnerForm(forms.ModelForm): def clean(self): cleaned_data = super(PartnerForm, self).clean() if cleaned_data.get('http_auth'): if not cleaned_data.get('http_auth_user'): self._errors['http_auth_user'] = self.error_class( ['HTTP username is mandatory when HTTP authentication is enabled']) if not cleaned_data.get('http_auth_pass'): self._errors['http_auth_pass'] = self.error_class( ['HTTP password is mandatory when HTTP authentication is enabled']) if cleaned_data.get('encryption') and not cleaned_data.get('encryption_key'): self._errors['encryption_key'] = self.error_class( ['Encryption Key is mandatory when message encryption is enabled']) if cleaned_data.get('signature') and not cleaned_data.get('signature_key'): self._errors['signature_key'] = self.error_class( ['Signature Key is mandatory when message signature is enabled']) if cleaned_data.get('mdn') and not cleaned_data.get('mdn_mode'): self._errors['mdn_mode'] = self.error_class(['MDN Mode needs to be specified']) if cleaned_data.get('mdn_sign') and not cleaned_data.get('signature_key'): self._errors['signature_key'] = self.error_class( ['Signature Key is mandatory when signed mdn is requested']) return cleaned_data class Meta: <|code_end|> . Use current file imports: (from pyas2 import models from django import forms from pyas2 import viewlib) and context including class names, function names, or small code snippets from other files: # Path: pyas2/models.py # DEFAULT_ENTRY = ('', "---------") # CONTENT_TYPE_CHOICES = ( # ('application/EDI-X12', 'application/EDI-X12'), # ('application/EDIFACT', 'application/EDIFACT'), # ('application/edi-consent', 'application/edi-consent'), # ('application/XML', 'application/XML'), # ('text/CSV', 'text/CSV'), # ) # ENCRYPT_ALG_CHOICES = ( # ('des_ede3_cbc', '3DES'), # ('des_cbc', 'DES'), # ('aes_128_cbc', 'AES-128'), # ('aes_192_cbc', 'AES-192'), # ('aes_256_cbc', 'AES-256'), # ('rc2_40_cbc', 'RC2-40'), # ) # SIGN_ALG_CHOICES = ( # ('sha1', 'SHA-1'), # ) # MDN_TYPE_CHOICES = ( # ('SYNC', 'Synchronous'), # ('ASYNC', 'Asynchronous'), # ) # DIRECTION_CHOICES = ( # ('IN', _('Inbound')), # ('OUT', _('Outbound')), # ) # STATUS_CHOICES = ( # ('S', _('Success')), # ('E', _('Error')), # ('W', _('Warning')), # ('P', _('Pending')), # ('R', _('Retry')), # ('IP', _('In Process')), # ) # MODE_CHOICES = ( # ('SYNC', _('Synchronous')), # ('ASYNC', _('Asynchronous')), # ) # STATUS_CHOICES = ( # ('S', _('Success')), # ('E', _('Error')), # ('W', _('Warning')), # ) # STATUS_CHOICES = ( # ('S', _('Sent')), # ('R', _('Received')), # ('P', _('Pending')), # ) # def get_certificate_path(instance, filename): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def getorganizations(): # def getpartners(): # def check_odirs(sender, instance, created, **kwargs): # def check_pdirs(sender, instance, created, **kwargs): # def update_dirs(): # class PrivateCertificate(models.Model): # class PublicCertificate(models.Model): # class Organization(models.Model): # class Partner(models.Model): # class Message(models.Model): # class Payload(models.Model): # class Log(models.Model): # class MDN(models.Model): # # Path: pyas2/viewlib.py # def datetimefrom(): # def datetimeuntil(): # def url_with_querystring(path, **kwargs): # def indent_x12(content): # def indent_edifact(content): # def indent_xml(content): # EDIFACT_INDENT = re.compile(''' # (?<!\?) #if no preceding escape (?) # ' #apostrophe # (?![\n\r]) #if no following CR of LF # ''', re.VERBOSE) . Output only the next line.
model = models.Partner
Given the code snippet: <|code_start|> if not cleaned_data.get('http_auth_pass'): self._errors['http_auth_pass'] = self.error_class( ['HTTP password is mandatory when HTTP authentication is enabled']) if cleaned_data.get('encryption') and not cleaned_data.get('encryption_key'): self._errors['encryption_key'] = self.error_class( ['Encryption Key is mandatory when message encryption is enabled']) if cleaned_data.get('signature') and not cleaned_data.get('signature_key'): self._errors['signature_key'] = self.error_class( ['Signature Key is mandatory when message signature is enabled']) if cleaned_data.get('mdn') and not cleaned_data.get('mdn_mode'): self._errors['mdn_mode'] = self.error_class(['MDN Mode needs to be specified']) if cleaned_data.get('mdn_sign') and not cleaned_data.get('signature_key'): self._errors['signature_key'] = self.error_class( ['Signature Key is mandatory when signed mdn is requested']) return cleaned_data class Meta: model = models.Partner exclude = [] class PrivateCertificateForm(forms.ModelForm): certificate_passphrase = forms.CharField(widget=forms.PasswordInput()) class Meta: model = models.PrivateCertificate fields = ['certificate', 'ca_cert', 'certificate_passphrase'] class Select(forms.Form): <|code_end|> , generate the next line using the imports in this file: from pyas2 import models from django import forms from pyas2 import viewlib and context (functions, classes, or occasionally code) from other files: # Path: pyas2/models.py # DEFAULT_ENTRY = ('', "---------") # CONTENT_TYPE_CHOICES = ( # ('application/EDI-X12', 'application/EDI-X12'), # ('application/EDIFACT', 'application/EDIFACT'), # ('application/edi-consent', 'application/edi-consent'), # ('application/XML', 'application/XML'), # ('text/CSV', 'text/CSV'), # ) # ENCRYPT_ALG_CHOICES = ( # ('des_ede3_cbc', '3DES'), # ('des_cbc', 'DES'), # ('aes_128_cbc', 'AES-128'), # ('aes_192_cbc', 'AES-192'), # ('aes_256_cbc', 'AES-256'), # ('rc2_40_cbc', 'RC2-40'), # ) # SIGN_ALG_CHOICES = ( # ('sha1', 'SHA-1'), # ) # MDN_TYPE_CHOICES = ( # ('SYNC', 'Synchronous'), # ('ASYNC', 'Asynchronous'), # ) # DIRECTION_CHOICES = ( # ('IN', _('Inbound')), # ('OUT', _('Outbound')), # ) # STATUS_CHOICES = ( # ('S', _('Success')), # ('E', _('Error')), # ('W', _('Warning')), # ('P', _('Pending')), # ('R', _('Retry')), # ('IP', _('In Process')), # ) # MODE_CHOICES = ( # ('SYNC', _('Synchronous')), # ('ASYNC', _('Asynchronous')), # ) # STATUS_CHOICES = ( # ('S', _('Success')), # ('E', _('Error')), # ('W', _('Warning')), # ) # STATUS_CHOICES = ( # ('S', _('Sent')), # ('R', _('Received')), # ('P', _('Pending')), # ) # def get_certificate_path(instance, filename): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def getorganizations(): # def getpartners(): # def check_odirs(sender, instance, created, **kwargs): # def check_pdirs(sender, instance, created, **kwargs): # def update_dirs(): # class PrivateCertificate(models.Model): # class PublicCertificate(models.Model): # class Organization(models.Model): # class Partner(models.Model): # class Message(models.Model): # class Payload(models.Model): # class Log(models.Model): # class MDN(models.Model): # # Path: pyas2/viewlib.py # def datetimefrom(): # def datetimeuntil(): # def url_with_querystring(path, **kwargs): # def indent_x12(content): # def indent_edifact(content): # def indent_xml(content): # EDIFACT_INDENT = re.compile(''' # (?<!\?) #if no preceding escape (?) # ' #apostrophe # (?![\n\r]) #if no following CR of LF # ''', re.VERBOSE) . Output only the next line.
datefrom = forms.DateTimeField(initial=viewlib.datetimefrom)
Next line prediction: <|code_start|> class Command(BaseCommand): help = _(u'Send all pending asynchronous mdns to your trading partners') def handle(self, *args, **options): # First part of script sends asynchronous MDNs for inbound messages received from partners # Fetch all the pending asynchronous MDN objects pyas2init.logger.info(_(u'Sending all pending asynchronous MDNs')) <|code_end|> . Use current file imports: (from django.core.management.base import BaseCommand from django.utils.translation import ugettext as _ from pyas2 import models from pyas2 import pyas2init from email.parser import HeaderParser from django.utils import timezone from datetime import timedelta import requests) and context including class names, function names, or small code snippets from other files: # Path: pyas2/models.py # DEFAULT_ENTRY = ('', "---------") # CONTENT_TYPE_CHOICES = ( # ('application/EDI-X12', 'application/EDI-X12'), # ('application/EDIFACT', 'application/EDIFACT'), # ('application/edi-consent', 'application/edi-consent'), # ('application/XML', 'application/XML'), # ('text/CSV', 'text/CSV'), # ) # ENCRYPT_ALG_CHOICES = ( # ('des_ede3_cbc', '3DES'), # ('des_cbc', 'DES'), # ('aes_128_cbc', 'AES-128'), # ('aes_192_cbc', 'AES-192'), # ('aes_256_cbc', 'AES-256'), # ('rc2_40_cbc', 'RC2-40'), # ) # SIGN_ALG_CHOICES = ( # ('sha1', 'SHA-1'), # ) # MDN_TYPE_CHOICES = ( # ('SYNC', 'Synchronous'), # ('ASYNC', 'Asynchronous'), # ) # DIRECTION_CHOICES = ( # ('IN', _('Inbound')), # ('OUT', _('Outbound')), # ) # STATUS_CHOICES = ( # ('S', _('Success')), # ('E', _('Error')), # ('W', _('Warning')), # ('P', _('Pending')), # ('R', _('Retry')), # ('IP', _('In Process')), # ) # MODE_CHOICES = ( # ('SYNC', _('Synchronous')), # ('ASYNC', _('Asynchronous')), # ) # STATUS_CHOICES = ( # ('S', _('Success')), # ('E', _('Error')), # ('W', _('Warning')), # ) # STATUS_CHOICES = ( # ('S', _('Sent')), # ('R', _('Received')), # ('P', _('Pending')), # ) # def get_certificate_path(instance, filename): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def getorganizations(): # def getpartners(): # def check_odirs(sender, instance, created, **kwargs): # def check_pdirs(sender, instance, created, **kwargs): # def update_dirs(): # class PrivateCertificate(models.Model): # class PublicCertificate(models.Model): # class Organization(models.Model): # class Partner(models.Model): # class Message(models.Model): # class Payload(models.Model): # class Log(models.Model): # class MDN(models.Model): # # Path: pyas2/pyas2init.py # def initialize(): # def initserverlogging(logname): . Output only the next line.
in_pending_mdns = models.MDN.objects.filter(status='P') # , timestamp__gt=time_threshold) --> why do this?
Using the snippet: <|code_start|> class Command(BaseCommand): help = _(u'Send all pending asynchronous mdns to your trading partners') def handle(self, *args, **options): # First part of script sends asynchronous MDNs for inbound messages received from partners # Fetch all the pending asynchronous MDN objects <|code_end|> , determine the next line of code. You have imports: from django.core.management.base import BaseCommand from django.utils.translation import ugettext as _ from pyas2 import models from pyas2 import pyas2init from email.parser import HeaderParser from django.utils import timezone from datetime import timedelta import requests and context (class names, function names, or code) available: # Path: pyas2/models.py # DEFAULT_ENTRY = ('', "---------") # CONTENT_TYPE_CHOICES = ( # ('application/EDI-X12', 'application/EDI-X12'), # ('application/EDIFACT', 'application/EDIFACT'), # ('application/edi-consent', 'application/edi-consent'), # ('application/XML', 'application/XML'), # ('text/CSV', 'text/CSV'), # ) # ENCRYPT_ALG_CHOICES = ( # ('des_ede3_cbc', '3DES'), # ('des_cbc', 'DES'), # ('aes_128_cbc', 'AES-128'), # ('aes_192_cbc', 'AES-192'), # ('aes_256_cbc', 'AES-256'), # ('rc2_40_cbc', 'RC2-40'), # ) # SIGN_ALG_CHOICES = ( # ('sha1', 'SHA-1'), # ) # MDN_TYPE_CHOICES = ( # ('SYNC', 'Synchronous'), # ('ASYNC', 'Asynchronous'), # ) # DIRECTION_CHOICES = ( # ('IN', _('Inbound')), # ('OUT', _('Outbound')), # ) # STATUS_CHOICES = ( # ('S', _('Success')), # ('E', _('Error')), # ('W', _('Warning')), # ('P', _('Pending')), # ('R', _('Retry')), # ('IP', _('In Process')), # ) # MODE_CHOICES = ( # ('SYNC', _('Synchronous')), # ('ASYNC', _('Asynchronous')), # ) # STATUS_CHOICES = ( # ('S', _('Success')), # ('E', _('Error')), # ('W', _('Warning')), # ) # STATUS_CHOICES = ( # ('S', _('Sent')), # ('R', _('Received')), # ('P', _('Pending')), # ) # def get_certificate_path(instance, filename): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def getorganizations(): # def getpartners(): # def check_odirs(sender, instance, created, **kwargs): # def check_pdirs(sender, instance, created, **kwargs): # def update_dirs(): # class PrivateCertificate(models.Model): # class PublicCertificate(models.Model): # class Organization(models.Model): # class Partner(models.Model): # class Message(models.Model): # class Payload(models.Model): # class Log(models.Model): # class MDN(models.Model): # # Path: pyas2/pyas2init.py # def initialize(): # def initserverlogging(logname): . Output only the next line.
pyas2init.logger.info(_(u'Sending all pending asynchronous MDNs'))
Here is a snippet: <|code_start|> class Command(BaseCommand): help = _(u'Starts the PyAS2 server') def handle(self, *args, **options): try: except Exception: raise ImportError(_(u'Dependency failure: cherrypy library is needed to start the as2 server')) cherrypy.config.update({ 'global': { 'log.screen': False, <|code_end|> . Write the next line using the current file imports: from django.core.management.base import BaseCommand from django.core.handlers.wsgi import WSGIHandler from django.utils.translation import ugettext as _ from pyas2 import pyas2init from cherrypy import wsgiserver import pyas2 import os import cherrypy and context from other files: # Path: pyas2/pyas2init.py # def initialize(): # def initserverlogging(logname): , which may include functions, classes, or code. Output only the next line.
'log.error_file': os.path.join(pyas2init.gsettings['log_dir'], 'cherrypy_error.log'),
Here is a snippet: <|code_start|> def decompress_message(message, payload): """ Function for decompressing the message """ decompressed_content = None if payload.get_content_type() == 'application/pkcs7-mime' \ and payload.get_param('smime-type') == 'compressed-data': <|code_end|> . Write the next line using the current file imports: import requests import email import hashlib import as2utils import os import base64 from django.utils.translation import ugettext as _ from email.mime.multipart import MIMEMultipart from email.parser import HeaderParser from pyas2 import models from pyas2 import pyas2init from string import Template and context from other files: # Path: pyas2/models.py # DEFAULT_ENTRY = ('', "---------") # CONTENT_TYPE_CHOICES = ( # ('application/EDI-X12', 'application/EDI-X12'), # ('application/EDIFACT', 'application/EDIFACT'), # ('application/edi-consent', 'application/edi-consent'), # ('application/XML', 'application/XML'), # ('text/CSV', 'text/CSV'), # ) # ENCRYPT_ALG_CHOICES = ( # ('des_ede3_cbc', '3DES'), # ('des_cbc', 'DES'), # ('aes_128_cbc', 'AES-128'), # ('aes_192_cbc', 'AES-192'), # ('aes_256_cbc', 'AES-256'), # ('rc2_40_cbc', 'RC2-40'), # ) # SIGN_ALG_CHOICES = ( # ('sha1', 'SHA-1'), # ) # MDN_TYPE_CHOICES = ( # ('SYNC', 'Synchronous'), # ('ASYNC', 'Asynchronous'), # ) # DIRECTION_CHOICES = ( # ('IN', _('Inbound')), # ('OUT', _('Outbound')), # ) # STATUS_CHOICES = ( # ('S', _('Success')), # ('E', _('Error')), # ('W', _('Warning')), # ('P', _('Pending')), # ('R', _('Retry')), # ('IP', _('In Process')), # ) # MODE_CHOICES = ( # ('SYNC', _('Synchronous')), # ('ASYNC', _('Asynchronous')), # ) # STATUS_CHOICES = ( # ('S', _('Success')), # ('E', _('Error')), # ('W', _('Warning')), # ) # STATUS_CHOICES = ( # ('S', _('Sent')), # ('R', _('Received')), # ('P', _('Pending')), # ) # def get_certificate_path(instance, filename): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def getorganizations(): # def getpartners(): # def check_odirs(sender, instance, created, **kwargs): # def check_pdirs(sender, instance, created, **kwargs): # def update_dirs(): # class PrivateCertificate(models.Model): # class PublicCertificate(models.Model): # class Organization(models.Model): # class Partner(models.Model): # class Message(models.Model): # class Payload(models.Model): # class Log(models.Model): # class MDN(models.Model): # # Path: pyas2/pyas2init.py # def initialize(): # def initserverlogging(logname): , which may include functions, classes, or code. Output only the next line.
models.Log.objects.create(message=message, status='S',
Given the code snippet: <|code_start|> def decompress_message(message, payload): """ Function for decompressing the message """ decompressed_content = None if payload.get_content_type() == 'application/pkcs7-mime' \ and payload.get_param('smime-type') == 'compressed-data': models.Log.objects.create(message=message, status='S', text=_(u'Decompressing the payload')) message.compressed = True # Decode the data to binary if its base64 encoded compressed_content = payload.get_payload() try: compressed_content.encode('ascii') compressed_content = base64.b64decode(payload.get_payload()) except UnicodeDecodeError: pass <|code_end|> , generate the next line using the imports in this file: import requests import email import hashlib import as2utils import os import base64 from django.utils.translation import ugettext as _ from email.mime.multipart import MIMEMultipart from email.parser import HeaderParser from pyas2 import models from pyas2 import pyas2init from string import Template and context (functions, classes, or occasionally code) from other files: # Path: pyas2/models.py # DEFAULT_ENTRY = ('', "---------") # CONTENT_TYPE_CHOICES = ( # ('application/EDI-X12', 'application/EDI-X12'), # ('application/EDIFACT', 'application/EDIFACT'), # ('application/edi-consent', 'application/edi-consent'), # ('application/XML', 'application/XML'), # ('text/CSV', 'text/CSV'), # ) # ENCRYPT_ALG_CHOICES = ( # ('des_ede3_cbc', '3DES'), # ('des_cbc', 'DES'), # ('aes_128_cbc', 'AES-128'), # ('aes_192_cbc', 'AES-192'), # ('aes_256_cbc', 'AES-256'), # ('rc2_40_cbc', 'RC2-40'), # ) # SIGN_ALG_CHOICES = ( # ('sha1', 'SHA-1'), # ) # MDN_TYPE_CHOICES = ( # ('SYNC', 'Synchronous'), # ('ASYNC', 'Asynchronous'), # ) # DIRECTION_CHOICES = ( # ('IN', _('Inbound')), # ('OUT', _('Outbound')), # ) # STATUS_CHOICES = ( # ('S', _('Success')), # ('E', _('Error')), # ('W', _('Warning')), # ('P', _('Pending')), # ('R', _('Retry')), # ('IP', _('In Process')), # ) # MODE_CHOICES = ( # ('SYNC', _('Synchronous')), # ('ASYNC', _('Asynchronous')), # ) # STATUS_CHOICES = ( # ('S', _('Success')), # ('E', _('Error')), # ('W', _('Warning')), # ) # STATUS_CHOICES = ( # ('S', _('Sent')), # ('R', _('Received')), # ('P', _('Pending')), # ) # def get_certificate_path(instance, filename): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def getorganizations(): # def getpartners(): # def check_odirs(sender, instance, created, **kwargs): # def check_pdirs(sender, instance, created, **kwargs): # def update_dirs(): # class PrivateCertificate(models.Model): # class PublicCertificate(models.Model): # class Organization(models.Model): # class Partner(models.Model): # class Message(models.Model): # class Payload(models.Model): # class Log(models.Model): # class MDN(models.Model): # # Path: pyas2/pyas2init.py # def initialize(): # def initserverlogging(logname): . Output only the next line.
pyas2init.logger.debug(
Continue the code snippet: <|code_start|> handler = LinuxEventHandler(logger=logger, dir_watch_data=dir_watch_data, cond=cond, tasks=tasks) notifier = pyinotify.Notifier(watch_manager, handler) notifier.loop() # end of linux-specific ################################################################################## class Command(BaseCommand): help = _(u'Daemon process that watches the outbox of all as2 partners and ' u'triggers sendmessage when files become available') def handle(self, *args, **options): pyas2init.logger.info(_(u'Starting PYAS2 send daemon.')) try: engine_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) engine_socket.bind(('127.0.0.1', pyas2init.gsettings['daemon_port'])) except socket.error: engine_socket.close() raise CommandError(_(u'An instance of the send daemon is already running')) else: atexit.register(engine_socket.close) cond = threading.Condition() tasks = set() dir_watch_data = [] orgs = models.Organization.objects.all() partners = models.Partner.objects.all() python_executable_path = pyas2init.gsettings['python_path'] managepy_path = pyas2init.gsettings['managepy_path'] for partner in partners: for org in orgs: dir_watch_data.append({}) <|code_end|> . Use current file imports: from django.core.management.base import BaseCommand, CommandError from django.utils.translation import ugettext as _ from pyas2 import models from pyas2 import pyas2init from pyas2 import as2utils import time import atexit import socket import os import sys import subprocess import threading import win32file import win32con import pyinotify and context (classes, functions, or code) from other files: # Path: pyas2/models.py # DEFAULT_ENTRY = ('', "---------") # CONTENT_TYPE_CHOICES = ( # ('application/EDI-X12', 'application/EDI-X12'), # ('application/EDIFACT', 'application/EDIFACT'), # ('application/edi-consent', 'application/edi-consent'), # ('application/XML', 'application/XML'), # ('text/CSV', 'text/CSV'), # ) # ENCRYPT_ALG_CHOICES = ( # ('des_ede3_cbc', '3DES'), # ('des_cbc', 'DES'), # ('aes_128_cbc', 'AES-128'), # ('aes_192_cbc', 'AES-192'), # ('aes_256_cbc', 'AES-256'), # ('rc2_40_cbc', 'RC2-40'), # ) # SIGN_ALG_CHOICES = ( # ('sha1', 'SHA-1'), # ) # MDN_TYPE_CHOICES = ( # ('SYNC', 'Synchronous'), # ('ASYNC', 'Asynchronous'), # ) # DIRECTION_CHOICES = ( # ('IN', _('Inbound')), # ('OUT', _('Outbound')), # ) # STATUS_CHOICES = ( # ('S', _('Success')), # ('E', _('Error')), # ('W', _('Warning')), # ('P', _('Pending')), # ('R', _('Retry')), # ('IP', _('In Process')), # ) # MODE_CHOICES = ( # ('SYNC', _('Synchronous')), # ('ASYNC', _('Asynchronous')), # ) # STATUS_CHOICES = ( # ('S', _('Success')), # ('E', _('Error')), # ('W', _('Warning')), # ) # STATUS_CHOICES = ( # ('S', _('Sent')), # ('R', _('Received')), # ('P', _('Pending')), # ) # def get_certificate_path(instance, filename): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def getorganizations(): # def getpartners(): # def check_odirs(sender, instance, created, **kwargs): # def check_pdirs(sender, instance, created, **kwargs): # def update_dirs(): # class PrivateCertificate(models.Model): # class PublicCertificate(models.Model): # class Organization(models.Model): # class Partner(models.Model): # class Message(models.Model): # class Payload(models.Model): # class Log(models.Model): # class MDN(models.Model): # # Path: pyas2/pyas2init.py # def initialize(): # def initserverlogging(logname): # # Path: pyas2/as2utils.py # def senderrorreport(message, errortext): # def txtexc(mention_exception_type=True): # def safe_unicode(value): # def __init__(self, msg, *args, **kwargs): # def __unicode__(self): # def __str__(self): # def join(*paths): # def dirshouldbethere(path): # def opendata(filename, mode, charset=None, errors='strict'): # def readdata(filename, charset=None, errors='strict'): # def storefile(targetdir, filename, content, archive): # def unescape_as2name(ename): # def escape_as2name(uename): # def extractpayload(message, **kwargs): # def mimetostring(msg, headerlen): # def extractpayload_fromstring1(msg, boundary): # def extractpayload_fromstring2(msg, boundary): # def canonicalize2(msg): # def canonicalize(msg): # def compress_payload(payload): # def decompress_payload(payload): # def encrypt_payload(payload, key, cipher): # def decrypt_payload(payload, key, passphrase): # def sign_payload(data, key, passphrase): # def verify_payload(msg, raw_sig, cert, ca_cert, verify_cert): # def get_key_passphrase(self): # def check_binary_sig(signature, boundary, content): # class AS2Error(Exception): # class As2Exception(AS2Error): # class As2DuplicateDocument(AS2Error): # class As2PartnerNotFound(AS2Error): # class As2InsufficientSecurity(AS2Error): # class As2DecompressionFailed(AS2Error): # class As2DecryptionFailed(AS2Error): # class As2InvalidSignature(AS2Error): # class CompressedDataAttr(univ.Sequence): # class Content(univ.OctetString): # class CompressedDataPayload(univ.Sequence): # class CompressedData(univ.Sequence): # class CompressedDataMain(univ.Sequence): . Output only the next line.
dir_watch_data[-1]['path'] = as2utils.join(pyas2init.gsettings['root_dir'], 'messages',
Given the code snippet: <|code_start|> list_filter = ('name', 'as2_name') fieldsets = ( (None, { 'fields': ( 'name', 'as2_name', 'email_address', 'target_url', 'subject', 'content_type', 'confirmation_message') }), ('Http Authentication', { 'classes': ('collapse', 'wide'), 'fields': ('http_auth', 'http_auth_user', 'http_auth_pass', 'https_ca_cert') }), ('Security Settings', { 'classes': ('collapse', 'wide'), 'fields': ('compress', 'encryption', 'encryption_key', 'signature', 'signature_key') }), ('MDN Settings', { 'classes': ('collapse', 'wide'), 'fields': ('mdn', 'mdn_mode', 'mdn_sign') }), ('Advanced Settings', { 'classes': ('collapse', 'wide'), 'fields': ('keep_filename', 'cmd_send', 'cmd_receive') }), ) class OrganizationAdmin(admin.ModelAdmin): list_display = ['name', 'as2_name'] list_filter = ('name', 'as2_name') <|code_end|> , generate the next line using the imports in this file: from django.contrib import admin from pyas2 import forms from pyas2 import models import os and context (functions, classes, or occasionally code) from other files: # Path: pyas2/forms.py # HIDDEN_INPUT = forms.widgets.HiddenInput # class PartnerForm(forms.ModelForm): # class Meta: # class PrivateCertificateForm(forms.ModelForm): # class Meta: # class Select(forms.Form): # class MessageSearchForm(Select): # class MDNSearchForm(Select): # class SendMessageForm(forms.Form): # def clean(self): # def __init__(self, *args, **kwargs): # def __init__(self, *args, **kwargs): # def __init__(self, *args, **kwargs): # # Path: pyas2/models.py # DEFAULT_ENTRY = ('', "---------") # CONTENT_TYPE_CHOICES = ( # ('application/EDI-X12', 'application/EDI-X12'), # ('application/EDIFACT', 'application/EDIFACT'), # ('application/edi-consent', 'application/edi-consent'), # ('application/XML', 'application/XML'), # ('text/CSV', 'text/CSV'), # ) # ENCRYPT_ALG_CHOICES = ( # ('des_ede3_cbc', '3DES'), # ('des_cbc', 'DES'), # ('aes_128_cbc', 'AES-128'), # ('aes_192_cbc', 'AES-192'), # ('aes_256_cbc', 'AES-256'), # ('rc2_40_cbc', 'RC2-40'), # ) # SIGN_ALG_CHOICES = ( # ('sha1', 'SHA-1'), # ) # MDN_TYPE_CHOICES = ( # ('SYNC', 'Synchronous'), # ('ASYNC', 'Asynchronous'), # ) # DIRECTION_CHOICES = ( # ('IN', _('Inbound')), # ('OUT', _('Outbound')), # ) # STATUS_CHOICES = ( # ('S', _('Success')), # ('E', _('Error')), # ('W', _('Warning')), # ('P', _('Pending')), # ('R', _('Retry')), # ('IP', _('In Process')), # ) # MODE_CHOICES = ( # ('SYNC', _('Synchronous')), # ('ASYNC', _('Asynchronous')), # ) # STATUS_CHOICES = ( # ('S', _('Success')), # ('E', _('Error')), # ('W', _('Warning')), # ) # STATUS_CHOICES = ( # ('S', _('Sent')), # ('R', _('Received')), # ('P', _('Pending')), # ) # def get_certificate_path(instance, filename): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def getorganizations(): # def getpartners(): # def check_odirs(sender, instance, created, **kwargs): # def check_pdirs(sender, instance, created, **kwargs): # def update_dirs(): # class PrivateCertificate(models.Model): # class PublicCertificate(models.Model): # class Organization(models.Model): # class Partner(models.Model): # class Message(models.Model): # class Payload(models.Model): # class Log(models.Model): # class MDN(models.Model): . Output only the next line.
admin.site.register(models.PrivateCertificate, PrivateCertificateAdmin)
Predict the next line after this snippet: <|code_start|> class Command(BaseCommand): help = _(u'Send an as2 message to your trading partner') args = '<organization_as2name partner_as2name path_to_payload>' def add_arguments(self, parser): parser.add_argument('organization_as2name', type=str) parser.add_argument('partner_as2name', type=str) parser.add_argument('path_to_payload', type=str) parser.add_argument( '--delete', action='store_true', dest='delete', default=False, help=_(u'Delete source file after processing') ) def handle(self, *args, **options): # Check if organization and partner exists try: <|code_end|> using the current file's imports: from django.core.management.base import BaseCommand, CommandError from django.utils.translation import ugettext as _ from pyas2 import models from pyas2 import as2lib from pyas2 import as2utils from pyas2 import pyas2init import traceback import email.utils import shutil import time import os import sys and any relevant context from other files: # Path: pyas2/models.py # DEFAULT_ENTRY = ('', "---------") # CONTENT_TYPE_CHOICES = ( # ('application/EDI-X12', 'application/EDI-X12'), # ('application/EDIFACT', 'application/EDIFACT'), # ('application/edi-consent', 'application/edi-consent'), # ('application/XML', 'application/XML'), # ('text/CSV', 'text/CSV'), # ) # ENCRYPT_ALG_CHOICES = ( # ('des_ede3_cbc', '3DES'), # ('des_cbc', 'DES'), # ('aes_128_cbc', 'AES-128'), # ('aes_192_cbc', 'AES-192'), # ('aes_256_cbc', 'AES-256'), # ('rc2_40_cbc', 'RC2-40'), # ) # SIGN_ALG_CHOICES = ( # ('sha1', 'SHA-1'), # ) # MDN_TYPE_CHOICES = ( # ('SYNC', 'Synchronous'), # ('ASYNC', 'Asynchronous'), # ) # DIRECTION_CHOICES = ( # ('IN', _('Inbound')), # ('OUT', _('Outbound')), # ) # STATUS_CHOICES = ( # ('S', _('Success')), # ('E', _('Error')), # ('W', _('Warning')), # ('P', _('Pending')), # ('R', _('Retry')), # ('IP', _('In Process')), # ) # MODE_CHOICES = ( # ('SYNC', _('Synchronous')), # ('ASYNC', _('Asynchronous')), # ) # STATUS_CHOICES = ( # ('S', _('Success')), # ('E', _('Error')), # ('W', _('Warning')), # ) # STATUS_CHOICES = ( # ('S', _('Sent')), # ('R', _('Received')), # ('P', _('Pending')), # ) # def get_certificate_path(instance, filename): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def getorganizations(): # def getpartners(): # def check_odirs(sender, instance, created, **kwargs): # def check_pdirs(sender, instance, created, **kwargs): # def update_dirs(): # class PrivateCertificate(models.Model): # class PublicCertificate(models.Model): # class Organization(models.Model): # class Partner(models.Model): # class Message(models.Model): # class Payload(models.Model): # class Log(models.Model): # class MDN(models.Model): # # Path: pyas2/as2lib.py # def decompress_message(message, payload): # def save_message(message, payload, raw_payload): # def build_mdn(message, status, **kwargs): # def build_message(message): # def send_message(message, payload): # def save_mdn(message, mdn_content): # def run_post_send(message): # def run_post_receive(message, full_filename): # # Path: pyas2/as2utils.py # def senderrorreport(message, errortext): # def txtexc(mention_exception_type=True): # def safe_unicode(value): # def __init__(self, msg, *args, **kwargs): # def __unicode__(self): # def __str__(self): # def join(*paths): # def dirshouldbethere(path): # def opendata(filename, mode, charset=None, errors='strict'): # def readdata(filename, charset=None, errors='strict'): # def storefile(targetdir, filename, content, archive): # def unescape_as2name(ename): # def escape_as2name(uename): # def extractpayload(message, **kwargs): # def mimetostring(msg, headerlen): # def extractpayload_fromstring1(msg, boundary): # def extractpayload_fromstring2(msg, boundary): # def canonicalize2(msg): # def canonicalize(msg): # def compress_payload(payload): # def decompress_payload(payload): # def encrypt_payload(payload, key, cipher): # def decrypt_payload(payload, key, passphrase): # def sign_payload(data, key, passphrase): # def verify_payload(msg, raw_sig, cert, ca_cert, verify_cert): # def get_key_passphrase(self): # def check_binary_sig(signature, boundary, content): # class AS2Error(Exception): # class As2Exception(AS2Error): # class As2DuplicateDocument(AS2Error): # class As2PartnerNotFound(AS2Error): # class As2InsufficientSecurity(AS2Error): # class As2DecompressionFailed(AS2Error): # class As2DecryptionFailed(AS2Error): # class As2InvalidSignature(AS2Error): # class CompressedDataAttr(univ.Sequence): # class Content(univ.OctetString): # class CompressedDataPayload(univ.Sequence): # class CompressedData(univ.Sequence): # class CompressedDataMain(univ.Sequence): # # Path: pyas2/pyas2init.py # def initialize(): # def initserverlogging(logname): . Output only the next line.
org = models.Organization.objects.get(as2_name=options['organization_as2name'])
Given the following code snippet before the placeholder: <|code_start|> STATUS_CHOICES = ( ('S', _('Sent')), ('R', _('Received')), ('P', _('Pending')), ) message_id = models.CharField(max_length=250, primary_key=True) timestamp = models.DateTimeField(auto_now_add=True) status = models.CharField(max_length=2, choices=STATUS_CHOICES) file = models.CharField(max_length=500) headers = models.TextField(null=True) return_url = models.URLField(null=True) signed = models.BooleanField(default=False) def __str__(self): return self.message_id def getorganizations(): return [DEFAULT_ENTRY] + [(l, '%s (%s)' % (l, n)) for (l, n) in Organization.objects.values_list('as2_name', 'name')] def getpartners(): return [DEFAULT_ENTRY] + [(l, '%s (%s)' % (l, n)) for (l, n) in Partner.objects.values_list('as2_name', 'name')] @receiver(post_save, sender=Organization) def check_odirs(sender, instance, created, **kwargs): partners = Partner.objects.all() for partner in partners: <|code_end|> , predict the next line using imports from the current file: from django.db import models from django.core.files.storage import FileSystemStorage from django.utils.translation import ugettext as _ from django.db.models.signals import post_save from django.dispatch import receiver from pyas2 import pyas2init from pyas2 import as2utils import os and context including class names, function names, and sometimes code from other files: # Path: pyas2/pyas2init.py # def initialize(): # def initserverlogging(logname): # # Path: pyas2/as2utils.py # def senderrorreport(message, errortext): # def txtexc(mention_exception_type=True): # def safe_unicode(value): # def __init__(self, msg, *args, **kwargs): # def __unicode__(self): # def __str__(self): # def join(*paths): # def dirshouldbethere(path): # def opendata(filename, mode, charset=None, errors='strict'): # def readdata(filename, charset=None, errors='strict'): # def storefile(targetdir, filename, content, archive): # def unescape_as2name(ename): # def escape_as2name(uename): # def extractpayload(message, **kwargs): # def mimetostring(msg, headerlen): # def extractpayload_fromstring1(msg, boundary): # def extractpayload_fromstring2(msg, boundary): # def canonicalize2(msg): # def canonicalize(msg): # def compress_payload(payload): # def decompress_payload(payload): # def encrypt_payload(payload, key, cipher): # def decrypt_payload(payload, key, passphrase): # def sign_payload(data, key, passphrase): # def verify_payload(msg, raw_sig, cert, ca_cert, verify_cert): # def get_key_passphrase(self): # def check_binary_sig(signature, boundary, content): # class AS2Error(Exception): # class As2Exception(AS2Error): # class As2DuplicateDocument(AS2Error): # class As2PartnerNotFound(AS2Error): # class As2InsufficientSecurity(AS2Error): # class As2DecompressionFailed(AS2Error): # class As2DecryptionFailed(AS2Error): # class As2InvalidSignature(AS2Error): # class CompressedDataAttr(univ.Sequence): # class Content(univ.OctetString): # class CompressedDataPayload(univ.Sequence): # class CompressedData(univ.Sequence): # class CompressedDataMain(univ.Sequence): . Output only the next line.
as2utils.dirshouldbethere(
Continue the code snippet: <|code_start|> staff_required = user_passes_test(lambda u: u.is_staff) superuser_required = user_passes_test(lambda u: u.is_superuser) urlpatterns = [ url(r'^login.*', auth_views.login, {'template_name': 'admin/login.html'}, name='login'), url(r'^logout.*', auth_views.logout, {'next_page': 'home'}, name='logout'), url(r'^password_change/$', auth_views.password_change, name='password_change'), url(r'^password_change/done/$', auth_views.password_change_done, name='password_change_done'), <|code_end|> . Use current file imports: from django.conf.urls import url from django.contrib.auth.decorators import login_required, user_passes_test from django.contrib.auth import views as auth_views from pyas2 import views and context (classes, functions, or code) from other files: # Path: pyas2/views.py # def server_error(request, template_name='500.html'): # def client_error(request, template_name='400.html'): # def home(request, *kw, **kwargs): # def get_queryset(self): # def get_context_data(self, **kwargs): # def get(self, request, *args, **kwargs): # def post(self, request, *args, **kwargs): # def get(self, request, pk, *args, **kwargs): # def get_queryset(self): # def get(self, request, *args, **kwargs): # def post(self, request, *args, **kwargs): # def get(self, request, pk, *args, **kwargs): # def get(self, request, *args, **kwargs): # def post(self, request, *args, **kwargs): # def resend_message(request, pk, *args, **kwargs): # def send_async_mdn(request, *args, **kwargs): # def retry_failed_comms(request, *args, **kwargs): # def cancel_retries(request, pk, *args, **kwargs): # def send_test_mail_managers(request, *args, **kwargs): # def download_cert(request, pk, *args, **kwargs): # def as2receive(request, *args, **kwargs): # class MessageList(ListView): # class MessageDetail(DetailView): # class MessageSearch(View): # class PayloadView(View): # class MDNList(ListView): # class MDNSearch(View): # class MDNView(View): # class SendMessage(View): . Output only the next line.
url(r'^home.*', login_required(views.home, login_url='login'), name='home'),
Predict the next line for this snippet: <|code_start|> # Declare global variables gsettings = {} logger = None convertini2logger = { 'DEBUG': logging.DEBUG, 'INFO': logging.INFO, 'WARNING': logging.WARNING, 'ERROR': logging.ERROR, 'CRITICAL': logging.CRITICAL, 'STARTINFO': 25 } def initialize(): """ Function initializes the global variables for pyAS2 """ global gsettings pyas2_settings = {} if hasattr(settings, 'PYAS2'): pyas2_settings = settings.PYAS2 if not gsettings: gsettings['environment'] = pyas2_settings.get('ENVIRONMENT', 'production') gsettings['port'] = pyas2_settings.get('PORT', 8080) gsettings['ssl_certificate'] = pyas2_settings.get('SSLCERTIFICATE', None) gsettings['ssl_private_key'] = pyas2_settings.get('SSLPRIVATEKEY', None) gsettings['environment_text'] = pyas2_settings.get('ENVIRONMENTTEXT', 'Production') gsettings['environment_text_color'] = pyas2_settings.get('ENVIRONMENTTEXTCOLOR', 'Black') gsettings['root_dir'] = settings.BASE_DIR gsettings['python_path'] = pyas2_settings.get('PYTHONPATH', sys.executable) <|code_end|> with the help of current file imports: import logging import os import sys from django.conf import settings from pyas2 import as2utils and context from other files: # Path: pyas2/as2utils.py # def senderrorreport(message, errortext): # def txtexc(mention_exception_type=True): # def safe_unicode(value): # def __init__(self, msg, *args, **kwargs): # def __unicode__(self): # def __str__(self): # def join(*paths): # def dirshouldbethere(path): # def opendata(filename, mode, charset=None, errors='strict'): # def readdata(filename, charset=None, errors='strict'): # def storefile(targetdir, filename, content, archive): # def unescape_as2name(ename): # def escape_as2name(uename): # def extractpayload(message, **kwargs): # def mimetostring(msg, headerlen): # def extractpayload_fromstring1(msg, boundary): # def extractpayload_fromstring2(msg, boundary): # def canonicalize2(msg): # def canonicalize(msg): # def compress_payload(payload): # def decompress_payload(payload): # def encrypt_payload(payload, key, cipher): # def decrypt_payload(payload, key, passphrase): # def sign_payload(data, key, passphrase): # def verify_payload(msg, raw_sig, cert, ca_cert, verify_cert): # def get_key_passphrase(self): # def check_binary_sig(signature, boundary, content): # class AS2Error(Exception): # class As2Exception(AS2Error): # class As2DuplicateDocument(AS2Error): # class As2PartnerNotFound(AS2Error): # class As2InsufficientSecurity(AS2Error): # class As2DecompressionFailed(AS2Error): # class As2DecryptionFailed(AS2Error): # class As2InvalidSignature(AS2Error): # class CompressedDataAttr(univ.Sequence): # class Content(univ.OctetString): # class CompressedDataPayload(univ.Sequence): # class CompressedData(univ.Sequence): # class CompressedDataMain(univ.Sequence): , which may contain function names, class names, or code. Output only the next line.
gsettings['managepy_path'] = as2utils.join(settings.BASE_DIR, 'manage.py')
Given snippet: <|code_start|> TEST_DIR = os.path.join((os.path.dirname( os.path.abspath(__file__))), 'fixtures') class AS2SendReceiveTest(TestCase): """Test cases for the AS2 server and client. We will be testing each permutation as defined in RFC 4130 Section 2.4.2 """ @classmethod def setUpTestData(cls): # Every test needs a client. cls.client = Client() cls.header_parser = HeaderParser() # Load the client and server certificates <|code_end|> , continue by predicting the next line. Consider current file imports: from django.test import TestCase, Client from pyas2 import models from pyas2 import as2lib from email import utils as emailutils from email.parser import HeaderParser from email import message_from_string from itertools import izip import os and context: # Path: pyas2/models.py # DEFAULT_ENTRY = ('', "---------") # CONTENT_TYPE_CHOICES = ( # ('application/EDI-X12', 'application/EDI-X12'), # ('application/EDIFACT', 'application/EDIFACT'), # ('application/edi-consent', 'application/edi-consent'), # ('application/XML', 'application/XML'), # ('text/CSV', 'text/CSV'), # ) # ENCRYPT_ALG_CHOICES = ( # ('des_ede3_cbc', '3DES'), # ('des_cbc', 'DES'), # ('aes_128_cbc', 'AES-128'), # ('aes_192_cbc', 'AES-192'), # ('aes_256_cbc', 'AES-256'), # ('rc2_40_cbc', 'RC2-40'), # ) # SIGN_ALG_CHOICES = ( # ('sha1', 'SHA-1'), # ) # MDN_TYPE_CHOICES = ( # ('SYNC', 'Synchronous'), # ('ASYNC', 'Asynchronous'), # ) # DIRECTION_CHOICES = ( # ('IN', _('Inbound')), # ('OUT', _('Outbound')), # ) # STATUS_CHOICES = ( # ('S', _('Success')), # ('E', _('Error')), # ('W', _('Warning')), # ('P', _('Pending')), # ('R', _('Retry')), # ('IP', _('In Process')), # ) # MODE_CHOICES = ( # ('SYNC', _('Synchronous')), # ('ASYNC', _('Asynchronous')), # ) # STATUS_CHOICES = ( # ('S', _('Success')), # ('E', _('Error')), # ('W', _('Warning')), # ) # STATUS_CHOICES = ( # ('S', _('Sent')), # ('R', _('Received')), # ('P', _('Pending')), # ) # def get_certificate_path(instance, filename): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def getorganizations(): # def getpartners(): # def check_odirs(sender, instance, created, **kwargs): # def check_pdirs(sender, instance, created, **kwargs): # def update_dirs(): # class PrivateCertificate(models.Model): # class PublicCertificate(models.Model): # class Organization(models.Model): # class Partner(models.Model): # class Message(models.Model): # class Payload(models.Model): # class Log(models.Model): # class MDN(models.Model): # # Path: pyas2/as2lib.py # def decompress_message(message, payload): # def save_message(message, payload, raw_payload): # def build_mdn(message, status, **kwargs): # def build_message(message): # def send_message(message, payload): # def save_mdn(message, mdn_content): # def run_post_send(message): # def run_post_receive(message, full_filename): which might include code, classes, or functions. Output only the next line.
cls.server_key = models.PrivateCertificate.objects.create(
Given the following code snippet before the placeholder: <|code_start|> with open(out_message.mdn.file, 'rb') as mdn_file: mdn_content = mdn_file.read() # Switch the out and in messages, this is to prevent duplicate message from being picked out_message.delete() in_message.pk = message_id in_message.payload = None in_message.save() # Send the async mdn and check for its status content_type = http_headers.pop('HTTP_CONTENT_TYPE') response = self.client.post('/pyas2/as2receive', data=mdn_content, content_type=content_type, **http_headers) self.assertEqual(response.status_code, 200) in_message = models.Message.objects.get(message_id=message_id) # AS2SendReceiveTest.printLogs(in_message) self.assertEqual(in_message.status, 'S') def buildSendMessage(self, message_id, partner): """ Function builds the message and posts the request. """ message = models.Message.objects.create(message_id='%s_IN' % message_id, partner=partner, organization=self.organization, direction='OUT', status='IP', payload=self.payload) <|code_end|> , predict the next line using imports from the current file: from django.test import TestCase, Client from pyas2 import models from pyas2 import as2lib from email import utils as emailutils from email.parser import HeaderParser from email import message_from_string from itertools import izip import os and context including class names, function names, and sometimes code from other files: # Path: pyas2/models.py # DEFAULT_ENTRY = ('', "---------") # CONTENT_TYPE_CHOICES = ( # ('application/EDI-X12', 'application/EDI-X12'), # ('application/EDIFACT', 'application/EDIFACT'), # ('application/edi-consent', 'application/edi-consent'), # ('application/XML', 'application/XML'), # ('text/CSV', 'text/CSV'), # ) # ENCRYPT_ALG_CHOICES = ( # ('des_ede3_cbc', '3DES'), # ('des_cbc', 'DES'), # ('aes_128_cbc', 'AES-128'), # ('aes_192_cbc', 'AES-192'), # ('aes_256_cbc', 'AES-256'), # ('rc2_40_cbc', 'RC2-40'), # ) # SIGN_ALG_CHOICES = ( # ('sha1', 'SHA-1'), # ) # MDN_TYPE_CHOICES = ( # ('SYNC', 'Synchronous'), # ('ASYNC', 'Asynchronous'), # ) # DIRECTION_CHOICES = ( # ('IN', _('Inbound')), # ('OUT', _('Outbound')), # ) # STATUS_CHOICES = ( # ('S', _('Success')), # ('E', _('Error')), # ('W', _('Warning')), # ('P', _('Pending')), # ('R', _('Retry')), # ('IP', _('In Process')), # ) # MODE_CHOICES = ( # ('SYNC', _('Synchronous')), # ('ASYNC', _('Asynchronous')), # ) # STATUS_CHOICES = ( # ('S', _('Success')), # ('E', _('Error')), # ('W', _('Warning')), # ) # STATUS_CHOICES = ( # ('S', _('Sent')), # ('R', _('Received')), # ('P', _('Pending')), # ) # def get_certificate_path(instance, filename): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def getorganizations(): # def getpartners(): # def check_odirs(sender, instance, created, **kwargs): # def check_pdirs(sender, instance, created, **kwargs): # def update_dirs(): # class PrivateCertificate(models.Model): # class PublicCertificate(models.Model): # class Organization(models.Model): # class Partner(models.Model): # class Message(models.Model): # class Payload(models.Model): # class Log(models.Model): # class MDN(models.Model): # # Path: pyas2/as2lib.py # def decompress_message(message, payload): # def save_message(message, payload, raw_payload): # def build_mdn(message, status, **kwargs): # def build_message(message): # def send_message(message, payload): # def save_mdn(message, mdn_content): # def run_post_send(message): # def run_post_receive(message, full_filename): . Output only the next line.
processed_payload = as2lib.build_message(message)
Here is a snippet: <|code_start|> class Command(BaseCommand): help = _(u'Retrying all failed outbound communications') def handle(self, *args, **options): pyas2init.logger.info(_(u'Retrying all failed outbound messages')) # Get the list of all messages with status retry <|code_end|> . Write the next line using the current file imports: from django.core.management.base import BaseCommand from django.utils.translation import ugettext as _ from pyas2 import models from pyas2 import pyas2init from pyas2 import as2lib from pyas2 import as2utils and context from other files: # Path: pyas2/models.py # DEFAULT_ENTRY = ('', "---------") # CONTENT_TYPE_CHOICES = ( # ('application/EDI-X12', 'application/EDI-X12'), # ('application/EDIFACT', 'application/EDIFACT'), # ('application/edi-consent', 'application/edi-consent'), # ('application/XML', 'application/XML'), # ('text/CSV', 'text/CSV'), # ) # ENCRYPT_ALG_CHOICES = ( # ('des_ede3_cbc', '3DES'), # ('des_cbc', 'DES'), # ('aes_128_cbc', 'AES-128'), # ('aes_192_cbc', 'AES-192'), # ('aes_256_cbc', 'AES-256'), # ('rc2_40_cbc', 'RC2-40'), # ) # SIGN_ALG_CHOICES = ( # ('sha1', 'SHA-1'), # ) # MDN_TYPE_CHOICES = ( # ('SYNC', 'Synchronous'), # ('ASYNC', 'Asynchronous'), # ) # DIRECTION_CHOICES = ( # ('IN', _('Inbound')), # ('OUT', _('Outbound')), # ) # STATUS_CHOICES = ( # ('S', _('Success')), # ('E', _('Error')), # ('W', _('Warning')), # ('P', _('Pending')), # ('R', _('Retry')), # ('IP', _('In Process')), # ) # MODE_CHOICES = ( # ('SYNC', _('Synchronous')), # ('ASYNC', _('Asynchronous')), # ) # STATUS_CHOICES = ( # ('S', _('Success')), # ('E', _('Error')), # ('W', _('Warning')), # ) # STATUS_CHOICES = ( # ('S', _('Sent')), # ('R', _('Received')), # ('P', _('Pending')), # ) # def get_certificate_path(instance, filename): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def getorganizations(): # def getpartners(): # def check_odirs(sender, instance, created, **kwargs): # def check_pdirs(sender, instance, created, **kwargs): # def update_dirs(): # class PrivateCertificate(models.Model): # class PublicCertificate(models.Model): # class Organization(models.Model): # class Partner(models.Model): # class Message(models.Model): # class Payload(models.Model): # class Log(models.Model): # class MDN(models.Model): # # Path: pyas2/pyas2init.py # def initialize(): # def initserverlogging(logname): # # Path: pyas2/as2lib.py # def decompress_message(message, payload): # def save_message(message, payload, raw_payload): # def build_mdn(message, status, **kwargs): # def build_message(message): # def send_message(message, payload): # def save_mdn(message, mdn_content): # def run_post_send(message): # def run_post_receive(message, full_filename): # # Path: pyas2/as2utils.py # def senderrorreport(message, errortext): # def txtexc(mention_exception_type=True): # def safe_unicode(value): # def __init__(self, msg, *args, **kwargs): # def __unicode__(self): # def __str__(self): # def join(*paths): # def dirshouldbethere(path): # def opendata(filename, mode, charset=None, errors='strict'): # def readdata(filename, charset=None, errors='strict'): # def storefile(targetdir, filename, content, archive): # def unescape_as2name(ename): # def escape_as2name(uename): # def extractpayload(message, **kwargs): # def mimetostring(msg, headerlen): # def extractpayload_fromstring1(msg, boundary): # def extractpayload_fromstring2(msg, boundary): # def canonicalize2(msg): # def canonicalize(msg): # def compress_payload(payload): # def decompress_payload(payload): # def encrypt_payload(payload, key, cipher): # def decrypt_payload(payload, key, passphrase): # def sign_payload(data, key, passphrase): # def verify_payload(msg, raw_sig, cert, ca_cert, verify_cert): # def get_key_passphrase(self): # def check_binary_sig(signature, boundary, content): # class AS2Error(Exception): # class As2Exception(AS2Error): # class As2DuplicateDocument(AS2Error): # class As2PartnerNotFound(AS2Error): # class As2InsufficientSecurity(AS2Error): # class As2DecompressionFailed(AS2Error): # class As2DecryptionFailed(AS2Error): # class As2InvalidSignature(AS2Error): # class CompressedDataAttr(univ.Sequence): # class Content(univ.OctetString): # class CompressedDataPayload(univ.Sequence): # class CompressedData(univ.Sequence): # class CompressedDataMain(univ.Sequence): , which may include functions, classes, or code. Output only the next line.
failed_msgs = models.Message.objects.filter(status='R', direction='OUT')
Using the snippet: <|code_start|> class Command(BaseCommand): help = _(u'Retrying all failed outbound communications') def handle(self, *args, **options): <|code_end|> , determine the next line of code. You have imports: from django.core.management.base import BaseCommand from django.utils.translation import ugettext as _ from pyas2 import models from pyas2 import pyas2init from pyas2 import as2lib from pyas2 import as2utils and context (class names, function names, or code) available: # Path: pyas2/models.py # DEFAULT_ENTRY = ('', "---------") # CONTENT_TYPE_CHOICES = ( # ('application/EDI-X12', 'application/EDI-X12'), # ('application/EDIFACT', 'application/EDIFACT'), # ('application/edi-consent', 'application/edi-consent'), # ('application/XML', 'application/XML'), # ('text/CSV', 'text/CSV'), # ) # ENCRYPT_ALG_CHOICES = ( # ('des_ede3_cbc', '3DES'), # ('des_cbc', 'DES'), # ('aes_128_cbc', 'AES-128'), # ('aes_192_cbc', 'AES-192'), # ('aes_256_cbc', 'AES-256'), # ('rc2_40_cbc', 'RC2-40'), # ) # SIGN_ALG_CHOICES = ( # ('sha1', 'SHA-1'), # ) # MDN_TYPE_CHOICES = ( # ('SYNC', 'Synchronous'), # ('ASYNC', 'Asynchronous'), # ) # DIRECTION_CHOICES = ( # ('IN', _('Inbound')), # ('OUT', _('Outbound')), # ) # STATUS_CHOICES = ( # ('S', _('Success')), # ('E', _('Error')), # ('W', _('Warning')), # ('P', _('Pending')), # ('R', _('Retry')), # ('IP', _('In Process')), # ) # MODE_CHOICES = ( # ('SYNC', _('Synchronous')), # ('ASYNC', _('Asynchronous')), # ) # STATUS_CHOICES = ( # ('S', _('Success')), # ('E', _('Error')), # ('W', _('Warning')), # ) # STATUS_CHOICES = ( # ('S', _('Sent')), # ('R', _('Received')), # ('P', _('Pending')), # ) # def get_certificate_path(instance, filename): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def getorganizations(): # def getpartners(): # def check_odirs(sender, instance, created, **kwargs): # def check_pdirs(sender, instance, created, **kwargs): # def update_dirs(): # class PrivateCertificate(models.Model): # class PublicCertificate(models.Model): # class Organization(models.Model): # class Partner(models.Model): # class Message(models.Model): # class Payload(models.Model): # class Log(models.Model): # class MDN(models.Model): # # Path: pyas2/pyas2init.py # def initialize(): # def initserverlogging(logname): # # Path: pyas2/as2lib.py # def decompress_message(message, payload): # def save_message(message, payload, raw_payload): # def build_mdn(message, status, **kwargs): # def build_message(message): # def send_message(message, payload): # def save_mdn(message, mdn_content): # def run_post_send(message): # def run_post_receive(message, full_filename): # # Path: pyas2/as2utils.py # def senderrorreport(message, errortext): # def txtexc(mention_exception_type=True): # def safe_unicode(value): # def __init__(self, msg, *args, **kwargs): # def __unicode__(self): # def __str__(self): # def join(*paths): # def dirshouldbethere(path): # def opendata(filename, mode, charset=None, errors='strict'): # def readdata(filename, charset=None, errors='strict'): # def storefile(targetdir, filename, content, archive): # def unescape_as2name(ename): # def escape_as2name(uename): # def extractpayload(message, **kwargs): # def mimetostring(msg, headerlen): # def extractpayload_fromstring1(msg, boundary): # def extractpayload_fromstring2(msg, boundary): # def canonicalize2(msg): # def canonicalize(msg): # def compress_payload(payload): # def decompress_payload(payload): # def encrypt_payload(payload, key, cipher): # def decrypt_payload(payload, key, passphrase): # def sign_payload(data, key, passphrase): # def verify_payload(msg, raw_sig, cert, ca_cert, verify_cert): # def get_key_passphrase(self): # def check_binary_sig(signature, boundary, content): # class AS2Error(Exception): # class As2Exception(AS2Error): # class As2DuplicateDocument(AS2Error): # class As2PartnerNotFound(AS2Error): # class As2InsufficientSecurity(AS2Error): # class As2DecompressionFailed(AS2Error): # class As2DecryptionFailed(AS2Error): # class As2InvalidSignature(AS2Error): # class CompressedDataAttr(univ.Sequence): # class Content(univ.OctetString): # class CompressedDataPayload(univ.Sequence): # class CompressedData(univ.Sequence): # class CompressedDataMain(univ.Sequence): . Output only the next line.
pyas2init.logger.info(_(u'Retrying all failed outbound messages'))
Predict the next line after this snippet: <|code_start|> class Command(BaseCommand): help = _(u'Retrying all failed outbound communications') def handle(self, *args, **options): pyas2init.logger.info(_(u'Retrying all failed outbound messages')) # Get the list of all messages with status retry failed_msgs = models.Message.objects.filter(status='R', direction='OUT') for failed_msg in failed_msgs: # Increase the retry count if not failed_msg.retries: failed_msg.retries = 1 else: failed_msg.retries += failed_msg.retries # if max retries has exceeded then mark message status as error if failed_msg.retries > pyas2init.gsettings['max_retries']: failed_msg.status = 'E' models.Log.objects.create(message=failed_msg, status='E', text=_(u'Message exceeded maximum retries, marked as error')) failed_msg.save() continue pyas2init.logger.info(_(u'Retrying send of message with ID %s' % failed_msg)) try: # Build and resend the AS2 message <|code_end|> using the current file's imports: from django.core.management.base import BaseCommand from django.utils.translation import ugettext as _ from pyas2 import models from pyas2 import pyas2init from pyas2 import as2lib from pyas2 import as2utils and any relevant context from other files: # Path: pyas2/models.py # DEFAULT_ENTRY = ('', "---------") # CONTENT_TYPE_CHOICES = ( # ('application/EDI-X12', 'application/EDI-X12'), # ('application/EDIFACT', 'application/EDIFACT'), # ('application/edi-consent', 'application/edi-consent'), # ('application/XML', 'application/XML'), # ('text/CSV', 'text/CSV'), # ) # ENCRYPT_ALG_CHOICES = ( # ('des_ede3_cbc', '3DES'), # ('des_cbc', 'DES'), # ('aes_128_cbc', 'AES-128'), # ('aes_192_cbc', 'AES-192'), # ('aes_256_cbc', 'AES-256'), # ('rc2_40_cbc', 'RC2-40'), # ) # SIGN_ALG_CHOICES = ( # ('sha1', 'SHA-1'), # ) # MDN_TYPE_CHOICES = ( # ('SYNC', 'Synchronous'), # ('ASYNC', 'Asynchronous'), # ) # DIRECTION_CHOICES = ( # ('IN', _('Inbound')), # ('OUT', _('Outbound')), # ) # STATUS_CHOICES = ( # ('S', _('Success')), # ('E', _('Error')), # ('W', _('Warning')), # ('P', _('Pending')), # ('R', _('Retry')), # ('IP', _('In Process')), # ) # MODE_CHOICES = ( # ('SYNC', _('Synchronous')), # ('ASYNC', _('Asynchronous')), # ) # STATUS_CHOICES = ( # ('S', _('Success')), # ('E', _('Error')), # ('W', _('Warning')), # ) # STATUS_CHOICES = ( # ('S', _('Sent')), # ('R', _('Received')), # ('P', _('Pending')), # ) # def get_certificate_path(instance, filename): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def getorganizations(): # def getpartners(): # def check_odirs(sender, instance, created, **kwargs): # def check_pdirs(sender, instance, created, **kwargs): # def update_dirs(): # class PrivateCertificate(models.Model): # class PublicCertificate(models.Model): # class Organization(models.Model): # class Partner(models.Model): # class Message(models.Model): # class Payload(models.Model): # class Log(models.Model): # class MDN(models.Model): # # Path: pyas2/pyas2init.py # def initialize(): # def initserverlogging(logname): # # Path: pyas2/as2lib.py # def decompress_message(message, payload): # def save_message(message, payload, raw_payload): # def build_mdn(message, status, **kwargs): # def build_message(message): # def send_message(message, payload): # def save_mdn(message, mdn_content): # def run_post_send(message): # def run_post_receive(message, full_filename): # # Path: pyas2/as2utils.py # def senderrorreport(message, errortext): # def txtexc(mention_exception_type=True): # def safe_unicode(value): # def __init__(self, msg, *args, **kwargs): # def __unicode__(self): # def __str__(self): # def join(*paths): # def dirshouldbethere(path): # def opendata(filename, mode, charset=None, errors='strict'): # def readdata(filename, charset=None, errors='strict'): # def storefile(targetdir, filename, content, archive): # def unescape_as2name(ename): # def escape_as2name(uename): # def extractpayload(message, **kwargs): # def mimetostring(msg, headerlen): # def extractpayload_fromstring1(msg, boundary): # def extractpayload_fromstring2(msg, boundary): # def canonicalize2(msg): # def canonicalize(msg): # def compress_payload(payload): # def decompress_payload(payload): # def encrypt_payload(payload, key, cipher): # def decrypt_payload(payload, key, passphrase): # def sign_payload(data, key, passphrase): # def verify_payload(msg, raw_sig, cert, ca_cert, verify_cert): # def get_key_passphrase(self): # def check_binary_sig(signature, boundary, content): # class AS2Error(Exception): # class As2Exception(AS2Error): # class As2DuplicateDocument(AS2Error): # class As2PartnerNotFound(AS2Error): # class As2InsufficientSecurity(AS2Error): # class As2DecompressionFailed(AS2Error): # class As2DecryptionFailed(AS2Error): # class As2InvalidSignature(AS2Error): # class CompressedDataAttr(univ.Sequence): # class Content(univ.OctetString): # class CompressedDataPayload(univ.Sequence): # class CompressedData(univ.Sequence): # class CompressedDataMain(univ.Sequence): . Output only the next line.
payload = as2lib.build_message(failed_msg)
Given snippet: <|code_start|> class Command(BaseCommand): help = _(u'Automatic maintenance for the AS2 server. ' u'Cleans up all the old logs, messages and archived files.') def handle(self, *args, **options): pyas2init.logger.info(_(u'Automatic maintenance process started')) max_archive_dt = timezone.now() - timedelta( pyas2init.gsettings['max_arch_days']) max_archive_ts = int(max_archive_dt.strftime("%s")) pyas2init.logger.info( _(u'Delete all DB Objects older than max archive days')) <|code_end|> , continue by predicting the next line. Consider current file imports: from django.core.management.base import BaseCommand from django.utils.translation import ugettext as _ from datetime import timedelta from django.utils import timezone from pyas2 import models from pyas2 import pyas2init import os import glob and context: # Path: pyas2/models.py # DEFAULT_ENTRY = ('', "---------") # CONTENT_TYPE_CHOICES = ( # ('application/EDI-X12', 'application/EDI-X12'), # ('application/EDIFACT', 'application/EDIFACT'), # ('application/edi-consent', 'application/edi-consent'), # ('application/XML', 'application/XML'), # ('text/CSV', 'text/CSV'), # ) # ENCRYPT_ALG_CHOICES = ( # ('des_ede3_cbc', '3DES'), # ('des_cbc', 'DES'), # ('aes_128_cbc', 'AES-128'), # ('aes_192_cbc', 'AES-192'), # ('aes_256_cbc', 'AES-256'), # ('rc2_40_cbc', 'RC2-40'), # ) # SIGN_ALG_CHOICES = ( # ('sha1', 'SHA-1'), # ) # MDN_TYPE_CHOICES = ( # ('SYNC', 'Synchronous'), # ('ASYNC', 'Asynchronous'), # ) # DIRECTION_CHOICES = ( # ('IN', _('Inbound')), # ('OUT', _('Outbound')), # ) # STATUS_CHOICES = ( # ('S', _('Success')), # ('E', _('Error')), # ('W', _('Warning')), # ('P', _('Pending')), # ('R', _('Retry')), # ('IP', _('In Process')), # ) # MODE_CHOICES = ( # ('SYNC', _('Synchronous')), # ('ASYNC', _('Asynchronous')), # ) # STATUS_CHOICES = ( # ('S', _('Success')), # ('E', _('Error')), # ('W', _('Warning')), # ) # STATUS_CHOICES = ( # ('S', _('Sent')), # ('R', _('Received')), # ('P', _('Pending')), # ) # def get_certificate_path(instance, filename): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def getorganizations(): # def getpartners(): # def check_odirs(sender, instance, created, **kwargs): # def check_pdirs(sender, instance, created, **kwargs): # def update_dirs(): # class PrivateCertificate(models.Model): # class PublicCertificate(models.Model): # class Organization(models.Model): # class Partner(models.Model): # class Message(models.Model): # class Payload(models.Model): # class Log(models.Model): # class MDN(models.Model): # # Path: pyas2/pyas2init.py # def initialize(): # def initserverlogging(logname): which might include code, classes, or functions. Output only the next line.
old_message = models.Message.objects.filter(
Given snippet: <|code_start|> class Command(BaseCommand): help = _(u'Automatic maintenance for the AS2 server. ' u'Cleans up all the old logs, messages and archived files.') def handle(self, *args, **options): <|code_end|> , continue by predicting the next line. Consider current file imports: from django.core.management.base import BaseCommand from django.utils.translation import ugettext as _ from datetime import timedelta from django.utils import timezone from pyas2 import models from pyas2 import pyas2init import os import glob and context: # Path: pyas2/models.py # DEFAULT_ENTRY = ('', "---------") # CONTENT_TYPE_CHOICES = ( # ('application/EDI-X12', 'application/EDI-X12'), # ('application/EDIFACT', 'application/EDIFACT'), # ('application/edi-consent', 'application/edi-consent'), # ('application/XML', 'application/XML'), # ('text/CSV', 'text/CSV'), # ) # ENCRYPT_ALG_CHOICES = ( # ('des_ede3_cbc', '3DES'), # ('des_cbc', 'DES'), # ('aes_128_cbc', 'AES-128'), # ('aes_192_cbc', 'AES-192'), # ('aes_256_cbc', 'AES-256'), # ('rc2_40_cbc', 'RC2-40'), # ) # SIGN_ALG_CHOICES = ( # ('sha1', 'SHA-1'), # ) # MDN_TYPE_CHOICES = ( # ('SYNC', 'Synchronous'), # ('ASYNC', 'Asynchronous'), # ) # DIRECTION_CHOICES = ( # ('IN', _('Inbound')), # ('OUT', _('Outbound')), # ) # STATUS_CHOICES = ( # ('S', _('Success')), # ('E', _('Error')), # ('W', _('Warning')), # ('P', _('Pending')), # ('R', _('Retry')), # ('IP', _('In Process')), # ) # MODE_CHOICES = ( # ('SYNC', _('Synchronous')), # ('ASYNC', _('Asynchronous')), # ) # STATUS_CHOICES = ( # ('S', _('Success')), # ('E', _('Error')), # ('W', _('Warning')), # ) # STATUS_CHOICES = ( # ('S', _('Sent')), # ('R', _('Received')), # ('P', _('Pending')), # ) # def get_certificate_path(instance, filename): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def __str__(self): # def getorganizations(): # def getpartners(): # def check_odirs(sender, instance, created, **kwargs): # def check_pdirs(sender, instance, created, **kwargs): # def update_dirs(): # class PrivateCertificate(models.Model): # class PublicCertificate(models.Model): # class Organization(models.Model): # class Partner(models.Model): # class Message(models.Model): # class Payload(models.Model): # class Log(models.Model): # class MDN(models.Model): # # Path: pyas2/pyas2init.py # def initialize(): # def initserverlogging(logname): which might include code, classes, or functions. Output only the next line.
pyas2init.logger.info(_(u'Automatic maintenance process started'))
Given snippet: <|code_start|> register = template.Library() @register.simple_tag def get_init(key): <|code_end|> , continue by predicting the next line. Consider current file imports: from django import template from pyas2 import pyas2init and context: # Path: pyas2/pyas2init.py # def initialize(): # def initserverlogging(logname): which might include code, classes, or functions. Output only the next line.
return pyas2init.gsettings.get(key,'')
Given the code snippet: <|code_start|> 'mnist_ceda': 'models/mnist_ceda.pkl', 'mnist_cnn': 'models/mnist_lenet_dropout.pkl', 'cifar_vgg_16': 'models/cifar_vgg_16_dropout.pkl', 'cifar_vgg_32': 'models/cifar_vgg_32_dropout.pkl', 'cifar_vgg_64': 'models/cifar_vgg_64_dropout.pkl', }) PROBA_SAFETY_URL = ( 'https://github.com/matthewwicker/ProbabilisticSafetyforBNNs/raw/master' '/MNIST/concurMNIST2/MNIST_Networks') PROBA_SAFETY_MODEL_PATHS = ml_collections.ConfigDict({ 'mnist_mlp_1_1024': 'VIMODEL_MNIST_1_1024_relu.net.npz', 'mnist_mlp_1_128': 'VIMODEL_MNIST_1_128_relu.net.npz', 'mnist_mlp_1_2048': 'VIMODEL_MNIST_1_2048_relu.net.npz', 'mnist_mlp_1_256': 'VIMODEL_MNIST_1_256_relu.net.npz', 'mnist_mlp_1_4096': 'VIMODEL_MNIST_1_4096_relu.net.npz', 'mnist_mlp_1_512': 'VIMODEL_MNIST_1_512_relu.net.npz', 'mnist_mlp_1_64': 'VIMODEL_MNIST_1_64_relu.net.npz', 'mnist_mlp_2_1024': 'VIMODEL_MNIST_2_1024_relu.net.npz', 'mnist_mlp_2_128': 'VIMODEL_MNIST_2_128_relu.net.npz', 'mnist_mlp_2_256': 'VIMODEL_MNIST_2_256_relu.net.npz', 'mnist_mlp_2_512': 'VIMODEL_MNIST_2_512_relu.net.npz', 'mnist_mlp_2_64': 'VIMODEL_MNIST_2_64_relu.net.npz', }) def _load_pickled_model(root_dir: str, model_name: str) -> ModelParams: model_path = getattr(INTERNAL_MODEL_PATHS, model_name.lower()) if model_path.endswith('mnist_ceda.pkl'): <|code_end|> , generate the next line using the imports in this file: import dataclasses import os import pickle import urllib import jax.numpy as jnp import jax_verify import ml_collections import numpy as np from typing import Any, Optional from jax_verify.extensions.functional_lagrangian import verify_utils from jax_verify.src import utils as jv_utils and context (functions, classes, or occasionally code) from other files: # Path: jax_verify/extensions/functional_lagrangian/verify_utils.py # class AbstractParams(abc.ABC): # class FCParams(AbstractParams): # class ConvParams(AbstractParams): # class SpecType(enum.Enum): # class Distribution(enum.Enum): # class NetworkType(enum.Enum): # class InnerVerifInstance: # def __call__(self, inputs: Tensor) -> Tensor: # def params(self): # def has_bounds(self): # def params(self): # def params(self): # def same_lagrangian_form_pre_post(self) -> bool: # UNCERTAINTY = 'uncertainty' # ADVERSARIAL = 'adversarial' # ADVERSARIAL_SOFTMAX = 'adversarial_softmax' # PROBABILITY_THRESHOLD = 'probability_threshold' # GAUSSIAN = 'gaussian' # BERNOULLI = 'bernoulli' # DETERMINISTIC = 'deterministic' # STOCHASTIC = 'stochastic' # # Path: jax_verify/src/utils.py # def open_file(name, *open_args, root_dir='/tmp/jax_verify', **open_kwargs): # def bind_nonbound_args( # fun: Callable[..., Tensor], # *all_in_args: Union[Bound, Tensor], # **kwargs # ) -> Callable[..., Tensor]: # def tensorbound_fun(*bound_args): # def filter_jaxverify_kwargs(kwargs: Dict[str, Any]) -> Dict[str, Any]: # def simple_propagation(fn): # def wrapper(context, *args, **kwargs): # def batch_value_and_grad(fun, batch_dims, *args, **kwargs): # def nobatch_fun(*nobatch_inps): # def objective_chunk( # obj_shape: Sequence[int], # chunk_index: int, # nb_parallel_nodes: int, # ): # def chunked_bounds( # bound_shape: Tuple[int, ...], # max_parallel_nodes: int, # bound_fn: Callable[[Tensor], Tuple[Tensor, Tensor]], # ) -> Tuple[Tensor, Tensor]: # def bound_chunk(chunk_index: int) -> Tuple[Tensor, Tensor]: . Output only the next line.
with jv_utils.open_file(model_path, 'rb', root_dir=root_dir) as f:
Next line prediction: <|code_start|> ] return params class AttacksTest(parameterized.TestCase): def setUp(self): super().setUp() self.prng_seq = hk.PRNGSequence(1234) self.data_spec = make_data_spec(next(self.prng_seq)) def test_forward_deterministic(self): params = make_params(next(self.prng_seq)) self._check_deterministic_behavior(params) def test_forward_almost_no_randomness(self): params = make_params(next(self.prng_seq), std=1e-8, dropout_rate=1e-8) self._check_deterministic_behavior(params) def test_forward_gaussian(self): params = make_params(next(self.prng_seq), std=1.0) self._check_stochastic_behavior(params) def test_forward_dropout(self): params = make_params(next(self.prng_seq), dropout_rate=0.8) self._check_stochastic_behavior(params) def test_adversarial_integration(self): spec_type = verify_utils.SpecType.ADVERSARIAL params = make_params(next(self.prng_seq), std=0.1, dropout_rate=0.2) <|code_end|> . Use current file imports: (from absl.testing import absltest from absl.testing import parameterized from jax_verify.extensions.functional_lagrangian import attacks from jax_verify.extensions.functional_lagrangian import verify_utils import chex import haiku as hk import jax import jax.numpy as jnp import jax_verify) and context including class names, function names, or small code snippets from other files: # Path: jax_verify/extensions/functional_lagrangian/attacks.py # def sample_truncated_normal( # mean: Tensor, # std: Tensor, # bounds: IntervalBound, # prng_key: PRNGKey # ) -> Tensor: # def sample_dropout( # mean: Tensor, # dropout_rate: float, # prng_key: PRNGKey, # ) -> Tensor: # def make_params_sampling_fn( # params: Union[ModelParams, ModelParamsElided], # ) -> Callable[[PRNGKey], Union[ModelParams, ModelParamsElided]]: # def sample_fn(key: PRNGKey): # def make_forward( # model_params: ModelParams, # num_samples: int, # ) -> Callable[[Tensor, PRNGKey], Tensor]: # def single_forward(inputs, prng_key): # def multiple_forward(inputs, prng_key): # def _run_attack( # max_objective_fn: Callable[[Tensor, PRNGKey], Tensor], # projection_fn: Callable[[Tensor], Tensor], # x_init: Tensor, # prng_key: PRNGKey, # num_steps: int, # learning_rate: float, # ): # def body_fn(it, inputs): # def adversarial_attack( # params: ModelParams, # data_spec: DataSpec, # spec_type: verify_utils.SpecType, # key: PRNGKey, # num_steps: int, # learning_rate: float, # num_samples: int = 1, # ) -> float: # def max_objective_fn_uncertainty(x, prng_key): # def max_objective_fn_adversarial(x, prng_key): # def max_objective_fn_adversarial_softmax(x, prng_key): # # Path: jax_verify/extensions/functional_lagrangian/verify_utils.py # class AbstractParams(abc.ABC): # class FCParams(AbstractParams): # class ConvParams(AbstractParams): # class SpecType(enum.Enum): # class Distribution(enum.Enum): # class NetworkType(enum.Enum): # class InnerVerifInstance: # def __call__(self, inputs: Tensor) -> Tensor: # def params(self): # def has_bounds(self): # def params(self): # def params(self): # def same_lagrangian_form_pre_post(self) -> bool: # UNCERTAINTY = 'uncertainty' # ADVERSARIAL = 'adversarial' # ADVERSARIAL_SOFTMAX = 'adversarial_softmax' # PROBABILITY_THRESHOLD = 'probability_threshold' # GAUSSIAN = 'gaussian' # BERNOULLI = 'bernoulli' # DETERMINISTIC = 'deterministic' # STOCHASTIC = 'stochastic' . Output only the next line.
attacks.adversarial_attack(
Given the code snippet: <|code_start|># coding=utf-8 # Copyright 2021 DeepMind Technologies Limited. # # 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 # # http://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. """Attacks test.""" EPS = 0.1 def make_data_spec(prng_key): """Create data specification from config.""" x = jax.random.normal(prng_key, [8]) input_bounds = (x - EPS, x + EPS) <|code_end|> , generate the next line using the imports in this file: from absl.testing import absltest from absl.testing import parameterized from jax_verify.extensions.functional_lagrangian import attacks from jax_verify.extensions.functional_lagrangian import verify_utils import chex import haiku as hk import jax import jax.numpy as jnp import jax_verify and context (functions, classes, or occasionally code) from other files: # Path: jax_verify/extensions/functional_lagrangian/attacks.py # def sample_truncated_normal( # mean: Tensor, # std: Tensor, # bounds: IntervalBound, # prng_key: PRNGKey # ) -> Tensor: # def sample_dropout( # mean: Tensor, # dropout_rate: float, # prng_key: PRNGKey, # ) -> Tensor: # def make_params_sampling_fn( # params: Union[ModelParams, ModelParamsElided], # ) -> Callable[[PRNGKey], Union[ModelParams, ModelParamsElided]]: # def sample_fn(key: PRNGKey): # def make_forward( # model_params: ModelParams, # num_samples: int, # ) -> Callable[[Tensor, PRNGKey], Tensor]: # def single_forward(inputs, prng_key): # def multiple_forward(inputs, prng_key): # def _run_attack( # max_objective_fn: Callable[[Tensor, PRNGKey], Tensor], # projection_fn: Callable[[Tensor], Tensor], # x_init: Tensor, # prng_key: PRNGKey, # num_steps: int, # learning_rate: float, # ): # def body_fn(it, inputs): # def adversarial_attack( # params: ModelParams, # data_spec: DataSpec, # spec_type: verify_utils.SpecType, # key: PRNGKey, # num_steps: int, # learning_rate: float, # num_samples: int = 1, # ) -> float: # def max_objective_fn_uncertainty(x, prng_key): # def max_objective_fn_adversarial(x, prng_key): # def max_objective_fn_adversarial_softmax(x, prng_key): # # Path: jax_verify/extensions/functional_lagrangian/verify_utils.py # class AbstractParams(abc.ABC): # class FCParams(AbstractParams): # class ConvParams(AbstractParams): # class SpecType(enum.Enum): # class Distribution(enum.Enum): # class NetworkType(enum.Enum): # class InnerVerifInstance: # def __call__(self, inputs: Tensor) -> Tensor: # def params(self): # def has_bounds(self): # def params(self): # def params(self): # def same_lagrangian_form_pre_post(self) -> bool: # UNCERTAINTY = 'uncertainty' # ADVERSARIAL = 'adversarial' # ADVERSARIAL_SOFTMAX = 'adversarial_softmax' # PROBABILITY_THRESHOLD = 'probability_threshold' # GAUSSIAN = 'gaussian' # BERNOULLI = 'bernoulli' # DETERMINISTIC = 'deterministic' # STOCHASTIC = 'stochastic' . Output only the next line.
return verify_utils.DataSpec(
Given the code snippet: <|code_start|># coding=utf-8 # Copyright 2021 DeepMind Technologies Limited. # # 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 # # http://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. # Lint as: python3 """Routines to solve the subproblem during verification.""" _EPS = 1e-10 CvxpyConstraint = cp.constraints.constraint.Constraint Tensor = np.ndarray <|code_end|> , generate the next line using the imports in this file: from typing import Dict, List, Optional, Tuple, Union from absl import logging from cvxpy.reductions.solvers.defines import INSTALLED_MI_SOLVERS as MIP_SOLVERS from jax_verify.src.mip_solver import relaxation import cvxpy as cp import jax import jax.numpy as jnp import numpy as np and context (functions, classes, or occasionally code) from other files: # Path: jax_verify/src/mip_solver/relaxation.py # class RelaxVariable(bound_propagation.Bound): # class OptRelaxVariable(RelaxVariable): # class BinaryVariable(): # class MIPActivationConstraint: # class LinearConstraint: # class RelaxActivationConstraint: # class RelaxationSolver(metaclass=abc.ABCMeta): # class MIPSolver(RelaxationSolver): # class RelaxationTransform(bound_propagation.GraphTransform[RelaxVariable]): # class OptimizedRelaxationTransform( # bound_propagation.GraphTransform[OptRelaxVariable]): # def __init__(self, idx: bound_propagation.Index, base_bound): # def set_constraints(self, constraints): # def lower(self): # def upper(self): # def __init__(self, base_relax_variable, optimize_transform): # def shape(self): # def lower(self): # def upper(self): # def _optimized_bounds(self): # def __init__(self, idx, shape): # def __init__(self, outvar, invar, binvar, mask, binscale, scale, bias, sense): # def encode_into_solver(self, solver: 'MIPSolver', index: int): # def __init__(self, vars_and_coeffs, bias, sense): # def bias(self, index: int): # def vars_and_coeffs(self, index: int): # def encode_into_solver(self, solver: 'RelaxationSolver', index: int): # def __init__(self, outvar, invar, mask, scale, bias, sense): # def encode_into_solver(self, solver: 'RelaxationSolver', index: int): # def maybe_create_solver_variable( # self, # var: RelaxVariable, # index: int): # def _create_solver_relax_variable( # self, # var: RelaxVariable, # index: int): # def _variable_already_created( # self, # var: Union[RelaxVariable, BinaryVariable], # ) -> bool: # def create_linear_solver_constraint( # self, # constraint: LinearConstraint, # index: int): # def create_activation_solver_constraint( # self, # constraint: RelaxActivationConstraint, # act_index: int, # slope: float, # bias: float): # def minimize_objective( # self, # var_name: str, # objective: Tensor, # objective_bias: float, # time_limit_millis: Optional[int], # ) -> Tuple[float, Dict[str, Tensor], bool]: # def maybe_create_solver_variable( # self, # var: Union[RelaxVariable, BinaryVariable], # index: int): # def _create_solver_bool_variable( # self, # var: BinaryVariable, # index: int): # def create_mip_activation_solver_constraint( # self, # constraint: MIPActivationConstraint, # act_index: int, # binslope: float, # slope: float, # bias: float): # def encode_relaxation( # solver_ctor: Callable[[], RelaxationSolver], # env: Dict[jax.core.Var, Union[RelaxVariable, Tensor]], # index: int, # ) -> RelaxationSolver: # def solve_relaxation( # solver_ctor: Callable[[], RelaxationSolver], # objective: Tensor, # objective_bias: float, # variable_opt: RelaxVariable, # env: Dict[jax.core.Var, Union[RelaxVariable, Tensor]], # index: int, # time_limit_millis: Optional[int] = None, # ) -> Tuple[float, Dict[str, Tensor], bool]: # def _get_linear(primitive, outval, *eqn_invars, **params): # def funx(x): # def fungrad(i, args): # def _get_relu_relax(lower, upper): # def _relax_input( # index: bound_propagation.Index, in_bounds: bound_propagation.Bound, # ) -> RelaxVariable: # def _relax_primitive( # index: bound_propagation.Index, out_bounds: bound_propagation.Bound, # primitive: jax.core.Primitive, # *args, use_mip: bool = False, **kwargs # ) -> RelaxVariable: # def __init__( # self, # boundprop_transform: bound_propagation.BoundTransform, # use_mip: bool = False, # ): # def input_transform(self, context, lower_bound, upper_bound): # def primitive_transform(self, context, primitive, *args, **params): # def __init__( # self, # transform: bound_propagation.GraphTransform[RelaxVariable], # solver_ctor: Callable[[], RelaxationSolver], # time_limit_millis: Optional[int] = None): # def tight_bounds(self, variable: RelaxVariable) -> ibp.IntervalBound: # def input_transform( # self, # context: bound_propagation.TransformContext, # lower_bound: Tensor, # upper_bound: Tensor, # ) -> RelaxVariable: # def primitive_transform( # self, # context: bound_propagation.TransformContext, # primitive: jax.core.Primitive, # *args: Union[RelaxVariable, Tensor], # **params, # ) -> RelaxVariable: . Output only the next line.
Variable = Union[relaxation.RelaxVariable,
Predict the next line after this snippet: <|code_start|> def make_toy_verif_instance(seed=None, label=None, target_label=None, nn='mlp'): """Mainly used for unit testing.""" key = jax.random.PRNGKey(0) if seed is None else jax.random.PRNGKey(seed) if nn == 'mlp': layer_sizes = '5, 5, 5' layer_sizes = np.fromstring(layer_sizes, dtype=int, sep=',') params = make_mlp_params(layer_sizes, key) inp_shape = (1, layer_sizes[0]) else: if nn == 'cnn_simple': pad = 'VALID' # Input and filter size match -> filter is applied at just one location. else: pad = 'SAME' # Input is padded on right/bottom to form 3x3 input layer_sizes = [(1, 2, 2, 1), { 'n_h': 2, 'n_w': 2, 'n_cout': 2, 'padding': pad, 'stride': 1, 'n_cin': 1 }, 3] inp_shape = layer_sizes[0] params = make_cnn_params(layer_sizes, key) <|code_end|> using the current file's imports: import jax import jax.numpy as jnp import jax.random as random import numpy as np from jax_verify.extensions.sdp_verify import utils and any relevant context from other files: # Path: jax_verify/extensions/sdp_verify/utils.py # class SdpDualVerifInstance(_SdpDualVerifInstance): # class VerifInstanceTypes(enum.Enum): # class DualVarTypes(enum.Enum): # def mlp_layer_sizes(params): # def nn_layer_sizes(params): # def layer_sizes_from_bounds(bounds): # def predict_mlp(params, inputs): # def fwd(inputs, layer_params): # def predict_cnn(params, inputs, include_preactivations=False): # def get_network_activs(params, x): # def get_layer_params(fun_to_extract, example_input): # def _get_const_input_arg(eqn): # def boundprop(params, bounds_in): # def init_bound(x, epsilon, input_bounds=(0., 1.), add_batch_dim=True): # def ibp_bound_elided(verif_instance): # def ibp_bound_nonelided(verif_instance): # def make_relu_robust_verif_instance( # params, bounds=None, target_label=1, label=2, input_bounds=None): # def make_relu_robust_verif_instance_elided( # params, bounds=None, input_bounds=None): # def output_size_and_verif_type(params, bounds): # def elide_params(params, label, target_label, op_size): # def preprocess_cifar(image, inception_preprocess=False, perturbation=False): # def preprocessed_cifar_eps_and_input_bounds( # shape=(32, 32, 3), epsilon=2/255, inception_preprocess=False): # def adv_objective(model_fn, x, label, target_label): # def fgsm_single(model_fn, x, label, target_label, epsilon, num_steps, # step_size, input_bounds=(0., 1.)): # def untargeted_margin_loss(logits, labels): # def pgd_default(model_fn, x, label, epsilon, num_steps, step_size, # input_bounds=(0., 1.)): # def pgd(adv_loss, x_init, epsilon, num_steps, step_size, input_bounds=(0., 1.)): # def scale_by_variable_opt(multipliers): # def init_fn(params): # def update_fn(updates, _, params=None): # def flatten(pytree, backend=np): # def unflatten_like(a, pytree): # def structure_like(tree1, tree2): # MLP_ELIDED = 'mlp_elided' # CNN_ELIDED = 'cnn_elided' # EQUALITY = 'equality' # INEQUALITY = 'inequality' . Output only the next line.
bounds = utils.boundprop(
Next line prediction: <|code_start|># coding=utf-8 # Copyright 2021 DeepMind Technologies Limited. # # 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 # # http://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. # Lint as: python3 """Tests for cvxpy_verify.py.""" NO_MIP_SOLVERS_MESSAGE = 'No mixed-integer solver is installed.' class CvxpyTest(parameterized.TestCase): @unittest.skipUnless(MIP_SOLVERS, NO_MIP_SOLVERS_MESSAGE) def test_mip_status(self): """Test toy MIP is solved optimally by cvxpy.""" for seed in range(10): verif_instance = test_utils.make_toy_verif_instance(seed) <|code_end|> . Use current file imports: (import unittest import jax.numpy as jnp from absl.testing import absltest from absl.testing import parameterized from cvxpy.reductions.solvers.defines import INSTALLED_MI_SOLVERS as MIP_SOLVERS from jax_verify.extensions.sdp_verify import cvxpy_verify from jax_verify.extensions.sdp_verify import utils from jax_verify.tests.sdp_verify import test_utils) and context including class names, function names, or small code snippets from other files: # Path: jax_verify/extensions/sdp_verify/cvxpy_verify.py # def solve_mip_mlp_elided(verif_instance): # def solve_lp_primal_elided(verif_instance): # def solve_sdp_mlp_elided(verif_instance, solver_name='SCS', verbose=False, # check_feasibility=False, feasibility_margin=0.0): # def _slice(i): # def p_slice(i, j): # def _violation(arr): # def _violation_leq(arr1, arr2): # def check_sdp_bounds_numpy(P, verif_instance, input_bounds=(0, 1)): # P = cp.Variable((1 + sum(layer_sizes), 1 + sum(layer_sizes))) # # Path: jax_verify/extensions/sdp_verify/utils.py # class SdpDualVerifInstance(_SdpDualVerifInstance): # class VerifInstanceTypes(enum.Enum): # class DualVarTypes(enum.Enum): # def mlp_layer_sizes(params): # def nn_layer_sizes(params): # def layer_sizes_from_bounds(bounds): # def predict_mlp(params, inputs): # def fwd(inputs, layer_params): # def predict_cnn(params, inputs, include_preactivations=False): # def get_network_activs(params, x): # def get_layer_params(fun_to_extract, example_input): # def _get_const_input_arg(eqn): # def boundprop(params, bounds_in): # def init_bound(x, epsilon, input_bounds=(0., 1.), add_batch_dim=True): # def ibp_bound_elided(verif_instance): # def ibp_bound_nonelided(verif_instance): # def make_relu_robust_verif_instance( # params, bounds=None, target_label=1, label=2, input_bounds=None): # def make_relu_robust_verif_instance_elided( # params, bounds=None, input_bounds=None): # def output_size_and_verif_type(params, bounds): # def elide_params(params, label, target_label, op_size): # def preprocess_cifar(image, inception_preprocess=False, perturbation=False): # def preprocessed_cifar_eps_and_input_bounds( # shape=(32, 32, 3), epsilon=2/255, inception_preprocess=False): # def adv_objective(model_fn, x, label, target_label): # def fgsm_single(model_fn, x, label, target_label, epsilon, num_steps, # step_size, input_bounds=(0., 1.)): # def untargeted_margin_loss(logits, labels): # def pgd_default(model_fn, x, label, epsilon, num_steps, step_size, # input_bounds=(0., 1.)): # def pgd(adv_loss, x_init, epsilon, num_steps, step_size, input_bounds=(0., 1.)): # def scale_by_variable_opt(multipliers): # def init_fn(params): # def update_fn(updates, _, params=None): # def flatten(pytree, backend=np): # def unflatten_like(a, pytree): # def structure_like(tree1, tree2): # MLP_ELIDED = 'mlp_elided' # CNN_ELIDED = 'cnn_elided' # EQUALITY = 'equality' # INEQUALITY = 'inequality' # # Path: jax_verify/tests/sdp_verify/test_utils.py # def _init_fc_layer(key, n_in, n_out): # def _init_conv_layer(key, n_h, n_w, n_cout, n_cin): # def make_mlp_params(layer_sizes, key): # def make_cnn_params(layer_sizes, key): # def make_toy_verif_instance(seed=None, label=None, target_label=None, nn='mlp'): # def make_mlp_layer_from_conv_layer(layer_params, input_bounds): # def make_mlp_verif_instance_from_cnn(verif_instance): # W = random.normal(k1, (n_in, n_out))/ n_in # W = random.normal(k1, (n_h, n_w, n_cin, n_cout)) . Output only the next line.
val, info = cvxpy_verify.solve_mip_mlp_elided(verif_instance)
Based on the snippet: <|code_start|># Lint as: python3 """Tests for cvxpy_verify.py.""" NO_MIP_SOLVERS_MESSAGE = 'No mixed-integer solver is installed.' class CvxpyTest(parameterized.TestCase): @unittest.skipUnless(MIP_SOLVERS, NO_MIP_SOLVERS_MESSAGE) def test_mip_status(self): """Test toy MIP is solved optimally by cvxpy.""" for seed in range(10): verif_instance = test_utils.make_toy_verif_instance(seed) val, info = cvxpy_verify.solve_mip_mlp_elided(verif_instance) status = info['problem'].status assert val is not None assert status in ('optimal', 'optimal_inaccurate'), f'Status is {status}.' def test_sdp_status(self): """Test toy SDP is solved optimally by cvxpy.""" for seed in range(10): verif_instance = test_utils.make_toy_verif_instance(seed) val, info = cvxpy_verify.solve_sdp_mlp_elided(verif_instance) status = info['problem'].status assert val is not None assert status in ('optimal', 'optimal_inaccurate'), f'Status is {status}.' def _fgsm_example_and_bound(params, target_label, label): <|code_end|> , predict the immediate next line with the help of imports: import unittest import jax.numpy as jnp from absl.testing import absltest from absl.testing import parameterized from cvxpy.reductions.solvers.defines import INSTALLED_MI_SOLVERS as MIP_SOLVERS from jax_verify.extensions.sdp_verify import cvxpy_verify from jax_verify.extensions.sdp_verify import utils from jax_verify.tests.sdp_verify import test_utils and context (classes, functions, sometimes code) from other files: # Path: jax_verify/extensions/sdp_verify/cvxpy_verify.py # def solve_mip_mlp_elided(verif_instance): # def solve_lp_primal_elided(verif_instance): # def solve_sdp_mlp_elided(verif_instance, solver_name='SCS', verbose=False, # check_feasibility=False, feasibility_margin=0.0): # def _slice(i): # def p_slice(i, j): # def _violation(arr): # def _violation_leq(arr1, arr2): # def check_sdp_bounds_numpy(P, verif_instance, input_bounds=(0, 1)): # P = cp.Variable((1 + sum(layer_sizes), 1 + sum(layer_sizes))) # # Path: jax_verify/extensions/sdp_verify/utils.py # class SdpDualVerifInstance(_SdpDualVerifInstance): # class VerifInstanceTypes(enum.Enum): # class DualVarTypes(enum.Enum): # def mlp_layer_sizes(params): # def nn_layer_sizes(params): # def layer_sizes_from_bounds(bounds): # def predict_mlp(params, inputs): # def fwd(inputs, layer_params): # def predict_cnn(params, inputs, include_preactivations=False): # def get_network_activs(params, x): # def get_layer_params(fun_to_extract, example_input): # def _get_const_input_arg(eqn): # def boundprop(params, bounds_in): # def init_bound(x, epsilon, input_bounds=(0., 1.), add_batch_dim=True): # def ibp_bound_elided(verif_instance): # def ibp_bound_nonelided(verif_instance): # def make_relu_robust_verif_instance( # params, bounds=None, target_label=1, label=2, input_bounds=None): # def make_relu_robust_verif_instance_elided( # params, bounds=None, input_bounds=None): # def output_size_and_verif_type(params, bounds): # def elide_params(params, label, target_label, op_size): # def preprocess_cifar(image, inception_preprocess=False, perturbation=False): # def preprocessed_cifar_eps_and_input_bounds( # shape=(32, 32, 3), epsilon=2/255, inception_preprocess=False): # def adv_objective(model_fn, x, label, target_label): # def fgsm_single(model_fn, x, label, target_label, epsilon, num_steps, # step_size, input_bounds=(0., 1.)): # def untargeted_margin_loss(logits, labels): # def pgd_default(model_fn, x, label, epsilon, num_steps, step_size, # input_bounds=(0., 1.)): # def pgd(adv_loss, x_init, epsilon, num_steps, step_size, input_bounds=(0., 1.)): # def scale_by_variable_opt(multipliers): # def init_fn(params): # def update_fn(updates, _, params=None): # def flatten(pytree, backend=np): # def unflatten_like(a, pytree): # def structure_like(tree1, tree2): # MLP_ELIDED = 'mlp_elided' # CNN_ELIDED = 'cnn_elided' # EQUALITY = 'equality' # INEQUALITY = 'inequality' # # Path: jax_verify/tests/sdp_verify/test_utils.py # def _init_fc_layer(key, n_in, n_out): # def _init_conv_layer(key, n_h, n_w, n_cout, n_cin): # def make_mlp_params(layer_sizes, key): # def make_cnn_params(layer_sizes, key): # def make_toy_verif_instance(seed=None, label=None, target_label=None, nn='mlp'): # def make_mlp_layer_from_conv_layer(layer_params, input_bounds): # def make_mlp_verif_instance_from_cnn(verif_instance): # W = random.normal(k1, (n_in, n_out))/ n_in # W = random.normal(k1, (n_h, n_w, n_cin, n_cout)) . Output only the next line.
model_fn = lambda x: utils.predict_mlp(params, x)
Next line prediction: <|code_start|># coding=utf-8 # Copyright 2021 DeepMind Technologies Limited. # # 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 # # http://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. # Lint as: python3 """Tests for cvxpy_verify.py.""" NO_MIP_SOLVERS_MESSAGE = 'No mixed-integer solver is installed.' class CvxpyTest(parameterized.TestCase): @unittest.skipUnless(MIP_SOLVERS, NO_MIP_SOLVERS_MESSAGE) def test_mip_status(self): """Test toy MIP is solved optimally by cvxpy.""" for seed in range(10): <|code_end|> . Use current file imports: (import unittest import jax.numpy as jnp from absl.testing import absltest from absl.testing import parameterized from cvxpy.reductions.solvers.defines import INSTALLED_MI_SOLVERS as MIP_SOLVERS from jax_verify.extensions.sdp_verify import cvxpy_verify from jax_verify.extensions.sdp_verify import utils from jax_verify.tests.sdp_verify import test_utils) and context including class names, function names, or small code snippets from other files: # Path: jax_verify/extensions/sdp_verify/cvxpy_verify.py # def solve_mip_mlp_elided(verif_instance): # def solve_lp_primal_elided(verif_instance): # def solve_sdp_mlp_elided(verif_instance, solver_name='SCS', verbose=False, # check_feasibility=False, feasibility_margin=0.0): # def _slice(i): # def p_slice(i, j): # def _violation(arr): # def _violation_leq(arr1, arr2): # def check_sdp_bounds_numpy(P, verif_instance, input_bounds=(0, 1)): # P = cp.Variable((1 + sum(layer_sizes), 1 + sum(layer_sizes))) # # Path: jax_verify/extensions/sdp_verify/utils.py # class SdpDualVerifInstance(_SdpDualVerifInstance): # class VerifInstanceTypes(enum.Enum): # class DualVarTypes(enum.Enum): # def mlp_layer_sizes(params): # def nn_layer_sizes(params): # def layer_sizes_from_bounds(bounds): # def predict_mlp(params, inputs): # def fwd(inputs, layer_params): # def predict_cnn(params, inputs, include_preactivations=False): # def get_network_activs(params, x): # def get_layer_params(fun_to_extract, example_input): # def _get_const_input_arg(eqn): # def boundprop(params, bounds_in): # def init_bound(x, epsilon, input_bounds=(0., 1.), add_batch_dim=True): # def ibp_bound_elided(verif_instance): # def ibp_bound_nonelided(verif_instance): # def make_relu_robust_verif_instance( # params, bounds=None, target_label=1, label=2, input_bounds=None): # def make_relu_robust_verif_instance_elided( # params, bounds=None, input_bounds=None): # def output_size_and_verif_type(params, bounds): # def elide_params(params, label, target_label, op_size): # def preprocess_cifar(image, inception_preprocess=False, perturbation=False): # def preprocessed_cifar_eps_and_input_bounds( # shape=(32, 32, 3), epsilon=2/255, inception_preprocess=False): # def adv_objective(model_fn, x, label, target_label): # def fgsm_single(model_fn, x, label, target_label, epsilon, num_steps, # step_size, input_bounds=(0., 1.)): # def untargeted_margin_loss(logits, labels): # def pgd_default(model_fn, x, label, epsilon, num_steps, step_size, # input_bounds=(0., 1.)): # def pgd(adv_loss, x_init, epsilon, num_steps, step_size, input_bounds=(0., 1.)): # def scale_by_variable_opt(multipliers): # def init_fn(params): # def update_fn(updates, _, params=None): # def flatten(pytree, backend=np): # def unflatten_like(a, pytree): # def structure_like(tree1, tree2): # MLP_ELIDED = 'mlp_elided' # CNN_ELIDED = 'cnn_elided' # EQUALITY = 'equality' # INEQUALITY = 'inequality' # # Path: jax_verify/tests/sdp_verify/test_utils.py # def _init_fc_layer(key, n_in, n_out): # def _init_conv_layer(key, n_h, n_w, n_cout, n_cin): # def make_mlp_params(layer_sizes, key): # def make_cnn_params(layer_sizes, key): # def make_toy_verif_instance(seed=None, label=None, target_label=None, nn='mlp'): # def make_mlp_layer_from_conv_layer(layer_params, input_bounds): # def make_mlp_verif_instance_from_cnn(verif_instance): # W = random.normal(k1, (n_in, n_out))/ n_in # W = random.normal(k1, (n_h, n_w, n_cin, n_cout)) . Output only the next line.
verif_instance = test_utils.make_toy_verif_instance(seed)
Given the code snippet: <|code_start|> tight_input_bounds = jax_verify.IntervalBound(z, z) fun_to_prop = functools.partial(model.apply, params) tight_output_bounds = jax_verify.interval_bound_propagation( fun_to_prop, tight_input_bounds) model_eval = model.apply(params, z) # Because the input lower bound is equal to the input upper bound, the value # of the output bounds should be the same and correspond to the value of the # forward pass. self.assertAlmostEqual(tight_output_bounds.lower.tolist(), tight_output_bounds.upper.tolist()) self.assertAlmostEqual(tight_output_bounds.lower.tolist(), model_eval.tolist()) @parameterized.named_parameters( ('Sequential', sequential_model), ('Residual', residual_model), ('ResidualAll', residual_model_intermediate), ('1elt_list', single_element_list_model), ('dict_output', dict_output_model) ) def test_matching_output_structure(self, model): def _check_matching_structures(output_tree, bound_tree): """Replace all bounds/arrays with True, then compare pytrees.""" output_struct = tree.traverse( lambda x: True if isinstance(x, jnp.ndarray) else None, output_tree) bound_struct = tree.traverse( <|code_end|> , generate the next line using the imports in this file: import functools import chex import haiku as hk import jax import jax.numpy as jnp import jax_verify import tree from absl.testing import absltest from absl.testing import parameterized from jax_verify.src import bound_propagation and context (functions, classes, or occasionally code) from other files: # Path: jax_verify/src/bound_propagation.py # def bound_propagation( # prop_alg: PropagationAlgorithm[Repr], # function: Callable[..., Nest[Tensor]], # *bounds: Nest[GraphInput], # graph_simplifier=synthetic_primitives.default_simplifier, # ) -> Tuple[ # Nest[Union[Repr, Tensor]], # Dict[jax.core.Var, Union[Repr, Tensor, Bound]]]: # """Performs Bound Propagation on the model implemented by `function`. # # Args: # prop_alg: Algorithm specifying how to traverse the graph and how to # transform each node. # function: Pure function inputs -> outputs. If the function to propagate # through has a more complex signature, the use of `functools.partial` can # solve that problem. # *bounds: Nest of `IntervalBound` objects containing the lower and upper # bounds on all the inputs, or `Tensor`s containing known inputs directly. # graph_simplifier: Function transforming the JaxPR graph into a simpler # graph. Default value is a function identifying specific activation # functions, followed by grouping of linear sequences and quadratic forms. # Returns: # bounds: Bounds over all the outputs of the function, with the same structure # as the output of `function` # env: Mapping from the node of the computations to their representation. # """ # # Replace all the jittable bounds by standard bound object. # bounds = unjit_inputs(*bounds) # # # Parse the computation graph. # placeholder_inputs = jax.tree_util.tree_map( # lambda b: b.lower if isinstance(b, Bound) else b, # bounds) # jaxpr_maker = jax.make_jaxpr(function) # parsed = jaxpr_maker(*placeholder_inputs) # output_shapes = jax.eval_shape(function, *placeholder_inputs) # # flat_is_bound, _ = jax.tree_util.tree_flatten( # jax.tree_util.tree_map(lambda b: isinstance(b, Bound), bounds)) # inp_is_bound = {var: is_bound # for var, is_bound in zip(parsed.jaxpr.invars, flat_is_bound)} # simplified_graph = synthetic_primitives.simplify_graph( # graph_simplifier, parsed.jaxpr, inp_is_bound) # graph = PropagationGraph(simplified_graph, parsed.literals) # # outvals, env = prop_alg.propagate(graph, bounds) # # # Make outvals into the same tree structure than the output of the function. # tree_structure = jax.tree_util.tree_structure(output_shapes) # outvals = jax.tree_util.tree_unflatten(tree_structure, outvals) # # return outvals, env . Output only the next line.
lambda x: True if isinstance(x, bound_propagation.Bound) else None,
Here is a snippet: <|code_start|> ConfigDict = ml_collections.ConfigDict DataSpec = verify_utils.DataSpec IntervalBound = jax_verify.IntervalBound SpecType = verify_utils.SpecType Tensor = jnp.array LayerParams = verify_utils.LayerParams ModelParams = verify_utils.ModelParams ModelParamsElided = verify_utils.ModelParamsElided DATA_PATH = ml_collections.ConfigDict({ 'emnist_CEDA': 'emnist_CEDA.pkl', 'mnist': 'mnist', 'cifar10': 'cifar10', 'emnist': 'emnist', 'cifar100': 'cifar100', }) def load_dataset( root_dir: str, dataset: str, ) -> Tuple[Sequence[np.ndarray], Sequence[np.ndarray]]: """Loads the MNIST/CIFAR/EMNIST test set examples, saved as numpy arrays.""" data_path = DATA_PATH.get(dataset) if dataset == 'emnist_CEDA': <|code_end|> . Write the next line using the current file imports: import os import pickle import jax.numpy as jnp import jax_verify import ml_collections import numpy as np from typing import Sequence, Tuple from jax_verify.extensions.functional_lagrangian import verify_utils from jax_verify.extensions.sdp_verify import utils as sdp_utils from jax_verify.src import utils as jv_utils and context from other files: # Path: jax_verify/extensions/functional_lagrangian/verify_utils.py # class AbstractParams(abc.ABC): # class FCParams(AbstractParams): # class ConvParams(AbstractParams): # class SpecType(enum.Enum): # class Distribution(enum.Enum): # class NetworkType(enum.Enum): # class InnerVerifInstance: # def __call__(self, inputs: Tensor) -> Tensor: # def params(self): # def has_bounds(self): # def params(self): # def params(self): # def same_lagrangian_form_pre_post(self) -> bool: # UNCERTAINTY = 'uncertainty' # ADVERSARIAL = 'adversarial' # ADVERSARIAL_SOFTMAX = 'adversarial_softmax' # PROBABILITY_THRESHOLD = 'probability_threshold' # GAUSSIAN = 'gaussian' # BERNOULLI = 'bernoulli' # DETERMINISTIC = 'deterministic' # STOCHASTIC = 'stochastic' # # Path: jax_verify/extensions/sdp_verify/utils.py # class SdpDualVerifInstance(_SdpDualVerifInstance): # class VerifInstanceTypes(enum.Enum): # class DualVarTypes(enum.Enum): # def mlp_layer_sizes(params): # def nn_layer_sizes(params): # def layer_sizes_from_bounds(bounds): # def predict_mlp(params, inputs): # def fwd(inputs, layer_params): # def predict_cnn(params, inputs, include_preactivations=False): # def get_network_activs(params, x): # def get_layer_params(fun_to_extract, example_input): # def _get_const_input_arg(eqn): # def boundprop(params, bounds_in): # def init_bound(x, epsilon, input_bounds=(0., 1.), add_batch_dim=True): # def ibp_bound_elided(verif_instance): # def ibp_bound_nonelided(verif_instance): # def make_relu_robust_verif_instance( # params, bounds=None, target_label=1, label=2, input_bounds=None): # def make_relu_robust_verif_instance_elided( # params, bounds=None, input_bounds=None): # def output_size_and_verif_type(params, bounds): # def elide_params(params, label, target_label, op_size): # def preprocess_cifar(image, inception_preprocess=False, perturbation=False): # def preprocessed_cifar_eps_and_input_bounds( # shape=(32, 32, 3), epsilon=2/255, inception_preprocess=False): # def adv_objective(model_fn, x, label, target_label): # def fgsm_single(model_fn, x, label, target_label, epsilon, num_steps, # step_size, input_bounds=(0., 1.)): # def untargeted_margin_loss(logits, labels): # def pgd_default(model_fn, x, label, epsilon, num_steps, step_size, # input_bounds=(0., 1.)): # def pgd(adv_loss, x_init, epsilon, num_steps, step_size, input_bounds=(0., 1.)): # def scale_by_variable_opt(multipliers): # def init_fn(params): # def update_fn(updates, _, params=None): # def flatten(pytree, backend=np): # def unflatten_like(a, pytree): # def structure_like(tree1, tree2): # MLP_ELIDED = 'mlp_elided' # CNN_ELIDED = 'cnn_elided' # EQUALITY = 'equality' # INEQUALITY = 'inequality' # # Path: jax_verify/src/utils.py # def open_file(name, *open_args, root_dir='/tmp/jax_verify', **open_kwargs): # def bind_nonbound_args( # fun: Callable[..., Tensor], # *all_in_args: Union[Bound, Tensor], # **kwargs # ) -> Callable[..., Tensor]: # def tensorbound_fun(*bound_args): # def filter_jaxverify_kwargs(kwargs: Dict[str, Any]) -> Dict[str, Any]: # def simple_propagation(fn): # def wrapper(context, *args, **kwargs): # def batch_value_and_grad(fun, batch_dims, *args, **kwargs): # def nobatch_fun(*nobatch_inps): # def objective_chunk( # obj_shape: Sequence[int], # chunk_index: int, # nb_parallel_nodes: int, # ): # def chunked_bounds( # bound_shape: Tuple[int, ...], # max_parallel_nodes: int, # bound_fn: Callable[[Tensor], Tuple[Tensor, Tensor]], # ) -> Tuple[Tensor, Tensor]: # def bound_chunk(chunk_index: int) -> Tuple[Tensor, Tensor]: , which may include functions, classes, or code. Output only the next line.
with jv_utils.open_file(data_path, 'rb', root_dir=root_dir) as f:
Given snippet: <|code_start|># Lint as: python3 """Tests for cvxpy_verify.py.""" class ParamExtractionTest(parameterized.TestCase): """Test the functions extracting network parameters from functions.""" def check_fun_extract(self, fun_to_extract, example_inputs): extracted_params = utils.get_layer_params(fun_to_extract, example_inputs) eval_original = fun_to_extract(example_inputs) eval_extracted = utils.predict_cnn(extracted_params, example_inputs) self.assertAlmostEqual(jnp.abs(eval_original - eval_extracted).max(), 0.0) def test_cnn_extract(self): """Test that weights from a CNN can be extracted.""" key = random.PRNGKey(0) k1, k2 = random.split(key) input_sizes = (1, 2, 2, 1) layer_sizes = [input_sizes, { 'n_h': 2, 'n_w': 2, 'n_cout': 2, 'padding': 'VALID', 'stride': 1, 'n_cin': 1 }, 3] <|code_end|> , continue by predicting the next line. Consider current file imports: import functools import jax.numpy as jnp import jax.random as random from absl.testing import absltest from absl.testing import parameterized from jax_verify.extensions.sdp_verify import utils from jax_verify.tests.sdp_verify import test_utils and context: # Path: jax_verify/extensions/sdp_verify/utils.py # class SdpDualVerifInstance(_SdpDualVerifInstance): # class VerifInstanceTypes(enum.Enum): # class DualVarTypes(enum.Enum): # def mlp_layer_sizes(params): # def nn_layer_sizes(params): # def layer_sizes_from_bounds(bounds): # def predict_mlp(params, inputs): # def fwd(inputs, layer_params): # def predict_cnn(params, inputs, include_preactivations=False): # def get_network_activs(params, x): # def get_layer_params(fun_to_extract, example_input): # def _get_const_input_arg(eqn): # def boundprop(params, bounds_in): # def init_bound(x, epsilon, input_bounds=(0., 1.), add_batch_dim=True): # def ibp_bound_elided(verif_instance): # def ibp_bound_nonelided(verif_instance): # def make_relu_robust_verif_instance( # params, bounds=None, target_label=1, label=2, input_bounds=None): # def make_relu_robust_verif_instance_elided( # params, bounds=None, input_bounds=None): # def output_size_and_verif_type(params, bounds): # def elide_params(params, label, target_label, op_size): # def preprocess_cifar(image, inception_preprocess=False, perturbation=False): # def preprocessed_cifar_eps_and_input_bounds( # shape=(32, 32, 3), epsilon=2/255, inception_preprocess=False): # def adv_objective(model_fn, x, label, target_label): # def fgsm_single(model_fn, x, label, target_label, epsilon, num_steps, # step_size, input_bounds=(0., 1.)): # def untargeted_margin_loss(logits, labels): # def pgd_default(model_fn, x, label, epsilon, num_steps, step_size, # input_bounds=(0., 1.)): # def pgd(adv_loss, x_init, epsilon, num_steps, step_size, input_bounds=(0., 1.)): # def scale_by_variable_opt(multipliers): # def init_fn(params): # def update_fn(updates, _, params=None): # def flatten(pytree, backend=np): # def unflatten_like(a, pytree): # def structure_like(tree1, tree2): # MLP_ELIDED = 'mlp_elided' # CNN_ELIDED = 'cnn_elided' # EQUALITY = 'equality' # INEQUALITY = 'inequality' # # Path: jax_verify/tests/sdp_verify/test_utils.py # def _init_fc_layer(key, n_in, n_out): # def _init_conv_layer(key, n_h, n_w, n_cout, n_cin): # def make_mlp_params(layer_sizes, key): # def make_cnn_params(layer_sizes, key): # def make_toy_verif_instance(seed=None, label=None, target_label=None, nn='mlp'): # def make_mlp_layer_from_conv_layer(layer_params, input_bounds): # def make_mlp_verif_instance_from_cnn(verif_instance): # W = random.normal(k1, (n_in, n_out))/ n_in # W = random.normal(k1, (n_h, n_w, n_cin, n_cout)) which might include code, classes, or functions. Output only the next line.
cnn_params = test_utils.make_cnn_params(layer_sizes, k1)
Predict the next line after this snippet: <|code_start|># # http://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. """Elementary tests for the Lagrangian forms.""" INPUT_SHAPES = (('batched_0d', [1]), ('batched_1d', [1, 2]), ('batched_2d', [1, 2, 3]), ('batched_3d', [1, 2, 3, 4])) class ShapeTest(chex.TestCase): def setUp(self): super(ShapeTest, self).setUp() self._prng_seq = hk.PRNGSequence(13579) def _assert_output_shape(self, form, shape): x = jax.random.normal(next(self._prng_seq), shape) params = form.init_params(next(self._prng_seq), x.shape[1:]) out = form.apply(x, params, step=0) assert out.ndim == 1 @parameterized.named_parameters(*INPUT_SHAPES) def test_linear(self, shape): <|code_end|> using the current file's imports: from absl.testing import absltest from absl.testing import parameterized from jax_verify.extensions.functional_lagrangian import lagrangian_form import chex import haiku as hk import jax and any relevant context from other files: # Path: jax_verify/extensions/functional_lagrangian/lagrangian_form.py # def _flatten_spatial_dims(x: Tensor) -> Tensor: # def size_from_shape(shape: Shape) -> int: # def __init__(self, name): # def _init_params_per_sample(self, key: PRNGKey, *args) -> Params: # def init_params(self, key, *args, **kwargs): # def _apply(self, x: Tensor, lagrange_params: Params, step: int) -> Tensor: # def apply(self, x: Tensor, lagrange_params: Params, step: int) -> Tensor: # def process_params(self, lagrange_params: Params): # def name(self): # def __init__(self): # def _init_params_per_sample(self, # key: PRNGKey, # l_shape: Shape, # init_zeros: bool = True) -> Params: # def _apply_per_sample(self, x: Tensor, lagrange_params: Params, # step: int) -> Tensor: # def _apply(self, x: Tensor, lagrange_params: Params, step: int) -> Tensor: # def __init__(self): # def _init_params_per_sample(self, # key: PRNGKey, # l_shape: Shape, # init_zeros: bool = False) -> Params: # def _apply_per_sample(self, x: Tensor, lagrange_params: Params, # step: int) -> Tensor: # def _apply(self, x: Tensor, lagrange_params: Params, step: int) -> Tensor: # def get_lagrangian_form(config_lagrangian_form: ConfigDict) -> LagrangianForm: # class LagrangianForm(metaclass=abc.ABCMeta): # class Linear(LagrangianForm): # class LinearExp(LagrangianForm): . Output only the next line.
form = lagrangian_form.Linear()
Given the following code snippet before the placeholder: <|code_start|> return 1.0 def verify_cnn_single_dual(verif_instance): """Run verification for a CNN on a single MNIST/CIFAR problem.""" verif_instance = problem.make_sdp_verif_instance(verif_instance) solver_params = dict( use_exact_eig_train=FLAGS.use_exact_eig_train, use_exact_eig_eval=FLAGS.use_exact_eig_eval, n_iter_lanczos=FLAGS.n_iter_lanczos, eval_every=FLAGS.eval_every, opt_name=FLAGS.opt_name, anneal_factor=FLAGS.anneal_factor, lr_init=FLAGS.lr_init, kappa_zero_after=FLAGS.kappa_zero_after, kappa_reg_weight=FLAGS.kappa_reg_weight, ) # Set schedule steps_per_anneal = [int(x) for x in FLAGS.anneal_lengths.split(',')] num_steps = sum(steps_per_anneal) solver_params['steps_per_anneal'] = steps_per_anneal[:-1] + [int(1e9)] # Set learning rate multipliers kappa_shape = verif_instance.dual_shapes[-1] kappa_index = len(verif_instance.dual_shapes) - 1 assert len(kappa_shape) == 2 and kappa_shape[0] == 1 opt_multiplier_fn = functools.partial( _opt_multiplier_fn, kappa_index=kappa_index, kappa_dim=kappa_shape[1]) # Call solver <|code_end|> , predict the next line using imports from the current file: import functools import os import pickle import jax import jax.numpy as jnp import jax_verify import numpy as np from absl import app from absl import flags from jax_verify import sdp_verify from jax_verify.extensions.sdp_verify import boundprop_utils from jax_verify.extensions.sdp_verify import problem from jax_verify.extensions.sdp_verify import utils and context including class names, function names, and sometimes code from other files: # Path: jax_verify/sdp_verify.py # # Path: jax_verify/extensions/sdp_verify/boundprop_utils.py # def boundprop(params, x, epsilon, input_bounds, boundprop_type, # **extra_boundprop_kwargs): # def _crown_ibp_boundprop(params, x, epsilon, input_bounds): # def get_layer_act(layer_idx, inputs): # def _nonconvex_boundprop(params, x, epsilon, input_bounds, # nonconvex_boundprop_steps=100, # nonconvex_boundprop_nodes=128): # # Path: jax_verify/extensions/sdp_verify/problem.py # DEFAULT_DISABLED_DUAL_VARS = ('nu_quad', 'muminus2') # NECESSARY_DUAL_VARS = ('lam', 'muplus', 'muminus') # W0 = W0_orig * jnp.reshape(jnp.sqrt(sigmasq_z), (-1, 1)) # N = sum([np.prod(np.array(i)) for i in layer_sizes]) # def make_relu_network_lagrangian(dual_vars, params, bounds, obj): # def lagrangian(xs_list): # def relu_robustness_verif_instance_to_sdp(verif_instance): # def obj(x_final): # def make_inner_lagrangian(dual_vars): # def make_sdp_verif_instance(verif_instance): # def make_vae_sdp_verif_instance(params, data_x, bounds): # def recon_loss(x_final): # def make_inner_lagrangian(dual_vars): # def make_vae_semantic_spec_params(x, vae_params, classifier_params): # def get_dual_shapes_and_types(bounds_elided): # # Path: jax_verify/extensions/sdp_verify/utils.py # class SdpDualVerifInstance(_SdpDualVerifInstance): # class VerifInstanceTypes(enum.Enum): # class DualVarTypes(enum.Enum): # def mlp_layer_sizes(params): # def nn_layer_sizes(params): # def layer_sizes_from_bounds(bounds): # def predict_mlp(params, inputs): # def fwd(inputs, layer_params): # def predict_cnn(params, inputs, include_preactivations=False): # def get_network_activs(params, x): # def get_layer_params(fun_to_extract, example_input): # def _get_const_input_arg(eqn): # def boundprop(params, bounds_in): # def init_bound(x, epsilon, input_bounds=(0., 1.), add_batch_dim=True): # def ibp_bound_elided(verif_instance): # def ibp_bound_nonelided(verif_instance): # def make_relu_robust_verif_instance( # params, bounds=None, target_label=1, label=2, input_bounds=None): # def make_relu_robust_verif_instance_elided( # params, bounds=None, input_bounds=None): # def output_size_and_verif_type(params, bounds): # def elide_params(params, label, target_label, op_size): # def preprocess_cifar(image, inception_preprocess=False, perturbation=False): # def preprocessed_cifar_eps_and_input_bounds( # shape=(32, 32, 3), epsilon=2/255, inception_preprocess=False): # def adv_objective(model_fn, x, label, target_label): # def fgsm_single(model_fn, x, label, target_label, epsilon, num_steps, # step_size, input_bounds=(0., 1.)): # def untargeted_margin_loss(logits, labels): # def pgd_default(model_fn, x, label, epsilon, num_steps, step_size, # input_bounds=(0., 1.)): # def pgd(adv_loss, x_init, epsilon, num_steps, step_size, input_bounds=(0., 1.)): # def scale_by_variable_opt(multipliers): # def init_fn(params): # def update_fn(updates, _, params=None): # def flatten(pytree, backend=np): # def unflatten_like(a, pytree): # def structure_like(tree1, tree2): # MLP_ELIDED = 'mlp_elided' # CNN_ELIDED = 'cnn_elided' # EQUALITY = 'equality' # INEQUALITY = 'inequality' . Output only the next line.
obj_value, info = sdp_verify.solve_sdp_dual(
Using the snippet: <|code_start|>flags.DEFINE_string('opt_name', 'rmsprop', 'Optix class: "adam" "sgd" or "rmsprop"') flags.DEFINE_float('kappa_zero_after', 1e9, 'zero kappa_{1:n} after N steps') flags.DEFINE_float('kappa_reg_weight', -1, '-1 disables kappa regularization') FLAGS = flags.FLAGS def _load_dataset(dataset): """Loads the 10000 MNIST (CIFAR) test set examples, saved as numpy arrays.""" assert dataset in ('mnist', 'cifar10'), 'invalid dataset name' with jax_verify.open_file(os.path.join(dataset, 'x_test.npy'), 'rb') as f: xs = np.load(f) with jax_verify.open_file(os.path.join(dataset, 'y_test.npy'), 'rb') as f: ys = np.load(f) return xs, ys def _load_weights(path): with jax_verify.open_file(path, 'rb') as f: data = pickle.load(f) return data def get_verif_instance(params, x, label, target_label, epsilon, input_bounds=(0., 1.)): """Creates verif instance.""" if FLAGS.boundprop_type == 'ibp': bounds = utils.boundprop( params, utils.init_bound(x, epsilon, input_bounds=input_bounds)) else: <|code_end|> , determine the next line of code. You have imports: import functools import os import pickle import jax import jax.numpy as jnp import jax_verify import numpy as np from absl import app from absl import flags from jax_verify import sdp_verify from jax_verify.extensions.sdp_verify import boundprop_utils from jax_verify.extensions.sdp_verify import problem from jax_verify.extensions.sdp_verify import utils and context (class names, function names, or code) available: # Path: jax_verify/sdp_verify.py # # Path: jax_verify/extensions/sdp_verify/boundprop_utils.py # def boundprop(params, x, epsilon, input_bounds, boundprop_type, # **extra_boundprop_kwargs): # def _crown_ibp_boundprop(params, x, epsilon, input_bounds): # def get_layer_act(layer_idx, inputs): # def _nonconvex_boundprop(params, x, epsilon, input_bounds, # nonconvex_boundprop_steps=100, # nonconvex_boundprop_nodes=128): # # Path: jax_verify/extensions/sdp_verify/problem.py # DEFAULT_DISABLED_DUAL_VARS = ('nu_quad', 'muminus2') # NECESSARY_DUAL_VARS = ('lam', 'muplus', 'muminus') # W0 = W0_orig * jnp.reshape(jnp.sqrt(sigmasq_z), (-1, 1)) # N = sum([np.prod(np.array(i)) for i in layer_sizes]) # def make_relu_network_lagrangian(dual_vars, params, bounds, obj): # def lagrangian(xs_list): # def relu_robustness_verif_instance_to_sdp(verif_instance): # def obj(x_final): # def make_inner_lagrangian(dual_vars): # def make_sdp_verif_instance(verif_instance): # def make_vae_sdp_verif_instance(params, data_x, bounds): # def recon_loss(x_final): # def make_inner_lagrangian(dual_vars): # def make_vae_semantic_spec_params(x, vae_params, classifier_params): # def get_dual_shapes_and_types(bounds_elided): # # Path: jax_verify/extensions/sdp_verify/utils.py # class SdpDualVerifInstance(_SdpDualVerifInstance): # class VerifInstanceTypes(enum.Enum): # class DualVarTypes(enum.Enum): # def mlp_layer_sizes(params): # def nn_layer_sizes(params): # def layer_sizes_from_bounds(bounds): # def predict_mlp(params, inputs): # def fwd(inputs, layer_params): # def predict_cnn(params, inputs, include_preactivations=False): # def get_network_activs(params, x): # def get_layer_params(fun_to_extract, example_input): # def _get_const_input_arg(eqn): # def boundprop(params, bounds_in): # def init_bound(x, epsilon, input_bounds=(0., 1.), add_batch_dim=True): # def ibp_bound_elided(verif_instance): # def ibp_bound_nonelided(verif_instance): # def make_relu_robust_verif_instance( # params, bounds=None, target_label=1, label=2, input_bounds=None): # def make_relu_robust_verif_instance_elided( # params, bounds=None, input_bounds=None): # def output_size_and_verif_type(params, bounds): # def elide_params(params, label, target_label, op_size): # def preprocess_cifar(image, inception_preprocess=False, perturbation=False): # def preprocessed_cifar_eps_and_input_bounds( # shape=(32, 32, 3), epsilon=2/255, inception_preprocess=False): # def adv_objective(model_fn, x, label, target_label): # def fgsm_single(model_fn, x, label, target_label, epsilon, num_steps, # step_size, input_bounds=(0., 1.)): # def untargeted_margin_loss(logits, labels): # def pgd_default(model_fn, x, label, epsilon, num_steps, step_size, # input_bounds=(0., 1.)): # def pgd(adv_loss, x_init, epsilon, num_steps, step_size, input_bounds=(0., 1.)): # def scale_by_variable_opt(multipliers): # def init_fn(params): # def update_fn(updates, _, params=None): # def flatten(pytree, backend=np): # def unflatten_like(a, pytree): # def structure_like(tree1, tree2): # MLP_ELIDED = 'mlp_elided' # CNN_ELIDED = 'cnn_elided' # EQUALITY = 'equality' # INEQUALITY = 'inequality' . Output only the next line.
bounds = boundprop_utils.boundprop(
Continue the code snippet: <|code_start|> """Creates verif instance.""" if FLAGS.boundprop_type == 'ibp': bounds = utils.boundprop( params, utils.init_bound(x, epsilon, input_bounds=input_bounds)) else: bounds = boundprop_utils.boundprop( params, np.expand_dims(x, axis=0), epsilon, input_bounds, FLAGS.boundprop_type) verif_instance = utils.make_relu_robust_verif_instance( params, bounds, target_label=target_label, label=label, input_bounds=input_bounds) return verif_instance def _opt_multiplier_fn(path, kappa_index, kappa_dim=None): """Set adaptive learning rates.""" if FLAGS.custom_kappa_coeff > 0: kappa_lr_mul = FLAGS.custom_kappa_coeff if kappa_index in path: onehot = jax.nn.one_hot([0], kappa_dim) return onehot.at[(0, 0)].set(kappa_lr_mul) if 'lam' in path: return FLAGS.lam_coeff if path == (kappa_index - 1, 'nu'): return FLAGS.nu_coeff return 1.0 def verify_cnn_single_dual(verif_instance): """Run verification for a CNN on a single MNIST/CIFAR problem.""" <|code_end|> . Use current file imports: import functools import os import pickle import jax import jax.numpy as jnp import jax_verify import numpy as np from absl import app from absl import flags from jax_verify import sdp_verify from jax_verify.extensions.sdp_verify import boundprop_utils from jax_verify.extensions.sdp_verify import problem from jax_verify.extensions.sdp_verify import utils and context (classes, functions, or code) from other files: # Path: jax_verify/sdp_verify.py # # Path: jax_verify/extensions/sdp_verify/boundprop_utils.py # def boundprop(params, x, epsilon, input_bounds, boundprop_type, # **extra_boundprop_kwargs): # def _crown_ibp_boundprop(params, x, epsilon, input_bounds): # def get_layer_act(layer_idx, inputs): # def _nonconvex_boundprop(params, x, epsilon, input_bounds, # nonconvex_boundprop_steps=100, # nonconvex_boundprop_nodes=128): # # Path: jax_verify/extensions/sdp_verify/problem.py # DEFAULT_DISABLED_DUAL_VARS = ('nu_quad', 'muminus2') # NECESSARY_DUAL_VARS = ('lam', 'muplus', 'muminus') # W0 = W0_orig * jnp.reshape(jnp.sqrt(sigmasq_z), (-1, 1)) # N = sum([np.prod(np.array(i)) for i in layer_sizes]) # def make_relu_network_lagrangian(dual_vars, params, bounds, obj): # def lagrangian(xs_list): # def relu_robustness_verif_instance_to_sdp(verif_instance): # def obj(x_final): # def make_inner_lagrangian(dual_vars): # def make_sdp_verif_instance(verif_instance): # def make_vae_sdp_verif_instance(params, data_x, bounds): # def recon_loss(x_final): # def make_inner_lagrangian(dual_vars): # def make_vae_semantic_spec_params(x, vae_params, classifier_params): # def get_dual_shapes_and_types(bounds_elided): # # Path: jax_verify/extensions/sdp_verify/utils.py # class SdpDualVerifInstance(_SdpDualVerifInstance): # class VerifInstanceTypes(enum.Enum): # class DualVarTypes(enum.Enum): # def mlp_layer_sizes(params): # def nn_layer_sizes(params): # def layer_sizes_from_bounds(bounds): # def predict_mlp(params, inputs): # def fwd(inputs, layer_params): # def predict_cnn(params, inputs, include_preactivations=False): # def get_network_activs(params, x): # def get_layer_params(fun_to_extract, example_input): # def _get_const_input_arg(eqn): # def boundprop(params, bounds_in): # def init_bound(x, epsilon, input_bounds=(0., 1.), add_batch_dim=True): # def ibp_bound_elided(verif_instance): # def ibp_bound_nonelided(verif_instance): # def make_relu_robust_verif_instance( # params, bounds=None, target_label=1, label=2, input_bounds=None): # def make_relu_robust_verif_instance_elided( # params, bounds=None, input_bounds=None): # def output_size_and_verif_type(params, bounds): # def elide_params(params, label, target_label, op_size): # def preprocess_cifar(image, inception_preprocess=False, perturbation=False): # def preprocessed_cifar_eps_and_input_bounds( # shape=(32, 32, 3), epsilon=2/255, inception_preprocess=False): # def adv_objective(model_fn, x, label, target_label): # def fgsm_single(model_fn, x, label, target_label, epsilon, num_steps, # step_size, input_bounds=(0., 1.)): # def untargeted_margin_loss(logits, labels): # def pgd_default(model_fn, x, label, epsilon, num_steps, step_size, # input_bounds=(0., 1.)): # def pgd(adv_loss, x_init, epsilon, num_steps, step_size, input_bounds=(0., 1.)): # def scale_by_variable_opt(multipliers): # def init_fn(params): # def update_fn(updates, _, params=None): # def flatten(pytree, backend=np): # def unflatten_like(a, pytree): # def structure_like(tree1, tree2): # MLP_ELIDED = 'mlp_elided' # CNN_ELIDED = 'cnn_elided' # EQUALITY = 'equality' # INEQUALITY = 'inequality' . Output only the next line.
verif_instance = problem.make_sdp_verif_instance(verif_instance)
Continue the code snippet: <|code_start|>flags.DEFINE_float('eval_every', 1000, 'Iterations per log.') flags.DEFINE_float('lr_init', 1e-3, 'initial learning rate') flags.DEFINE_float('anneal_factor', 0.1, 'learning rate anneal factor') flags.DEFINE_string('opt_name', 'rmsprop', 'Optix class: "adam" "sgd" or "rmsprop"') flags.DEFINE_float('kappa_zero_after', 1e9, 'zero kappa_{1:n} after N steps') flags.DEFINE_float('kappa_reg_weight', -1, '-1 disables kappa regularization') FLAGS = flags.FLAGS def _load_dataset(dataset): """Loads the 10000 MNIST (CIFAR) test set examples, saved as numpy arrays.""" assert dataset in ('mnist', 'cifar10'), 'invalid dataset name' with jax_verify.open_file(os.path.join(dataset, 'x_test.npy'), 'rb') as f: xs = np.load(f) with jax_verify.open_file(os.path.join(dataset, 'y_test.npy'), 'rb') as f: ys = np.load(f) return xs, ys def _load_weights(path): with jax_verify.open_file(path, 'rb') as f: data = pickle.load(f) return data def get_verif_instance(params, x, label, target_label, epsilon, input_bounds=(0., 1.)): """Creates verif instance.""" if FLAGS.boundprop_type == 'ibp': <|code_end|> . Use current file imports: import functools import os import pickle import jax import jax.numpy as jnp import jax_verify import numpy as np from absl import app from absl import flags from jax_verify import sdp_verify from jax_verify.extensions.sdp_verify import boundprop_utils from jax_verify.extensions.sdp_verify import problem from jax_verify.extensions.sdp_verify import utils and context (classes, functions, or code) from other files: # Path: jax_verify/sdp_verify.py # # Path: jax_verify/extensions/sdp_verify/boundprop_utils.py # def boundprop(params, x, epsilon, input_bounds, boundprop_type, # **extra_boundprop_kwargs): # def _crown_ibp_boundprop(params, x, epsilon, input_bounds): # def get_layer_act(layer_idx, inputs): # def _nonconvex_boundprop(params, x, epsilon, input_bounds, # nonconvex_boundprop_steps=100, # nonconvex_boundprop_nodes=128): # # Path: jax_verify/extensions/sdp_verify/problem.py # DEFAULT_DISABLED_DUAL_VARS = ('nu_quad', 'muminus2') # NECESSARY_DUAL_VARS = ('lam', 'muplus', 'muminus') # W0 = W0_orig * jnp.reshape(jnp.sqrt(sigmasq_z), (-1, 1)) # N = sum([np.prod(np.array(i)) for i in layer_sizes]) # def make_relu_network_lagrangian(dual_vars, params, bounds, obj): # def lagrangian(xs_list): # def relu_robustness_verif_instance_to_sdp(verif_instance): # def obj(x_final): # def make_inner_lagrangian(dual_vars): # def make_sdp_verif_instance(verif_instance): # def make_vae_sdp_verif_instance(params, data_x, bounds): # def recon_loss(x_final): # def make_inner_lagrangian(dual_vars): # def make_vae_semantic_spec_params(x, vae_params, classifier_params): # def get_dual_shapes_and_types(bounds_elided): # # Path: jax_verify/extensions/sdp_verify/utils.py # class SdpDualVerifInstance(_SdpDualVerifInstance): # class VerifInstanceTypes(enum.Enum): # class DualVarTypes(enum.Enum): # def mlp_layer_sizes(params): # def nn_layer_sizes(params): # def layer_sizes_from_bounds(bounds): # def predict_mlp(params, inputs): # def fwd(inputs, layer_params): # def predict_cnn(params, inputs, include_preactivations=False): # def get_network_activs(params, x): # def get_layer_params(fun_to_extract, example_input): # def _get_const_input_arg(eqn): # def boundprop(params, bounds_in): # def init_bound(x, epsilon, input_bounds=(0., 1.), add_batch_dim=True): # def ibp_bound_elided(verif_instance): # def ibp_bound_nonelided(verif_instance): # def make_relu_robust_verif_instance( # params, bounds=None, target_label=1, label=2, input_bounds=None): # def make_relu_robust_verif_instance_elided( # params, bounds=None, input_bounds=None): # def output_size_and_verif_type(params, bounds): # def elide_params(params, label, target_label, op_size): # def preprocess_cifar(image, inception_preprocess=False, perturbation=False): # def preprocessed_cifar_eps_and_input_bounds( # shape=(32, 32, 3), epsilon=2/255, inception_preprocess=False): # def adv_objective(model_fn, x, label, target_label): # def fgsm_single(model_fn, x, label, target_label, epsilon, num_steps, # step_size, input_bounds=(0., 1.)): # def untargeted_margin_loss(logits, labels): # def pgd_default(model_fn, x, label, epsilon, num_steps, step_size, # input_bounds=(0., 1.)): # def pgd(adv_loss, x_init, epsilon, num_steps, step_size, input_bounds=(0., 1.)): # def scale_by_variable_opt(multipliers): # def init_fn(params): # def update_fn(updates, _, params=None): # def flatten(pytree, backend=np): # def unflatten_like(a, pytree): # def structure_like(tree1, tree2): # MLP_ELIDED = 'mlp_elided' # CNN_ELIDED = 'cnn_elided' # EQUALITY = 'equality' # INEQUALITY = 'inequality' . Output only the next line.
bounds = utils.boundprop(
Predict the next line for this snippet: <|code_start|> """Sample uniformly some point respecting the bounds. Args: key: Random number generator bounds: Tuple containing [lower bound, upper bound] nb_points: How many points to sample. axis: Which dimension to add to correspond to the number of points. Returns: points: Points contained between the given bounds. """ lb, ub = bounds act_shape = lb.shape to_sample_shape = act_shape[:axis] + (nb_points,) + act_shape[axis:] unif_samples = jax.random.uniform(key, to_sample_shape) broad_lb = jnp.expand_dims(lb, axis) broad_ub = jnp.expand_dims(ub, axis) bound_range = broad_ub - broad_lb return broad_lb + unif_samples * bound_range def set_up_toy_problem(rng_key, batch_size, architecture): key_1, key_2 = jax.random.split(rng_key) params = sdp_test_utils.make_mlp_params(architecture, key_2) inputs = jax.random.uniform(key_1, (batch_size, architecture[0])) eps = 0.1 lb = jnp.maximum(jnp.minimum(inputs - eps, 1.), 0.) ub = jnp.maximum(jnp.minimum(inputs + eps, 1.), 0.) <|code_end|> with the help of current file imports: import functools import jax import jax.numpy as jnp from typing import Tuple from jax_verify.extensions.sdp_verify import utils from jax_verify.tests.sdp_verify import test_utils as sdp_test_utils and context from other files: # Path: jax_verify/extensions/sdp_verify/utils.py # class SdpDualVerifInstance(_SdpDualVerifInstance): # class VerifInstanceTypes(enum.Enum): # class DualVarTypes(enum.Enum): # def mlp_layer_sizes(params): # def nn_layer_sizes(params): # def layer_sizes_from_bounds(bounds): # def predict_mlp(params, inputs): # def fwd(inputs, layer_params): # def predict_cnn(params, inputs, include_preactivations=False): # def get_network_activs(params, x): # def get_layer_params(fun_to_extract, example_input): # def _get_const_input_arg(eqn): # def boundprop(params, bounds_in): # def init_bound(x, epsilon, input_bounds=(0., 1.), add_batch_dim=True): # def ibp_bound_elided(verif_instance): # def ibp_bound_nonelided(verif_instance): # def make_relu_robust_verif_instance( # params, bounds=None, target_label=1, label=2, input_bounds=None): # def make_relu_robust_verif_instance_elided( # params, bounds=None, input_bounds=None): # def output_size_and_verif_type(params, bounds): # def elide_params(params, label, target_label, op_size): # def preprocess_cifar(image, inception_preprocess=False, perturbation=False): # def preprocessed_cifar_eps_and_input_bounds( # shape=(32, 32, 3), epsilon=2/255, inception_preprocess=False): # def adv_objective(model_fn, x, label, target_label): # def fgsm_single(model_fn, x, label, target_label, epsilon, num_steps, # step_size, input_bounds=(0., 1.)): # def untargeted_margin_loss(logits, labels): # def pgd_default(model_fn, x, label, epsilon, num_steps, step_size, # input_bounds=(0., 1.)): # def pgd(adv_loss, x_init, epsilon, num_steps, step_size, input_bounds=(0., 1.)): # def scale_by_variable_opt(multipliers): # def init_fn(params): # def update_fn(updates, _, params=None): # def flatten(pytree, backend=np): # def unflatten_like(a, pytree): # def structure_like(tree1, tree2): # MLP_ELIDED = 'mlp_elided' # CNN_ELIDED = 'cnn_elided' # EQUALITY = 'equality' # INEQUALITY = 'inequality' # # Path: jax_verify/tests/sdp_verify/test_utils.py # def _init_fc_layer(key, n_in, n_out): # def _init_conv_layer(key, n_h, n_w, n_cout, n_cin): # def make_mlp_params(layer_sizes, key): # def make_cnn_params(layer_sizes, key): # def make_toy_verif_instance(seed=None, label=None, target_label=None, nn='mlp'): # def make_mlp_layer_from_conv_layer(layer_params, input_bounds): # def make_mlp_verif_instance_from_cnn(verif_instance): # W = random.normal(k1, (n_in, n_out))/ n_in # W = random.normal(k1, (n_h, n_w, n_cin, n_cout)) , which may contain function names, class names, or code. Output only the next line.
fun = functools.partial(utils.predict_cnn, params)
Given snippet: <|code_start|> def sample_bounded_points(key: jnp.ndarray, bounds: Tuple[jnp.ndarray, jnp.ndarray], nb_points: int, axis: int = 0) -> jnp.ndarray: """Sample uniformly some point respecting the bounds. Args: key: Random number generator bounds: Tuple containing [lower bound, upper bound] nb_points: How many points to sample. axis: Which dimension to add to correspond to the number of points. Returns: points: Points contained between the given bounds. """ lb, ub = bounds act_shape = lb.shape to_sample_shape = act_shape[:axis] + (nb_points,) + act_shape[axis:] unif_samples = jax.random.uniform(key, to_sample_shape) broad_lb = jnp.expand_dims(lb, axis) broad_ub = jnp.expand_dims(ub, axis) bound_range = broad_ub - broad_lb return broad_lb + unif_samples * bound_range def set_up_toy_problem(rng_key, batch_size, architecture): key_1, key_2 = jax.random.split(rng_key) <|code_end|> , continue by predicting the next line. Consider current file imports: import functools import jax import jax.numpy as jnp from typing import Tuple from jax_verify.extensions.sdp_verify import utils from jax_verify.tests.sdp_verify import test_utils as sdp_test_utils and context: # Path: jax_verify/extensions/sdp_verify/utils.py # class SdpDualVerifInstance(_SdpDualVerifInstance): # class VerifInstanceTypes(enum.Enum): # class DualVarTypes(enum.Enum): # def mlp_layer_sizes(params): # def nn_layer_sizes(params): # def layer_sizes_from_bounds(bounds): # def predict_mlp(params, inputs): # def fwd(inputs, layer_params): # def predict_cnn(params, inputs, include_preactivations=False): # def get_network_activs(params, x): # def get_layer_params(fun_to_extract, example_input): # def _get_const_input_arg(eqn): # def boundprop(params, bounds_in): # def init_bound(x, epsilon, input_bounds=(0., 1.), add_batch_dim=True): # def ibp_bound_elided(verif_instance): # def ibp_bound_nonelided(verif_instance): # def make_relu_robust_verif_instance( # params, bounds=None, target_label=1, label=2, input_bounds=None): # def make_relu_robust_verif_instance_elided( # params, bounds=None, input_bounds=None): # def output_size_and_verif_type(params, bounds): # def elide_params(params, label, target_label, op_size): # def preprocess_cifar(image, inception_preprocess=False, perturbation=False): # def preprocessed_cifar_eps_and_input_bounds( # shape=(32, 32, 3), epsilon=2/255, inception_preprocess=False): # def adv_objective(model_fn, x, label, target_label): # def fgsm_single(model_fn, x, label, target_label, epsilon, num_steps, # step_size, input_bounds=(0., 1.)): # def untargeted_margin_loss(logits, labels): # def pgd_default(model_fn, x, label, epsilon, num_steps, step_size, # input_bounds=(0., 1.)): # def pgd(adv_loss, x_init, epsilon, num_steps, step_size, input_bounds=(0., 1.)): # def scale_by_variable_opt(multipliers): # def init_fn(params): # def update_fn(updates, _, params=None): # def flatten(pytree, backend=np): # def unflatten_like(a, pytree): # def structure_like(tree1, tree2): # MLP_ELIDED = 'mlp_elided' # CNN_ELIDED = 'cnn_elided' # EQUALITY = 'equality' # INEQUALITY = 'inequality' # # Path: jax_verify/tests/sdp_verify/test_utils.py # def _init_fc_layer(key, n_in, n_out): # def _init_conv_layer(key, n_h, n_w, n_cout, n_cin): # def make_mlp_params(layer_sizes, key): # def make_cnn_params(layer_sizes, key): # def make_toy_verif_instance(seed=None, label=None, target_label=None, nn='mlp'): # def make_mlp_layer_from_conv_layer(layer_params, input_bounds): # def make_mlp_verif_instance_from_cnn(verif_instance): # W = random.normal(k1, (n_in, n_out))/ n_in # W = random.normal(k1, (n_h, n_w, n_cin, n_cout)) which might include code, classes, or functions. Output only the next line.
params = sdp_test_utils.make_mlp_params(architecture, key_2)
Here is a snippet: <|code_start|># coding=utf-8 # Copyright 2021 DeepMind Technologies Limited. # # 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 # # http://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. """Traverses a network, applying a transformation to each node in the graph. This is accomplished by traversing the JaxPR representation of the computation. """ Tensor = jnp.ndarray T = TypeVar('T') Nest = Union[T, Sequence[T], Dict[Any, T]] <|code_end|> . Write the next line using the current file imports: import abc import collections import dataclasses import functools import jax import jax.numpy as jnp from typing import Any, Callable, Dict, Generic, List, Optional, Sequence, Tuple, TypeVar, Union from jax_verify.src import synthetic_primitives and context from other files: # Path: jax_verify/src/synthetic_primitives.py # T = TypeVar('T') # LINEAR_OP = [ # lax.reshape_p, # lax.squeeze_p, # lax.transpose_p, # lax.broadcast_in_dim_p, # lax.gather_p, # lax.reduce_sum_p, # lax.add_p, # lax.scatter_add_p, # lax.sub_p, # linear_p, # ] # BILINEAR_OP = [ # lax.dot_general_p, # lax.conv_general_dilated_p, # lax.mul_p, # posbilinear_p, # ] # def simplify_graph( # graph_simplifier: GraphSimplifier, # graph: jax.core.Jaxpr, # var_is_bound: VarIsBoundDict, # ) -> jax.core.Jaxpr: # def _simplify_graph( # var_is_bound: VarIsBoundDict, # graph: jax.core.Jaxpr, # graph_simplifier: GraphSimplifier, # ) -> jax.core.Jaxpr: # def __init__( # self, # fn: Callable[..., Tensor], # upstream_simplifier: Optional[SimpleSimplifier], # primitive: 'FakePrimitive', # *arg_shapes: Sequence[int], # **params): # def graph(self) -> jax.core.Jaxpr: # def capture_literals(self) -> Dict[int, str]: # def primitive(self) -> 'FakePrimitive': # def params(self) -> Dict[str, Any]: # def simplify(self, graph_simplifier: SimpleSimplifier): # def _mark_outputs_whether_bounds(eqn, var_is_bound): # def jax_primitive_subgraph(eqn: jax.core.JaxprEqn) -> Optional[jax.core.Jaxpr]: # def _propagate_var_is_bound(graph: jax.core.Jaxpr, # var_is_bound: VarIsBoundDict): # def detect( # synthetic_primitive_specs: Sequence[SyntheticPrimitiveSpec], # graph: jax.core.Jaxpr, # ) -> jax.core.Jaxpr: # def _next_equation( # synthetic_primitive_specs: Sequence[SyntheticPrimitiveSpec], # graph: jax.core.Jaxpr, # eqn_idx: int, # ) -> Tuple[jax.core.JaxprEqn, int]: # def _equal_literal_values(lhs, rhs) -> bool: # def _matches( # spec: jax.core.Jaxpr, # capture_literals: Dict[int, str], # graph: jax.core.Jaxpr, # eqn_idx: int, # ) -> Tuple[ # def _differing_literals( # graph: jax.core.Jaxpr, # alt_graph: jax.core.Jaxpr, # ) -> Sequence[jax.core.Literal]: # def _is_linear_eqn(eqn: jax.core.JaxprEqn, var_is_bound: VarIsBoundDict): # def _is_posbilinear_eqn(eqn, var_is_bound): # def _find_eqn(eqn_list: List[jax.core.JaxprEqn], var: jax.core.Var) -> int: # def group_posbilinear(graph: jax.core.Jaxpr, # var_is_bound: VarIsBoundDict, # ) -> jax.core.Jaxpr: # def group_linear_sequence(graph: jax.core.Jaxpr, # var_is_bound: VarIsBoundDict, # ) -> jax.core.Jaxpr: # def hoist_constant_computations(graph: jax.core.Jaxpr, # var_is_bound: VarIsBoundDict # ) -> jax.core.Jaxpr: # def expand_softmax_simplifier(graph: jax.core.Jaxpr, # var_is_bound: VarIsBoundDict # ) -> jax.core.Jaxpr: # def __init__(self, name, impl): # def bind(self, *args, **kwargs): # def name(self): # def __str__(self): # def __repr__(self): # def simplifier_composition(*graph_simplifiers: GraphSimplifier # ) -> GraphSimplifier: # def _subgraph_bind(*args, jax_verify_subgraph, jax_verify_keepjvargs): # def __init__(self, name): # def bind(self, *args, **kwargs): # def activation_specs() -> Sequence[SyntheticPrimitiveSpec]: # class SyntheticPrimitiveSpec: # class FakePrimitive: # class SubgraphPrimitive(FakePrimitive): , which may include functions, classes, or code. Output only the next line.
Primitive = Union[jax.core.Primitive, synthetic_primitives.FakePrimitive]
Given the code snippet: <|code_start|># you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://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. """Small helper functions.""" Params = collections.namedtuple('Params', ['inner', 'outer']) ParamsTypes = collections.namedtuple('ParamsTypes', ['inner', 'outer', 'lagrangian_form']) DataSpec = collections.namedtuple( 'DataSpec', ['input', 'true_label', 'target_label', 'epsilon', 'input_bounds']) Array = chex.Array ArrayTree = chex.ArrayTree ConfigDict = ml_collections.ConfigDict IntervalBound = jax_verify.IntervalBound Tensor = jnp.array LayerParams = Union['FCParams', 'ConvParams'] <|code_end|> , generate the next line using the imports in this file: import abc import collections import dataclasses import enum import chex import jax.numpy as jnp import jax_verify import ml_collections from typing import Callable, List, Optional, Union from jax_verify.extensions.functional_lagrangian import lagrangian_form from jax_verify.extensions.sdp_verify import utils as sdp_utils and context (functions, classes, or occasionally code) from other files: # Path: jax_verify/extensions/functional_lagrangian/lagrangian_form.py # def _flatten_spatial_dims(x: Tensor) -> Tensor: # def size_from_shape(shape: Shape) -> int: # def __init__(self, name): # def _init_params_per_sample(self, key: PRNGKey, *args) -> Params: # def init_params(self, key, *args, **kwargs): # def _apply(self, x: Tensor, lagrange_params: Params, step: int) -> Tensor: # def apply(self, x: Tensor, lagrange_params: Params, step: int) -> Tensor: # def process_params(self, lagrange_params: Params): # def name(self): # def __init__(self): # def _init_params_per_sample(self, # key: PRNGKey, # l_shape: Shape, # init_zeros: bool = True) -> Params: # def _apply_per_sample(self, x: Tensor, lagrange_params: Params, # step: int) -> Tensor: # def _apply(self, x: Tensor, lagrange_params: Params, step: int) -> Tensor: # def __init__(self): # def _init_params_per_sample(self, # key: PRNGKey, # l_shape: Shape, # init_zeros: bool = False) -> Params: # def _apply_per_sample(self, x: Tensor, lagrange_params: Params, # step: int) -> Tensor: # def _apply(self, x: Tensor, lagrange_params: Params, step: int) -> Tensor: # def get_lagrangian_form(config_lagrangian_form: ConfigDict) -> LagrangianForm: # class LagrangianForm(metaclass=abc.ABCMeta): # class Linear(LagrangianForm): # class LinearExp(LagrangianForm): # # Path: jax_verify/extensions/sdp_verify/utils.py # class SdpDualVerifInstance(_SdpDualVerifInstance): # class VerifInstanceTypes(enum.Enum): # class DualVarTypes(enum.Enum): # def mlp_layer_sizes(params): # def nn_layer_sizes(params): # def layer_sizes_from_bounds(bounds): # def predict_mlp(params, inputs): # def fwd(inputs, layer_params): # def predict_cnn(params, inputs, include_preactivations=False): # def get_network_activs(params, x): # def get_layer_params(fun_to_extract, example_input): # def _get_const_input_arg(eqn): # def boundprop(params, bounds_in): # def init_bound(x, epsilon, input_bounds=(0., 1.), add_batch_dim=True): # def ibp_bound_elided(verif_instance): # def ibp_bound_nonelided(verif_instance): # def make_relu_robust_verif_instance( # params, bounds=None, target_label=1, label=2, input_bounds=None): # def make_relu_robust_verif_instance_elided( # params, bounds=None, input_bounds=None): # def output_size_and_verif_type(params, bounds): # def elide_params(params, label, target_label, op_size): # def preprocess_cifar(image, inception_preprocess=False, perturbation=False): # def preprocessed_cifar_eps_and_input_bounds( # shape=(32, 32, 3), epsilon=2/255, inception_preprocess=False): # def adv_objective(model_fn, x, label, target_label): # def fgsm_single(model_fn, x, label, target_label, epsilon, num_steps, # step_size, input_bounds=(0., 1.)): # def untargeted_margin_loss(logits, labels): # def pgd_default(model_fn, x, label, epsilon, num_steps, step_size, # input_bounds=(0., 1.)): # def pgd(adv_loss, x_init, epsilon, num_steps, step_size, input_bounds=(0., 1.)): # def scale_by_variable_opt(multipliers): # def init_fn(params): # def update_fn(updates, _, params=None): # def flatten(pytree, backend=np): # def unflatten_like(a, pytree): # def structure_like(tree1, tree2): # MLP_ELIDED = 'mlp_elided' # CNN_ELIDED = 'cnn_elided' # EQUALITY = 'equality' # INEQUALITY = 'inequality' . Output only the next line.
LagrangianForm = lagrangian_form.LagrangianForm
Continue the code snippet: <|code_start|> """Small helper functions.""" Params = collections.namedtuple('Params', ['inner', 'outer']) ParamsTypes = collections.namedtuple('ParamsTypes', ['inner', 'outer', 'lagrangian_form']) DataSpec = collections.namedtuple( 'DataSpec', ['input', 'true_label', 'target_label', 'epsilon', 'input_bounds']) Array = chex.Array ArrayTree = chex.ArrayTree ConfigDict = ml_collections.ConfigDict IntervalBound = jax_verify.IntervalBound Tensor = jnp.array LayerParams = Union['FCParams', 'ConvParams'] LagrangianForm = lagrangian_form.LagrangianForm ModelParams = List[LayerParams] ModelParamsElided = ModelParams class AbstractParams(abc.ABC): """AbstractParams.""" def __call__(self, inputs: Tensor) -> Tensor: """Forward pass on layer.""" <|code_end|> . Use current file imports: import abc import collections import dataclasses import enum import chex import jax.numpy as jnp import jax_verify import ml_collections from typing import Callable, List, Optional, Union from jax_verify.extensions.functional_lagrangian import lagrangian_form from jax_verify.extensions.sdp_verify import utils as sdp_utils and context (classes, functions, or code) from other files: # Path: jax_verify/extensions/functional_lagrangian/lagrangian_form.py # def _flatten_spatial_dims(x: Tensor) -> Tensor: # def size_from_shape(shape: Shape) -> int: # def __init__(self, name): # def _init_params_per_sample(self, key: PRNGKey, *args) -> Params: # def init_params(self, key, *args, **kwargs): # def _apply(self, x: Tensor, lagrange_params: Params, step: int) -> Tensor: # def apply(self, x: Tensor, lagrange_params: Params, step: int) -> Tensor: # def process_params(self, lagrange_params: Params): # def name(self): # def __init__(self): # def _init_params_per_sample(self, # key: PRNGKey, # l_shape: Shape, # init_zeros: bool = True) -> Params: # def _apply_per_sample(self, x: Tensor, lagrange_params: Params, # step: int) -> Tensor: # def _apply(self, x: Tensor, lagrange_params: Params, step: int) -> Tensor: # def __init__(self): # def _init_params_per_sample(self, # key: PRNGKey, # l_shape: Shape, # init_zeros: bool = False) -> Params: # def _apply_per_sample(self, x: Tensor, lagrange_params: Params, # step: int) -> Tensor: # def _apply(self, x: Tensor, lagrange_params: Params, step: int) -> Tensor: # def get_lagrangian_form(config_lagrangian_form: ConfigDict) -> LagrangianForm: # class LagrangianForm(metaclass=abc.ABCMeta): # class Linear(LagrangianForm): # class LinearExp(LagrangianForm): # # Path: jax_verify/extensions/sdp_verify/utils.py # class SdpDualVerifInstance(_SdpDualVerifInstance): # class VerifInstanceTypes(enum.Enum): # class DualVarTypes(enum.Enum): # def mlp_layer_sizes(params): # def nn_layer_sizes(params): # def layer_sizes_from_bounds(bounds): # def predict_mlp(params, inputs): # def fwd(inputs, layer_params): # def predict_cnn(params, inputs, include_preactivations=False): # def get_network_activs(params, x): # def get_layer_params(fun_to_extract, example_input): # def _get_const_input_arg(eqn): # def boundprop(params, bounds_in): # def init_bound(x, epsilon, input_bounds=(0., 1.), add_batch_dim=True): # def ibp_bound_elided(verif_instance): # def ibp_bound_nonelided(verif_instance): # def make_relu_robust_verif_instance( # params, bounds=None, target_label=1, label=2, input_bounds=None): # def make_relu_robust_verif_instance_elided( # params, bounds=None, input_bounds=None): # def output_size_and_verif_type(params, bounds): # def elide_params(params, label, target_label, op_size): # def preprocess_cifar(image, inception_preprocess=False, perturbation=False): # def preprocessed_cifar_eps_and_input_bounds( # shape=(32, 32, 3), epsilon=2/255, inception_preprocess=False): # def adv_objective(model_fn, x, label, target_label): # def fgsm_single(model_fn, x, label, target_label, epsilon, num_steps, # step_size, input_bounds=(0., 1.)): # def untargeted_margin_loss(logits, labels): # def pgd_default(model_fn, x, label, epsilon, num_steps, step_size, # input_bounds=(0., 1.)): # def pgd(adv_loss, x_init, epsilon, num_steps, step_size, input_bounds=(0., 1.)): # def scale_by_variable_opt(multipliers): # def init_fn(params): # def update_fn(updates, _, params=None): # def flatten(pytree, backend=np): # def unflatten_like(a, pytree): # def structure_like(tree1, tree2): # MLP_ELIDED = 'mlp_elided' # CNN_ELIDED = 'cnn_elided' # EQUALITY = 'equality' # INEQUALITY = 'inequality' . Output only the next line.
return sdp_utils.fwd(inputs, self.params)
Continue the code snippet: <|code_start|>""" MLP_PATH = 'models/raghunathan18_pgdnn.pkl' CNN_PATH = 'models/mnist_wongsmall_eps_10_adv.pkl' ALL_BOUNDPROP_METHODS = ( jax_verify.interval_bound_propagation, jax_verify.forward_fastlin_bound_propagation, jax_verify.backward_fastlin_bound_propagation, jax_verify.ibpforwardfastlin_bound_propagation, jax_verify.forward_crown_bound_propagation, jax_verify.backward_crown_bound_propagation, jax_verify.crownibp_bound_propagation, ) flags.DEFINE_string('model', 'mlp', 'mlp or cnn') flags.DEFINE_string('boundprop_method', '', 'Any boundprop method, such as `interval_bound_propagation`' ' `forward_fastlin_bound_propagation` or ' ' `crown_bound_propagation`.' 'Empty string defaults to IBP.') FLAGS = flags.FLAGS def load_model(model_name): """Load model parameters and prediction function.""" # Choose appropriate prediction function if model_name == 'mlp': model_path = MLP_PATH def model_fn(params, inputs): inputs = np.reshape(inputs, (inputs.shape[0], -1)) <|code_end|> . Use current file imports: import functools import pickle import jax.numpy as jnp import jax_verify import numpy as np from absl import app from absl import flags from absl import logging from jax_verify.extensions.sdp_verify import utils and context (classes, functions, or code) from other files: # Path: jax_verify/extensions/sdp_verify/utils.py # class SdpDualVerifInstance(_SdpDualVerifInstance): # class VerifInstanceTypes(enum.Enum): # class DualVarTypes(enum.Enum): # def mlp_layer_sizes(params): # def nn_layer_sizes(params): # def layer_sizes_from_bounds(bounds): # def predict_mlp(params, inputs): # def fwd(inputs, layer_params): # def predict_cnn(params, inputs, include_preactivations=False): # def get_network_activs(params, x): # def get_layer_params(fun_to_extract, example_input): # def _get_const_input_arg(eqn): # def boundprop(params, bounds_in): # def init_bound(x, epsilon, input_bounds=(0., 1.), add_batch_dim=True): # def ibp_bound_elided(verif_instance): # def ibp_bound_nonelided(verif_instance): # def make_relu_robust_verif_instance( # params, bounds=None, target_label=1, label=2, input_bounds=None): # def make_relu_robust_verif_instance_elided( # params, bounds=None, input_bounds=None): # def output_size_and_verif_type(params, bounds): # def elide_params(params, label, target_label, op_size): # def preprocess_cifar(image, inception_preprocess=False, perturbation=False): # def preprocessed_cifar_eps_and_input_bounds( # shape=(32, 32, 3), epsilon=2/255, inception_preprocess=False): # def adv_objective(model_fn, x, label, target_label): # def fgsm_single(model_fn, x, label, target_label, epsilon, num_steps, # step_size, input_bounds=(0., 1.)): # def untargeted_margin_loss(logits, labels): # def pgd_default(model_fn, x, label, epsilon, num_steps, step_size, # input_bounds=(0., 1.)): # def pgd(adv_loss, x_init, epsilon, num_steps, step_size, input_bounds=(0., 1.)): # def scale_by_variable_opt(multipliers): # def init_fn(params): # def update_fn(updates, _, params=None): # def flatten(pytree, backend=np): # def unflatten_like(a, pytree): # def structure_like(tree1, tree2): # MLP_ELIDED = 'mlp_elided' # CNN_ELIDED = 'cnn_elided' # EQUALITY = 'equality' # INEQUALITY = 'inequality' . Output only the next line.
return utils.predict_mlp(params, inputs)
Given snippet: <|code_start|> """Hessian-vector product for H_lambda - refer to docstring for `Av()`.""" lag_grad = lambda v2: flatten(jax.grad(lagrangian)(v2)) hv_v = jax.grad(lambda v2: jnp.vdot(lag_grad(v2), v))(zeros) hv_flat = flatten(hv_v) return hv_flat def Av(v): """Matrix-vector product. Args: v: vector, DeviceArray Returns: Av: vector, Device array. A is defined as diag(kappa) - M(lambda) where M(lambda) = [0, g_lambda'; g_lambda, H_lambda], and these terms correspond to L~(z) = c_lambda + g_lambda' z + z' H_lambda z """ # Expand Mv=[0 g'; g H] [v0;v1] = [g'v1; v0*g + H(v1)] = [Mv0;Mv1] # Compute Mv0 term mv_zero = jnp.reshape(jnp.vdot(g_lambda, v[1:]), (1,)) # Compute Mv1 term mv_rest = Hv(v[1:]) + v[0] * g_lambda mv = jnp.concatenate([mv_zero, mv_rest], axis=0) diag_kappa_v = jnp.reshape(dual_vars[-1], mv.shape) * v av = diag_kappa_v - mv return jnp.reshape(av, v.shape) # Construct dual function (dual_vars[-1]=kappa) if exact: <|code_end|> , continue by predicting the next line. Consider current file imports: import collections import functools import jax import jax.numpy as jnp import jax.scipy import numpy as np import optax import tree from absl import logging from jax_verify.extensions.sdp_verify import eigenvector_utils from jax_verify.extensions.sdp_verify import utils and context: # Path: jax_verify/extensions/sdp_verify/eigenvector_utils.py # def safe_eigh(a, UPLO=None, symmetrize_input=True): # def lanczos_alg(matrix_vector_product, # dim, # order, # rng_key, # dynamic_unroll=True, # use_jax=True, # verbose=False): # def _index_update(array, index, value): # def _lanczos_alg_dynamic_unroll( # matrix_vector_product, dim, order, rng_key): # def _body_fn_update_alpha(i, vecs, tridiag, beta): # def body_fn(i, vals): # def _make_pos(vecx): # def max_eigenvector_lanczos(matrix_vector_product, dim, order, key, scl=-1, # dynamic_unroll=True, use_safe_eig_vec=True): # def get_eig_vec(vals): # def min_eigenvector_lanczos(matrix_vector_product, *args, **kwargs): # def max_eigenvector_exact(matrix_vector_product, vec_dim, scl=-1, # report_all=False): # def batched_Hv(v_batched): # def min_eigenvector_exact(matrix_vector_product, vec_dim, scl=-1, # report_all=False): # H = batched_Hv(jnp.eye(vec_dim)) # H = (H + H.T)/2 # # Path: jax_verify/extensions/sdp_verify/utils.py # class SdpDualVerifInstance(_SdpDualVerifInstance): # class VerifInstanceTypes(enum.Enum): # class DualVarTypes(enum.Enum): # def mlp_layer_sizes(params): # def nn_layer_sizes(params): # def layer_sizes_from_bounds(bounds): # def predict_mlp(params, inputs): # def fwd(inputs, layer_params): # def predict_cnn(params, inputs, include_preactivations=False): # def get_network_activs(params, x): # def get_layer_params(fun_to_extract, example_input): # def _get_const_input_arg(eqn): # def boundprop(params, bounds_in): # def init_bound(x, epsilon, input_bounds=(0., 1.), add_batch_dim=True): # def ibp_bound_elided(verif_instance): # def ibp_bound_nonelided(verif_instance): # def make_relu_robust_verif_instance( # params, bounds=None, target_label=1, label=2, input_bounds=None): # def make_relu_robust_verif_instance_elided( # params, bounds=None, input_bounds=None): # def output_size_and_verif_type(params, bounds): # def elide_params(params, label, target_label, op_size): # def preprocess_cifar(image, inception_preprocess=False, perturbation=False): # def preprocessed_cifar_eps_and_input_bounds( # shape=(32, 32, 3), epsilon=2/255, inception_preprocess=False): # def adv_objective(model_fn, x, label, target_label): # def fgsm_single(model_fn, x, label, target_label, epsilon, num_steps, # step_size, input_bounds=(0., 1.)): # def untargeted_margin_loss(logits, labels): # def pgd_default(model_fn, x, label, epsilon, num_steps, step_size, # input_bounds=(0., 1.)): # def pgd(adv_loss, x_init, epsilon, num_steps, step_size, input_bounds=(0., 1.)): # def scale_by_variable_opt(multipliers): # def init_fn(params): # def update_fn(updates, _, params=None): # def flatten(pytree, backend=np): # def unflatten_like(a, pytree): # def structure_like(tree1, tree2): # MLP_ELIDED = 'mlp_elided' # CNN_ELIDED = 'cnn_elided' # EQUALITY = 'equality' # INEQUALITY = 'inequality' which might include code, classes, or functions. Output only the next line.
eig_vec, eig_info = eigenvector_utils.min_eigenvector_exact(
Continue the code snippet: <|code_start|> def _schedule(values: List[float], boundaries: List[int], dtype=jnp.float32) -> Callable[[chex.Array], chex.Numeric]: """Schedule the value of p, the proportion of elements to be modified.""" large_step = max(boundaries) + 1 boundaries = boundaries + [large_step, large_step + 1] num_values = len(values) values = jnp.array(values, dtype=jnp.float32) large_step = jnp.array([large_step] * len(boundaries), dtype=jnp.int32) boundaries = jnp.array(boundaries, dtype=jnp.int32) def _get(step): """Returns the value according to the current step and schedule.""" b = boundaries - jnp.minimum(step + 1, large_step + 1) b = jnp.where(b < 0, large_step, b) idx = jnp.minimum(jnp.argmin(b), num_values - 1) return values[idx].astype(dtype) return _get class Square: """Performs a blackbox optimization as in https://arxiv.org/pdf/1912.00049.""" def __init__( self, num_steps: int, epsilon: chex.Numeric, <|code_end|> . Use current file imports: from typing import Callable, List, Tuple from jax_verify.extensions.functional_lagrangian.inner_solvers.pga import utils import chex import jax import jax.numpy as jnp and context (classes, functions, or code) from other files: # Path: jax_verify/extensions/functional_lagrangian/inner_solvers/pga/utils.py # def linf_project_fn(epsilon: float, bounds: Tuple[float, float]) -> ProjectFn: # def project_fn(x, origin_x): # def bounded_initialize_fn( # bounds: Optional[Tuple[chex.Array, chex.Array]] = None,) -> InitializeFn: # def _initialize_fn(rng, x): # def noop_initialize_fn() -> InitializeFn: # def _initialize_fn(rng, x): . Output only the next line.
initialize_fn: utils.InitializeFn,
Given the code snippet: <|code_start|># nu_quad: IBP quadratic matrix constraint: (x_i - l_i)(x_j - u_j) <= 0 # muminus: x'>=0 # muminus2: Triangle linear Relu relaxation - u(Wx+b) - ul - (u-l)x' >= 0 # where l = min(l, 0), u = max(u, 0) # muplus: x'>=Wx+b DualVar = collections.namedtuple( 'DualVar', ['lam', 'nu', 'nu_quad', 'muminus', 'muplus', 'muminus2']) DualVarFin = collections.namedtuple('DualVarFin', ['nu', 'nu_quad']) DEFAULT_DISABLED_DUAL_VARS = ('nu_quad', 'muminus2') NECESSARY_DUAL_VARS = ('lam', 'muplus', 'muminus') def make_relu_network_lagrangian(dual_vars, params, bounds, obj): """Returns a function that computes the Lagrangian for a ReLU network. This function assumes `params` represent a feedforward ReLU network i.e. x_{i+1} = relu(W_i x_i + b_i). It defines the Lagrangian by applying the objective `obj` to the final layer activations, and encoding the Lagrangian terms for each of the constraints defining the ReLU network. It then returns this function. Args: dual_vars: A length L+1 list of dual variables at each layer params: A length L list of (W, b) pairs, elided network weights bounds: A length L+1 list of `IntBound`s, elided bounds at each layer obj: function, taking final layer activations as input Returns: Function that computes Lagrangian L(x) with fixed `dual_vars`. """ <|code_end|> , generate the next line using the imports in this file: import collections import jax.numpy as jnp import numpy as np from jax_verify.extensions.sdp_verify import utils and context (functions, classes, or occasionally code) from other files: # Path: jax_verify/extensions/sdp_verify/utils.py # class SdpDualVerifInstance(_SdpDualVerifInstance): # class VerifInstanceTypes(enum.Enum): # class DualVarTypes(enum.Enum): # def mlp_layer_sizes(params): # def nn_layer_sizes(params): # def layer_sizes_from_bounds(bounds): # def predict_mlp(params, inputs): # def fwd(inputs, layer_params): # def predict_cnn(params, inputs, include_preactivations=False): # def get_network_activs(params, x): # def get_layer_params(fun_to_extract, example_input): # def _get_const_input_arg(eqn): # def boundprop(params, bounds_in): # def init_bound(x, epsilon, input_bounds=(0., 1.), add_batch_dim=True): # def ibp_bound_elided(verif_instance): # def ibp_bound_nonelided(verif_instance): # def make_relu_robust_verif_instance( # params, bounds=None, target_label=1, label=2, input_bounds=None): # def make_relu_robust_verif_instance_elided( # params, bounds=None, input_bounds=None): # def output_size_and_verif_type(params, bounds): # def elide_params(params, label, target_label, op_size): # def preprocess_cifar(image, inception_preprocess=False, perturbation=False): # def preprocessed_cifar_eps_and_input_bounds( # shape=(32, 32, 3), epsilon=2/255, inception_preprocess=False): # def adv_objective(model_fn, x, label, target_label): # def fgsm_single(model_fn, x, label, target_label, epsilon, num_steps, # step_size, input_bounds=(0., 1.)): # def untargeted_margin_loss(logits, labels): # def pgd_default(model_fn, x, label, epsilon, num_steps, step_size, # input_bounds=(0., 1.)): # def pgd(adv_loss, x_init, epsilon, num_steps, step_size, input_bounds=(0., 1.)): # def scale_by_variable_opt(multipliers): # def init_fn(params): # def update_fn(updates, _, params=None): # def flatten(pytree, backend=np): # def unflatten_like(a, pytree): # def structure_like(tree1, tree2): # MLP_ELIDED = 'mlp_elided' # CNN_ELIDED = 'cnn_elided' # EQUALITY = 'equality' # INEQUALITY = 'inequality' . Output only the next line.
layer_sizes = utils.layer_sizes_from_bounds(bounds)
Based on the snippet: <|code_start|># 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. # Lint as: python3 """Tests for crown_boundprop.py.""" class BoundpropTest(parameterized.TestCase): def test_crown_boundprop(self): """Test CROWN bounds vs FGSM on Wong-Small MNIST CNN.""" crown_boundprop = functools.partial(boundprop_utils.boundprop, boundprop_type='crown_ibp') self._test_boundprop(crown_boundprop) def test_nonconvex_boundprop(self): """Test Nonconvex bounds vs FGSM on Wong-Small MNIST CNN.""" # Minimal test, since this already takes 70s. nonconvex_boundprop = functools.partial( boundprop_utils.boundprop, boundprop_type='nonconvex', nonconvex_boundprop_steps=2) self._test_boundprop(nonconvex_boundprop, num_idxs_to_test=1) def test_ibp_boundprop(self): def boundprop(params, x, epsilon, input_bounds): assert len(x.shape) == 4 and x.shape[0] == 1, f'shape check {x.shape}' <|code_end|> , predict the immediate next line with the help of imports: import functools import pickle import jax import jax.numpy as jnp import jax_verify import numpy as np from absl.testing import absltest from absl.testing import parameterized from jax_verify.extensions.sdp_verify import boundprop_utils from jax_verify.extensions.sdp_verify import utils and context (classes, functions, sometimes code) from other files: # Path: jax_verify/extensions/sdp_verify/boundprop_utils.py # def boundprop(params, x, epsilon, input_bounds, boundprop_type, # **extra_boundprop_kwargs): # def _crown_ibp_boundprop(params, x, epsilon, input_bounds): # def get_layer_act(layer_idx, inputs): # def _nonconvex_boundprop(params, x, epsilon, input_bounds, # nonconvex_boundprop_steps=100, # nonconvex_boundprop_nodes=128): # # Path: jax_verify/extensions/sdp_verify/utils.py # class SdpDualVerifInstance(_SdpDualVerifInstance): # class VerifInstanceTypes(enum.Enum): # class DualVarTypes(enum.Enum): # def mlp_layer_sizes(params): # def nn_layer_sizes(params): # def layer_sizes_from_bounds(bounds): # def predict_mlp(params, inputs): # def fwd(inputs, layer_params): # def predict_cnn(params, inputs, include_preactivations=False): # def get_network_activs(params, x): # def get_layer_params(fun_to_extract, example_input): # def _get_const_input_arg(eqn): # def boundprop(params, bounds_in): # def init_bound(x, epsilon, input_bounds=(0., 1.), add_batch_dim=True): # def ibp_bound_elided(verif_instance): # def ibp_bound_nonelided(verif_instance): # def make_relu_robust_verif_instance( # params, bounds=None, target_label=1, label=2, input_bounds=None): # def make_relu_robust_verif_instance_elided( # params, bounds=None, input_bounds=None): # def output_size_and_verif_type(params, bounds): # def elide_params(params, label, target_label, op_size): # def preprocess_cifar(image, inception_preprocess=False, perturbation=False): # def preprocessed_cifar_eps_and_input_bounds( # shape=(32, 32, 3), epsilon=2/255, inception_preprocess=False): # def adv_objective(model_fn, x, label, target_label): # def fgsm_single(model_fn, x, label, target_label, epsilon, num_steps, # step_size, input_bounds=(0., 1.)): # def untargeted_margin_loss(logits, labels): # def pgd_default(model_fn, x, label, epsilon, num_steps, step_size, # input_bounds=(0., 1.)): # def pgd(adv_loss, x_init, epsilon, num_steps, step_size, input_bounds=(0., 1.)): # def scale_by_variable_opt(multipliers): # def init_fn(params): # def update_fn(updates, _, params=None): # def flatten(pytree, backend=np): # def unflatten_like(a, pytree): # def structure_like(tree1, tree2): # MLP_ELIDED = 'mlp_elided' # CNN_ELIDED = 'cnn_elided' # EQUALITY = 'equality' # INEQUALITY = 'inequality' . Output only the next line.
init_bound = utils.init_bound(x[0], epsilon, input_bounds=input_bounds)
Given the following code snippet before the placeholder: <|code_start|># coding=utf-8 # Copyright 2021 DeepMind Technologies Limited. # # 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 # # http://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. """Adversarial attacks.""" IntervalBound = jax_verify.IntervalBound Tensor = jnp.DeviceArray PRNGKey = jnp.DeviceArray <|code_end|> , predict the next line using imports from the current file: import dataclasses import jax import jax.numpy as jnp import jax_verify import optax from typing import Callable, Union from jax_verify.extensions.functional_lagrangian import verify_utils from jax_verify.extensions.sdp_verify import utils as sdp_utils and context including class names, function names, and sometimes code from other files: # Path: jax_verify/extensions/functional_lagrangian/verify_utils.py # class AbstractParams(abc.ABC): # class FCParams(AbstractParams): # class ConvParams(AbstractParams): # class SpecType(enum.Enum): # class Distribution(enum.Enum): # class NetworkType(enum.Enum): # class InnerVerifInstance: # def __call__(self, inputs: Tensor) -> Tensor: # def params(self): # def has_bounds(self): # def params(self): # def params(self): # def same_lagrangian_form_pre_post(self) -> bool: # UNCERTAINTY = 'uncertainty' # ADVERSARIAL = 'adversarial' # ADVERSARIAL_SOFTMAX = 'adversarial_softmax' # PROBABILITY_THRESHOLD = 'probability_threshold' # GAUSSIAN = 'gaussian' # BERNOULLI = 'bernoulli' # DETERMINISTIC = 'deterministic' # STOCHASTIC = 'stochastic' # # Path: jax_verify/extensions/sdp_verify/utils.py # class SdpDualVerifInstance(_SdpDualVerifInstance): # class VerifInstanceTypes(enum.Enum): # class DualVarTypes(enum.Enum): # def mlp_layer_sizes(params): # def nn_layer_sizes(params): # def layer_sizes_from_bounds(bounds): # def predict_mlp(params, inputs): # def fwd(inputs, layer_params): # def predict_cnn(params, inputs, include_preactivations=False): # def get_network_activs(params, x): # def get_layer_params(fun_to_extract, example_input): # def _get_const_input_arg(eqn): # def boundprop(params, bounds_in): # def init_bound(x, epsilon, input_bounds=(0., 1.), add_batch_dim=True): # def ibp_bound_elided(verif_instance): # def ibp_bound_nonelided(verif_instance): # def make_relu_robust_verif_instance( # params, bounds=None, target_label=1, label=2, input_bounds=None): # def make_relu_robust_verif_instance_elided( # params, bounds=None, input_bounds=None): # def output_size_and_verif_type(params, bounds): # def elide_params(params, label, target_label, op_size): # def preprocess_cifar(image, inception_preprocess=False, perturbation=False): # def preprocessed_cifar_eps_and_input_bounds( # shape=(32, 32, 3), epsilon=2/255, inception_preprocess=False): # def adv_objective(model_fn, x, label, target_label): # def fgsm_single(model_fn, x, label, target_label, epsilon, num_steps, # step_size, input_bounds=(0., 1.)): # def untargeted_margin_loss(logits, labels): # def pgd_default(model_fn, x, label, epsilon, num_steps, step_size, # input_bounds=(0., 1.)): # def pgd(adv_loss, x_init, epsilon, num_steps, step_size, input_bounds=(0., 1.)): # def scale_by_variable_opt(multipliers): # def init_fn(params): # def update_fn(updates, _, params=None): # def flatten(pytree, backend=np): # def unflatten_like(a, pytree): # def structure_like(tree1, tree2): # MLP_ELIDED = 'mlp_elided' # CNN_ELIDED = 'cnn_elided' # EQUALITY = 'equality' # INEQUALITY = 'inequality' . Output only the next line.
DataSpec = verify_utils.DataSpec
Predict the next line after this snippet: <|code_start|> std=layer_params.b_std, bounds=layer_params.b_bound, prng_key=key_b, ) layer_params = dataclasses.replace(layer_params, b=b_sampled) sampled_params.append(layer_params) return sampled_params return sample_fn def make_forward( model_params: ModelParams, num_samples: int, ) -> Callable[[Tensor, PRNGKey], Tensor]: """Make forward_fn with parameter sampling and averaging in softmax space. Args: model_params: model parameters. num_samples: number of samples drawn per call to forward_fn. Returns: function that draws parameter samples, averages their results in softmax space and takes the log. """ sampling_fn = make_params_sampling_fn(model_params) def single_forward(inputs, prng_key): sampled_params = sampling_fn(prng_key) <|code_end|> using the current file's imports: import dataclasses import jax import jax.numpy as jnp import jax_verify import optax from typing import Callable, Union from jax_verify.extensions.functional_lagrangian import verify_utils from jax_verify.extensions.sdp_verify import utils as sdp_utils and any relevant context from other files: # Path: jax_verify/extensions/functional_lagrangian/verify_utils.py # class AbstractParams(abc.ABC): # class FCParams(AbstractParams): # class ConvParams(AbstractParams): # class SpecType(enum.Enum): # class Distribution(enum.Enum): # class NetworkType(enum.Enum): # class InnerVerifInstance: # def __call__(self, inputs: Tensor) -> Tensor: # def params(self): # def has_bounds(self): # def params(self): # def params(self): # def same_lagrangian_form_pre_post(self) -> bool: # UNCERTAINTY = 'uncertainty' # ADVERSARIAL = 'adversarial' # ADVERSARIAL_SOFTMAX = 'adversarial_softmax' # PROBABILITY_THRESHOLD = 'probability_threshold' # GAUSSIAN = 'gaussian' # BERNOULLI = 'bernoulli' # DETERMINISTIC = 'deterministic' # STOCHASTIC = 'stochastic' # # Path: jax_verify/extensions/sdp_verify/utils.py # class SdpDualVerifInstance(_SdpDualVerifInstance): # class VerifInstanceTypes(enum.Enum): # class DualVarTypes(enum.Enum): # def mlp_layer_sizes(params): # def nn_layer_sizes(params): # def layer_sizes_from_bounds(bounds): # def predict_mlp(params, inputs): # def fwd(inputs, layer_params): # def predict_cnn(params, inputs, include_preactivations=False): # def get_network_activs(params, x): # def get_layer_params(fun_to_extract, example_input): # def _get_const_input_arg(eqn): # def boundprop(params, bounds_in): # def init_bound(x, epsilon, input_bounds=(0., 1.), add_batch_dim=True): # def ibp_bound_elided(verif_instance): # def ibp_bound_nonelided(verif_instance): # def make_relu_robust_verif_instance( # params, bounds=None, target_label=1, label=2, input_bounds=None): # def make_relu_robust_verif_instance_elided( # params, bounds=None, input_bounds=None): # def output_size_and_verif_type(params, bounds): # def elide_params(params, label, target_label, op_size): # def preprocess_cifar(image, inception_preprocess=False, perturbation=False): # def preprocessed_cifar_eps_and_input_bounds( # shape=(32, 32, 3), epsilon=2/255, inception_preprocess=False): # def adv_objective(model_fn, x, label, target_label): # def fgsm_single(model_fn, x, label, target_label, epsilon, num_steps, # step_size, input_bounds=(0., 1.)): # def untargeted_margin_loss(logits, labels): # def pgd_default(model_fn, x, label, epsilon, num_steps, step_size, # input_bounds=(0., 1.)): # def pgd(adv_loss, x_init, epsilon, num_steps, step_size, input_bounds=(0., 1.)): # def scale_by_variable_opt(multipliers): # def init_fn(params): # def update_fn(updates, _, params=None): # def flatten(pytree, backend=np): # def unflatten_like(a, pytree): # def structure_like(tree1, tree2): # MLP_ELIDED = 'mlp_elided' # CNN_ELIDED = 'cnn_elided' # EQUALITY = 'equality' # INEQUALITY = 'inequality' . Output only the next line.
logits = sdp_utils.predict_cnn(
Predict the next line after this snippet: <|code_start|> class SubpixIndexTestCase(unittest.TestCase): """ Tests for get_healsparse_subpix_indices """ def test_subpix_nside_lt_cov_nside(self): """ Test when subpix_nside is less than coverage nside """ # Test with no border... subpix_nside = 2 subpix_hpix = [16] subpix_border = 0.0 coverage_nside = 32 <|code_end|> using the current file's imports: import unittest import numpy.testing as testing import numpy as np import healpy as hp import os import esutil from redmapper.utilities import get_healsparse_subpix_indices and any relevant context from other files: # Path: redmapper/utilities.py # def get_healsparse_subpix_indices(subpix_nside, subpix_hpix, subpix_border, coverage_nside): # """ # Retrieve the coverage pixels that intersect the region, with a border. # # Parameters # ---------- # subpix_nside: `int` # Nside for the subregion # subpix_hpix: `list` # Pixel numbers for the subregion (ring format). # subpix_border: `float` # Border radius to cover outside subpix_hpix # coverage_nside: `int` # Nside of the healsparse coverage map # """ # # if len(subpix_hpix) == 0: # raise RuntimeError("subpix_hpix cannot be an empty list.") # if subpix_border > 0.0 and len(subpix_hpix) > 1: # raise NotImplementedError("Cannot read multiple subpixels with a border.") # # # First, we need to know which pixel(s) from nside_coverage are covered by # # subpix_hpix # # if subpix_nside == 0: # # Special case for the full sky # return None # elif subpix_nside == coverage_nside: # covpix = hp.ring2nest(subpix_nside, subpix_hpix) # elif subpix_nside > coverage_nside: # # what pixels are these contained in? # theta, phi = hp.pix2ang(subpix_nside, subpix_hpix, nest=False) # covpix = hp.ang2pix(coverage_nside, theta, phi, nest=True) # else: # # This is subpix_nside < coverage_nside # # what coverage pixels are contained in subpix_hpix? # subpix_hpix_nest = hp.ring2nest(subpix_nside, subpix_hpix) # bit_shift = 2 * int(np.round(np.log(coverage_nside / subpix_nside) / np.log(2))) # n_pix_per_pix = 2**bit_shift # covpix = np.zeros(len(subpix_hpix_nest) * n_pix_per_pix, dtype=np.int64) # for i, hpix in enumerate(subpix_hpix_nest): # covpix[i * n_pix_per_pix: (i + 1) * n_pix_per_pix] = np.left_shift(hpix, bit_shift) + np.arange(n_pix_per_pix) # # # And now if we have a border...(only if the length is 1) # if subpix_border > 0.0: # nside_testing = max([coverage_nside * 4, subpix_nside * 4]) # boundaries = hp.boundaries(subpix_nside, subpix_hpix[0], step=nside_testing/subpix_nside) # # extrapix = np.zeros(0, dtype=np.int64) # # # These are pixels that touch the boundary # for i in range(boundaries.shape[1]): # pixint = hp.query_disc(nside_testing, boundaries[:, i], # np.radians(subpix_border), inclusive=True, fact=8) # extrapix = np.append(extrapix, pixint) # # extrapix = np.unique(extrapix) # theta, phi = hp.pix2ang(nside_testing, extrapix) # covpix = np.unique(np.append(covpix, hp.ang2pix(coverage_nside, theta, phi, nest=True))) # # return covpix . Output only the next line.
covpix = get_healsparse_subpix_indices(subpix_nside, subpix_hpix, subpix_border, coverage_nside)
Next line prediction: <|code_start|> """ def find_center(self): """ Find the center using the CenteringWcenZred algorithm. This algorithm computes the primary centering likelihood algorithm by computing the connectivity of the members, as well as ensuring consistency between zred of the candidates and the cluster redshift. Will set self.maxind (index of best center); self.ra, self.dec (position of best center); self.ngood (number of good candidates); self.index[:] (indices of all the candidates); self.p_cen[:] (pcen centering probabilities); self.q_cen[:] (qcen unused miss probabilities); self.p_sat[:] (p_sat satellite probabilities). Returns ------- success: `bool` True when a center is successfully found. (Always True). """ # These are the galaxies considered as candidate centers use, = np.where((self.cluster.neighbors.r < self.cluster.r_lambda) & (self.cluster.neighbors.pfree >= self.config.percolation_pbcg_cut) & (self.cluster.neighbors.zred_chisq < self.config.wcen_zred_chisq_max) & ((self.cluster.neighbors.pmem > 0.0) | (np.abs(self.cluster.redshift - self.cluster.neighbors.zred) < 5.0 * self.cluster.neighbors.zred_e))) # Do the phi_cen filter mbar = self.cluster.mstar + self.config.wcen_Delta0 + self.config.wcen_Delta1 * np.log(self.cluster.Lambda / self.config.wcen_pivot) <|code_end|> . Use current file imports: (import fitsio import esutil import numpy as np from .utilities import gaussFunction from .utilities import interpol) and context including class names, function names, or small code snippets from other files: # Path: redmapper/utilities.py # def gaussFunction(x, *p): # """ # Compute a normalizes Gaussian G(x) for a given set of parameters # # Parameters # ---------- # x: `np.array` # Float array of x values # A: `float` # Normalization of the Gaussian # mu: `float` # Mean value (mu) for the Gaussian # sigma: `float` # Gaussian sigma # # Returns # ------- # pdf: `np.array` # Float array of Gaussian pdf values # """ # A, mu, sigma = p # return A*np.exp(-(x-mu)**2./(2.*sigma**2)) # # Path: redmapper/utilities.py # def interpol(v, x, xout): # """ # Port of IDL interpol.py. Does fast and simple linear interpolation. # # Parameters # ---------- # v: `np.array` # Float array of y (dependent) values to interpolate between # x: `np.array` # Float array of x (independent) values to interpolate between # xout: `np.array` # Float array of x values to compute interpolated values # # Returns # ------- # yout: `np.array` # Float array of y output values associated with xout # """ # # m = v.size # nOut = m # # s = np.clip(np.searchsorted(x, xout) - 1, 0, m - 2) # # diff = v[s + 1] - v[s] # # return (xout - x[s]) * diff / (x[s + 1] - x[s]) + v[s] . Output only the next line.
phi_cen = gaussFunction(self.cluster.neighbors.refmag[use],
Based on the snippet: <|code_start|> This algorithm computes the primary centering likelihood algorithm by computing the connectivity of the members, as well as ensuring consistency between zred of the candidates and the cluster redshift. Will set self.maxind (index of best center); self.ra, self.dec (position of best center); self.ngood (number of good candidates); self.index[:] (indices of all the candidates); self.p_cen[:] (pcen centering probabilities); self.q_cen[:] (qcen unused miss probabilities); self.p_sat[:] (p_sat satellite probabilities). Returns ------- success: `bool` True when a center is successfully found. (Always True). """ # These are the galaxies considered as candidate centers use, = np.where((self.cluster.neighbors.r < self.cluster.r_lambda) & (self.cluster.neighbors.pfree >= self.config.percolation_pbcg_cut) & (self.cluster.neighbors.zred_chisq < self.config.wcen_zred_chisq_max) & ((self.cluster.neighbors.pmem > 0.0) | (np.abs(self.cluster.redshift - self.cluster.neighbors.zred) < 5.0 * self.cluster.neighbors.zred_e))) # Do the phi_cen filter mbar = self.cluster.mstar + self.config.wcen_Delta0 + self.config.wcen_Delta1 * np.log(self.cluster.Lambda / self.config.wcen_pivot) phi_cen = gaussFunction(self.cluster.neighbors.refmag[use], 1. / (np.sqrt(2. * np.pi) * self.config.wcen_sigma_m), mbar, self.config.wcen_sigma_m) if self.zlambda_corr is not None: <|code_end|> , predict the immediate next line with the help of imports: import fitsio import esutil import numpy as np from .utilities import gaussFunction from .utilities import interpol and context (classes, functions, sometimes code) from other files: # Path: redmapper/utilities.py # def gaussFunction(x, *p): # """ # Compute a normalizes Gaussian G(x) for a given set of parameters # # Parameters # ---------- # x: `np.array` # Float array of x values # A: `float` # Normalization of the Gaussian # mu: `float` # Mean value (mu) for the Gaussian # sigma: `float` # Gaussian sigma # # Returns # ------- # pdf: `np.array` # Float array of Gaussian pdf values # """ # A, mu, sigma = p # return A*np.exp(-(x-mu)**2./(2.*sigma**2)) # # Path: redmapper/utilities.py # def interpol(v, x, xout): # """ # Port of IDL interpol.py. Does fast and simple linear interpolation. # # Parameters # ---------- # v: `np.array` # Float array of y (dependent) values to interpolate between # x: `np.array` # Float array of x (independent) values to interpolate between # xout: `np.array` # Float array of x values to compute interpolated values # # Returns # ------- # yout: `np.array` # Float array of y output values associated with xout # """ # # m = v.size # nOut = m # # s = np.clip(np.searchsorted(x, xout) - 1, 0, m - 2) # # diff = v[s + 1] - v[s] # # return (xout - x[s]) * diff / (x[s + 1] - x[s]) + v[s] . Output only the next line.
zrmod = interpol(self.zlambda_corr.zred_uncorr, self.zlambda_corr.z, self.cluster.redshift)
Given the following code snippet before the placeholder: <|code_start|> # validate the galfile and refmag type(self).__dict__['galfile'].validate('galfile') type(self).__dict__['refmag'].validate('refmag') # get galaxy file stats gal_stats = self._galfile_stats() self.galfile_area = gal_stats['area'] if (self.area is not None): if self.depthfile is not None: self.logger.info("WARNING: You should not need to set area in the config file when you have a depth map.") if (np.abs(self.area - gal_stats['area']) > 1e-3): self.logger.info("Config area is not equal to galaxy file area. Using config area.") gal_stats.pop('area') else: if self.depthfile is None and self.nside > 0 and len(self.hpix) > 0: raise RuntimeError("You must set a config file area if no depthfile is present and you are running a sub-region") self._set_vars_from_dict(gal_stats, check_none=True) if self.limmag_catalog is None: self.limmag_catalog = self.limmag_ref # Get wcen numbers if available self.set_wcen_vals() # Set some defaults if self.specfile_train is None: self.specfile_train = self.specfile # Record the cluster dtype for convenience <|code_end|> , predict the next line using imports from the current file: import yaml import fitsio import copy import numpy as np import re import os import logging from esutil.cosmology import Cosmo from .cluster import cluster_dtype_base, member_dtype_base from ._version import __version__ and context including class names, function names, and sometimes code from other files: # Path: redmapper/cluster.py # class Cluster(Entry): # class ClusterCatalog(Catalog): # def __init__(self, cat_vals=None, r0=None, beta=None, config=None, zredstr=None, bkg=None, cbkg=None, neighbors=None, zredbkg=None, dtype=None): # def reset(self): # def set_neighbors(self, neighbors): # def find_neighbors(self, radius, galcat, megaparsec=False, maxmag=None): # def update_neighbors_dist(self): # def clear_neighbors(self): # def _calc_radial_profile(self, idx=None, rscale=0.15): # def _calc_luminosity(self, normmag, idx=None): # def calc_bkg_density(self, r, chisq, refmag): # def calc_cbkg_density(self, r, col_index, col, refmag): # def calc_zred_bkg_density(self, r, zred, refmag): # def compute_bkg_local(self, mask, depth): # def calc_richness(self, mask, calc_err=True, index=None): # def calc_lambdacerr(self, maskgals, mstar, lam, rlam, pmem, cval, gamma): # def calc_richness_fit(self, mask, col_index, centcolor_in=None, rcut=0.5, mingal=5, sigint=0.05, calc_err=False): # def redshift(self): # def redshift(self, value): # def mstar(self): # def _update_mstar(self): # def mpc_scale(self): # def _update_mpc_scale(self): # def _compute_neighbor_r(self): # def copy(self): # def __copy__(self): # def __init__(self, array, **kwargs): # def from_catfile(cls, filename, **kwargs): # def zeros(cls, size, **kwargs): # def __getitem__(self, key): # # Path: redmapper/_version.py . Output only the next line.
self.cluster_dtype = copy.copy(cluster_dtype_base)