Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Continue the code snippet: <|code_start|> elif path.type == 'ordered': return OrderedComparator() elif path.type == 'uniquekey': return UniqueKeyComparator(keys=path.keys) class OrderedComparator: def __init__(self): self.DEL = [] self.SET= [] self.ADD = [] def decide(self, wanted, difference, present): if wanted and difference and not present: self.ADD.append( wanted ) elif not wanted and not difference and present: self.DEL.append( present ) elif wanted and difference and present: difference['.id'] = present['.id'] self.SET.append( difference ) def compare(self, wanted, present): <|code_end|> . Use current file imports: from itertools import zip_longest from mcm.datastructures import CmdPathRow and context (classes, functions, or code) from other files: # Path: mcm/datastructures.py # class CmdPathRow(dict): # # # def __str__(self): # bool_map = {True:'yes', False:'no', None:'""', '':'""'} # return ' '.join('{}={}'.format(key, bool_map.get(value, value)) for key, value in self.items()) # # # def __hash__(self): # return hash(tuple(self.items())) # # # def __sub__(self, other): # '''Return new instance with key,valie pairs from self not listed in other.''' # # diff = dict(set(self.items()) - set(other.items())) # return CmdPathRow( diff ) # # # def isunique(self, other, keys): # '''Test whether every key,value pair (from keys) is in other.''' # # pairs = set( (key,self[key]) for key in keys ) # return pairs <= set(other.items()) . Output only the next line.
fillval = CmdPathRow(dict())
Given the code snippet: <|code_start|> '=key=value', '=.id=value', ) key_value_tuples = ( ('key','value'), ('.id','value'), ) @pytest.mark.parametrize("word,expected", zip(api_words,key_value_tuples)) def test_converting_api_word_to_tuple(word, expected): assert convattrwrd(word) == expected @pytest.mark.parametrize("word,pair", zip(api_words,key_value_tuples)) def test_converting_tuple_to_api_word(word,pair): assert mkattrwrd(pair) == word @pytest.mark.parametrize("sentence,api_sentence", ( ( {'interface':'ether1','address':'1.1.1.1/23'}, ('=interface=ether1','=address=1.1.1.1/23') ), ( {'interface':'ether1','address':'1.1.1.1/23','.tag':2}, ('=interface=ether1','=address=1.1.1.1/23', '.tag=2') ), )) def test_api_sentence_creation(sentence,api_sentence): assert set(mksnt(sentence)) == set(api_sentence) @pytest.mark.parametrize("response,expected", ( ( ( ('=disabled=no','.tag=1'),('.tag=4','!done') ), ({'disabled':False},) ), )) def test_api_response_parsing(response,expected): <|code_end|> , generate the next line using the imports in this file: import pytest from mcm.librouteros.datastructures import parsresp, parsnt, mksnt, mkattrwrd, convattrwrd, castValToPy, castValToApi, raiseIfFatal, trapCheck from mcm.librouteros.exceptions import CmdError, ConnError and context (functions, classes, or occasionally code) from other files: # Path: mcm/librouteros/datastructures.py # def parsresp(sentences): # ''' # Parse given response to set of dictionaries containing parsed sentences. # # :praam sentences: Iterable (tuple,list) with each element as a sentence # ''' # # response = map( parsnt, sentences ) # # filter out empty sentences # filtered = filter( None, response ) # return tuple( filtered ) # # def parsnt( snt ): # ''' # Parse given sentence from attribute words to dictionary. # Only retrieve words that start with '='. # This method may return an empty dictionary. # # :param snt: Iterable sentence. # :returns: Dictionary with attributes. # ''' # # attrs = ( word for word in snt if word.startswith( '=' ) ) # attrs = map( convattrwrd, attrs ) # # return dict( attrs ) # # def mksnt( data ): # ''' # Convert dictionary to attribute words. # # :param args: Dictionary with key value attributes. # Those will be converted to attribute words. # # :returns: Tuple with attribute words. # ''' # # converted = map( mkattrwrd, data.items() ) # return tuple( converted ) # # def mkattrwrd( kv ): # ''' # Make an attribute word out of key value tuple. Values and keys are automaticly casted # to api equivalents. # # :param kv: Two element tuple. First key, second value. # ''' # # key, value = kv # casted_value = castValToApi( value ) # prefix = '' if key == '.tag' else '=' # # return '{prefix}{key}={value}'.format( prefix=prefix, key=key, value=casted_value ) # # def convattrwrd( word ): # ''' # Make an key value tuple out of attribute word. Values and keys # are automaticly casted to python equivalents. # # :param word: Attribute word. # ''' # # splitted = word.split( '=', 2 ) # key = splitted[1] # value = splitted[2] # casted_value = castValToPy( value ) # # return ( key, casted_value ) # # def castValToPy( value ): # # try: # casted = int( value ) # except ValueError: # casted = to_py_mapping.get( value, value ) # return casted # # def castValToApi( value ): # # if type(value) == int: # return str(value) # else: # return to_api_mapping.get( value, str( value ) ) # # def raiseIfFatal( sentence ): # ''' # Check if a given sentence contains error message. If it does then raise an exception. # !fatal means that connection have been closed and no further transmission will work. # ''' # # if '!fatal' in sentence: # error = ', '.join( word for word in sentence if word != '!fatal' ) # raise ConnError( error ) # # def trapCheck( snts ): # ''' # Check for existance of !trap word. This word indicates that an error occured. # At least one !trap word in any sentence triggers an error. # Unfortunatelly mikrotik api may throw one or more errors as response. # # :param snts: Iterable with each sentence as tuple # ''' # # errmsgs = [] # # for snt in snts: # if '!trap' in snt: # emsg = ' '.join( word for word in snt ) # errmsgs.append( emsg ) # # if errmsgs: # e = ', '.join( errmsgs ) # raise CmdError( e ) # # Path: mcm/librouteros/exceptions.py # class CmdError( LibError ): # ''' # Commend execution errors. # ''' # # class ConnError( LibError ): # ''' # Connection related errors. # ''' . Output only the next line.
assert parsresp(response) == (expected)
Given snippet: <|code_start|>def test_converting_api_word_to_tuple(word, expected): assert convattrwrd(word) == expected @pytest.mark.parametrize("word,pair", zip(api_words,key_value_tuples)) def test_converting_tuple_to_api_word(word,pair): assert mkattrwrd(pair) == word @pytest.mark.parametrize("sentence,api_sentence", ( ( {'interface':'ether1','address':'1.1.1.1/23'}, ('=interface=ether1','=address=1.1.1.1/23') ), ( {'interface':'ether1','address':'1.1.1.1/23','.tag':2}, ('=interface=ether1','=address=1.1.1.1/23', '.tag=2') ), )) def test_api_sentence_creation(sentence,api_sentence): assert set(mksnt(sentence)) == set(api_sentence) @pytest.mark.parametrize("response,expected", ( ( ( ('=disabled=no','.tag=1'),('.tag=4','!done') ), ({'disabled':False},) ), )) def test_api_response_parsing(response,expected): assert parsresp(response) == (expected) @pytest.mark.parametrize("api_sentence,expected", ( ( ('.tag=1','!done'), dict() ), ( ('=disabled=false','=interface=ether1','.tag=2'), {'disabled':False,'interface':'ether1'} ), ( ('=disabled=false','=interface=ether1'), {'disabled':False,'interface':'ether1'} ), )) def test_api_sentence_parsing(api_sentence,expected): <|code_end|> , continue by predicting the next line. Consider current file imports: import pytest from mcm.librouteros.datastructures import parsresp, parsnt, mksnt, mkattrwrd, convattrwrd, castValToPy, castValToApi, raiseIfFatal, trapCheck from mcm.librouteros.exceptions import CmdError, ConnError and context: # Path: mcm/librouteros/datastructures.py # def parsresp(sentences): # ''' # Parse given response to set of dictionaries containing parsed sentences. # # :praam sentences: Iterable (tuple,list) with each element as a sentence # ''' # # response = map( parsnt, sentences ) # # filter out empty sentences # filtered = filter( None, response ) # return tuple( filtered ) # # def parsnt( snt ): # ''' # Parse given sentence from attribute words to dictionary. # Only retrieve words that start with '='. # This method may return an empty dictionary. # # :param snt: Iterable sentence. # :returns: Dictionary with attributes. # ''' # # attrs = ( word for word in snt if word.startswith( '=' ) ) # attrs = map( convattrwrd, attrs ) # # return dict( attrs ) # # def mksnt( data ): # ''' # Convert dictionary to attribute words. # # :param args: Dictionary with key value attributes. # Those will be converted to attribute words. # # :returns: Tuple with attribute words. # ''' # # converted = map( mkattrwrd, data.items() ) # return tuple( converted ) # # def mkattrwrd( kv ): # ''' # Make an attribute word out of key value tuple. Values and keys are automaticly casted # to api equivalents. # # :param kv: Two element tuple. First key, second value. # ''' # # key, value = kv # casted_value = castValToApi( value ) # prefix = '' if key == '.tag' else '=' # # return '{prefix}{key}={value}'.format( prefix=prefix, key=key, value=casted_value ) # # def convattrwrd( word ): # ''' # Make an key value tuple out of attribute word. Values and keys # are automaticly casted to python equivalents. # # :param word: Attribute word. # ''' # # splitted = word.split( '=', 2 ) # key = splitted[1] # value = splitted[2] # casted_value = castValToPy( value ) # # return ( key, casted_value ) # # def castValToPy( value ): # # try: # casted = int( value ) # except ValueError: # casted = to_py_mapping.get( value, value ) # return casted # # def castValToApi( value ): # # if type(value) == int: # return str(value) # else: # return to_api_mapping.get( value, str( value ) ) # # def raiseIfFatal( sentence ): # ''' # Check if a given sentence contains error message. If it does then raise an exception. # !fatal means that connection have been closed and no further transmission will work. # ''' # # if '!fatal' in sentence: # error = ', '.join( word for word in sentence if word != '!fatal' ) # raise ConnError( error ) # # def trapCheck( snts ): # ''' # Check for existance of !trap word. This word indicates that an error occured. # At least one !trap word in any sentence triggers an error. # Unfortunatelly mikrotik api may throw one or more errors as response. # # :param snts: Iterable with each sentence as tuple # ''' # # errmsgs = [] # # for snt in snts: # if '!trap' in snt: # emsg = ' '.join( word for word in snt ) # errmsgs.append( emsg ) # # if errmsgs: # e = ', '.join( errmsgs ) # raise CmdError( e ) # # Path: mcm/librouteros/exceptions.py # class CmdError( LibError ): # ''' # Commend execution errors. # ''' # # class ConnError( LibError ): # ''' # Connection related errors. # ''' which might include code, classes, or functions. Output only the next line.
assert parsnt(api_sentence) == expected
Given the code snippet: <|code_start|> (1, '1'), (0, '0') )) def test_casting_from_python_to_api(python_type, api_type): assert castValToApi(python_type) == api_type api_words = ( '=key=value', '=.id=value', ) key_value_tuples = ( ('key','value'), ('.id','value'), ) @pytest.mark.parametrize("word,expected", zip(api_words,key_value_tuples)) def test_converting_api_word_to_tuple(word, expected): assert convattrwrd(word) == expected @pytest.mark.parametrize("word,pair", zip(api_words,key_value_tuples)) def test_converting_tuple_to_api_word(word,pair): assert mkattrwrd(pair) == word @pytest.mark.parametrize("sentence,api_sentence", ( ( {'interface':'ether1','address':'1.1.1.1/23'}, ('=interface=ether1','=address=1.1.1.1/23') ), ( {'interface':'ether1','address':'1.1.1.1/23','.tag':2}, ('=interface=ether1','=address=1.1.1.1/23', '.tag=2') ), )) def test_api_sentence_creation(sentence,api_sentence): <|code_end|> , generate the next line using the imports in this file: import pytest from mcm.librouteros.datastructures import parsresp, parsnt, mksnt, mkattrwrd, convattrwrd, castValToPy, castValToApi, raiseIfFatal, trapCheck from mcm.librouteros.exceptions import CmdError, ConnError and context (functions, classes, or occasionally code) from other files: # Path: mcm/librouteros/datastructures.py # def parsresp(sentences): # ''' # Parse given response to set of dictionaries containing parsed sentences. # # :praam sentences: Iterable (tuple,list) with each element as a sentence # ''' # # response = map( parsnt, sentences ) # # filter out empty sentences # filtered = filter( None, response ) # return tuple( filtered ) # # def parsnt( snt ): # ''' # Parse given sentence from attribute words to dictionary. # Only retrieve words that start with '='. # This method may return an empty dictionary. # # :param snt: Iterable sentence. # :returns: Dictionary with attributes. # ''' # # attrs = ( word for word in snt if word.startswith( '=' ) ) # attrs = map( convattrwrd, attrs ) # # return dict( attrs ) # # def mksnt( data ): # ''' # Convert dictionary to attribute words. # # :param args: Dictionary with key value attributes. # Those will be converted to attribute words. # # :returns: Tuple with attribute words. # ''' # # converted = map( mkattrwrd, data.items() ) # return tuple( converted ) # # def mkattrwrd( kv ): # ''' # Make an attribute word out of key value tuple. Values and keys are automaticly casted # to api equivalents. # # :param kv: Two element tuple. First key, second value. # ''' # # key, value = kv # casted_value = castValToApi( value ) # prefix = '' if key == '.tag' else '=' # # return '{prefix}{key}={value}'.format( prefix=prefix, key=key, value=casted_value ) # # def convattrwrd( word ): # ''' # Make an key value tuple out of attribute word. Values and keys # are automaticly casted to python equivalents. # # :param word: Attribute word. # ''' # # splitted = word.split( '=', 2 ) # key = splitted[1] # value = splitted[2] # casted_value = castValToPy( value ) # # return ( key, casted_value ) # # def castValToPy( value ): # # try: # casted = int( value ) # except ValueError: # casted = to_py_mapping.get( value, value ) # return casted # # def castValToApi( value ): # # if type(value) == int: # return str(value) # else: # return to_api_mapping.get( value, str( value ) ) # # def raiseIfFatal( sentence ): # ''' # Check if a given sentence contains error message. If it does then raise an exception. # !fatal means that connection have been closed and no further transmission will work. # ''' # # if '!fatal' in sentence: # error = ', '.join( word for word in sentence if word != '!fatal' ) # raise ConnError( error ) # # def trapCheck( snts ): # ''' # Check for existance of !trap word. This word indicates that an error occured. # At least one !trap word in any sentence triggers an error. # Unfortunatelly mikrotik api may throw one or more errors as response. # # :param snts: Iterable with each sentence as tuple # ''' # # errmsgs = [] # # for snt in snts: # if '!trap' in snt: # emsg = ' '.join( word for word in snt ) # errmsgs.append( emsg ) # # if errmsgs: # e = ', '.join( errmsgs ) # raise CmdError( e ) # # Path: mcm/librouteros/exceptions.py # class CmdError( LibError ): # ''' # Commend execution errors. # ''' # # class ConnError( LibError ): # ''' # Connection related errors. # ''' . Output only the next line.
assert set(mksnt(sentence)) == set(api_sentence)
Predict the next line after this snippet: <|code_start|>@pytest.mark.parametrize("python_type,api_type", ( (True, 'yes'), (False, 'no'), (None, ''), ('string', 'string'), ('22.2', '22.2'), (22.2, '22.2'), (22, '22'), (1, '1'), (0, '0') )) def test_casting_from_python_to_api(python_type, api_type): assert castValToApi(python_type) == api_type api_words = ( '=key=value', '=.id=value', ) key_value_tuples = ( ('key','value'), ('.id','value'), ) @pytest.mark.parametrize("word,expected", zip(api_words,key_value_tuples)) def test_converting_api_word_to_tuple(word, expected): assert convattrwrd(word) == expected @pytest.mark.parametrize("word,pair", zip(api_words,key_value_tuples)) def test_converting_tuple_to_api_word(word,pair): <|code_end|> using the current file's imports: import pytest from mcm.librouteros.datastructures import parsresp, parsnt, mksnt, mkattrwrd, convattrwrd, castValToPy, castValToApi, raiseIfFatal, trapCheck from mcm.librouteros.exceptions import CmdError, ConnError and any relevant context from other files: # Path: mcm/librouteros/datastructures.py # def parsresp(sentences): # ''' # Parse given response to set of dictionaries containing parsed sentences. # # :praam sentences: Iterable (tuple,list) with each element as a sentence # ''' # # response = map( parsnt, sentences ) # # filter out empty sentences # filtered = filter( None, response ) # return tuple( filtered ) # # def parsnt( snt ): # ''' # Parse given sentence from attribute words to dictionary. # Only retrieve words that start with '='. # This method may return an empty dictionary. # # :param snt: Iterable sentence. # :returns: Dictionary with attributes. # ''' # # attrs = ( word for word in snt if word.startswith( '=' ) ) # attrs = map( convattrwrd, attrs ) # # return dict( attrs ) # # def mksnt( data ): # ''' # Convert dictionary to attribute words. # # :param args: Dictionary with key value attributes. # Those will be converted to attribute words. # # :returns: Tuple with attribute words. # ''' # # converted = map( mkattrwrd, data.items() ) # return tuple( converted ) # # def mkattrwrd( kv ): # ''' # Make an attribute word out of key value tuple. Values and keys are automaticly casted # to api equivalents. # # :param kv: Two element tuple. First key, second value. # ''' # # key, value = kv # casted_value = castValToApi( value ) # prefix = '' if key == '.tag' else '=' # # return '{prefix}{key}={value}'.format( prefix=prefix, key=key, value=casted_value ) # # def convattrwrd( word ): # ''' # Make an key value tuple out of attribute word. Values and keys # are automaticly casted to python equivalents. # # :param word: Attribute word. # ''' # # splitted = word.split( '=', 2 ) # key = splitted[1] # value = splitted[2] # casted_value = castValToPy( value ) # # return ( key, casted_value ) # # def castValToPy( value ): # # try: # casted = int( value ) # except ValueError: # casted = to_py_mapping.get( value, value ) # return casted # # def castValToApi( value ): # # if type(value) == int: # return str(value) # else: # return to_api_mapping.get( value, str( value ) ) # # def raiseIfFatal( sentence ): # ''' # Check if a given sentence contains error message. If it does then raise an exception. # !fatal means that connection have been closed and no further transmission will work. # ''' # # if '!fatal' in sentence: # error = ', '.join( word for word in sentence if word != '!fatal' ) # raise ConnError( error ) # # def trapCheck( snts ): # ''' # Check for existance of !trap word. This word indicates that an error occured. # At least one !trap word in any sentence triggers an error. # Unfortunatelly mikrotik api may throw one or more errors as response. # # :param snts: Iterable with each sentence as tuple # ''' # # errmsgs = [] # # for snt in snts: # if '!trap' in snt: # emsg = ' '.join( word for word in snt ) # errmsgs.append( emsg ) # # if errmsgs: # e = ', '.join( errmsgs ) # raise CmdError( e ) # # Path: mcm/librouteros/exceptions.py # class CmdError( LibError ): # ''' # Commend execution errors. # ''' # # class ConnError( LibError ): # ''' # Connection related errors. # ''' . Output only the next line.
assert mkattrwrd(pair) == word
Continue the code snippet: <|code_start|> )) def test_casting_from_api_to_python(api_type, python_type): assert castValToPy( api_type ) == python_type @pytest.mark.parametrize("python_type,api_type", ( (True, 'yes'), (False, 'no'), (None, ''), ('string', 'string'), ('22.2', '22.2'), (22.2, '22.2'), (22, '22'), (1, '1'), (0, '0') )) def test_casting_from_python_to_api(python_type, api_type): assert castValToApi(python_type) == api_type api_words = ( '=key=value', '=.id=value', ) key_value_tuples = ( ('key','value'), ('.id','value'), ) @pytest.mark.parametrize("word,expected", zip(api_words,key_value_tuples)) def test_converting_api_word_to_tuple(word, expected): <|code_end|> . Use current file imports: import pytest from mcm.librouteros.datastructures import parsresp, parsnt, mksnt, mkattrwrd, convattrwrd, castValToPy, castValToApi, raiseIfFatal, trapCheck from mcm.librouteros.exceptions import CmdError, ConnError and context (classes, functions, or code) from other files: # Path: mcm/librouteros/datastructures.py # def parsresp(sentences): # ''' # Parse given response to set of dictionaries containing parsed sentences. # # :praam sentences: Iterable (tuple,list) with each element as a sentence # ''' # # response = map( parsnt, sentences ) # # filter out empty sentences # filtered = filter( None, response ) # return tuple( filtered ) # # def parsnt( snt ): # ''' # Parse given sentence from attribute words to dictionary. # Only retrieve words that start with '='. # This method may return an empty dictionary. # # :param snt: Iterable sentence. # :returns: Dictionary with attributes. # ''' # # attrs = ( word for word in snt if word.startswith( '=' ) ) # attrs = map( convattrwrd, attrs ) # # return dict( attrs ) # # def mksnt( data ): # ''' # Convert dictionary to attribute words. # # :param args: Dictionary with key value attributes. # Those will be converted to attribute words. # # :returns: Tuple with attribute words. # ''' # # converted = map( mkattrwrd, data.items() ) # return tuple( converted ) # # def mkattrwrd( kv ): # ''' # Make an attribute word out of key value tuple. Values and keys are automaticly casted # to api equivalents. # # :param kv: Two element tuple. First key, second value. # ''' # # key, value = kv # casted_value = castValToApi( value ) # prefix = '' if key == '.tag' else '=' # # return '{prefix}{key}={value}'.format( prefix=prefix, key=key, value=casted_value ) # # def convattrwrd( word ): # ''' # Make an key value tuple out of attribute word. Values and keys # are automaticly casted to python equivalents. # # :param word: Attribute word. # ''' # # splitted = word.split( '=', 2 ) # key = splitted[1] # value = splitted[2] # casted_value = castValToPy( value ) # # return ( key, casted_value ) # # def castValToPy( value ): # # try: # casted = int( value ) # except ValueError: # casted = to_py_mapping.get( value, value ) # return casted # # def castValToApi( value ): # # if type(value) == int: # return str(value) # else: # return to_api_mapping.get( value, str( value ) ) # # def raiseIfFatal( sentence ): # ''' # Check if a given sentence contains error message. If it does then raise an exception. # !fatal means that connection have been closed and no further transmission will work. # ''' # # if '!fatal' in sentence: # error = ', '.join( word for word in sentence if word != '!fatal' ) # raise ConnError( error ) # # def trapCheck( snts ): # ''' # Check for existance of !trap word. This word indicates that an error occured. # At least one !trap word in any sentence triggers an error. # Unfortunatelly mikrotik api may throw one or more errors as response. # # :param snts: Iterable with each sentence as tuple # ''' # # errmsgs = [] # # for snt in snts: # if '!trap' in snt: # emsg = ' '.join( word for word in snt ) # errmsgs.append( emsg ) # # if errmsgs: # e = ', '.join( errmsgs ) # raise CmdError( e ) # # Path: mcm/librouteros/exceptions.py # class CmdError( LibError ): # ''' # Commend execution errors. # ''' # # class ConnError( LibError ): # ''' # Connection related errors. # ''' . Output only the next line.
assert convattrwrd(word) == expected
Next line prediction: <|code_start|> def test_trap_string_in_sentences_raises_exception(): with pytest.raises(CmdError): trapCheck(('!trap','=key=value')) def test_raises_when_fatal(): with pytest.raises(ConnError): raiseIfFatal(('!fatal','connection terminated by remote hoost')) def test_does_not_raise_exception_if_no_fatal_string(): raiseIfFatal( 'some string without error' ) @pytest.mark.parametrize("api_type,python_type", ( ('yes', True), ('no', False), ('true', True), ('false', False), ('', None), ('string', 'string'), ('22.2', '22.2'), ('22', 22), )) def test_casting_from_api_to_python(api_type, python_type): <|code_end|> . Use current file imports: (import pytest from mcm.librouteros.datastructures import parsresp, parsnt, mksnt, mkattrwrd, convattrwrd, castValToPy, castValToApi, raiseIfFatal, trapCheck from mcm.librouteros.exceptions import CmdError, ConnError) and context including class names, function names, or small code snippets from other files: # Path: mcm/librouteros/datastructures.py # def parsresp(sentences): # ''' # Parse given response to set of dictionaries containing parsed sentences. # # :praam sentences: Iterable (tuple,list) with each element as a sentence # ''' # # response = map( parsnt, sentences ) # # filter out empty sentences # filtered = filter( None, response ) # return tuple( filtered ) # # def parsnt( snt ): # ''' # Parse given sentence from attribute words to dictionary. # Only retrieve words that start with '='. # This method may return an empty dictionary. # # :param snt: Iterable sentence. # :returns: Dictionary with attributes. # ''' # # attrs = ( word for word in snt if word.startswith( '=' ) ) # attrs = map( convattrwrd, attrs ) # # return dict( attrs ) # # def mksnt( data ): # ''' # Convert dictionary to attribute words. # # :param args: Dictionary with key value attributes. # Those will be converted to attribute words. # # :returns: Tuple with attribute words. # ''' # # converted = map( mkattrwrd, data.items() ) # return tuple( converted ) # # def mkattrwrd( kv ): # ''' # Make an attribute word out of key value tuple. Values and keys are automaticly casted # to api equivalents. # # :param kv: Two element tuple. First key, second value. # ''' # # key, value = kv # casted_value = castValToApi( value ) # prefix = '' if key == '.tag' else '=' # # return '{prefix}{key}={value}'.format( prefix=prefix, key=key, value=casted_value ) # # def convattrwrd( word ): # ''' # Make an key value tuple out of attribute word. Values and keys # are automaticly casted to python equivalents. # # :param word: Attribute word. # ''' # # splitted = word.split( '=', 2 ) # key = splitted[1] # value = splitted[2] # casted_value = castValToPy( value ) # # return ( key, casted_value ) # # def castValToPy( value ): # # try: # casted = int( value ) # except ValueError: # casted = to_py_mapping.get( value, value ) # return casted # # def castValToApi( value ): # # if type(value) == int: # return str(value) # else: # return to_api_mapping.get( value, str( value ) ) # # def raiseIfFatal( sentence ): # ''' # Check if a given sentence contains error message. If it does then raise an exception. # !fatal means that connection have been closed and no further transmission will work. # ''' # # if '!fatal' in sentence: # error = ', '.join( word for word in sentence if word != '!fatal' ) # raise ConnError( error ) # # def trapCheck( snts ): # ''' # Check for existance of !trap word. This word indicates that an error occured. # At least one !trap word in any sentence triggers an error. # Unfortunatelly mikrotik api may throw one or more errors as response. # # :param snts: Iterable with each sentence as tuple # ''' # # errmsgs = [] # # for snt in snts: # if '!trap' in snt: # emsg = ' '.join( word for word in snt ) # errmsgs.append( emsg ) # # if errmsgs: # e = ', '.join( errmsgs ) # raise CmdError( e ) # # Path: mcm/librouteros/exceptions.py # class CmdError( LibError ): # ''' # Commend execution errors. # ''' # # class ConnError( LibError ): # ''' # Connection related errors. # ''' . Output only the next line.
assert castValToPy( api_type ) == python_type
Using the snippet: <|code_start|>def test_does_not_raise_exception_if_no_fatal_string(): raiseIfFatal( 'some string without error' ) @pytest.mark.parametrize("api_type,python_type", ( ('yes', True), ('no', False), ('true', True), ('false', False), ('', None), ('string', 'string'), ('22.2', '22.2'), ('22', 22), )) def test_casting_from_api_to_python(api_type, python_type): assert castValToPy( api_type ) == python_type @pytest.mark.parametrize("python_type,api_type", ( (True, 'yes'), (False, 'no'), (None, ''), ('string', 'string'), ('22.2', '22.2'), (22.2, '22.2'), (22, '22'), (1, '1'), (0, '0') )) def test_casting_from_python_to_api(python_type, api_type): <|code_end|> , determine the next line of code. You have imports: import pytest from mcm.librouteros.datastructures import parsresp, parsnt, mksnt, mkattrwrd, convattrwrd, castValToPy, castValToApi, raiseIfFatal, trapCheck from mcm.librouteros.exceptions import CmdError, ConnError and context (class names, function names, or code) available: # Path: mcm/librouteros/datastructures.py # def parsresp(sentences): # ''' # Parse given response to set of dictionaries containing parsed sentences. # # :praam sentences: Iterable (tuple,list) with each element as a sentence # ''' # # response = map( parsnt, sentences ) # # filter out empty sentences # filtered = filter( None, response ) # return tuple( filtered ) # # def parsnt( snt ): # ''' # Parse given sentence from attribute words to dictionary. # Only retrieve words that start with '='. # This method may return an empty dictionary. # # :param snt: Iterable sentence. # :returns: Dictionary with attributes. # ''' # # attrs = ( word for word in snt if word.startswith( '=' ) ) # attrs = map( convattrwrd, attrs ) # # return dict( attrs ) # # def mksnt( data ): # ''' # Convert dictionary to attribute words. # # :param args: Dictionary with key value attributes. # Those will be converted to attribute words. # # :returns: Tuple with attribute words. # ''' # # converted = map( mkattrwrd, data.items() ) # return tuple( converted ) # # def mkattrwrd( kv ): # ''' # Make an attribute word out of key value tuple. Values and keys are automaticly casted # to api equivalents. # # :param kv: Two element tuple. First key, second value. # ''' # # key, value = kv # casted_value = castValToApi( value ) # prefix = '' if key == '.tag' else '=' # # return '{prefix}{key}={value}'.format( prefix=prefix, key=key, value=casted_value ) # # def convattrwrd( word ): # ''' # Make an key value tuple out of attribute word. Values and keys # are automaticly casted to python equivalents. # # :param word: Attribute word. # ''' # # splitted = word.split( '=', 2 ) # key = splitted[1] # value = splitted[2] # casted_value = castValToPy( value ) # # return ( key, casted_value ) # # def castValToPy( value ): # # try: # casted = int( value ) # except ValueError: # casted = to_py_mapping.get( value, value ) # return casted # # def castValToApi( value ): # # if type(value) == int: # return str(value) # else: # return to_api_mapping.get( value, str( value ) ) # # def raiseIfFatal( sentence ): # ''' # Check if a given sentence contains error message. If it does then raise an exception. # !fatal means that connection have been closed and no further transmission will work. # ''' # # if '!fatal' in sentence: # error = ', '.join( word for word in sentence if word != '!fatal' ) # raise ConnError( error ) # # def trapCheck( snts ): # ''' # Check for existance of !trap word. This word indicates that an error occured. # At least one !trap word in any sentence triggers an error. # Unfortunatelly mikrotik api may throw one or more errors as response. # # :param snts: Iterable with each sentence as tuple # ''' # # errmsgs = [] # # for snt in snts: # if '!trap' in snt: # emsg = ' '.join( word for word in snt ) # errmsgs.append( emsg ) # # if errmsgs: # e = ', '.join( errmsgs ) # raise CmdError( e ) # # Path: mcm/librouteros/exceptions.py # class CmdError( LibError ): # ''' # Commend execution errors. # ''' # # class ConnError( LibError ): # ''' # Connection related errors. # ''' . Output only the next line.
assert castValToApi(python_type) == api_type
Based on the snippet: <|code_start|># -*- coding: UTF-8 -*- def test_trap_string_in_sentences_raises_exception(): with pytest.raises(CmdError): trapCheck(('!trap','=key=value')) def test_raises_when_fatal(): with pytest.raises(ConnError): <|code_end|> , predict the immediate next line with the help of imports: import pytest from mcm.librouteros.datastructures import parsresp, parsnt, mksnt, mkattrwrd, convattrwrd, castValToPy, castValToApi, raiseIfFatal, trapCheck from mcm.librouteros.exceptions import CmdError, ConnError and context (classes, functions, sometimes code) from other files: # Path: mcm/librouteros/datastructures.py # def parsresp(sentences): # ''' # Parse given response to set of dictionaries containing parsed sentences. # # :praam sentences: Iterable (tuple,list) with each element as a sentence # ''' # # response = map( parsnt, sentences ) # # filter out empty sentences # filtered = filter( None, response ) # return tuple( filtered ) # # def parsnt( snt ): # ''' # Parse given sentence from attribute words to dictionary. # Only retrieve words that start with '='. # This method may return an empty dictionary. # # :param snt: Iterable sentence. # :returns: Dictionary with attributes. # ''' # # attrs = ( word for word in snt if word.startswith( '=' ) ) # attrs = map( convattrwrd, attrs ) # # return dict( attrs ) # # def mksnt( data ): # ''' # Convert dictionary to attribute words. # # :param args: Dictionary with key value attributes. # Those will be converted to attribute words. # # :returns: Tuple with attribute words. # ''' # # converted = map( mkattrwrd, data.items() ) # return tuple( converted ) # # def mkattrwrd( kv ): # ''' # Make an attribute word out of key value tuple. Values and keys are automaticly casted # to api equivalents. # # :param kv: Two element tuple. First key, second value. # ''' # # key, value = kv # casted_value = castValToApi( value ) # prefix = '' if key == '.tag' else '=' # # return '{prefix}{key}={value}'.format( prefix=prefix, key=key, value=casted_value ) # # def convattrwrd( word ): # ''' # Make an key value tuple out of attribute word. Values and keys # are automaticly casted to python equivalents. # # :param word: Attribute word. # ''' # # splitted = word.split( '=', 2 ) # key = splitted[1] # value = splitted[2] # casted_value = castValToPy( value ) # # return ( key, casted_value ) # # def castValToPy( value ): # # try: # casted = int( value ) # except ValueError: # casted = to_py_mapping.get( value, value ) # return casted # # def castValToApi( value ): # # if type(value) == int: # return str(value) # else: # return to_api_mapping.get( value, str( value ) ) # # def raiseIfFatal( sentence ): # ''' # Check if a given sentence contains error message. If it does then raise an exception. # !fatal means that connection have been closed and no further transmission will work. # ''' # # if '!fatal' in sentence: # error = ', '.join( word for word in sentence if word != '!fatal' ) # raise ConnError( error ) # # def trapCheck( snts ): # ''' # Check for existance of !trap word. This word indicates that an error occured. # At least one !trap word in any sentence triggers an error. # Unfortunatelly mikrotik api may throw one or more errors as response. # # :param snts: Iterable with each sentence as tuple # ''' # # errmsgs = [] # # for snt in snts: # if '!trap' in snt: # emsg = ' '.join( word for word in snt ) # errmsgs.append( emsg ) # # if errmsgs: # e = ', '.join( errmsgs ) # raise CmdError( e ) # # Path: mcm/librouteros/exceptions.py # class CmdError( LibError ): # ''' # Commend execution errors. # ''' # # class ConnError( LibError ): # ''' # Connection related errors. # ''' . Output only the next line.
raiseIfFatal(('!fatal','connection terminated by remote hoost'))
Predict the next line after this snippet: <|code_start|># -*- coding: UTF-8 -*- def test_trap_string_in_sentences_raises_exception(): with pytest.raises(CmdError): trapCheck(('!trap','=key=value')) def test_raises_when_fatal(): <|code_end|> using the current file's imports: import pytest from mcm.librouteros.datastructures import parsresp, parsnt, mksnt, mkattrwrd, convattrwrd, castValToPy, castValToApi, raiseIfFatal, trapCheck from mcm.librouteros.exceptions import CmdError, ConnError and any relevant context from other files: # Path: mcm/librouteros/datastructures.py # def parsresp(sentences): # ''' # Parse given response to set of dictionaries containing parsed sentences. # # :praam sentences: Iterable (tuple,list) with each element as a sentence # ''' # # response = map( parsnt, sentences ) # # filter out empty sentences # filtered = filter( None, response ) # return tuple( filtered ) # # def parsnt( snt ): # ''' # Parse given sentence from attribute words to dictionary. # Only retrieve words that start with '='. # This method may return an empty dictionary. # # :param snt: Iterable sentence. # :returns: Dictionary with attributes. # ''' # # attrs = ( word for word in snt if word.startswith( '=' ) ) # attrs = map( convattrwrd, attrs ) # # return dict( attrs ) # # def mksnt( data ): # ''' # Convert dictionary to attribute words. # # :param args: Dictionary with key value attributes. # Those will be converted to attribute words. # # :returns: Tuple with attribute words. # ''' # # converted = map( mkattrwrd, data.items() ) # return tuple( converted ) # # def mkattrwrd( kv ): # ''' # Make an attribute word out of key value tuple. Values and keys are automaticly casted # to api equivalents. # # :param kv: Two element tuple. First key, second value. # ''' # # key, value = kv # casted_value = castValToApi( value ) # prefix = '' if key == '.tag' else '=' # # return '{prefix}{key}={value}'.format( prefix=prefix, key=key, value=casted_value ) # # def convattrwrd( word ): # ''' # Make an key value tuple out of attribute word. Values and keys # are automaticly casted to python equivalents. # # :param word: Attribute word. # ''' # # splitted = word.split( '=', 2 ) # key = splitted[1] # value = splitted[2] # casted_value = castValToPy( value ) # # return ( key, casted_value ) # # def castValToPy( value ): # # try: # casted = int( value ) # except ValueError: # casted = to_py_mapping.get( value, value ) # return casted # # def castValToApi( value ): # # if type(value) == int: # return str(value) # else: # return to_api_mapping.get( value, str( value ) ) # # def raiseIfFatal( sentence ): # ''' # Check if a given sentence contains error message. If it does then raise an exception. # !fatal means that connection have been closed and no further transmission will work. # ''' # # if '!fatal' in sentence: # error = ', '.join( word for word in sentence if word != '!fatal' ) # raise ConnError( error ) # # def trapCheck( snts ): # ''' # Check for existance of !trap word. This word indicates that an error occured. # At least one !trap word in any sentence triggers an error. # Unfortunatelly mikrotik api may throw one or more errors as response. # # :param snts: Iterable with each sentence as tuple # ''' # # errmsgs = [] # # for snt in snts: # if '!trap' in snt: # emsg = ' '.join( word for word in snt ) # errmsgs.append( emsg ) # # if errmsgs: # e = ', '.join( errmsgs ) # raise CmdError( e ) # # Path: mcm/librouteros/exceptions.py # class CmdError( LibError ): # ''' # Commend execution errors. # ''' # # class ConnError( LibError ): # ''' # Connection related errors. # ''' . Output only the next line.
with pytest.raises(ConnError):
Continue the code snippet: <|code_start|> :param word: Attribute word. ''' splitted = word.split( '=', 2 ) key = splitted[1] value = splitted[2] casted_value = castValToPy( value ) return ( key, casted_value ) def trapCheck( snts ): ''' Check for existance of !trap word. This word indicates that an error occured. At least one !trap word in any sentence triggers an error. Unfortunatelly mikrotik api may throw one or more errors as response. :param snts: Iterable with each sentence as tuple ''' errmsgs = [] for snt in snts: if '!trap' in snt: emsg = ' '.join( word for word in snt ) errmsgs.append( emsg ) if errmsgs: e = ', '.join( errmsgs ) <|code_end|> . Use current file imports: from mcm.librouteros.exceptions import CmdError, ConnError and context (classes, functions, or code) from other files: # Path: mcm/librouteros/exceptions.py # class CmdError( LibError ): # ''' # Commend execution errors. # ''' # # class ConnError( LibError ): # ''' # Connection related errors. # ''' . Output only the next line.
raise CmdError( e )
Given the code snippet: <|code_start|> def trapCheck( snts ): ''' Check for existance of !trap word. This word indicates that an error occured. At least one !trap word in any sentence triggers an error. Unfortunatelly mikrotik api may throw one or more errors as response. :param snts: Iterable with each sentence as tuple ''' errmsgs = [] for snt in snts: if '!trap' in snt: emsg = ' '.join( word for word in snt ) errmsgs.append( emsg ) if errmsgs: e = ', '.join( errmsgs ) raise CmdError( e ) def raiseIfFatal( sentence ): ''' Check if a given sentence contains error message. If it does then raise an exception. !fatal means that connection have been closed and no further transmission will work. ''' if '!fatal' in sentence: error = ', '.join( word for word in sentence if word != '!fatal' ) <|code_end|> , generate the next line using the imports in this file: from mcm.librouteros.exceptions import CmdError, ConnError and context (functions, classes, or occasionally code) from other files: # Path: mcm/librouteros/exceptions.py # class CmdError( LibError ): # ''' # Commend execution errors. # ''' # # class ConnError( LibError ): # ''' # Connection related errors. # ''' . Output only the next line.
raise ConnError( error )
Based on the snippet: <|code_start|>@pytest.mark.skipif( version_info > (3,2), reason='Using python >= 3.3' ) def test_module_uses_time_as_timer(): '''Assert that time.time is used when time.monotonic is not available.''' assert timer == time @pytest.mark.parametrize("v1,v2,oper,result", ( ('4.11','3.12',operator.gt,True), ('4.11','5.12',operator.gt,False), ('4.11','4.11',operator.ge,True), ('4.14','4.11',operator.ge,True), ('4.11','5.12',operator.ge,False), ('4.11','5.12',operator.lt,True), ('6.11','5.12',operator.lt,False), ('4.11','4.11',operator.le,True), ('4.1','4.11',operator.le,True), ('6.11','5.12',operator.le,False), ('4.11','4.11',operator.eq,True), ('4.10','4.1',operator.eq,False), ('4.10','4.1',operator.ne,True), ('4.11','4.11',operator.ne,False), )) def test_version_comparison(v1,v2,oper,result): assert vcmp(v1=v1,v2=v2,op=oper) == result @patch('mcm.tools.timer', side_effect=[14705.275287508, 14711.190629636]) class Test_StopWatch: def test_sets_start_value_on_entering(self, timermock): <|code_end|> , predict the immediate next line with the help of imports: from mock import patch from sys import version_info from time import monotonic from time import time from mcm.tools import StopWatch, timer, vcmp, ChainMap import operator import pytest and context (classes, functions, sometimes code) from other files: # Path: mcm/tools.py # class StopWatch: # class ChainMap(UserDict): # def __enter__(self): # def __exit__(self, exc_type, exc_value, traceback): # def vcmp(v1, v2, op): # def __init__(self, *maps): # def __getitem__(self, key): . Output only the next line.
with StopWatch() as st:
Using the snippet: <|code_start|># -*- coding: UTF-8 -*- try: except ImportError: @pytest.mark.skipif( version_info < (3,3), reason='Requires python >= 3.3' ) def test_module_uses_monotonic_as_timer(): '''Assert that time.monotonic is used.''' <|code_end|> , determine the next line of code. You have imports: from mock import patch from sys import version_info from time import monotonic from time import time from mcm.tools import StopWatch, timer, vcmp, ChainMap import operator import pytest and context (class names, function names, or code) available: # Path: mcm/tools.py # class StopWatch: # class ChainMap(UserDict): # def __enter__(self): # def __exit__(self, exc_type, exc_value, traceback): # def vcmp(v1, v2, op): # def __init__(self, *maps): # def __getitem__(self, key): . Output only the next line.
assert timer == monotonic
Here is a snippet: <|code_start|> @pytest.mark.skipif( version_info < (3,3), reason='Requires python >= 3.3' ) def test_module_uses_monotonic_as_timer(): '''Assert that time.monotonic is used.''' assert timer == monotonic @pytest.mark.skipif( version_info > (3,2), reason='Using python >= 3.3' ) def test_module_uses_time_as_timer(): '''Assert that time.time is used when time.monotonic is not available.''' assert timer == time @pytest.mark.parametrize("v1,v2,oper,result", ( ('4.11','3.12',operator.gt,True), ('4.11','5.12',operator.gt,False), ('4.11','4.11',operator.ge,True), ('4.14','4.11',operator.ge,True), ('4.11','5.12',operator.ge,False), ('4.11','5.12',operator.lt,True), ('6.11','5.12',operator.lt,False), ('4.11','4.11',operator.le,True), ('4.1','4.11',operator.le,True), ('6.11','5.12',operator.le,False), ('4.11','4.11',operator.eq,True), ('4.10','4.1',operator.eq,False), ('4.10','4.1',operator.ne,True), ('4.11','4.11',operator.ne,False), )) def test_version_comparison(v1,v2,oper,result): <|code_end|> . Write the next line using the current file imports: from mock import patch from sys import version_info from time import monotonic from time import time from mcm.tools import StopWatch, timer, vcmp, ChainMap import operator import pytest and context from other files: # Path: mcm/tools.py # class StopWatch: # class ChainMap(UserDict): # def __enter__(self): # def __exit__(self, exc_type, exc_value, traceback): # def vcmp(v1, v2, op): # def __init__(self, *maps): # def __getitem__(self, key): , which may include functions, classes, or code. Output only the next line.
assert vcmp(v1=v1,v2=v2,op=oper) == result
Based on the snippet: <|code_start|> ('4.10','4.1',operator.ne,True), ('4.11','4.11',operator.ne,False), )) def test_version_comparison(v1,v2,oper,result): assert vcmp(v1=v1,v2=v2,op=oper) == result @patch('mcm.tools.timer', side_effect=[14705.275287508, 14711.190629636]) class Test_StopWatch: def test_sets_start_value_on_entering(self, timermock): with StopWatch() as st: assert st.start == 14705.275287508 def test_sets_stop_value_on_exiting(self, timermock): with StopWatch() as st: pass assert st.stop == 14711.190629636 def test_calculates_runtime_value_rounded_to_2_digits(self, timermock): with StopWatch() as st: pass assert st.runtime == 5.92 class Test_ChainMap: def setup(self): self.default_dict = dict(port=123, timeout=10) self.override_dict = dict(port=222) <|code_end|> , predict the immediate next line with the help of imports: from mock import patch from sys import version_info from time import monotonic from time import time from mcm.tools import StopWatch, timer, vcmp, ChainMap import operator import pytest and context (classes, functions, sometimes code) from other files: # Path: mcm/tools.py # class StopWatch: # class ChainMap(UserDict): # def __enter__(self): # def __exit__(self, exc_type, exc_value, traceback): # def vcmp(v1, v2, op): # def __init__(self, *maps): # def __getitem__(self, key): . Output only the next line.
self.chained = ChainMap(self.override_dict, self.default_dict)
Given the following code snippet before the placeholder: <|code_start|># -*- coding: UTF-8 -*- logger = getLogger('mcm.' + __name__) class MasterAdapter: def __init__(self, device): self.device = device def read(self, path): content = self.device.read(path=path.absolute) data = self.assemble_data(data=content) for row in data: logger.debug('{path} {data}'.format(path=path.absolute, data=row)) return data def close(self): self.device.close() @staticmethod def assemble_data(data): <|code_end|> , predict the next line using imports from the current file: from mcm.datastructures import CmdPathRow from mcm.exceptions import WriteError from logging import getLogger and context including class names, function names, and sometimes code from other files: # Path: mcm/datastructures.py # class CmdPathRow(dict): # # # def __str__(self): # bool_map = {True:'yes', False:'no', None:'""', '':'""'} # return ' '.join('{}={}'.format(key, bool_map.get(value, value)) for key, value in self.items()) # # # def __hash__(self): # return hash(tuple(self.items())) # # # def __sub__(self, other): # '''Return new instance with key,valie pairs from self not listed in other.''' # # diff = dict(set(self.items()) - set(other.items())) # return CmdPathRow( diff ) # # # def isunique(self, other, keys): # '''Test whether every key,value pair (from keys) is in other.''' # # pairs = set( (key,self[key]) for key in keys ) # return pairs <= set(other.items()) # # Path: mcm/exceptions.py # class WriteError(Exception): # ''' # Exception raised when writing to master or slave occured. # ''' . Output only the next line.
return tuple(CmdPathRow(elem) for elem in data)
Using the snippet: <|code_start|> def __init__(self, device): self.device = device def read(self, path): content = self.device.read(path=path.absolute) data = self.assemble_data(data=content) for row in data: logger.debug('{path} {data}'.format(path=path.absolute, data=row)) return data def close(self): self.device.close() @staticmethod def assemble_data(data): return tuple(CmdPathRow(elem) for elem in data) class SlaveAdapter(MasterAdapter): def write(self, path, action, data): for row in data: try: self.device.write(path=path.absolute, action=action, data=row) logger.info('{path} {action} {data}'.format(path=path.absolute, action=action, data=row)) <|code_end|> , determine the next line of code. You have imports: from mcm.datastructures import CmdPathRow from mcm.exceptions import WriteError from logging import getLogger and context (class names, function names, or code) available: # Path: mcm/datastructures.py # class CmdPathRow(dict): # # # def __str__(self): # bool_map = {True:'yes', False:'no', None:'""', '':'""'} # return ' '.join('{}={}'.format(key, bool_map.get(value, value)) for key, value in self.items()) # # # def __hash__(self): # return hash(tuple(self.items())) # # # def __sub__(self, other): # '''Return new instance with key,valie pairs from self not listed in other.''' # # diff = dict(set(self.items()) - set(other.items())) # return CmdPathRow( diff ) # # # def isunique(self, other, keys): # '''Test whether every key,value pair (from keys) is in other.''' # # pairs = set( (key,self[key]) for key in keys ) # return pairs <= set(other.items()) # # Path: mcm/exceptions.py # class WriteError(Exception): # ''' # Exception raised when writing to master or slave occured. # ''' . Output only the next line.
except WriteError as error:
Given snippet: <|code_start|># -*- coding: UTF-8 -*- def validate_list(lst, allowed): forbidden = set(lst) - set(allowed) if forbidden: <|code_end|> , continue by predicting the next line. Consider current file imports: from mcm.exceptions import ValidateError and context: # Path: mcm/exceptions.py # class ValidateError(Exception): # ''' # Exception raised when a general validation error occurs. # ''' which might include code, classes, or functions. Output only the next line.
raise ValidateError()
Here is a snippet: <|code_start|> @pytest.fixture def read_only_routeros(): return ReadOnlyRouterOS(api=MagicMock()) class StaticConfig_Tests: def setup(self): data = [ {'path':'test_path', 'strategy':'exact', 'rules':[ {'key':'value'} ]} ] self.TestCls = StaticConfig(data=data) def test_read_returns_valid_rules(self): returned = self.TestCls.read(path='test_path') assert returned == [{'key':'value'}] def test_has_close_method(self): assert ismethod(self.TestCls.close) class RouterOsAPIDevice_Tests(TestCase): def setUp(self): <|code_end|> . Write the next line using the current file imports: from mock import MagicMock, patch from unittest import TestCase from inspect import ismethod from mcm.iodevices import RouterOsAPIDevice, StaticConfig, ReadOnlyRouterOS from mcm.librouteros import CmdError from mcm.exceptions import ReadError, WriteError import pytest and context from other files: # Path: mcm/iodevices.py # class RouterOsAPIDevice(ReadOnlyRouterOS): # # # def write(self, path, action, data): # command = self.cmd_action_join(path=path, action=action) # method = getattr(self, action) # method(command=command, data=data) # # # def DEL(self, command, data): # ID = {'.id':data['.id']} # try: # self.api.run(cmd=command, args=ID) # except CmdError as error: # raise WriteError(error) # # # def SET(self, command, data): # try: # self.api.run(cmd=command, args=data) # except CmdError as error: # raise WriteError(error) # # # def ADD(self, command, data): # try: # self.api.run(cmd=command, args=data) # except CmdError as error: # raise WriteError(error) # # class StaticConfig: # # # def __init__(self, data): # self.data = data # # # def read(self, path): # for section in self.data: # if section['path'] == path: # return section['rules'] # # # def close(self): # pass # # class ReadOnlyRouterOS: # # # def __init__(self, api): # self.api = api # # # def read(self, path): # cmd = self.cmd_action_join(path=path, action='GET') # try: # data = self.api.run(cmd=cmd) # except CmdError as error: # raise ReadError(error) # return self.filter_dynamic(data) # # # def write(self, path, action, data): # pass # # # def close(self): # self.api.close() # # # @staticmethod # def cmd_action_join(path, action): # actions = dict(ADD='add', SET='set', DEL='remove', GET='getall') # return pjoin(path, actions[action]) # # # @staticmethod # def filter_dynamic(data): # return tuple(row for row in data if not row.get('dynamic')) # # Path: mcm/librouteros/exceptions.py # class CmdError( LibError ): # ''' # Commend execution errors. # ''' # # Path: mcm/exceptions.py # class ReadError(Exception): # ''' # Exception raised when reading from master or slave occured. # ''' # # class WriteError(Exception): # ''' # Exception raised when writing to master or slave occured. # ''' , which may include functions, classes, or code. Output only the next line.
self.TestCls = RouterOsAPIDevice(api=MagicMock())
Continue the code snippet: <|code_start|># -*- coding: UTF-8 -*- @pytest.fixture def read_only_routeros(): return ReadOnlyRouterOS(api=MagicMock()) class StaticConfig_Tests: def setup(self): data = [ {'path':'test_path', 'strategy':'exact', 'rules':[ {'key':'value'} ]} ] <|code_end|> . Use current file imports: from mock import MagicMock, patch from unittest import TestCase from inspect import ismethod from mcm.iodevices import RouterOsAPIDevice, StaticConfig, ReadOnlyRouterOS from mcm.librouteros import CmdError from mcm.exceptions import ReadError, WriteError import pytest and context (classes, functions, or code) from other files: # Path: mcm/iodevices.py # class RouterOsAPIDevice(ReadOnlyRouterOS): # # # def write(self, path, action, data): # command = self.cmd_action_join(path=path, action=action) # method = getattr(self, action) # method(command=command, data=data) # # # def DEL(self, command, data): # ID = {'.id':data['.id']} # try: # self.api.run(cmd=command, args=ID) # except CmdError as error: # raise WriteError(error) # # # def SET(self, command, data): # try: # self.api.run(cmd=command, args=data) # except CmdError as error: # raise WriteError(error) # # # def ADD(self, command, data): # try: # self.api.run(cmd=command, args=data) # except CmdError as error: # raise WriteError(error) # # class StaticConfig: # # # def __init__(self, data): # self.data = data # # # def read(self, path): # for section in self.data: # if section['path'] == path: # return section['rules'] # # # def close(self): # pass # # class ReadOnlyRouterOS: # # # def __init__(self, api): # self.api = api # # # def read(self, path): # cmd = self.cmd_action_join(path=path, action='GET') # try: # data = self.api.run(cmd=cmd) # except CmdError as error: # raise ReadError(error) # return self.filter_dynamic(data) # # # def write(self, path, action, data): # pass # # # def close(self): # self.api.close() # # # @staticmethod # def cmd_action_join(path, action): # actions = dict(ADD='add', SET='set', DEL='remove', GET='getall') # return pjoin(path, actions[action]) # # # @staticmethod # def filter_dynamic(data): # return tuple(row for row in data if not row.get('dynamic')) # # Path: mcm/librouteros/exceptions.py # class CmdError( LibError ): # ''' # Commend execution errors. # ''' # # Path: mcm/exceptions.py # class ReadError(Exception): # ''' # Exception raised when reading from master or slave occured. # ''' # # class WriteError(Exception): # ''' # Exception raised when writing to master or slave occured. # ''' . Output only the next line.
self.TestCls = StaticConfig(data=data)
Using the snippet: <|code_start|> def setup(self): data = [ {'path':'test_path', 'strategy':'exact', 'rules':[ {'key':'value'} ]} ] self.TestCls = StaticConfig(data=data) def test_read_returns_valid_rules(self): returned = self.TestCls.read(path='test_path') assert returned == [{'key':'value'}] def test_has_close_method(self): assert ismethod(self.TestCls.close) class RouterOsAPIDevice_Tests(TestCase): def setUp(self): self.TestCls = RouterOsAPIDevice(api=MagicMock()) self.pathmock = MagicMock() self.datamock = MagicMock() @patch.object(RouterOsAPIDevice, 'filter_dynamic') @patch.object(RouterOsAPIDevice, 'cmd_action_join') def test_read_calls_api_run_method(self, joinmock, filter_mock): self.TestCls.read(self.pathmock) self.TestCls.api.run.assert_called_once_with(cmd=joinmock.return_value) @patch.object(RouterOsAPIDevice, 'cmd_action_join') def test_read_raises_ReadError(self, joinmock): <|code_end|> , determine the next line of code. You have imports: from mock import MagicMock, patch from unittest import TestCase from inspect import ismethod from mcm.iodevices import RouterOsAPIDevice, StaticConfig, ReadOnlyRouterOS from mcm.librouteros import CmdError from mcm.exceptions import ReadError, WriteError import pytest and context (class names, function names, or code) available: # Path: mcm/iodevices.py # class RouterOsAPIDevice(ReadOnlyRouterOS): # # # def write(self, path, action, data): # command = self.cmd_action_join(path=path, action=action) # method = getattr(self, action) # method(command=command, data=data) # # # def DEL(self, command, data): # ID = {'.id':data['.id']} # try: # self.api.run(cmd=command, args=ID) # except CmdError as error: # raise WriteError(error) # # # def SET(self, command, data): # try: # self.api.run(cmd=command, args=data) # except CmdError as error: # raise WriteError(error) # # # def ADD(self, command, data): # try: # self.api.run(cmd=command, args=data) # except CmdError as error: # raise WriteError(error) # # class StaticConfig: # # # def __init__(self, data): # self.data = data # # # def read(self, path): # for section in self.data: # if section['path'] == path: # return section['rules'] # # # def close(self): # pass # # class ReadOnlyRouterOS: # # # def __init__(self, api): # self.api = api # # # def read(self, path): # cmd = self.cmd_action_join(path=path, action='GET') # try: # data = self.api.run(cmd=cmd) # except CmdError as error: # raise ReadError(error) # return self.filter_dynamic(data) # # # def write(self, path, action, data): # pass # # # def close(self): # self.api.close() # # # @staticmethod # def cmd_action_join(path, action): # actions = dict(ADD='add', SET='set', DEL='remove', GET='getall') # return pjoin(path, actions[action]) # # # @staticmethod # def filter_dynamic(data): # return tuple(row for row in data if not row.get('dynamic')) # # Path: mcm/librouteros/exceptions.py # class CmdError( LibError ): # ''' # Commend execution errors. # ''' # # Path: mcm/exceptions.py # class ReadError(Exception): # ''' # Exception raised when reading from master or slave occured. # ''' # # class WriteError(Exception): # ''' # Exception raised when writing to master or slave occured. # ''' . Output only the next line.
self.TestCls.api.run.side_effect = CmdError
Given the code snippet: <|code_start|> data = [ {'path':'test_path', 'strategy':'exact', 'rules':[ {'key':'value'} ]} ] self.TestCls = StaticConfig(data=data) def test_read_returns_valid_rules(self): returned = self.TestCls.read(path='test_path') assert returned == [{'key':'value'}] def test_has_close_method(self): assert ismethod(self.TestCls.close) class RouterOsAPIDevice_Tests(TestCase): def setUp(self): self.TestCls = RouterOsAPIDevice(api=MagicMock()) self.pathmock = MagicMock() self.datamock = MagicMock() @patch.object(RouterOsAPIDevice, 'filter_dynamic') @patch.object(RouterOsAPIDevice, 'cmd_action_join') def test_read_calls_api_run_method(self, joinmock, filter_mock): self.TestCls.read(self.pathmock) self.TestCls.api.run.assert_called_once_with(cmd=joinmock.return_value) @patch.object(RouterOsAPIDevice, 'cmd_action_join') def test_read_raises_ReadError(self, joinmock): self.TestCls.api.run.side_effect = CmdError <|code_end|> , generate the next line using the imports in this file: from mock import MagicMock, patch from unittest import TestCase from inspect import ismethod from mcm.iodevices import RouterOsAPIDevice, StaticConfig, ReadOnlyRouterOS from mcm.librouteros import CmdError from mcm.exceptions import ReadError, WriteError import pytest and context (functions, classes, or occasionally code) from other files: # Path: mcm/iodevices.py # class RouterOsAPIDevice(ReadOnlyRouterOS): # # # def write(self, path, action, data): # command = self.cmd_action_join(path=path, action=action) # method = getattr(self, action) # method(command=command, data=data) # # # def DEL(self, command, data): # ID = {'.id':data['.id']} # try: # self.api.run(cmd=command, args=ID) # except CmdError as error: # raise WriteError(error) # # # def SET(self, command, data): # try: # self.api.run(cmd=command, args=data) # except CmdError as error: # raise WriteError(error) # # # def ADD(self, command, data): # try: # self.api.run(cmd=command, args=data) # except CmdError as error: # raise WriteError(error) # # class StaticConfig: # # # def __init__(self, data): # self.data = data # # # def read(self, path): # for section in self.data: # if section['path'] == path: # return section['rules'] # # # def close(self): # pass # # class ReadOnlyRouterOS: # # # def __init__(self, api): # self.api = api # # # def read(self, path): # cmd = self.cmd_action_join(path=path, action='GET') # try: # data = self.api.run(cmd=cmd) # except CmdError as error: # raise ReadError(error) # return self.filter_dynamic(data) # # # def write(self, path, action, data): # pass # # # def close(self): # self.api.close() # # # @staticmethod # def cmd_action_join(path, action): # actions = dict(ADD='add', SET='set', DEL='remove', GET='getall') # return pjoin(path, actions[action]) # # # @staticmethod # def filter_dynamic(data): # return tuple(row for row in data if not row.get('dynamic')) # # Path: mcm/librouteros/exceptions.py # class CmdError( LibError ): # ''' # Commend execution errors. # ''' # # Path: mcm/exceptions.py # class ReadError(Exception): # ''' # Exception raised when reading from master or slave occured. # ''' # # class WriteError(Exception): # ''' # Exception raised when writing to master or slave occured. # ''' . Output only the next line.
with pytest.raises(ReadError):
Using the snippet: <|code_start|> self.TestCls.write(path=self.pathmock, action='ADD', data=None) joinmock.assert_called_once_with(path=self.pathmock, action='ADD') @patch.object(RouterOsAPIDevice, 'DEL') @patch.object(RouterOsAPIDevice, 'cmd_action_join') def test_write_calls_DEL_when_cmd_is_DEL(self, joinmock, delmock): self.TestCls.write(data='data', path=self.pathmock, action='DEL') delmock.assert_called_once_with(command=joinmock.return_value, data='data') @patch.object(RouterOsAPIDevice, 'ADD') @patch.object(RouterOsAPIDevice, 'cmd_action_join') def test_write_calls_ADD_when_cmd_is_ADD(self, joinmock, addmock): self.TestCls.write(data='data', path=self.pathmock, action='ADD') addmock.assert_called_once_with(command=joinmock.return_value, data='data') @patch.object(RouterOsAPIDevice, 'SET') @patch.object(RouterOsAPIDevice, 'cmd_action_join') def test_write_calls_SET_when_cmd_is_SET(self, joinmock, setmock): self.TestCls.write(data='data', path=self.pathmock, action='SET') setmock.assert_called_once_with(command=joinmock.return_value, data='data') def test_DEL_calls_api_run_only_with_ID(self): data = {'.id':'*1', 'address':'1.1.1.1/24'} self.TestCls.DEL(command='/ip/address/remove', data=data) self.TestCls.api.run.assert_called_once_with(cmd='/ip/address/remove', args={'.id':'*1'}) def test_DEL_raises_WriteError(self): self.TestCls.api.run.side_effect = CmdError <|code_end|> , determine the next line of code. You have imports: from mock import MagicMock, patch from unittest import TestCase from inspect import ismethod from mcm.iodevices import RouterOsAPIDevice, StaticConfig, ReadOnlyRouterOS from mcm.librouteros import CmdError from mcm.exceptions import ReadError, WriteError import pytest and context (class names, function names, or code) available: # Path: mcm/iodevices.py # class RouterOsAPIDevice(ReadOnlyRouterOS): # # # def write(self, path, action, data): # command = self.cmd_action_join(path=path, action=action) # method = getattr(self, action) # method(command=command, data=data) # # # def DEL(self, command, data): # ID = {'.id':data['.id']} # try: # self.api.run(cmd=command, args=ID) # except CmdError as error: # raise WriteError(error) # # # def SET(self, command, data): # try: # self.api.run(cmd=command, args=data) # except CmdError as error: # raise WriteError(error) # # # def ADD(self, command, data): # try: # self.api.run(cmd=command, args=data) # except CmdError as error: # raise WriteError(error) # # class StaticConfig: # # # def __init__(self, data): # self.data = data # # # def read(self, path): # for section in self.data: # if section['path'] == path: # return section['rules'] # # # def close(self): # pass # # class ReadOnlyRouterOS: # # # def __init__(self, api): # self.api = api # # # def read(self, path): # cmd = self.cmd_action_join(path=path, action='GET') # try: # data = self.api.run(cmd=cmd) # except CmdError as error: # raise ReadError(error) # return self.filter_dynamic(data) # # # def write(self, path, action, data): # pass # # # def close(self): # self.api.close() # # # @staticmethod # def cmd_action_join(path, action): # actions = dict(ADD='add', SET='set', DEL='remove', GET='getall') # return pjoin(path, actions[action]) # # # @staticmethod # def filter_dynamic(data): # return tuple(row for row in data if not row.get('dynamic')) # # Path: mcm/librouteros/exceptions.py # class CmdError( LibError ): # ''' # Commend execution errors. # ''' # # Path: mcm/exceptions.py # class ReadError(Exception): # ''' # Exception raised when reading from master or slave occured. # ''' # # class WriteError(Exception): # ''' # Exception raised when writing to master or slave occured. # ''' . Output only the next line.
with self.assertRaises(WriteError):
Based on the snippet: <|code_start|># -*- coding: UTF-8 -*- def test_validate_list_raises_ValidateError_when_list_passed_contains_forbidden_elements(): with pytest.raises(ValidateError): validate_list(lst=[1,2,3], allowed=[1,2] ) def test_validate_val_raises_ValidateError_when_value_passed_is_not_in_allowed(): with pytest.raises(ValidateError): <|code_end|> , predict the immediate next line with the help of imports: import pytest from mcm.validators import validate_list, validate_value, validate_type from mcm.exceptions import ValidateError and context (classes, functions, sometimes code) from other files: # Path: mcm/validators.py # def validate_list(lst, allowed): # # forbidden = set(lst) - set(allowed) # if forbidden: # raise ValidateError() # # def validate_value(val, allowed): # # if val not in allowed: # raise ValidateError() # # def validate_type(val, allowed): # # if type(val) != allowed: # raise ValidateError() # # Path: mcm/exceptions.py # class ValidateError(Exception): # ''' # Exception raised when a general validation error occurs. # ''' . Output only the next line.
validate_value(val='abc', allowed=('single', 'generic'))
Given the code snippet: <|code_start|># -*- coding: UTF-8 -*- def test_validate_list_raises_ValidateError_when_list_passed_contains_forbidden_elements(): with pytest.raises(ValidateError): validate_list(lst=[1,2,3], allowed=[1,2] ) def test_validate_val_raises_ValidateError_when_value_passed_is_not_in_allowed(): with pytest.raises(ValidateError): validate_value(val='abc', allowed=('single', 'generic')) def test_validate_type_raises_ValidateErrot_if_provided_value_is_not_the_same_type(): with pytest.raises(ValidateError): <|code_end|> , generate the next line using the imports in this file: import pytest from mcm.validators import validate_list, validate_value, validate_type from mcm.exceptions import ValidateError and context (functions, classes, or occasionally code) from other files: # Path: mcm/validators.py # def validate_list(lst, allowed): # # forbidden = set(lst) - set(allowed) # if forbidden: # raise ValidateError() # # def validate_value(val, allowed): # # if val not in allowed: # raise ValidateError() # # def validate_type(val, allowed): # # if type(val) != allowed: # raise ValidateError() # # Path: mcm/exceptions.py # class ValidateError(Exception): # ''' # Exception raised when a general validation error occurs. # ''' . Output only the next line.
validate_type(val=1, allowed=str)
Given the following code snippet before the placeholder: <|code_start|># -*- coding: UTF-8 -*- def enclen( length ): ''' Encode given length in mikrotik format. length: Integer < 268435456. returns: Encoded length in bytes. ''' if length < 128: ored_length = length offset = -1 elif length < 16384: ored_length = length | 0x8000 offset = -2 elif length < 2097152: ored_length = length | 0xC00000 offset = -3 elif length < 268435456: ored_length = length | 0xE0000000 offset = -4 else: <|code_end|> , predict the next line using imports from the current file: from socket import SHUT_RDWR, error as SOCKET_ERROR, timeout as SOCKET_TIMEOUT from struct import pack, unpack from mcm.librouteros.exceptions import ConnError and context including class names, function names, and sometimes code from other files: # Path: mcm/librouteros/exceptions.py # class ConnError( LibError ): # ''' # Connection related errors. # ''' . Output only the next line.
raise ConnError( 'unable to encode length of {}'
Given snippet: <|code_start|># -*- coding: UTF-8 -*- @patch( 'mcm.librouteros.api.parsresp' ) @patch( 'mcm.librouteros.api.mksnt' ) @patch( 'mcm.librouteros.api.trapCheck' ) @patch( 'mcm.librouteros.api.raiseIfFatal' ) <|code_end|> , continue by predicting the next line. Consider current file imports: import unittest from mock import MagicMock, patch from mcm.librouteros.api import Api from mcm.librouteros.exceptions import CmdError, ConnError, LibError from mcm.librouteros.connections import ReaderWriter and context: # Path: mcm/librouteros/api.py # class Api: # # # def __init__( self, rwo ): # self.rwo = rwo # # # def run( self, cmd, args = dict() ): # ''' # Run any 'non interactive' command. Returns parsed response. # # cmd Command word eg. /ip/address/print. # args Dictionary with key, value pairs. # ''' # # snt = (cmd,) + mksnt( args ) # self.rwo.writeSnt( snt ) # response = self._readResponse() # trapCheck( response ) # raiseIfFatal( response ) # # return parsresp( response ) # # # def _readResponse( self ): # ''' # Read whole response. # # returns Read sentences as tuple. # ''' # # snts = [] # # while True: # # snt = self.rwo.readSnt() # snts.append( snt ) # # if '!done' in snt: # break # # return tuple( snts ) # # # def close( self ): # ''' # Send /quit and close the connection. # ''' # # try: # self.rwo.writeSnt( ('/quit',) ) # self.rwo.readSnt() # except LibError: # pass # finally: # self.rwo.close() # # # def __del__( self ): # ''' # On garbage collection run close(). # ''' # self.close() # # Path: mcm/librouteros/exceptions.py # class CmdError( LibError ): # ''' # Commend execution errors. # ''' # # class ConnError( LibError ): # ''' # Connection related errors. # ''' # # class LibError( Exception ): # ''' # This is a base exception for all other. # ''' # # Path: mcm/librouteros/connections.py # class ReaderWriter: # # # def __init__( self, sock, log ): # self.sock = sock # self.log = log # # # def writeSnt( self, snt ): # ''' # Write sentence to connection. # # sentence: Iterable (tuple or list) with words. # ''' # # encoded = encsnt( snt ) # self.writeSock( encoded ) # log_snt( self.log, snt, 'write' ) # # # def readSnt( self ): # ''' # Read sentence from connection. # # returns: Sentence as tuple with words in it. # ''' # # snt = [] # for length in iter( self.getLen, 0 ): # word = self.readSock( length ) # snt.append( word ) # # decoded = decsnt( snt ) # log_snt( self.log, decoded, 'read' ) # # return decoded # # # def readSock( self, length ): # ''' # Read as many bytes from socket as specified in length. # Loop as long as every byte is read unless exception is raised. # ''' # # data = bytearray() # # try: # while length: # read = self.sock.recv(length) # if not read: # raise ConnError( 'Connection unexpectedly closed. Read {read}/{total} bytes.' # .format(read = len(data), total = (len(data) + length))) # data += read # length -= len(read) # # except SOCKET_TIMEOUT: # raise ConnError( 'Socket timed out. Read {read}/{total} bytes.' # .format(read = len(data), total = (len(data) + length))) # except SOCKET_ERROR as estr: # raise ConnError( 'Failed to read from socket. {reason}'.format(reason = estr)) # # return data # # # def writeSock( self, string ): # ''' # Write given string to socket. Loop as long as every byte in # string is written unless exception is raised. # ''' # # try: # self.sock.sendall(string) # except SOCKET_TIMEOUT as error: # raise ConnError('Socket timed out. ' + str(error)) # except SOCKET_ERROR as error: # raise ConnError('Failed to write to socket. ' + str(error)) # # # def getLen( self ): # ''' # Read encoded length and return it as integer. # ''' # # first_byte = self.readSock( 1 ) # first_byte_int = unpack( 'B', first_byte )[0] # # if first_byte_int < 128: # bytes_to_read = 0 # elif first_byte_int < 192: # bytes_to_read = 1 # elif first_byte_int < 224: # bytes_to_read = 2 # elif first_byte_int < 240: # bytes_to_read = 3 # else: # raise ConnError( 'unknown controll byte received {0!r}' # .format( first_byte ) ) # # additional_bytes = self.readSock( bytes_to_read ) # # return declen( first_byte + additional_bytes ) # # # def close( self ): # # # do not do anything if socket is already closed # if self.sock._closed: # return # # shutdown socket # try: # self.sock.shutdown( SHUT_RDWR ) # except SOCKET_ERROR: # pass # finally: # self.sock.close() which might include code, classes, or functions. Output only the next line.
@patch.object( Api, '_readResponse' )
Predict the next line after this snippet: <|code_start|># -*- coding: UTF-8 -*- @patch( 'mcm.librouteros.api.parsresp' ) @patch( 'mcm.librouteros.api.mksnt' ) @patch( 'mcm.librouteros.api.trapCheck' ) @patch( 'mcm.librouteros.api.raiseIfFatal' ) @patch.object( Api, '_readResponse' ) @patch.object( Api, 'close' ) class RunMethod(unittest.TestCase): def setUp(self): <|code_end|> using the current file's imports: import unittest from mock import MagicMock, patch from mcm.librouteros.api import Api from mcm.librouteros.exceptions import CmdError, ConnError, LibError from mcm.librouteros.connections import ReaderWriter and any relevant context from other files: # Path: mcm/librouteros/api.py # class Api: # # # def __init__( self, rwo ): # self.rwo = rwo # # # def run( self, cmd, args = dict() ): # ''' # Run any 'non interactive' command. Returns parsed response. # # cmd Command word eg. /ip/address/print. # args Dictionary with key, value pairs. # ''' # # snt = (cmd,) + mksnt( args ) # self.rwo.writeSnt( snt ) # response = self._readResponse() # trapCheck( response ) # raiseIfFatal( response ) # # return parsresp( response ) # # # def _readResponse( self ): # ''' # Read whole response. # # returns Read sentences as tuple. # ''' # # snts = [] # # while True: # # snt = self.rwo.readSnt() # snts.append( snt ) # # if '!done' in snt: # break # # return tuple( snts ) # # # def close( self ): # ''' # Send /quit and close the connection. # ''' # # try: # self.rwo.writeSnt( ('/quit',) ) # self.rwo.readSnt() # except LibError: # pass # finally: # self.rwo.close() # # # def __del__( self ): # ''' # On garbage collection run close(). # ''' # self.close() # # Path: mcm/librouteros/exceptions.py # class CmdError( LibError ): # ''' # Commend execution errors. # ''' # # class ConnError( LibError ): # ''' # Connection related errors. # ''' # # class LibError( Exception ): # ''' # This is a base exception for all other. # ''' # # Path: mcm/librouteros/connections.py # class ReaderWriter: # # # def __init__( self, sock, log ): # self.sock = sock # self.log = log # # # def writeSnt( self, snt ): # ''' # Write sentence to connection. # # sentence: Iterable (tuple or list) with words. # ''' # # encoded = encsnt( snt ) # self.writeSock( encoded ) # log_snt( self.log, snt, 'write' ) # # # def readSnt( self ): # ''' # Read sentence from connection. # # returns: Sentence as tuple with words in it. # ''' # # snt = [] # for length in iter( self.getLen, 0 ): # word = self.readSock( length ) # snt.append( word ) # # decoded = decsnt( snt ) # log_snt( self.log, decoded, 'read' ) # # return decoded # # # def readSock( self, length ): # ''' # Read as many bytes from socket as specified in length. # Loop as long as every byte is read unless exception is raised. # ''' # # data = bytearray() # # try: # while length: # read = self.sock.recv(length) # if not read: # raise ConnError( 'Connection unexpectedly closed. Read {read}/{total} bytes.' # .format(read = len(data), total = (len(data) + length))) # data += read # length -= len(read) # # except SOCKET_TIMEOUT: # raise ConnError( 'Socket timed out. Read {read}/{total} bytes.' # .format(read = len(data), total = (len(data) + length))) # except SOCKET_ERROR as estr: # raise ConnError( 'Failed to read from socket. {reason}'.format(reason = estr)) # # return data # # # def writeSock( self, string ): # ''' # Write given string to socket. Loop as long as every byte in # string is written unless exception is raised. # ''' # # try: # self.sock.sendall(string) # except SOCKET_TIMEOUT as error: # raise ConnError('Socket timed out. ' + str(error)) # except SOCKET_ERROR as error: # raise ConnError('Failed to write to socket. ' + str(error)) # # # def getLen( self ): # ''' # Read encoded length and return it as integer. # ''' # # first_byte = self.readSock( 1 ) # first_byte_int = unpack( 'B', first_byte )[0] # # if first_byte_int < 128: # bytes_to_read = 0 # elif first_byte_int < 192: # bytes_to_read = 1 # elif first_byte_int < 224: # bytes_to_read = 2 # elif first_byte_int < 240: # bytes_to_read = 3 # else: # raise ConnError( 'unknown controll byte received {0!r}' # .format( first_byte ) ) # # additional_bytes = self.readSock( bytes_to_read ) # # return declen( first_byte + additional_bytes ) # # # def close( self ): # # # do not do anything if socket is already closed # if self.sock._closed: # return # # shutdown socket # try: # self.sock.shutdown( SHUT_RDWR ) # except SOCKET_ERROR: # pass # finally: # self.sock.close() . Output only the next line.
rwo = MagicMock( spec = ReaderWriter )
Given snippet: <|code_start|># -*- coding: UTF-8 -*- class CmdPathConfigurator_Tests(TestCase): def setUp(self): self.addfunc = MagicMock() self.delfunc = MagicMock() self.setfunc = MagicMock() <|code_end|> , continue by predicting the next line. Consider current file imports: from mock import MagicMock, patch from unittest import TestCase from mcm.configurators import CmdPathConfigurator, real_action, no_action, Configurator from mcm.exceptions import ReadError from mcm.librouteros.exceptions import ConnError and context: # Path: mcm/configurators.py # class CmdPathConfigurator: # # # def __init__(self, configurator, path, comparator, addfunc, setfunc, delfunc): # self.configurator = configurator # self.path = path # self.comparator = comparator # self.ADD = MethodType( addfunc, self ) # self.DEL = MethodType( delfunc, self ) # self.SET = MethodType( setfunc, self ) # # # @classmethod # def with_ensure(cls, configurator, path): # comparator = get_comparator(path=path) # return cls(configurator=configurator, path=path, comparator=comparator, # addfunc=real_action, setfunc=real_action, delfunc=no_action) # # @classmethod # def with_exact(cls, configurator, path): # comparator = get_comparator(path=path) # return cls(configurator=configurator, path=path, comparator=comparator, # addfunc=real_action, setfunc=real_action, delfunc=real_action) # # # def run(self): # # data = self.readData() # result = self.compareData(data) # self.applyData(data=result) # # # def applyData(self, data): # # for action in self.path.modord: # action_data = self.extartActionData( data=data, action=action ) # action_method = getattr(self, action) # action_method(action, action_data) # # # def compareData(self, data): # # master_data, slave_data = data # return self.comparator.compare(wanted=master_data, present=slave_data) # # # def readData(self): # # master_data = self.configurator.master.read( path=self.path ) # slave_data = self.configurator.slave.read( path=self.path ) # return master_data, slave_data # # # @staticmethod # def extartActionData(data, action): # # ADD, SET, DEL = data # action_map = {'ADD':ADD, 'SET':SET, 'DEL':DEL} # return action_map[action] # # def real_action(self, action, data): # # self.configurator.slave.write(data=data, path=self.path, action=action) # # def no_action(self, action, data): # pass # # class Configurator: # # # def __init__(self, master, slave): # self.master = master # self.slave = slave # # # def run(self, paths): # for path in paths: # configurator = self.getPathConfigurator(path=path) # try: # configurator.run() # except ReadError as error: # msg = 'Failed to read {path} {reason}'.format(path=path.absolute, reason=error) # logger.error(msg) # except ConnError as error: # msg = 'Connection broken {reason}'.format(reason=error) # logger.error(msg) # break # # self.master.close() # self.slave.close() # # # def getPathConfigurator(self, path): # strategy = 'with_' + path.strategy # constructor = getattr(CmdPathConfigurator, strategy) # return constructor(configurator=self, path=path) # # Path: mcm/exceptions.py # class ReadError(Exception): # ''' # Exception raised when reading from master or slave occured. # ''' # # Path: mcm/librouteros/exceptions.py # class ConnError( LibError ): # ''' # Connection related errors. # ''' which might include code, classes, or functions. Output only the next line.
self.TestCls = CmdPathConfigurator( path=MagicMock(), configurator=MagicMock(), comparator=MagicMock(), addfunc=self.addfunc, delfunc=self.delfunc, setfunc=self.setfunc )
Given snippet: <|code_start|> self.TestCls.configurator.master.read.assert_called_once_with(path=self.TestCls.path) def test_extractActionData_returns_ADD_data_when_requested(self): data = ADD, SET, DEL = ( MagicMock(), MagicMock(), MagicMock() ) returned = self.TestCls.extartActionData(data=data, action='ADD') self.assertEqual(returned, ADD) def test_extractActionData_returns_SET_data_when_requested(self): data = ADD, SET, DEL = ( MagicMock(), MagicMock(), MagicMock() ) returned = self.TestCls.extartActionData(data=data, action='SET') self.assertEqual(returned, SET) def test_extractActionData_returns_DEL_data_when_requested(self): data = ADD, SET, DEL = ( MagicMock(), MagicMock(), MagicMock() ) returned = self.TestCls.extartActionData(data=data, action='DEL') self.assertEqual(returned, DEL) @patch('mcm.configurators.get_comparator') @patch.object(CmdPathConfigurator, '__init__', return_value=None) class Strategy_Factory_Tests(TestCase): def setUp(self): self.path, self.configurator = MagicMock(), MagicMock() def test_with_ensure_calls_init_with_appropriate_methods(self, initmock, cmpmock): CmdPathConfigurator.with_ensure(path=self.path, configurator=self.configurator) initmock.assert_called_once_with(path=self.path, comparator=cmpmock.return_value, configurator=self.configurator, <|code_end|> , continue by predicting the next line. Consider current file imports: from mock import MagicMock, patch from unittest import TestCase from mcm.configurators import CmdPathConfigurator, real_action, no_action, Configurator from mcm.exceptions import ReadError from mcm.librouteros.exceptions import ConnError and context: # Path: mcm/configurators.py # class CmdPathConfigurator: # # # def __init__(self, configurator, path, comparator, addfunc, setfunc, delfunc): # self.configurator = configurator # self.path = path # self.comparator = comparator # self.ADD = MethodType( addfunc, self ) # self.DEL = MethodType( delfunc, self ) # self.SET = MethodType( setfunc, self ) # # # @classmethod # def with_ensure(cls, configurator, path): # comparator = get_comparator(path=path) # return cls(configurator=configurator, path=path, comparator=comparator, # addfunc=real_action, setfunc=real_action, delfunc=no_action) # # @classmethod # def with_exact(cls, configurator, path): # comparator = get_comparator(path=path) # return cls(configurator=configurator, path=path, comparator=comparator, # addfunc=real_action, setfunc=real_action, delfunc=real_action) # # # def run(self): # # data = self.readData() # result = self.compareData(data) # self.applyData(data=result) # # # def applyData(self, data): # # for action in self.path.modord: # action_data = self.extartActionData( data=data, action=action ) # action_method = getattr(self, action) # action_method(action, action_data) # # # def compareData(self, data): # # master_data, slave_data = data # return self.comparator.compare(wanted=master_data, present=slave_data) # # # def readData(self): # # master_data = self.configurator.master.read( path=self.path ) # slave_data = self.configurator.slave.read( path=self.path ) # return master_data, slave_data # # # @staticmethod # def extartActionData(data, action): # # ADD, SET, DEL = data # action_map = {'ADD':ADD, 'SET':SET, 'DEL':DEL} # return action_map[action] # # def real_action(self, action, data): # # self.configurator.slave.write(data=data, path=self.path, action=action) # # def no_action(self, action, data): # pass # # class Configurator: # # # def __init__(self, master, slave): # self.master = master # self.slave = slave # # # def run(self, paths): # for path in paths: # configurator = self.getPathConfigurator(path=path) # try: # configurator.run() # except ReadError as error: # msg = 'Failed to read {path} {reason}'.format(path=path.absolute, reason=error) # logger.error(msg) # except ConnError as error: # msg = 'Connection broken {reason}'.format(reason=error) # logger.error(msg) # break # # self.master.close() # self.slave.close() # # # def getPathConfigurator(self, path): # strategy = 'with_' + path.strategy # constructor = getattr(CmdPathConfigurator, strategy) # return constructor(configurator=self, path=path) # # Path: mcm/exceptions.py # class ReadError(Exception): # ''' # Exception raised when reading from master or slave occured. # ''' # # Path: mcm/librouteros/exceptions.py # class ConnError( LibError ): # ''' # Connection related errors. # ''' which might include code, classes, or functions. Output only the next line.
addfunc=real_action, delfunc=no_action, setfunc=real_action)
Given the following code snippet before the placeholder: <|code_start|> self.TestCls.configurator.master.read.assert_called_once_with(path=self.TestCls.path) def test_extractActionData_returns_ADD_data_when_requested(self): data = ADD, SET, DEL = ( MagicMock(), MagicMock(), MagicMock() ) returned = self.TestCls.extartActionData(data=data, action='ADD') self.assertEqual(returned, ADD) def test_extractActionData_returns_SET_data_when_requested(self): data = ADD, SET, DEL = ( MagicMock(), MagicMock(), MagicMock() ) returned = self.TestCls.extartActionData(data=data, action='SET') self.assertEqual(returned, SET) def test_extractActionData_returns_DEL_data_when_requested(self): data = ADD, SET, DEL = ( MagicMock(), MagicMock(), MagicMock() ) returned = self.TestCls.extartActionData(data=data, action='DEL') self.assertEqual(returned, DEL) @patch('mcm.configurators.get_comparator') @patch.object(CmdPathConfigurator, '__init__', return_value=None) class Strategy_Factory_Tests(TestCase): def setUp(self): self.path, self.configurator = MagicMock(), MagicMock() def test_with_ensure_calls_init_with_appropriate_methods(self, initmock, cmpmock): CmdPathConfigurator.with_ensure(path=self.path, configurator=self.configurator) initmock.assert_called_once_with(path=self.path, comparator=cmpmock.return_value, configurator=self.configurator, <|code_end|> , predict the next line using imports from the current file: from mock import MagicMock, patch from unittest import TestCase from mcm.configurators import CmdPathConfigurator, real_action, no_action, Configurator from mcm.exceptions import ReadError from mcm.librouteros.exceptions import ConnError and context including class names, function names, and sometimes code from other files: # Path: mcm/configurators.py # class CmdPathConfigurator: # # # def __init__(self, configurator, path, comparator, addfunc, setfunc, delfunc): # self.configurator = configurator # self.path = path # self.comparator = comparator # self.ADD = MethodType( addfunc, self ) # self.DEL = MethodType( delfunc, self ) # self.SET = MethodType( setfunc, self ) # # # @classmethod # def with_ensure(cls, configurator, path): # comparator = get_comparator(path=path) # return cls(configurator=configurator, path=path, comparator=comparator, # addfunc=real_action, setfunc=real_action, delfunc=no_action) # # @classmethod # def with_exact(cls, configurator, path): # comparator = get_comparator(path=path) # return cls(configurator=configurator, path=path, comparator=comparator, # addfunc=real_action, setfunc=real_action, delfunc=real_action) # # # def run(self): # # data = self.readData() # result = self.compareData(data) # self.applyData(data=result) # # # def applyData(self, data): # # for action in self.path.modord: # action_data = self.extartActionData( data=data, action=action ) # action_method = getattr(self, action) # action_method(action, action_data) # # # def compareData(self, data): # # master_data, slave_data = data # return self.comparator.compare(wanted=master_data, present=slave_data) # # # def readData(self): # # master_data = self.configurator.master.read( path=self.path ) # slave_data = self.configurator.slave.read( path=self.path ) # return master_data, slave_data # # # @staticmethod # def extartActionData(data, action): # # ADD, SET, DEL = data # action_map = {'ADD':ADD, 'SET':SET, 'DEL':DEL} # return action_map[action] # # def real_action(self, action, data): # # self.configurator.slave.write(data=data, path=self.path, action=action) # # def no_action(self, action, data): # pass # # class Configurator: # # # def __init__(self, master, slave): # self.master = master # self.slave = slave # # # def run(self, paths): # for path in paths: # configurator = self.getPathConfigurator(path=path) # try: # configurator.run() # except ReadError as error: # msg = 'Failed to read {path} {reason}'.format(path=path.absolute, reason=error) # logger.error(msg) # except ConnError as error: # msg = 'Connection broken {reason}'.format(reason=error) # logger.error(msg) # break # # self.master.close() # self.slave.close() # # # def getPathConfigurator(self, path): # strategy = 'with_' + path.strategy # constructor = getattr(CmdPathConfigurator, strategy) # return constructor(configurator=self, path=path) # # Path: mcm/exceptions.py # class ReadError(Exception): # ''' # Exception raised when reading from master or slave occured. # ''' # # Path: mcm/librouteros/exceptions.py # class ConnError( LibError ): # ''' # Connection related errors. # ''' . Output only the next line.
addfunc=real_action, delfunc=no_action, setfunc=real_action)
Next line prediction: <|code_start|> CmdPathConfigurator.with_ensure(path=self.path, configurator=self.configurator) initmock.assert_called_once_with(path=self.path, comparator=cmpmock.return_value, configurator=self.configurator, addfunc=real_action, delfunc=no_action, setfunc=real_action) def test_with_exact_calls_init_with_appropriate_methods(self, initmock, cmpmock): CmdPathConfigurator.with_exact(path=self.path, configurator=self.configurator) initmock.assert_called_once_with(path=self.path, comparator=cmpmock.return_value, configurator=self.configurator, addfunc=real_action, delfunc=real_action, setfunc=real_action) class StrategyMethods_Tests(TestCase): def setUp(self): self.cls = MagicMock() self.data = MagicMock() def test_real_action_calls_slaves_write(self): real_action(self.cls, 'ADD', self.data) self.cls.configurator.slave.write.assert_called_once_with(data=self.data, path=self.cls.path, action='ADD') def test_no_action_does_not_call_masters_write(self): no_action(self.cls, 'ADD', self.data) self.assertEqual( self.cls.configurator.master.write.call_count, 0 ) class Configurator_Tests(TestCase): def setUp(self): <|code_end|> . Use current file imports: (from mock import MagicMock, patch from unittest import TestCase from mcm.configurators import CmdPathConfigurator, real_action, no_action, Configurator from mcm.exceptions import ReadError from mcm.librouteros.exceptions import ConnError) and context including class names, function names, or small code snippets from other files: # Path: mcm/configurators.py # class CmdPathConfigurator: # # # def __init__(self, configurator, path, comparator, addfunc, setfunc, delfunc): # self.configurator = configurator # self.path = path # self.comparator = comparator # self.ADD = MethodType( addfunc, self ) # self.DEL = MethodType( delfunc, self ) # self.SET = MethodType( setfunc, self ) # # # @classmethod # def with_ensure(cls, configurator, path): # comparator = get_comparator(path=path) # return cls(configurator=configurator, path=path, comparator=comparator, # addfunc=real_action, setfunc=real_action, delfunc=no_action) # # @classmethod # def with_exact(cls, configurator, path): # comparator = get_comparator(path=path) # return cls(configurator=configurator, path=path, comparator=comparator, # addfunc=real_action, setfunc=real_action, delfunc=real_action) # # # def run(self): # # data = self.readData() # result = self.compareData(data) # self.applyData(data=result) # # # def applyData(self, data): # # for action in self.path.modord: # action_data = self.extartActionData( data=data, action=action ) # action_method = getattr(self, action) # action_method(action, action_data) # # # def compareData(self, data): # # master_data, slave_data = data # return self.comparator.compare(wanted=master_data, present=slave_data) # # # def readData(self): # # master_data = self.configurator.master.read( path=self.path ) # slave_data = self.configurator.slave.read( path=self.path ) # return master_data, slave_data # # # @staticmethod # def extartActionData(data, action): # # ADD, SET, DEL = data # action_map = {'ADD':ADD, 'SET':SET, 'DEL':DEL} # return action_map[action] # # def real_action(self, action, data): # # self.configurator.slave.write(data=data, path=self.path, action=action) # # def no_action(self, action, data): # pass # # class Configurator: # # # def __init__(self, master, slave): # self.master = master # self.slave = slave # # # def run(self, paths): # for path in paths: # configurator = self.getPathConfigurator(path=path) # try: # configurator.run() # except ReadError as error: # msg = 'Failed to read {path} {reason}'.format(path=path.absolute, reason=error) # logger.error(msg) # except ConnError as error: # msg = 'Connection broken {reason}'.format(reason=error) # logger.error(msg) # break # # self.master.close() # self.slave.close() # # # def getPathConfigurator(self, path): # strategy = 'with_' + path.strategy # constructor = getattr(CmdPathConfigurator, strategy) # return constructor(configurator=self, path=path) # # Path: mcm/exceptions.py # class ReadError(Exception): # ''' # Exception raised when reading from master or slave occured. # ''' # # Path: mcm/librouteros/exceptions.py # class ConnError( LibError ): # ''' # Connection related errors. # ''' . Output only the next line.
self.TestCls = Configurator(master=MagicMock(), slave=MagicMock())
Continue the code snippet: <|code_start|> def test_real_action_calls_slaves_write(self): real_action(self.cls, 'ADD', self.data) self.cls.configurator.slave.write.assert_called_once_with(data=self.data, path=self.cls.path, action='ADD') def test_no_action_does_not_call_masters_write(self): no_action(self.cls, 'ADD', self.data) self.assertEqual( self.cls.configurator.master.write.call_count, 0 ) class Configurator_Tests(TestCase): def setUp(self): self.TestCls = Configurator(master=MagicMock(), slave=MagicMock()) self.path = MagicMock() @patch.object(Configurator, 'getPathConfigurator') def test_run_calls_getPathConfigurator(self, pathcfgmock): self.TestCls.run(paths=(self.path,)) pathcfgmock.assert_any_call(path=self.path) @patch.object(Configurator, 'getPathConfigurator') def test_run_calls_run(self, pathcfgmock): '''After calling getPathConfigurator, assert that its run() was called.''' self.TestCls.run(paths=(self.path,)) pathcfgmock.return_value.run.assert_called_once_with() @patch.object(Configurator, 'getPathConfigurator') def test_run_catches_ReadError(self, pathcfgmock): <|code_end|> . Use current file imports: from mock import MagicMock, patch from unittest import TestCase from mcm.configurators import CmdPathConfigurator, real_action, no_action, Configurator from mcm.exceptions import ReadError from mcm.librouteros.exceptions import ConnError and context (classes, functions, or code) from other files: # Path: mcm/configurators.py # class CmdPathConfigurator: # # # def __init__(self, configurator, path, comparator, addfunc, setfunc, delfunc): # self.configurator = configurator # self.path = path # self.comparator = comparator # self.ADD = MethodType( addfunc, self ) # self.DEL = MethodType( delfunc, self ) # self.SET = MethodType( setfunc, self ) # # # @classmethod # def with_ensure(cls, configurator, path): # comparator = get_comparator(path=path) # return cls(configurator=configurator, path=path, comparator=comparator, # addfunc=real_action, setfunc=real_action, delfunc=no_action) # # @classmethod # def with_exact(cls, configurator, path): # comparator = get_comparator(path=path) # return cls(configurator=configurator, path=path, comparator=comparator, # addfunc=real_action, setfunc=real_action, delfunc=real_action) # # # def run(self): # # data = self.readData() # result = self.compareData(data) # self.applyData(data=result) # # # def applyData(self, data): # # for action in self.path.modord: # action_data = self.extartActionData( data=data, action=action ) # action_method = getattr(self, action) # action_method(action, action_data) # # # def compareData(self, data): # # master_data, slave_data = data # return self.comparator.compare(wanted=master_data, present=slave_data) # # # def readData(self): # # master_data = self.configurator.master.read( path=self.path ) # slave_data = self.configurator.slave.read( path=self.path ) # return master_data, slave_data # # # @staticmethod # def extartActionData(data, action): # # ADD, SET, DEL = data # action_map = {'ADD':ADD, 'SET':SET, 'DEL':DEL} # return action_map[action] # # def real_action(self, action, data): # # self.configurator.slave.write(data=data, path=self.path, action=action) # # def no_action(self, action, data): # pass # # class Configurator: # # # def __init__(self, master, slave): # self.master = master # self.slave = slave # # # def run(self, paths): # for path in paths: # configurator = self.getPathConfigurator(path=path) # try: # configurator.run() # except ReadError as error: # msg = 'Failed to read {path} {reason}'.format(path=path.absolute, reason=error) # logger.error(msg) # except ConnError as error: # msg = 'Connection broken {reason}'.format(reason=error) # logger.error(msg) # break # # self.master.close() # self.slave.close() # # # def getPathConfigurator(self, path): # strategy = 'with_' + path.strategy # constructor = getattr(CmdPathConfigurator, strategy) # return constructor(configurator=self, path=path) # # Path: mcm/exceptions.py # class ReadError(Exception): # ''' # Exception raised when reading from master or slave occured. # ''' # # Path: mcm/librouteros/exceptions.py # class ConnError( LibError ): # ''' # Connection related errors. # ''' . Output only the next line.
pathcfgmock.return_value.run.side_effect = ReadError
Next line prediction: <|code_start|> def test_no_action_does_not_call_masters_write(self): no_action(self.cls, 'ADD', self.data) self.assertEqual( self.cls.configurator.master.write.call_count, 0 ) class Configurator_Tests(TestCase): def setUp(self): self.TestCls = Configurator(master=MagicMock(), slave=MagicMock()) self.path = MagicMock() @patch.object(Configurator, 'getPathConfigurator') def test_run_calls_getPathConfigurator(self, pathcfgmock): self.TestCls.run(paths=(self.path,)) pathcfgmock.assert_any_call(path=self.path) @patch.object(Configurator, 'getPathConfigurator') def test_run_calls_run(self, pathcfgmock): '''After calling getPathConfigurator, assert that its run() was called.''' self.TestCls.run(paths=(self.path,)) pathcfgmock.return_value.run.assert_called_once_with() @patch.object(Configurator, 'getPathConfigurator') def test_run_catches_ReadError(self, pathcfgmock): pathcfgmock.return_value.run.side_effect = ReadError self.TestCls.run(paths=(self.path,)) @patch.object(Configurator, 'getPathConfigurator') def test_run_catches_ConnError(self, pathcfgmock): <|code_end|> . Use current file imports: (from mock import MagicMock, patch from unittest import TestCase from mcm.configurators import CmdPathConfigurator, real_action, no_action, Configurator from mcm.exceptions import ReadError from mcm.librouteros.exceptions import ConnError) and context including class names, function names, or small code snippets from other files: # Path: mcm/configurators.py # class CmdPathConfigurator: # # # def __init__(self, configurator, path, comparator, addfunc, setfunc, delfunc): # self.configurator = configurator # self.path = path # self.comparator = comparator # self.ADD = MethodType( addfunc, self ) # self.DEL = MethodType( delfunc, self ) # self.SET = MethodType( setfunc, self ) # # # @classmethod # def with_ensure(cls, configurator, path): # comparator = get_comparator(path=path) # return cls(configurator=configurator, path=path, comparator=comparator, # addfunc=real_action, setfunc=real_action, delfunc=no_action) # # @classmethod # def with_exact(cls, configurator, path): # comparator = get_comparator(path=path) # return cls(configurator=configurator, path=path, comparator=comparator, # addfunc=real_action, setfunc=real_action, delfunc=real_action) # # # def run(self): # # data = self.readData() # result = self.compareData(data) # self.applyData(data=result) # # # def applyData(self, data): # # for action in self.path.modord: # action_data = self.extartActionData( data=data, action=action ) # action_method = getattr(self, action) # action_method(action, action_data) # # # def compareData(self, data): # # master_data, slave_data = data # return self.comparator.compare(wanted=master_data, present=slave_data) # # # def readData(self): # # master_data = self.configurator.master.read( path=self.path ) # slave_data = self.configurator.slave.read( path=self.path ) # return master_data, slave_data # # # @staticmethod # def extartActionData(data, action): # # ADD, SET, DEL = data # action_map = {'ADD':ADD, 'SET':SET, 'DEL':DEL} # return action_map[action] # # def real_action(self, action, data): # # self.configurator.slave.write(data=data, path=self.path, action=action) # # def no_action(self, action, data): # pass # # class Configurator: # # # def __init__(self, master, slave): # self.master = master # self.slave = slave # # # def run(self, paths): # for path in paths: # configurator = self.getPathConfigurator(path=path) # try: # configurator.run() # except ReadError as error: # msg = 'Failed to read {path} {reason}'.format(path=path.absolute, reason=error) # logger.error(msg) # except ConnError as error: # msg = 'Connection broken {reason}'.format(reason=error) # logger.error(msg) # break # # self.master.close() # self.slave.close() # # # def getPathConfigurator(self, path): # strategy = 'with_' + path.strategy # constructor = getattr(CmdPathConfigurator, strategy) # return constructor(configurator=self, path=path) # # Path: mcm/exceptions.py # class ReadError(Exception): # ''' # Exception raised when reading from master or slave occured. # ''' # # Path: mcm/librouteros/exceptions.py # class ConnError( LibError ): # ''' # Connection related errors. # ''' . Output only the next line.
pathcfgmock.return_value.run.side_effect = ConnError
Here is a snippet: <|code_start|># -*- coding: UTF-8 -*- integers = (0, 127 ,130 ,2097140 ,268435440) encoded = (b'\x00', b'\x7f', b'\x80\x82', b'\xdf\xff\xf4', b'\xef\xff\xff\xf0') @pytest.mark.parametrize("integer,encoded", zip(integers, encoded)) def test_encoding(integer, encoded): <|code_end|> . Write the next line using the current file imports: import unittest import pytest from socket import SHUT_RDWR, error as SOCKET_ERROR, timeout as SOCKET_TIMEOUT, socket from mock import MagicMock, call, patch from mcm.librouteros import connections from mcm.librouteros.exceptions import ConnError and context from other files: # Path: mcm/librouteros/connections.py # def enclen( length ): # def declen( bytes ): # def decsnt( sentence ): # def encsnt( sentence ): # def encword( word ): # def log_snt( logger, sentence, direction ): # def __init__( self, sock, log ): # def writeSnt( self, snt ): # def readSnt( self ): # def readSock( self, length ): # def writeSock( self, string ): # def getLen( self ): # def close( self ): # XOR = 0 # XOR = 0x8000 # XOR = 0xC00000 # XOR = 0xE0000000 # class ReaderWriter: # # Path: mcm/librouteros/exceptions.py # class ConnError( LibError ): # ''' # Connection related errors. # ''' , which may include functions, classes, or code. Output only the next line.
assert connections.enclen(integer) == encoded
Given the code snippet: <|code_start|># -*- coding: UTF-8 -*- integers = (0, 127 ,130 ,2097140 ,268435440) encoded = (b'\x00', b'\x7f', b'\x80\x82', b'\xdf\xff\xf4', b'\xef\xff\xff\xf0') @pytest.mark.parametrize("integer,encoded", zip(integers, encoded)) def test_encoding(integer, encoded): assert connections.enclen(integer) == encoded @pytest.mark.parametrize("encoded,integer", zip(encoded, integers)) def test_decoding(encoded, integer): assert connections.declen(encoded) == integer def test_raises_if_lenghth_is_too_big(): '''Raises ConnError if length >= 268435456''' <|code_end|> , generate the next line using the imports in this file: import unittest import pytest from socket import SHUT_RDWR, error as SOCKET_ERROR, timeout as SOCKET_TIMEOUT, socket from mock import MagicMock, call, patch from mcm.librouteros import connections from mcm.librouteros.exceptions import ConnError and context (functions, classes, or occasionally code) from other files: # Path: mcm/librouteros/connections.py # def enclen( length ): # def declen( bytes ): # def decsnt( sentence ): # def encsnt( sentence ): # def encword( word ): # def log_snt( logger, sentence, direction ): # def __init__( self, sock, log ): # def writeSnt( self, snt ): # def readSnt( self ): # def readSock( self, length ): # def writeSock( self, string ): # def getLen( self ): # def close( self ): # XOR = 0 # XOR = 0x8000 # XOR = 0xC00000 # XOR = 0xE0000000 # class ReaderWriter: # # Path: mcm/librouteros/exceptions.py # class ConnError( LibError ): # ''' # Connection related errors. # ''' . Output only the next line.
with pytest.raises(ConnError):
Predict the next line after this snippet: <|code_start|># -*- coding: UTF-8 -*- logger = getLogger('mcm.' + __name__) class CmdPathConfigurator: def __init__(self, configurator, path, comparator, addfunc, setfunc, delfunc): self.configurator = configurator self.path = path self.comparator = comparator self.ADD = MethodType( addfunc, self ) self.DEL = MethodType( delfunc, self ) self.SET = MethodType( setfunc, self ) @classmethod def with_ensure(cls, configurator, path): <|code_end|> using the current file's imports: from types import MethodType from logging import getLogger from mcm.comparators import get_comparator from mcm.exceptions import ReadError from mcm.librouteros.exceptions import ConnError and any relevant context from other files: # Path: mcm/comparators.py # def get_comparator(path): # if path.type == 'single': # return SingleElementComparator() # elif path.type == 'ordered': # return OrderedComparator() # elif path.type == 'uniquekey': # return UniqueKeyComparator(keys=path.keys) # # Path: mcm/exceptions.py # class ReadError(Exception): # ''' # Exception raised when reading from master or slave occured. # ''' # # Path: mcm/librouteros/exceptions.py # class ConnError( LibError ): # ''' # Connection related errors. # ''' . Output only the next line.
comparator = get_comparator(path=path)
Predict the next line for this snippet: <|code_start|> def real_action(self, action, data): self.configurator.slave.write(data=data, path=self.path, action=action) def no_action(self, action, data): pass class Configurator: def __init__(self, master, slave): self.master = master self.slave = slave def run(self, paths): for path in paths: configurator = self.getPathConfigurator(path=path) try: configurator.run() <|code_end|> with the help of current file imports: from types import MethodType from logging import getLogger from mcm.comparators import get_comparator from mcm.exceptions import ReadError from mcm.librouteros.exceptions import ConnError and context from other files: # Path: mcm/comparators.py # def get_comparator(path): # if path.type == 'single': # return SingleElementComparator() # elif path.type == 'ordered': # return OrderedComparator() # elif path.type == 'uniquekey': # return UniqueKeyComparator(keys=path.keys) # # Path: mcm/exceptions.py # class ReadError(Exception): # ''' # Exception raised when reading from master or slave occured. # ''' # # Path: mcm/librouteros/exceptions.py # class ConnError( LibError ): # ''' # Connection related errors. # ''' , which may contain function names, class names, or code. Output only the next line.
except ReadError as error:
Predict the next line for this snippet: <|code_start|> def real_action(self, action, data): self.configurator.slave.write(data=data, path=self.path, action=action) def no_action(self, action, data): pass class Configurator: def __init__(self, master, slave): self.master = master self.slave = slave def run(self, paths): for path in paths: configurator = self.getPathConfigurator(path=path) try: configurator.run() except ReadError as error: msg = 'Failed to read {path} {reason}'.format(path=path.absolute, reason=error) logger.error(msg) <|code_end|> with the help of current file imports: from types import MethodType from logging import getLogger from mcm.comparators import get_comparator from mcm.exceptions import ReadError from mcm.librouteros.exceptions import ConnError and context from other files: # Path: mcm/comparators.py # def get_comparator(path): # if path.type == 'single': # return SingleElementComparator() # elif path.type == 'ordered': # return OrderedComparator() # elif path.type == 'uniquekey': # return UniqueKeyComparator(keys=path.keys) # # Path: mcm/exceptions.py # class ReadError(Exception): # ''' # Exception raised when reading from master or slave occured. # ''' # # Path: mcm/librouteros/exceptions.py # class ConnError( LibError ): # ''' # Connection related errors. # ''' , which may contain function names, class names, or code. Output only the next line.
except ConnError as error:
Given snippet: <|code_start|> @patch('mcm.datastructures.MENU_PATHS') class Test_CmdPath: @pytest.mark.parametrize("path",("/ip/address/", "ip/address", "/ip/address")) def test_absolute_attribute(self, paths_mock, path): cmd_path = make_cmdpath(path, strategy=None) assert cmd_path.absolute == '/ip/address' def test_strategy_attribute_is_the_same_as_passed_in_function_call(self, paths_mock): cmd_path = make_cmdpath('/ip/address', strategy='exact') assert cmd_path.strategy == 'exact' def test_calls_getitem_on_paths_data_structure(self, paths_mock): make_cmdpath('/ip/address', strategy='exact') paths_mock.__getitem__.assert_called_once_with('/ip/address') def test_calling_getitem_on_paths_data_structure_riases_KeyError_when_path_is_missing(self, paths_mock): paths_mock.__getitem__.side_effect = KeyError with pytest.raises(KeyError): make_cmdpath('/ip/address', 'exact') @pytest.mark.parametrize("data,expected", ( ( {'enabled':True}, 'enabled=yes' ), ( {'enabled':False}, 'enabled=no' ), ( {'servers':None}, 'servers=""' ), ( {'servers':''}, 'servers=""' ), )) def test_CmdPathRow_str(data, expected): <|code_end|> , continue by predicting the next line. Consider current file imports: from mock import patch from mcm.datastructures import CmdPathRow, make_cmdpath import pytest and context: # Path: mcm/datastructures.py # class CmdPathRow(dict): # # # def __str__(self): # bool_map = {True:'yes', False:'no', None:'""', '':'""'} # return ' '.join('{}={}'.format(key, bool_map.get(value, value)) for key, value in self.items()) # # # def __hash__(self): # return hash(tuple(self.items())) # # # def __sub__(self, other): # '''Return new instance with key,valie pairs from self not listed in other.''' # # diff = dict(set(self.items()) - set(other.items())) # return CmdPathRow( diff ) # # # def isunique(self, other, keys): # '''Test whether every key,value pair (from keys) is in other.''' # # pairs = set( (key,self[key]) for key in keys ) # return pairs <= set(other.items()) # # def make_cmdpath(path, strategy): # attrs = dict() # attrs['absolute'] = pjoin('/', path ).rstrip('/') # attrs['strategy'] = strategy # path_attrs = MENU_PATHS[path] # attrs['keys'] = path_attrs['keys'] # attrs['type'] = path_attrs['type'] # attrs['modord'] = path_attrs['modord'] # # return CmdPath(**attrs) which might include code, classes, or functions. Output only the next line.
assert str(CmdPathRow(data)) == expected
Predict the next line after this snippet: <|code_start|># -*- coding: UTF-8 -*- @patch('mcm.datastructures.MENU_PATHS') class Test_CmdPath: @pytest.mark.parametrize("path",("/ip/address/", "ip/address", "/ip/address")) def test_absolute_attribute(self, paths_mock, path): <|code_end|> using the current file's imports: from mock import patch from mcm.datastructures import CmdPathRow, make_cmdpath import pytest and any relevant context from other files: # Path: mcm/datastructures.py # class CmdPathRow(dict): # # # def __str__(self): # bool_map = {True:'yes', False:'no', None:'""', '':'""'} # return ' '.join('{}={}'.format(key, bool_map.get(value, value)) for key, value in self.items()) # # # def __hash__(self): # return hash(tuple(self.items())) # # # def __sub__(self, other): # '''Return new instance with key,valie pairs from self not listed in other.''' # # diff = dict(set(self.items()) - set(other.items())) # return CmdPathRow( diff ) # # # def isunique(self, other, keys): # '''Test whether every key,value pair (from keys) is in other.''' # # pairs = set( (key,self[key]) for key in keys ) # return pairs <= set(other.items()) # # def make_cmdpath(path, strategy): # attrs = dict() # attrs['absolute'] = pjoin('/', path ).rstrip('/') # attrs['strategy'] = strategy # path_attrs = MENU_PATHS[path] # attrs['keys'] = path_attrs['keys'] # attrs['type'] = path_attrs['type'] # attrs['modord'] = path_attrs['modord'] # # return CmdPath(**attrs) . Output only the next line.
cmd_path = make_cmdpath(path, strategy=None)
Given the following code snippet before the placeholder: <|code_start|> class StaticConfig: def __init__(self, data): self.data = data def read(self, path): for section in self.data: if section['path'] == path: return section['rules'] def close(self): pass class ReadOnlyRouterOS: def __init__(self, api): self.api = api def read(self, path): cmd = self.cmd_action_join(path=path, action='GET') try: data = self.api.run(cmd=cmd) <|code_end|> , predict the next line using imports from the current file: from posixpath import join as pjoin from mcm.librouteros import CmdError from mcm.exceptions import ReadError, WriteError and context including class names, function names, and sometimes code from other files: # Path: mcm/librouteros/exceptions.py # class CmdError( LibError ): # ''' # Commend execution errors. # ''' # # Path: mcm/exceptions.py # class ReadError(Exception): # ''' # Exception raised when reading from master or slave occured. # ''' # # class WriteError(Exception): # ''' # Exception raised when writing to master or slave occured. # ''' . Output only the next line.
except CmdError as error:
Given the code snippet: <|code_start|> class StaticConfig: def __init__(self, data): self.data = data def read(self, path): for section in self.data: if section['path'] == path: return section['rules'] def close(self): pass class ReadOnlyRouterOS: def __init__(self, api): self.api = api def read(self, path): cmd = self.cmd_action_join(path=path, action='GET') try: data = self.api.run(cmd=cmd) except CmdError as error: <|code_end|> , generate the next line using the imports in this file: from posixpath import join as pjoin from mcm.librouteros import CmdError from mcm.exceptions import ReadError, WriteError and context (functions, classes, or occasionally code) from other files: # Path: mcm/librouteros/exceptions.py # class CmdError( LibError ): # ''' # Commend execution errors. # ''' # # Path: mcm/exceptions.py # class ReadError(Exception): # ''' # Exception raised when reading from master or slave occured. # ''' # # class WriteError(Exception): # ''' # Exception raised when writing to master or slave occured. # ''' . Output only the next line.
raise ReadError(error)
Using the snippet: <|code_start|> def close(self): self.api.close() @staticmethod def cmd_action_join(path, action): actions = dict(ADD='add', SET='set', DEL='remove', GET='getall') return pjoin(path, actions[action]) @staticmethod def filter_dynamic(data): return tuple(row for row in data if not row.get('dynamic')) class RouterOsAPIDevice(ReadOnlyRouterOS): def write(self, path, action, data): command = self.cmd_action_join(path=path, action=action) method = getattr(self, action) method(command=command, data=data) def DEL(self, command, data): ID = {'.id':data['.id']} try: self.api.run(cmd=command, args=ID) except CmdError as error: <|code_end|> , determine the next line of code. You have imports: from posixpath import join as pjoin from mcm.librouteros import CmdError from mcm.exceptions import ReadError, WriteError and context (class names, function names, or code) available: # Path: mcm/librouteros/exceptions.py # class CmdError( LibError ): # ''' # Commend execution errors. # ''' # # Path: mcm/exceptions.py # class ReadError(Exception): # ''' # Exception raised when reading from master or slave occured. # ''' # # class WriteError(Exception): # ''' # Exception raised when writing to master or slave occured. # ''' . Output only the next line.
raise WriteError(error)
Given the following code snippet before the placeholder: <|code_start|> self.comparator.ADD.append.assert_called_once_with( self.wanted ) def test_appends_to_DEL(self): """If there is only present element, append it to DEL.""" self.comparator.decide(wanted=None, difference=None, present=self.present ) self.comparator.DEL.append.assert_called_once_with( self.present ) def test_appends_to_SET(self): """If there are wanted,difference,present, append difference to SET.""" self.comparator.decide(wanted=self.wanted, difference=self.difference, present=self.present ) self.comparator.SET.append.assert_called_once_with( self.difference ) def test_calls_setitem_on_difference(self): """Assert difference['.id'] was called""" present_id = self.present.__getitem__.return_value = MagicMock() self.comparator.decide(wanted=self.wanted, difference=self.difference, present=self.present ) self.difference.__setitem__.assert_called_once_with('.id', present_id) def test_calls_getitem_on_present(self): """Assert present['.id'] was called""" self.comparator.decide(wanted=self.wanted, difference=self.difference, present=self.present ) self.present.__getitem__.assert_called_once_with('.id') class UniqueKeyComparator_Tests: def setup(self): self.difference = MagicMock() self.present = MagicMock() self.wanted = MagicMock() <|code_end|> , predict the next line using imports from the current file: from mock import MagicMock, patch from mcm.comparators import UniqueKeyComparator, OrderedComparator and context including class names, function names, and sometimes code from other files: # Path: mcm/comparators.py # class UniqueKeyComparator: # # # def __init__(self, keys): # # self.keys = keys # self.SET = [] # self.ADD = [] # self.NO_DELETE = [] # # # def compare(self, wanted, present): # # for wanted_rule in wanted: # present_rule = self.findPair(searched=wanted_rule, present=present) # diff = wanted_rule - present_rule # self.decide(wanted_rule, diff, present_rule) # # DEL = set(present) - set(self.NO_DELETE) # return tuple(self.ADD), tuple(self.SET), tuple(DEL) # # # def decide(self, wanted, difference, present): # # if wanted and difference and not present: # self.ADD.append( wanted ) # elif wanted and difference and present: # self.NO_DELETE.append(present) # difference['.id'] = present['.id'] # self.SET.append( difference ) # elif wanted and not difference and present: # self.NO_DELETE.append(present) # # # def findPair(self, searched, present): # # for row in present: # if row.isunique(other=searched, keys=self.keys): # return row # else: # return CmdPathRow(dict()) # # class OrderedComparator: # # # def __init__(self): # # self.DEL = [] # self.SET= [] # self.ADD = [] # # # def decide(self, wanted, difference, present): # # if wanted and difference and not present: # self.ADD.append( wanted ) # elif not wanted and not difference and present: # self.DEL.append( present ) # elif wanted and difference and present: # difference['.id'] = present['.id'] # self.SET.append( difference ) # # # def compare(self, wanted, present): # # fillval = CmdPathRow(dict()) # for wanted_rule, present_rule in zip_longest(wanted, present, fillvalue=fillval): # diff = wanted_rule - present_rule # self.decide(wanted_rule, diff, present_rule) # # return tuple(self.ADD), tuple(self.SET), tuple(self.DEL) . Output only the next line.
self.comparator = UniqueKeyComparator( keys=('name',) )
Based on the snippet: <|code_start|># -*- coding: UTF-8 -*- @pytest.fixture def master_adapter(): return MasterAdapter(device=MagicMock()) @pytest.fixture def slave_adapter(): <|code_end|> , predict the immediate next line with the help of imports: from mock import MagicMock, patch from mcm.adapters import MasterAdapter, SlaveAdapter from mcm.exceptions import WriteError import pytest and context (classes, functions, sometimes code) from other files: # Path: mcm/adapters.py # class MasterAdapter: # # # def __init__(self, device): # self.device = device # # # def read(self, path): # content = self.device.read(path=path.absolute) # data = self.assemble_data(data=content) # for row in data: # logger.debug('{path} {data}'.format(path=path.absolute, data=row)) # return data # # # def close(self): # self.device.close() # # # @staticmethod # def assemble_data(data): # return tuple(CmdPathRow(elem) for elem in data) # # class SlaveAdapter(MasterAdapter): # # # def write(self, path, action, data): # for row in data: # try: # self.device.write(path=path.absolute, action=action, data=row) # logger.info('{path} {action} {data}'.format(path=path.absolute, action=action, data=row)) # except WriteError as error: # logger.error('Failed to send {path} {action} {data} to device: {reason}'.format(path=path.absolute, action=action, data=row, reason=error)) # # Path: mcm/exceptions.py # class WriteError(Exception): # ''' # Exception raised when writing to master or slave occured. # ''' . Output only the next line.
return SlaveAdapter(device=MagicMock())
Here is a snippet: <|code_start|>def test_MasterAdapter_calls_assemble_data(master_adapter, path): master_adapter.assemble_data = MagicMock() master_adapter.read(path=path) master_adapter.assemble_data.assert_called_once_with(data=master_adapter.device.read.return_value) @pytest.mark.parametrize("adapter", (master_adapter(), slave_adapter())) def test_adapters_device_close(adapter): adapter.close() adapter.device.close.assert_called_once_with() @patch('mcm.adapters.CmdPathRow') def test_assemble_data_calls_CmdPathRow(rowmock, master_adapter, data_set, data_row): master_adapter.assemble_data(data=data_set) rowmock.assert_any_call(data_row) @patch('mcm.adapters.CmdPathRow') def test_assemble_data_returns_tuple(rowmock, master_adapter, data_set, data_row): result = master_adapter.assemble_data(data=data_set) assert type(result) == tuple def test_SlaveAdapter_write_calls_device_write(slave_adapter, data_set, path, data_row): slave_adapter.write(path=path, action='ADD', data=data_set) slave_adapter.device.write.assert_any_call(path=path.absolute, action='ADD', data=data_row) def test_SlaveAdapter_write_catches_WriteError(slave_adapter, data_set, path): <|code_end|> . Write the next line using the current file imports: from mock import MagicMock, patch from mcm.adapters import MasterAdapter, SlaveAdapter from mcm.exceptions import WriteError import pytest and context from other files: # Path: mcm/adapters.py # class MasterAdapter: # # # def __init__(self, device): # self.device = device # # # def read(self, path): # content = self.device.read(path=path.absolute) # data = self.assemble_data(data=content) # for row in data: # logger.debug('{path} {data}'.format(path=path.absolute, data=row)) # return data # # # def close(self): # self.device.close() # # # @staticmethod # def assemble_data(data): # return tuple(CmdPathRow(elem) for elem in data) # # class SlaveAdapter(MasterAdapter): # # # def write(self, path, action, data): # for row in data: # try: # self.device.write(path=path.absolute, action=action, data=row) # logger.info('{path} {action} {data}'.format(path=path.absolute, action=action, data=row)) # except WriteError as error: # logger.error('Failed to send {path} {action} {data} to device: {reason}'.format(path=path.absolute, action=action, data=row, reason=error)) # # Path: mcm/exceptions.py # class WriteError(Exception): # ''' # Exception raised when writing to master or slave occured. # ''' , which may include functions, classes, or code. Output only the next line.
slave_adapter.device.side_effect = WriteError
Given snippet: <|code_start|>#!/usr/bin/env python ################################################################ ### Jose A Espinosa. CSN/CB-CRG Group. Jan 2016 ### ################################################################ ### Script creates BedTools objects from a file containing ### ### mice feeding behavior and uses tools from pybedtools to ### ### extract intermeals intervals (complement) and intersect ### ### them with day and experimental phases. ### ### Generates a bed file for each track with the result of ### ### the above described operations. ### ################################################################ base_dir = path.dirname(getcwd()) out_dir = base_dir + "/test/" mapping_data = mapping.MappingInfo(base_dir + "/sample_data/feeding_behavior/b2g.txt") <|code_end|> , continue by predicting the next line. Consider current file imports: import pybedtools from os import path, getcwd from pergola import mapping from pergola import intervals and context: # Path: pergola/mapping.py # class MappingInfo(): # def __init__(self, path, **kwargs): # def _correspondence_from_config(self, path): # def _tab_config(self, file_tab): # def _mapping_config(self, file_map): # def write(self, indent=0): # def check_path(path): # def write_chr(self, mode="w", path_w=None, min_c=None, max_c=None): # def write_chr_sizes(self, mode="w", path_w=None, file_n=None, min_c=None, max_c=None): # def write_cytoband(end, start=0, delta=43200, start_phase="light", mode="w", path_w=None, lab_bed=True, track_line=True): # def write_period_seq (end, start=0, delta=43200, tag="day", mode="w", path_w=None, name_file="period_seq", lab_bed=True, track_line=True): # # Path: pergola/intervals.py # class IntData(object): # def __init__(self, path, map_dict, header=True, **kwargs): # def _check_delimiter (self, path, delimiter): # def _reader_data(self): # def _pandas_df_reader(self, df): # def _set_fields_b(self, fields=None): # def _set_fields_g (self, map_dict): # def _simple_read(self): # def get_field_items(self, data, field="data_types", default=None): # def read(self, fields=None, relative_coord=False, intervals=False, int_step=None, fields2rel=None, multiply_t=None, # **kwargs): # def _min_max(self, list_data, f_start="start", f_end="end"): # def _time2rel_time(self, i_fields): # def _multiply_values(self, i_fields, factor=1): # def _create_int(self, start_int, int_step=None): # def _create_int_add_integ(self, start_int, integer=1): # def __del__(self): # def is_number(var): # def num(s): which might include code, classes, or functions. Output only the next line.
int_data = intervals.IntData(base_dir + "/sample_data/feeding_behavior/feedingBehavior_HF_mice.csv", map_dict=mapping_data.correspondence)
Next line prediction: <|code_start|>#!/usr/bin/env python ################################################################ ### Jose A Espinosa. CSN/CB-CRG Group. Jan 2016 ### ################################################################ ### Script creates BedTools objects from a file containing ### ### mice feeding behavior and uses tools from pybedtools to ### ### extract intermeals intervals (complement) and intersect ### ### them with day and experimental phases. ### ### Generates a bed file for each track with the result of ### ### the above described operations. ### ################################################################ base_dir = path.dirname(getcwd()) out_dir = base_dir + "/test/" mapping_data = mapping.MappingInfo(base_dir + "/sample_data/feeding_behavior/b2g.txt") <|code_end|> . Use current file imports: (import pybedtools from os import path, getcwd from pergola import mapping from pergola import intervals) and context including class names, function names, or small code snippets from other files: # Path: pergola/mapping.py # class MappingInfo(): # def __init__(self, path, **kwargs): # def _correspondence_from_config(self, path): # def _tab_config(self, file_tab): # def _mapping_config(self, file_map): # def write(self, indent=0): # def check_path(path): # def write_chr(self, mode="w", path_w=None, min_c=None, max_c=None): # def write_chr_sizes(self, mode="w", path_w=None, file_n=None, min_c=None, max_c=None): # def write_cytoband(end, start=0, delta=43200, start_phase="light", mode="w", path_w=None, lab_bed=True, track_line=True): # def write_period_seq (end, start=0, delta=43200, tag="day", mode="w", path_w=None, name_file="period_seq", lab_bed=True, track_line=True): # # Path: pergola/intervals.py # class IntData(object): # def __init__(self, path, map_dict, header=True, **kwargs): # def _check_delimiter (self, path, delimiter): # def _reader_data(self): # def _pandas_df_reader(self, df): # def _set_fields_b(self, fields=None): # def _set_fields_g (self, map_dict): # def _simple_read(self): # def get_field_items(self, data, field="data_types", default=None): # def read(self, fields=None, relative_coord=False, intervals=False, int_step=None, fields2rel=None, multiply_t=None, # **kwargs): # def _min_max(self, list_data, f_start="start", f_end="end"): # def _time2rel_time(self, i_fields): # def _multiply_values(self, i_fields, factor=1): # def _create_int(self, start_int, int_step=None): # def _create_int_add_integ(self, start_int, integer=1): # def __del__(self): # def is_number(var): # def num(s): . Output only the next line.
int_data = intervals.IntData(base_dir + "/sample_data/feeding_behavior/feedingBehavior_HF_mice.csv", map_dict=mapping_data.correspondence)
Next line prediction: <|code_start|>parent_parser.add_argument('-w', '--window_size', required=False, metavar="WINDOW_SIZE", type=int, help='Window size for bedGraph intervals, default value 300') parent_parser.add_argument('-nt', '--no_track_line', required=False, action='store_true', default=False, help='Track line no included in the bed file') parent_parser.add_argument('-fs', '--field_separator', required=False, type=str, default=False, help='Input file field separator') parent_parser.add_argument('-bl', '--bed_label', required=False, action='store_true', default=False, help='Show data_types as name field in bed file') parent_parser.add_argument('-c', '--color_file', required=False, metavar="PATH_COLOR_FILE", help='Dictionary assigning colors of data_types path') parent_parser.add_argument('-wm', '--window_mean', required=False, action='store_true', default=False, help='Window values averaged by the window size') parent_parser.add_argument('-vm', '--value_mean', required=False, action='store_true', help='Window values averaged by number of items within window') parent_parser.add_argument('-min', '--min_time', type=int, required=False, help='Initial time point to extract') parent_parser.add_argument('-max', '--max_time', type=int, required=False, help='Last time point to extract') parent_parser.add_argument('-ng', '--no_genome', required=False, dest='genome', action='store_false', help='Avoinds the creation of a FASTA file which allows to render a longitudinal trajectory' \ ' in a genome browser') parent_parser.add_argument('-np', '--no_phases', required=False, dest='phases', action='store_false', help='Avoids the creation of a phases bed file') parent_parser.set_defaults(genome=True) parent_parser.set_defaults(phases=True) parent_parser.add_argument('-o', '--output_file_name', help='File name for output files') parent_parser.add_argument('-sp', '--starting_phase', type=str, required=False, choices=_starting_phase_options, help='Sets the first phase to appear in the phases and cytoband file: light or dark\n') parent_parser.add_argument('-sh', '--shift', required=False, metavar="TIME_SHIFT", type=int, help='Time shift to be set for the first phase') <|code_end|> . Use current file imports: (from ._version import __version__ from sys import stderr from argparse import ArgumentParser, ArgumentTypeError from re import match from os.path import abspath, split, realpath from .mapping import check_path) and context including class names, function names, or small code snippets from other files: # Path: pergola/_version.py # # Path: pergola/mapping.py # def check_path(path): # """ # Check whether the input file exists and is accessible and if OK returns path # # :param path: path to the intervals file # # :returns: the path assessed # # """ # # assert isinstance(path, str), "Expected string or unicode, found %s." % type(path) # try: # f = open(path, "r") # except IOError: # raise IOError('File does not exist: %s' % path) # finally: # f.close() # return path . Output only the next line.
parent_parser.add_argument('-v', '--version', action='version', version='%(prog)s {version}'.format(version=__version__))
Predict the next line after this snippet: <|code_start|> tracks2merge = "" if track_action == "join_all": tracks2merge = tracks elif track_action == 'join_odd': tracks2merge = set([t for t in tracks if int(t) % 2]) elif track_action == 'join_even': tracks2merge = set([t for t in tracks if not int(t) % 2]) else: tracks2merge = "" print("Tracks to merge are: ", ",".join("'{0}'".format(t) for t in tracks2merge), file=stderr) if not tracks2merge: print(("No track action applied as track actions \'%s\' can not be applied to list of tracks provided \'%s\'"%(track_action, " ".join(tracks))), file=stderr) return (tracks2merge) def read_colors (path_color_file): """ Reads user colors for each data_type :param None path_color_file: :py:func:`str` path to read user color for data_types :returns: d_user_color dictionary {'data_type_1': 'orange', 'data_type_2':'blue'} """ <|code_end|> using the current file's imports: from ._version import __version__ from sys import stderr from argparse import ArgumentParser, ArgumentTypeError from re import match from os.path import abspath, split, realpath from .mapping import check_path and any relevant context from other files: # Path: pergola/_version.py # # Path: pergola/mapping.py # def check_path(path): # """ # Check whether the input file exists and is accessible and if OK returns path # # :param path: path to the intervals file # # :returns: the path assessed # # """ # # assert isinstance(path, str), "Expected string or unicode, found %s." % type(path) # try: # f = open(path, "r") # except IOError: # raise IOError('File does not exist: %s' % path) # finally: # f.close() # return path . Output only the next line.
check_path(path_color_file)
Next line prediction: <|code_start|>parser.add_argument('-b','--behavioral_type', help='Choose whether to work with drinking or feeding mice behavioral data', required=True, choices=_behaviors_available) args = parser.parse_args() print >> stderr, "Statistic to be calculated: %s" % args.statistic print >> stderr, "Working with mice %s behavioral data" % args.behavioral_type # Statistic to calculate statistic = args.statistic ## Dictionary to set colors of each type of food # food_sc orange # food_fat black # water blue # saccharin red ### Feeding data if args.behavioral_type == "feeding": data_type_1 = "food_sc" data_type_2 = "food_fat" data_type_col = {data_type_1: 'orange', data_type_2:'black'} ### Drinking data elif args.behavioral_type == 'drinking': data_type_1 = "water" data_type_2 = "saccharin" data_type_col = {data_type_1: 'blue', data_type_2:'red'} else: print >> stderr, "Behavioral data type not available in script, please try again with \"drinking\" or \"feeding\"" <|code_end|> . Use current file imports: (from argparse import ArgumentParser from os import path, getcwd, makedirs, chdir from shutil import rmtree from sys import stderr from pergola import mapping from pergola import intervals from pergola import tracks import subprocess import pybedtools) and context including class names, function names, or small code snippets from other files: # Path: pergola/mapping.py # class MappingInfo(): # def __init__(self, path, **kwargs): # def _correspondence_from_config(self, path): # def _tab_config(self, file_tab): # def _mapping_config(self, file_map): # def write(self, indent=0): # def check_path(path): # def write_chr(self, mode="w", path_w=None, min_c=None, max_c=None): # def write_chr_sizes(self, mode="w", path_w=None, file_n=None, min_c=None, max_c=None): # def write_cytoband(end, start=0, delta=43200, start_phase="light", mode="w", path_w=None, lab_bed=True, track_line=True): # def write_period_seq (end, start=0, delta=43200, tag="day", mode="w", path_w=None, name_file="period_seq", lab_bed=True, track_line=True): # # Path: pergola/intervals.py # class IntData(object): # def __init__(self, path, map_dict, header=True, **kwargs): # def _check_delimiter (self, path, delimiter): # def _reader_data(self): # def _pandas_df_reader(self, df): # def _set_fields_b(self, fields=None): # def _set_fields_g (self, map_dict): # def _simple_read(self): # def get_field_items(self, data, field="data_types", default=None): # def read(self, fields=None, relative_coord=False, intervals=False, int_step=None, fields2rel=None, multiply_t=None, # **kwargs): # def _min_max(self, list_data, f_start="start", f_end="end"): # def _time2rel_time(self, i_fields): # def _multiply_values(self, i_fields, factor=1): # def _create_int(self, start_int, int_step=None): # def _create_int_add_integ(self, start_int, integer=1): # def __del__(self): # def is_number(var): # def num(s): # # Path: pergola/tracks.py # class GenomicContainer(object): # class Track(GenomicContainer): # class BedToolConvertible(GenomicContainer): # class Bed(BedToolConvertible): # class BedGraph(BedToolConvertible): # class Gff(BedToolConvertible): # def __init__(self, data, fields=None, data_types=None, **kwargs): # def __iter__(self): # def next(self): # def save_track(self, mode="w", path=None, name_file=None, track_line=True, bed_label=False, gff_label=False): # def __init__(self, data, fields=None, data_types=None, list_tracks=None, min=0, max=0, **kwargs): # def convert(self, mode='bed', range_color=None, **kwargs): # def _convert2single_track(self, data_tuples, mode=None, **kwargs): # def _get_range(self, data_tr): # def remove(self, dict_t, tracks2remove): # def join_by_track(self, dict_t, tracks2join): # def join_by_dataType (self, dict_d, mode): # def track_convert2bed(self, track, in_call=False, **kwargs): # def track_convert2gff(self, track, in_call=False, **kwargs): # def track_convert2bedGraph(self, track, in_call=False, window=300, mean_win=False, mean_value=False, **kwargs): # def __init__(self, data, **kwargs): # def create_pybedtools(self): # def _tmp_track(self): # def __init__(self, data, **kwargs): # def __init__(self, data, **kwargs): # def win_mean (self): # def _win_mean (self, data, n_tracks): # def __init__(self, data, **kwargs): # def assign_color(set_data_types, color_restrictions=None): # def merge_tracks (tr_1, tr_2): . Output only the next line.
mapping_data = mapping.MappingInfo("../../sample_data/feeding_behavior/b2p.txt")
Based on the snippet: <|code_start|> args = parser.parse_args() print >> stderr, "Statistic to be calculated: %s" % args.statistic print >> stderr, "Working with mice %s behavioral data" % args.behavioral_type # Statistic to calculate statistic = args.statistic ## Dictionary to set colors of each type of food # food_sc orange # food_fat black # water blue # saccharin red ### Feeding data if args.behavioral_type == "feeding": data_type_1 = "food_sc" data_type_2 = "food_fat" data_type_col = {data_type_1: 'orange', data_type_2:'black'} ### Drinking data elif args.behavioral_type == 'drinking': data_type_1 = "water" data_type_2 = "saccharin" data_type_col = {data_type_1: 'blue', data_type_2:'red'} else: print >> stderr, "Behavioral data type not available in script, please try again with \"drinking\" or \"feeding\"" mapping_data = mapping.MappingInfo("../../sample_data/feeding_behavior/b2p.txt") <|code_end|> , predict the immediate next line with the help of imports: from argparse import ArgumentParser from os import path, getcwd, makedirs, chdir from shutil import rmtree from sys import stderr from pergola import mapping from pergola import intervals from pergola import tracks import subprocess import pybedtools and context (classes, functions, sometimes code) from other files: # Path: pergola/mapping.py # class MappingInfo(): # def __init__(self, path, **kwargs): # def _correspondence_from_config(self, path): # def _tab_config(self, file_tab): # def _mapping_config(self, file_map): # def write(self, indent=0): # def check_path(path): # def write_chr(self, mode="w", path_w=None, min_c=None, max_c=None): # def write_chr_sizes(self, mode="w", path_w=None, file_n=None, min_c=None, max_c=None): # def write_cytoband(end, start=0, delta=43200, start_phase="light", mode="w", path_w=None, lab_bed=True, track_line=True): # def write_period_seq (end, start=0, delta=43200, tag="day", mode="w", path_w=None, name_file="period_seq", lab_bed=True, track_line=True): # # Path: pergola/intervals.py # class IntData(object): # def __init__(self, path, map_dict, header=True, **kwargs): # def _check_delimiter (self, path, delimiter): # def _reader_data(self): # def _pandas_df_reader(self, df): # def _set_fields_b(self, fields=None): # def _set_fields_g (self, map_dict): # def _simple_read(self): # def get_field_items(self, data, field="data_types", default=None): # def read(self, fields=None, relative_coord=False, intervals=False, int_step=None, fields2rel=None, multiply_t=None, # **kwargs): # def _min_max(self, list_data, f_start="start", f_end="end"): # def _time2rel_time(self, i_fields): # def _multiply_values(self, i_fields, factor=1): # def _create_int(self, start_int, int_step=None): # def _create_int_add_integ(self, start_int, integer=1): # def __del__(self): # def is_number(var): # def num(s): # # Path: pergola/tracks.py # class GenomicContainer(object): # class Track(GenomicContainer): # class BedToolConvertible(GenomicContainer): # class Bed(BedToolConvertible): # class BedGraph(BedToolConvertible): # class Gff(BedToolConvertible): # def __init__(self, data, fields=None, data_types=None, **kwargs): # def __iter__(self): # def next(self): # def save_track(self, mode="w", path=None, name_file=None, track_line=True, bed_label=False, gff_label=False): # def __init__(self, data, fields=None, data_types=None, list_tracks=None, min=0, max=0, **kwargs): # def convert(self, mode='bed', range_color=None, **kwargs): # def _convert2single_track(self, data_tuples, mode=None, **kwargs): # def _get_range(self, data_tr): # def remove(self, dict_t, tracks2remove): # def join_by_track(self, dict_t, tracks2join): # def join_by_dataType (self, dict_d, mode): # def track_convert2bed(self, track, in_call=False, **kwargs): # def track_convert2gff(self, track, in_call=False, **kwargs): # def track_convert2bedGraph(self, track, in_call=False, window=300, mean_win=False, mean_value=False, **kwargs): # def __init__(self, data, **kwargs): # def create_pybedtools(self): # def _tmp_track(self): # def __init__(self, data, **kwargs): # def __init__(self, data, **kwargs): # def win_mean (self): # def _win_mean (self, data, n_tracks): # def __init__(self, data, **kwargs): # def assign_color(set_data_types, color_restrictions=None): # def merge_tracks (tr_1, tr_2): . Output only the next line.
int_data_b1 = intervals.IntData ("../../sample_data/feeding_beh_CB1_mice/intake_CB1_B1.csv", map_dict=mapping_data.correspondence)
Based on the snippet: <|code_start|> int_data_b1 = intervals.IntData ("../../sample_data/feeding_beh_CB1_mice/intake_CB1_B1.csv", map_dict=mapping_data.correspondence) int_data_b2 = intervals.IntData ("../../sample_data/feeding_beh_CB1_mice/intake_CB1_B2.csv", map_dict=mapping_data.correspondence) int_data_b3 = intervals.IntData ("../../sample_data/feeding_beh_CB1_mice/intake_CB1_B3.csv", map_dict=mapping_data.correspondence) int_data_b4 = intervals.IntData ("../../sample_data/feeding_beh_CB1_mice/intake_CB1_B4.csv", map_dict=mapping_data.correspondence) mapping_bed = mapping.MappingInfo("../../test/pybed2perg.txt") # base_dir = path.dirname(getcwd()) base_dir = getcwd() results_dir = "/results_by_day/" out_dir = base_dir + results_dir + args.behavioral_type + "_by_phases/" + statistic + "/" if path.exists(out_dir): rmtree(out_dir) makedirs(out_dir) chdir(out_dir) data_read_b1 = int_data_b1.read(relative_coord=True) data_read_b2 = int_data_b2.read(relative_coord=True) data_read_b3 = int_data_b3.read(relative_coord=True) data_read_b4 = int_data_b4.read(relative_coord=True) # Check the longest period of time of any batches end_time = max (int_data_b1.max - int_data_b1.min, int_data_b2.max - int_data_b2.min, int_data_b3.max - int_data_b3.min, int_data_b4.max - int_data_b4.min) <|code_end|> , predict the immediate next line with the help of imports: from argparse import ArgumentParser from os import path, getcwd, makedirs, chdir from shutil import rmtree from sys import stderr from pergola import mapping from pergola import intervals from pergola import tracks import subprocess import pybedtools and context (classes, functions, sometimes code) from other files: # Path: pergola/mapping.py # class MappingInfo(): # def __init__(self, path, **kwargs): # def _correspondence_from_config(self, path): # def _tab_config(self, file_tab): # def _mapping_config(self, file_map): # def write(self, indent=0): # def check_path(path): # def write_chr(self, mode="w", path_w=None, min_c=None, max_c=None): # def write_chr_sizes(self, mode="w", path_w=None, file_n=None, min_c=None, max_c=None): # def write_cytoband(end, start=0, delta=43200, start_phase="light", mode="w", path_w=None, lab_bed=True, track_line=True): # def write_period_seq (end, start=0, delta=43200, tag="day", mode="w", path_w=None, name_file="period_seq", lab_bed=True, track_line=True): # # Path: pergola/intervals.py # class IntData(object): # def __init__(self, path, map_dict, header=True, **kwargs): # def _check_delimiter (self, path, delimiter): # def _reader_data(self): # def _pandas_df_reader(self, df): # def _set_fields_b(self, fields=None): # def _set_fields_g (self, map_dict): # def _simple_read(self): # def get_field_items(self, data, field="data_types", default=None): # def read(self, fields=None, relative_coord=False, intervals=False, int_step=None, fields2rel=None, multiply_t=None, # **kwargs): # def _min_max(self, list_data, f_start="start", f_end="end"): # def _time2rel_time(self, i_fields): # def _multiply_values(self, i_fields, factor=1): # def _create_int(self, start_int, int_step=None): # def _create_int_add_integ(self, start_int, integer=1): # def __del__(self): # def is_number(var): # def num(s): # # Path: pergola/tracks.py # class GenomicContainer(object): # class Track(GenomicContainer): # class BedToolConvertible(GenomicContainer): # class Bed(BedToolConvertible): # class BedGraph(BedToolConvertible): # class Gff(BedToolConvertible): # def __init__(self, data, fields=None, data_types=None, **kwargs): # def __iter__(self): # def next(self): # def save_track(self, mode="w", path=None, name_file=None, track_line=True, bed_label=False, gff_label=False): # def __init__(self, data, fields=None, data_types=None, list_tracks=None, min=0, max=0, **kwargs): # def convert(self, mode='bed', range_color=None, **kwargs): # def _convert2single_track(self, data_tuples, mode=None, **kwargs): # def _get_range(self, data_tr): # def remove(self, dict_t, tracks2remove): # def join_by_track(self, dict_t, tracks2join): # def join_by_dataType (self, dict_d, mode): # def track_convert2bed(self, track, in_call=False, **kwargs): # def track_convert2gff(self, track, in_call=False, **kwargs): # def track_convert2bedGraph(self, track, in_call=False, window=300, mean_win=False, mean_value=False, **kwargs): # def __init__(self, data, **kwargs): # def create_pybedtools(self): # def _tmp_track(self): # def __init__(self, data, **kwargs): # def __init__(self, data, **kwargs): # def win_mean (self): # def _win_mean (self, data, n_tracks): # def __init__(self, data, **kwargs): # def assign_color(set_data_types, color_restrictions=None): # def merge_tracks (tr_1, tr_2): . Output only the next line.
data_read_all_batches = tracks.merge_tracks (tracks.merge_tracks (tracks.merge_tracks (data_read_b1, data_read_b2), data_read_b3), data_read_b4)
Here is a snippet: <|code_start|>parser.add_argument('-b','--behavioral_type', help='Choose whether to work with drinking or feeding mice behavioral data', required=True, choices=_behaviors_available) args = parser.parse_args() print >> stderr, "Statistic to be calculated: %s" % args.statistic print >> stderr, "Working with mice %s behavioral data" % args.behavioral_type # Statistic to calculate statistic = args.statistic ## Dictionary to set colors of each type of food # food_sc orange # food_fat black # water blue # saccharin red ### Feeding data if args.behavioral_type == "feeding": data_type_1 = "food_sc" data_type_2 = "food_fat" data_type_col = {data_type_1: 'orange', data_type_2:'black'} ### Drinking data elif args.behavioral_type == 'drinking': data_type_1 = "water" data_type_2 = "saccharin" data_type_col = {data_type_1: 'blue', data_type_2:'red'} else: print >> stderr, "Behavioral data type not available in script, please try again with \"drinking\" or \"feeding\"" <|code_end|> . Write the next line using the current file imports: from argparse import ArgumentParser from os import path, getcwd, makedirs, chdir from shutil import rmtree from sys import stderr from pergola import mapping from pergola import intervals from pergola import tracks import subprocess import pybedtools and context from other files: # Path: pergola/mapping.py # class MappingInfo(): # def __init__(self, path, **kwargs): # def _correspondence_from_config(self, path): # def _tab_config(self, file_tab): # def _mapping_config(self, file_map): # def write(self, indent=0): # def check_path(path): # def write_chr(self, mode="w", path_w=None, min_c=None, max_c=None): # def write_chr_sizes(self, mode="w", path_w=None, file_n=None, min_c=None, max_c=None): # def write_cytoband(end, start=0, delta=43200, start_phase="light", mode="w", path_w=None, lab_bed=True, track_line=True): # def write_period_seq (end, start=0, delta=43200, tag="day", mode="w", path_w=None, name_file="period_seq", lab_bed=True, track_line=True): # # Path: pergola/intervals.py # class IntData(object): # def __init__(self, path, map_dict, header=True, **kwargs): # def _check_delimiter (self, path, delimiter): # def _reader_data(self): # def _pandas_df_reader(self, df): # def _set_fields_b(self, fields=None): # def _set_fields_g (self, map_dict): # def _simple_read(self): # def get_field_items(self, data, field="data_types", default=None): # def read(self, fields=None, relative_coord=False, intervals=False, int_step=None, fields2rel=None, multiply_t=None, # **kwargs): # def _min_max(self, list_data, f_start="start", f_end="end"): # def _time2rel_time(self, i_fields): # def _multiply_values(self, i_fields, factor=1): # def _create_int(self, start_int, int_step=None): # def _create_int_add_integ(self, start_int, integer=1): # def __del__(self): # def is_number(var): # def num(s): # # Path: pergola/tracks.py # class GenomicContainer(object): # class Track(GenomicContainer): # class BedToolConvertible(GenomicContainer): # class Bed(BedToolConvertible): # class BedGraph(BedToolConvertible): # class Gff(BedToolConvertible): # def __init__(self, data, fields=None, data_types=None, **kwargs): # def __iter__(self): # def next(self): # def save_track(self, mode="w", path=None, name_file=None, track_line=True, bed_label=False, gff_label=False): # def __init__(self, data, fields=None, data_types=None, list_tracks=None, min=0, max=0, **kwargs): # def convert(self, mode='bed', range_color=None, **kwargs): # def _convert2single_track(self, data_tuples, mode=None, **kwargs): # def _get_range(self, data_tr): # def remove(self, dict_t, tracks2remove): # def join_by_track(self, dict_t, tracks2join): # def join_by_dataType (self, dict_d, mode): # def track_convert2bed(self, track, in_call=False, **kwargs): # def track_convert2gff(self, track, in_call=False, **kwargs): # def track_convert2bedGraph(self, track, in_call=False, window=300, mean_win=False, mean_value=False, **kwargs): # def __init__(self, data, **kwargs): # def create_pybedtools(self): # def _tmp_track(self): # def __init__(self, data, **kwargs): # def __init__(self, data, **kwargs): # def win_mean (self): # def _win_mean (self, data, n_tracks): # def __init__(self, data, **kwargs): # def assign_color(set_data_types, color_restrictions=None): # def merge_tracks (tr_1, tr_2): , which may include functions, classes, or code. Output only the next line.
mapping_data = mapping.MappingInfo("../../sample_data/feeding_behavior/b2g.txt")
Predict the next line for this snippet: <|code_start|> args = parser.parse_args() print >> stderr, "Statistic to be calculated: %s" % args.statistic print >> stderr, "Working with mice %s behavioral data" % args.behavioral_type # Statistic to calculate statistic = args.statistic ## Dictionary to set colors of each type of food # food_sc orange # food_fat black # water blue # saccharin red ### Feeding data if args.behavioral_type == "feeding": data_type_1 = "food_sc" data_type_2 = "food_fat" data_type_col = {data_type_1: 'orange', data_type_2:'black'} ### Drinking data elif args.behavioral_type == 'drinking': data_type_1 = "water" data_type_2 = "saccharin" data_type_col = {data_type_1: 'blue', data_type_2:'red'} else: print >> stderr, "Behavioral data type not available in script, please try again with \"drinking\" or \"feeding\"" mapping_data = mapping.MappingInfo("../../sample_data/feeding_behavior/b2g.txt") <|code_end|> with the help of current file imports: from argparse import ArgumentParser from os import path, getcwd, makedirs, chdir from shutil import rmtree from sys import stderr from pergola import mapping from pergola import intervals from pergola import tracks import subprocess import pybedtools and context from other files: # Path: pergola/mapping.py # class MappingInfo(): # def __init__(self, path, **kwargs): # def _correspondence_from_config(self, path): # def _tab_config(self, file_tab): # def _mapping_config(self, file_map): # def write(self, indent=0): # def check_path(path): # def write_chr(self, mode="w", path_w=None, min_c=None, max_c=None): # def write_chr_sizes(self, mode="w", path_w=None, file_n=None, min_c=None, max_c=None): # def write_cytoband(end, start=0, delta=43200, start_phase="light", mode="w", path_w=None, lab_bed=True, track_line=True): # def write_period_seq (end, start=0, delta=43200, tag="day", mode="w", path_w=None, name_file="period_seq", lab_bed=True, track_line=True): # # Path: pergola/intervals.py # class IntData(object): # def __init__(self, path, map_dict, header=True, **kwargs): # def _check_delimiter (self, path, delimiter): # def _reader_data(self): # def _pandas_df_reader(self, df): # def _set_fields_b(self, fields=None): # def _set_fields_g (self, map_dict): # def _simple_read(self): # def get_field_items(self, data, field="data_types", default=None): # def read(self, fields=None, relative_coord=False, intervals=False, int_step=None, fields2rel=None, multiply_t=None, # **kwargs): # def _min_max(self, list_data, f_start="start", f_end="end"): # def _time2rel_time(self, i_fields): # def _multiply_values(self, i_fields, factor=1): # def _create_int(self, start_int, int_step=None): # def _create_int_add_integ(self, start_int, integer=1): # def __del__(self): # def is_number(var): # def num(s): # # Path: pergola/tracks.py # class GenomicContainer(object): # class Track(GenomicContainer): # class BedToolConvertible(GenomicContainer): # class Bed(BedToolConvertible): # class BedGraph(BedToolConvertible): # class Gff(BedToolConvertible): # def __init__(self, data, fields=None, data_types=None, **kwargs): # def __iter__(self): # def next(self): # def save_track(self, mode="w", path=None, name_file=None, track_line=True, bed_label=False, gff_label=False): # def __init__(self, data, fields=None, data_types=None, list_tracks=None, min=0, max=0, **kwargs): # def convert(self, mode='bed', range_color=None, **kwargs): # def _convert2single_track(self, data_tuples, mode=None, **kwargs): # def _get_range(self, data_tr): # def remove(self, dict_t, tracks2remove): # def join_by_track(self, dict_t, tracks2join): # def join_by_dataType (self, dict_d, mode): # def track_convert2bed(self, track, in_call=False, **kwargs): # def track_convert2gff(self, track, in_call=False, **kwargs): # def track_convert2bedGraph(self, track, in_call=False, window=300, mean_win=False, mean_value=False, **kwargs): # def __init__(self, data, **kwargs): # def create_pybedtools(self): # def _tmp_track(self): # def __init__(self, data, **kwargs): # def __init__(self, data, **kwargs): # def win_mean (self): # def _win_mean (self, data, n_tracks): # def __init__(self, data, **kwargs): # def assign_color(set_data_types, color_restrictions=None): # def merge_tracks (tr_1, tr_2): , which may contain function names, class names, or code. Output only the next line.
int_data_b1 = intervals.IntData ("../../sample_data/feeding_beh_CB1_mice/intake_CB1_B1.csv", map_dict=mapping_data.correspondence)
Continue the code snippet: <|code_start|> int_data_b1 = intervals.IntData ("../../sample_data/feeding_beh_CB1_mice/intake_CB1_B1.csv", map_dict=mapping_data.correspondence) int_data_b2 = intervals.IntData ("../../sample_data/feeding_beh_CB1_mice/intake_CB1_B2.csv", map_dict=mapping_data.correspondence) int_data_b3 = intervals.IntData ("../../sample_data/feeding_beh_CB1_mice/intake_CB1_B3.csv", map_dict=mapping_data.correspondence) int_data_b4 = intervals.IntData ("../../sample_data/feeding_beh_CB1_mice/intake_CB1_B4.csv", map_dict=mapping_data.correspondence) mapping_bed = mapping.MappingInfo("../../test/pybed2perg.txt") # base_dir = path.dirname(getcwd()) base_dir = getcwd() out_dir = base_dir + "/results/" + args.behavioral_type + "_by_phases/" + statistic + "/" if path.exists(out_dir): rmtree(out_dir) makedirs(out_dir) chdir(out_dir) data_read_b1 = int_data_b1.read(relative_coord=True) data_read_b2 = int_data_b2.read(relative_coord=True) data_read_b3 = int_data_b3.read(relative_coord=True) data_read_b4 = int_data_b4.read(relative_coord=True) # Check the longest period of time of any batches end_time = max (int_data_b1.max - int_data_b1.min, int_data_b2.max - int_data_b2.min, int_data_b3.max - int_data_b3.min, int_data_b4.max - int_data_b4.min) <|code_end|> . Use current file imports: from argparse import ArgumentParser from os import path, getcwd, makedirs, chdir from shutil import rmtree from sys import stderr from pergola import mapping from pergola import intervals from pergola import tracks import subprocess import pybedtools and context (classes, functions, or code) from other files: # Path: pergola/mapping.py # class MappingInfo(): # def __init__(self, path, **kwargs): # def _correspondence_from_config(self, path): # def _tab_config(self, file_tab): # def _mapping_config(self, file_map): # def write(self, indent=0): # def check_path(path): # def write_chr(self, mode="w", path_w=None, min_c=None, max_c=None): # def write_chr_sizes(self, mode="w", path_w=None, file_n=None, min_c=None, max_c=None): # def write_cytoband(end, start=0, delta=43200, start_phase="light", mode="w", path_w=None, lab_bed=True, track_line=True): # def write_period_seq (end, start=0, delta=43200, tag="day", mode="w", path_w=None, name_file="period_seq", lab_bed=True, track_line=True): # # Path: pergola/intervals.py # class IntData(object): # def __init__(self, path, map_dict, header=True, **kwargs): # def _check_delimiter (self, path, delimiter): # def _reader_data(self): # def _pandas_df_reader(self, df): # def _set_fields_b(self, fields=None): # def _set_fields_g (self, map_dict): # def _simple_read(self): # def get_field_items(self, data, field="data_types", default=None): # def read(self, fields=None, relative_coord=False, intervals=False, int_step=None, fields2rel=None, multiply_t=None, # **kwargs): # def _min_max(self, list_data, f_start="start", f_end="end"): # def _time2rel_time(self, i_fields): # def _multiply_values(self, i_fields, factor=1): # def _create_int(self, start_int, int_step=None): # def _create_int_add_integ(self, start_int, integer=1): # def __del__(self): # def is_number(var): # def num(s): # # Path: pergola/tracks.py # class GenomicContainer(object): # class Track(GenomicContainer): # class BedToolConvertible(GenomicContainer): # class Bed(BedToolConvertible): # class BedGraph(BedToolConvertible): # class Gff(BedToolConvertible): # def __init__(self, data, fields=None, data_types=None, **kwargs): # def __iter__(self): # def next(self): # def save_track(self, mode="w", path=None, name_file=None, track_line=True, bed_label=False, gff_label=False): # def __init__(self, data, fields=None, data_types=None, list_tracks=None, min=0, max=0, **kwargs): # def convert(self, mode='bed', range_color=None, **kwargs): # def _convert2single_track(self, data_tuples, mode=None, **kwargs): # def _get_range(self, data_tr): # def remove(self, dict_t, tracks2remove): # def join_by_track(self, dict_t, tracks2join): # def join_by_dataType (self, dict_d, mode): # def track_convert2bed(self, track, in_call=False, **kwargs): # def track_convert2gff(self, track, in_call=False, **kwargs): # def track_convert2bedGraph(self, track, in_call=False, window=300, mean_win=False, mean_value=False, **kwargs): # def __init__(self, data, **kwargs): # def create_pybedtools(self): # def _tmp_track(self): # def __init__(self, data, **kwargs): # def __init__(self, data, **kwargs): # def win_mean (self): # def _win_mean (self, data, n_tracks): # def __init__(self, data, **kwargs): # def assign_color(set_data_types, color_restrictions=None): # def merge_tracks (tr_1, tr_2): . Output only the next line.
data_read_all_batches = tracks.merge_tracks (tracks.merge_tracks (tracks.merge_tracks (data_read_b1, data_read_b2), data_read_b3), data_read_b4)
Next line prediction: <|code_start|>#!/usr/bin/env python ################################################################ ### Jose A Espinosa. CSN/CB-CRG Group. Jan 2016 ### ################################################################ ### ### ### ### ### ### ### ### ### ### ### ### ################################################################ base_dir = path.dirname(getcwd()) out_dir = base_dir + "/test/" mapping_data = mapping.MappingInfo(base_dir + "/sample_data/feeding_behavior/b2g.txt") <|code_end|> . Use current file imports: (from pergola import mapping, intervals, tracks from os import path, getcwd) and context including class names, function names, or small code snippets from other files: # Path: pergola/mapping.py # class MappingInfo(): # def __init__(self, path, **kwargs): # def _correspondence_from_config(self, path): # def _tab_config(self, file_tab): # def _mapping_config(self, file_map): # def write(self, indent=0): # def check_path(path): # def write_chr(self, mode="w", path_w=None, min_c=None, max_c=None): # def write_chr_sizes(self, mode="w", path_w=None, file_n=None, min_c=None, max_c=None): # def write_cytoband(end, start=0, delta=43200, start_phase="light", mode="w", path_w=None, lab_bed=True, track_line=True): # def write_period_seq (end, start=0, delta=43200, tag="day", mode="w", path_w=None, name_file="period_seq", lab_bed=True, track_line=True): # # Path: pergola/intervals.py # class IntData(object): # def __init__(self, path, map_dict, header=True, **kwargs): # def _check_delimiter (self, path, delimiter): # def _reader_data(self): # def _pandas_df_reader(self, df): # def _set_fields_b(self, fields=None): # def _set_fields_g (self, map_dict): # def _simple_read(self): # def get_field_items(self, data, field="data_types", default=None): # def read(self, fields=None, relative_coord=False, intervals=False, int_step=None, fields2rel=None, multiply_t=None, # **kwargs): # def _min_max(self, list_data, f_start="start", f_end="end"): # def _time2rel_time(self, i_fields): # def _multiply_values(self, i_fields, factor=1): # def _create_int(self, start_int, int_step=None): # def _create_int_add_integ(self, start_int, integer=1): # def __del__(self): # def is_number(var): # def num(s): # # Path: pergola/tracks.py # class GenomicContainer(object): # class Track(GenomicContainer): # class BedToolConvertible(GenomicContainer): # class Bed(BedToolConvertible): # class BedGraph(BedToolConvertible): # class Gff(BedToolConvertible): # def __init__(self, data, fields=None, data_types=None, **kwargs): # def __iter__(self): # def next(self): # def save_track(self, mode="w", path=None, name_file=None, track_line=True, bed_label=False, gff_label=False): # def __init__(self, data, fields=None, data_types=None, list_tracks=None, min=0, max=0, **kwargs): # def convert(self, mode='bed', range_color=None, **kwargs): # def _convert2single_track(self, data_tuples, mode=None, **kwargs): # def _get_range(self, data_tr): # def remove(self, dict_t, tracks2remove): # def join_by_track(self, dict_t, tracks2join): # def join_by_dataType (self, dict_d, mode): # def track_convert2bed(self, track, in_call=False, **kwargs): # def track_convert2gff(self, track, in_call=False, **kwargs): # def track_convert2bedGraph(self, track, in_call=False, window=300, mean_win=False, mean_value=False, **kwargs): # def __init__(self, data, **kwargs): # def create_pybedtools(self): # def _tmp_track(self): # def __init__(self, data, **kwargs): # def __init__(self, data, **kwargs): # def win_mean (self): # def _win_mean (self, data, n_tracks): # def __init__(self, data, **kwargs): # def assign_color(set_data_types, color_restrictions=None): # def merge_tracks (tr_1, tr_2): . Output only the next line.
int_data = intervals.IntData(base_dir + "/sample_data/feeding_behavior/feedingBehavior_HF_mice.csv", map_dict=mapping_data.correspondence)
Predict the next line for this snippet: <|code_start|># In the cluster I use bedtools Pablo installation, because default cluster version has not map if home == "/users/cn/jespinosa" : pybedtools.helpers.set_bedtools_path('/users/cn/pprieto/soft/bedtools/bedtools2-2.19.1/bin') parser = ArgumentParser(description='File input arguments') parser.add_argument('-s','--speed', help='Bed file containing speed for one body part of the worn', required=True) parser.add_argument('-m','--motion', help='Bed file containing worm motion (forward, backward or paused)', required=True) parser.add_argument('-b','--bed_mapping', help='Mapping pergola file for bed files', required=True) parser.add_argument('-t', '--tag_out', required=False, type=str, help='Tag output file') args = parser.parse_args() if args.tag_out: tag_file = args.tag_out else: tag_file = "mean_speed_i_motionDir" print >> stderr, "Bed speed file: %s" % args.speed print >> stderr, "Bed motion file: %s" % args.motion print >> stderr, "Mapping bed to Pergola file: %s" % args.bed_mapping print >> stderr, "Output tag file: %s" % tag_file # base_dir = path.dirname(getcwd()) # dir_development = base_dir + "/c_elegans_data_test/" # # out_dir = base_dir + "/test/" # out_dir = base_dir + "/c_elegans_data_test/" # # mapping_bed = mapping.MappingInfo(base_dir + "/test/" + "bed2pergola.txt") <|code_end|> with the help of current file imports: from argparse import ArgumentParser from os import path, getcwd from csv import writer from os.path import expanduser from pergola import mapping from pergola import intervals from sys import stderr, exit import pybedtools and context from other files: # Path: pergola/mapping.py # class MappingInfo(): # def __init__(self, path, **kwargs): # def _correspondence_from_config(self, path): # def _tab_config(self, file_tab): # def _mapping_config(self, file_map): # def write(self, indent=0): # def check_path(path): # def write_chr(self, mode="w", path_w=None, min_c=None, max_c=None): # def write_chr_sizes(self, mode="w", path_w=None, file_n=None, min_c=None, max_c=None): # def write_cytoband(end, start=0, delta=43200, start_phase="light", mode="w", path_w=None, lab_bed=True, track_line=True): # def write_period_seq (end, start=0, delta=43200, tag="day", mode="w", path_w=None, name_file="period_seq", lab_bed=True, track_line=True): # # Path: pergola/intervals.py # class IntData(object): # def __init__(self, path, map_dict, header=True, **kwargs): # def _check_delimiter (self, path, delimiter): # def _reader_data(self): # def _pandas_df_reader(self, df): # def _set_fields_b(self, fields=None): # def _set_fields_g (self, map_dict): # def _simple_read(self): # def get_field_items(self, data, field="data_types", default=None): # def read(self, fields=None, relative_coord=False, intervals=False, int_step=None, fields2rel=None, multiply_t=None, # **kwargs): # def _min_max(self, list_data, f_start="start", f_end="end"): # def _time2rel_time(self, i_fields): # def _multiply_values(self, i_fields, factor=1): # def _create_int(self, start_int, int_step=None): # def _create_int_add_integ(self, start_int, integer=1): # def __del__(self): # def is_number(var): # def num(s): , which may contain function names, class names, or code. Output only the next line.
mapping_bed = mapping.MappingInfo(args.bed_mapping)
Predict the next line for this snippet: <|code_start|> tag_file = args.tag_out else: tag_file = "mean_speed_i_motionDir" print >> stderr, "Bed speed file: %s" % args.speed print >> stderr, "Bed motion file: %s" % args.motion print >> stderr, "Mapping bed to Pergola file: %s" % args.bed_mapping print >> stderr, "Output tag file: %s" % tag_file # base_dir = path.dirname(getcwd()) # dir_development = base_dir + "/c_elegans_data_test/" # # out_dir = base_dir + "/test/" # out_dir = base_dir + "/c_elegans_data_test/" # # mapping_bed = mapping.MappingInfo(base_dir + "/test/" + "bed2pergola.txt") mapping_bed = mapping.MappingInfo(args.bed_mapping) ## mapping_bed = mapping.MappingInfo("/Users/jespinosa/git/pergola/test/c_elegans_data_test/bed2pergola.txt") # speed bed file ## read file from input args # bed_speed_file = dir_development + "midbody.575_JU440_on_food_L_2011_02_17__16_43___3___11_features_speed.csv.bed" # bed_speed_file ='/Users/jespinosa/git/pergola/test/c_elegans_data_test/results_GB/midbody.575_JU440_on_food_L_2011_02_17__11_00___3___1_features.mat.GB.bed' ## bed_speed_file = '/Users/jespinosa/git/pergola/test/c_elegans_data_test/work/be/c8a7942756ee7053d0f9856e1caa88/bed_speed_no_tr' ## error to debug nextflow Paolo # bed_speed_file = dir_development + args.speed bed_speed_file = args.speed <|code_end|> with the help of current file imports: from argparse import ArgumentParser from os import path, getcwd from csv import writer from os.path import expanduser from pergola import mapping from pergola import intervals from sys import stderr, exit import pybedtools and context from other files: # Path: pergola/mapping.py # class MappingInfo(): # def __init__(self, path, **kwargs): # def _correspondence_from_config(self, path): # def _tab_config(self, file_tab): # def _mapping_config(self, file_map): # def write(self, indent=0): # def check_path(path): # def write_chr(self, mode="w", path_w=None, min_c=None, max_c=None): # def write_chr_sizes(self, mode="w", path_w=None, file_n=None, min_c=None, max_c=None): # def write_cytoband(end, start=0, delta=43200, start_phase="light", mode="w", path_w=None, lab_bed=True, track_line=True): # def write_period_seq (end, start=0, delta=43200, tag="day", mode="w", path_w=None, name_file="period_seq", lab_bed=True, track_line=True): # # Path: pergola/intervals.py # class IntData(object): # def __init__(self, path, map_dict, header=True, **kwargs): # def _check_delimiter (self, path, delimiter): # def _reader_data(self): # def _pandas_df_reader(self, df): # def _set_fields_b(self, fields=None): # def _set_fields_g (self, map_dict): # def _simple_read(self): # def get_field_items(self, data, field="data_types", default=None): # def read(self, fields=None, relative_coord=False, intervals=False, int_step=None, fields2rel=None, multiply_t=None, # **kwargs): # def _min_max(self, list_data, f_start="start", f_end="end"): # def _time2rel_time(self, i_fields): # def _multiply_values(self, i_fields, factor=1): # def _create_int(self, start_int, int_step=None): # def _create_int_add_integ(self, start_int, integer=1): # def __del__(self): # def is_number(var): # def num(s): , which may contain function names, class names, or code. Output only the next line.
int_data_speed = intervals.IntData(bed_speed_file, map_dict=mapping_bed.correspondence, header=False,
Given the following code snippet before the placeholder: <|code_start|># In the cluster I use bedtools Pablo installation, because default cluster version has not map if home == "/users/cn/jespinosa" : pybedtools.helpers.set_bedtools_path('/users/cn/pprieto/soft/bedtools/bedtools2-2.19.1/bin') parser = ArgumentParser(description='File input arguments') parser.add_argument('-f','--forward_file', help='forward bed file', required=True) parser.add_argument('-b','--backward_file', help='backard bed file', required=True) parser.add_argument('-m','--bed_mapping', help='Mapping pergola file for bed files', required=True) parser.add_argument('-c','--chrom_sizes', help='pping pergola file for bed files', required=True) args = parser.parse_args() print >> stderr, "Forward file: %s" % args.forward_file print >> stderr, "Backward file: %s" % args.backward_file print >> stderr, "Mapping file: %s" % args.bed_mapping print >> stderr, "Chrom_sizes file: %s" % args.chrom_sizes # # Input files forward_file = args.forward_file backward_file = args.backward_file bed_mapping = args.bed_mapping chrom_sizes = args.chrom_sizes # forward_file = '/Users/jespinosa/git/pergola/test/c_elegans_data_test/results_motion_GB/575_JU440_on_food_L_2011_02_17__11_00___3___1_features.matfile_worm.backward.csv.motion.bed' # backward_file = '/Users/jespinosa/git/pergola/test/c_elegans_data_test/results_motion_GB/575_JU440_on_food_L_2011_02_17__11_00___3___1_features.matfile_worm.forward.csv.motion.bed' # bed_mapping = '/Users/jespinosa/git/pergola/test/c_elegans_data_test/bed2pergola.txt' chr_file_n = "chrom.sizes" <|code_end|> , predict the next line using imports from the current file: from argparse import ArgumentParser from sys import stderr, exit from pergola import mapping from pergola import intervals from os.path import expanduser import pybedtools and context including class names, function names, and sometimes code from other files: # Path: pergola/mapping.py # class MappingInfo(): # def __init__(self, path, **kwargs): # def _correspondence_from_config(self, path): # def _tab_config(self, file_tab): # def _mapping_config(self, file_map): # def write(self, indent=0): # def check_path(path): # def write_chr(self, mode="w", path_w=None, min_c=None, max_c=None): # def write_chr_sizes(self, mode="w", path_w=None, file_n=None, min_c=None, max_c=None): # def write_cytoband(end, start=0, delta=43200, start_phase="light", mode="w", path_w=None, lab_bed=True, track_line=True): # def write_period_seq (end, start=0, delta=43200, tag="day", mode="w", path_w=None, name_file="period_seq", lab_bed=True, track_line=True): # # Path: pergola/intervals.py # class IntData(object): # def __init__(self, path, map_dict, header=True, **kwargs): # def _check_delimiter (self, path, delimiter): # def _reader_data(self): # def _pandas_df_reader(self, df): # def _set_fields_b(self, fields=None): # def _set_fields_g (self, map_dict): # def _simple_read(self): # def get_field_items(self, data, field="data_types", default=None): # def read(self, fields=None, relative_coord=False, intervals=False, int_step=None, fields2rel=None, multiply_t=None, # **kwargs): # def _min_max(self, list_data, f_start="start", f_end="end"): # def _time2rel_time(self, i_fields): # def _multiply_values(self, i_fields, factor=1): # def _create_int(self, start_int, int_step=None): # def _create_int_add_integ(self, start_int, integer=1): # def __del__(self): # def is_number(var): # def num(s): . Output only the next line.
mapping_bed = mapping.MappingInfo(bed_mapping)
Predict the next line after this snippet: <|code_start|> pybedtools.helpers.set_bedtools_path('/users/cn/pprieto/soft/bedtools/bedtools2-2.19.1/bin') parser = ArgumentParser(description='File input arguments') parser.add_argument('-f','--forward_file', help='forward bed file', required=True) parser.add_argument('-b','--backward_file', help='backard bed file', required=True) parser.add_argument('-m','--bed_mapping', help='Mapping pergola file for bed files', required=True) parser.add_argument('-c','--chrom_sizes', help='pping pergola file for bed files', required=True) args = parser.parse_args() print >> stderr, "Forward file: %s" % args.forward_file print >> stderr, "Backward file: %s" % args.backward_file print >> stderr, "Mapping file: %s" % args.bed_mapping print >> stderr, "Chrom_sizes file: %s" % args.chrom_sizes # # Input files forward_file = args.forward_file backward_file = args.backward_file bed_mapping = args.bed_mapping chrom_sizes = args.chrom_sizes # forward_file = '/Users/jespinosa/git/pergola/test/c_elegans_data_test/results_motion_GB/575_JU440_on_food_L_2011_02_17__11_00___3___1_features.matfile_worm.backward.csv.motion.bed' # backward_file = '/Users/jespinosa/git/pergola/test/c_elegans_data_test/results_motion_GB/575_JU440_on_food_L_2011_02_17__11_00___3___1_features.matfile_worm.forward.csv.motion.bed' # bed_mapping = '/Users/jespinosa/git/pergola/test/c_elegans_data_test/bed2pergola.txt' chr_file_n = "chrom.sizes" mapping_bed = mapping.MappingInfo(bed_mapping) <|code_end|> using the current file's imports: from argparse import ArgumentParser from sys import stderr, exit from pergola import mapping from pergola import intervals from os.path import expanduser import pybedtools and any relevant context from other files: # Path: pergola/mapping.py # class MappingInfo(): # def __init__(self, path, **kwargs): # def _correspondence_from_config(self, path): # def _tab_config(self, file_tab): # def _mapping_config(self, file_map): # def write(self, indent=0): # def check_path(path): # def write_chr(self, mode="w", path_w=None, min_c=None, max_c=None): # def write_chr_sizes(self, mode="w", path_w=None, file_n=None, min_c=None, max_c=None): # def write_cytoband(end, start=0, delta=43200, start_phase="light", mode="w", path_w=None, lab_bed=True, track_line=True): # def write_period_seq (end, start=0, delta=43200, tag="day", mode="w", path_w=None, name_file="period_seq", lab_bed=True, track_line=True): # # Path: pergola/intervals.py # class IntData(object): # def __init__(self, path, map_dict, header=True, **kwargs): # def _check_delimiter (self, path, delimiter): # def _reader_data(self): # def _pandas_df_reader(self, df): # def _set_fields_b(self, fields=None): # def _set_fields_g (self, map_dict): # def _simple_read(self): # def get_field_items(self, data, field="data_types", default=None): # def read(self, fields=None, relative_coord=False, intervals=False, int_step=None, fields2rel=None, multiply_t=None, # **kwargs): # def _min_max(self, list_data, f_start="start", f_end="end"): # def _time2rel_time(self, i_fields): # def _multiply_values(self, i_fields, factor=1): # def _create_int(self, start_int, int_step=None): # def _create_int_add_integ(self, start_int, integer=1): # def __del__(self): # def is_number(var): # def num(s): . Output only the next line.
forward = intervals.IntData(forward_file, map_dict=mapping_bed.correspondence, header=False,
Based on the snippet: <|code_start|> if window_mean: print("@@@Pergola_rules.py: Window mean set to....................... %d" % window_mean, file=stderr) else: window_mean = False if value_mean: print("@@@Pergola_rules.py: Value mean set to....................... %d" % value_mean, file=stderr) else: value_mean = False if no_track_line: track_line=False else: track_line=True print("@@@Pergola_rules.py: track_line set to............................ %s" % track_line, file=stderr) # Handling input file field delimiter if not separator: separator = "\t" print("@@@Pergola_rules.py input file field separator set by default to...... \"\\t\".", file=stderr) else: print("@@@Pergola_rules.py input file field separator set to..... \"%s\"" % separator, file=stderr) if bed_lab_sw: bed_lab = True print("@@@Pergola_rules.py: bed_label set to......................... %s" % bed_lab, file=stderr) else: bed_lab = False <|code_end|> , predict the immediate next line with the help of imports: from pergola import intervals from pergola import mapping from argparse import ArgumentParser from sys import stderr, exit from os.path import basename, splitext from pergola import parsers and context (classes, functions, sometimes code) from other files: # Path: pergola/intervals.py # class IntData(object): # def __init__(self, path, map_dict, header=True, **kwargs): # def _check_delimiter (self, path, delimiter): # def _reader_data(self): # def _pandas_df_reader(self, df): # def _set_fields_b(self, fields=None): # def _set_fields_g (self, map_dict): # def _simple_read(self): # def get_field_items(self, data, field="data_types", default=None): # def read(self, fields=None, relative_coord=False, intervals=False, int_step=None, fields2rel=None, multiply_t=None, # **kwargs): # def _min_max(self, list_data, f_start="start", f_end="end"): # def _time2rel_time(self, i_fields): # def _multiply_values(self, i_fields, factor=1): # def _create_int(self, start_int, int_step=None): # def _create_int_add_integ(self, start_int, integer=1): # def __del__(self): # def is_number(var): # def num(s): # # Path: pergola/mapping.py # class MappingInfo(): # def __init__(self, path, **kwargs): # def _correspondence_from_config(self, path): # def _tab_config(self, file_tab): # def _mapping_config(self, file_map): # def write(self, indent=0): # def check_path(path): # def write_chr(self, mode="w", path_w=None, min_c=None, max_c=None): # def write_chr_sizes(self, mode="w", path_w=None, file_n=None, min_c=None, max_c=None): # def write_cytoband(end, start=0, delta=43200, start_phase="light", mode="w", path_w=None, lab_bed=True, track_line=True): # def write_period_seq (end, start=0, delta=43200, tag="day", mode="w", path_w=None, name_file="period_seq", lab_bed=True, track_line=True): # # Path: pergola/parsers.py # PATH = abspath(split(realpath(__file__))[0]) # def parse_num_range(string): # def read_track_actions (tracks, track_action = "split_all"): # def read_colors (path_color_file): . Output only the next line.
intData = intervals.IntData(path, map_dict=map_file_dict.correspondence,
Based on the snippet: <|code_start|> output_file_n = args.output_file_name + "_" + str(idx + 1) else: output_file_n = args.output_file_name pergola_rules(path=input_file, map_file_path=args.mapping_file, sel_tracks=args.tracks, list=args.list, range=args.range, track_actions=args.track_actions, data_types_actions=args.data_types_actions, data_types_list=args.data_types_list, write_format=args.format, relative_coord=args.relative_coord, intervals_gen=args.intervals_gen, interval_step=args.interval_step, multiply_f=args.multiply_intervals, no_header=args.no_header, fields2read=args.fields_read, window_size=args.window_size, no_track_line=args.no_track_line, separator=args.field_separator, bed_lab_sw=args.bed_label, color_dict=args.color_file, window_mean=args.window_mean, value_mean=args.value_mean, min_t=args.min_time, max_t=args.max_time, phases=args.phases, genome=args.genome, output_file_name=output_file_n, starting_phase=args.starting_phase, shift=args.shift) def pergola_rules(path, map_file_path, sel_tracks=None, list=None, range=None, track_actions=None, data_types_actions=None, data_types_list=None, write_format=None, relative_coord=False, intervals_gen=False, multiply_f=None, no_header=False, fields2read=None, window_size=None, no_track_line=False, separator=None, bed_lab_sw=False, color_dict=None, window_mean=False, value_mean=False, min_t=None, max_t=None, interval_step=None, phases=False, genome=False, output_file_name=None, starting_phase=False, shift=None): print("@@@Pergola_rules.py: Input file: %s" % path, file=stderr) print("@@@Pergola_rules.py: Configuration file: %s" % map_file_path, file=stderr) # Tracks selected by user print("@@@Pergola_rules.py: Selected tracks are: ", sel_tracks, file=stderr) # Configuration file <|code_end|> , predict the immediate next line with the help of imports: from pergola import intervals from pergola import mapping from argparse import ArgumentParser from sys import stderr, exit from os.path import basename, splitext from pergola import parsers and context (classes, functions, sometimes code) from other files: # Path: pergola/intervals.py # class IntData(object): # def __init__(self, path, map_dict, header=True, **kwargs): # def _check_delimiter (self, path, delimiter): # def _reader_data(self): # def _pandas_df_reader(self, df): # def _set_fields_b(self, fields=None): # def _set_fields_g (self, map_dict): # def _simple_read(self): # def get_field_items(self, data, field="data_types", default=None): # def read(self, fields=None, relative_coord=False, intervals=False, int_step=None, fields2rel=None, multiply_t=None, # **kwargs): # def _min_max(self, list_data, f_start="start", f_end="end"): # def _time2rel_time(self, i_fields): # def _multiply_values(self, i_fields, factor=1): # def _create_int(self, start_int, int_step=None): # def _create_int_add_integ(self, start_int, integer=1): # def __del__(self): # def is_number(var): # def num(s): # # Path: pergola/mapping.py # class MappingInfo(): # def __init__(self, path, **kwargs): # def _correspondence_from_config(self, path): # def _tab_config(self, file_tab): # def _mapping_config(self, file_map): # def write(self, indent=0): # def check_path(path): # def write_chr(self, mode="w", path_w=None, min_c=None, max_c=None): # def write_chr_sizes(self, mode="w", path_w=None, file_n=None, min_c=None, max_c=None): # def write_cytoband(end, start=0, delta=43200, start_phase="light", mode="w", path_w=None, lab_bed=True, track_line=True): # def write_period_seq (end, start=0, delta=43200, tag="day", mode="w", path_w=None, name_file="period_seq", lab_bed=True, track_line=True): # # Path: pergola/parsers.py # PATH = abspath(split(realpath(__file__))[0]) # def parse_num_range(string): # def read_track_actions (tracks, track_action = "split_all"): # def read_colors (path_color_file): . Output only the next line.
map_file_dict = mapping.MappingInfo(map_file_path)
Continue the code snippet: <|code_start|># # Copyright (c) 2014-2019, Centre for Genomic Regulation (CRG). # Copyright (c) 2014-2019, Jose Espinosa-Carrasco and the respective authors. # # This file is part of Pergola. # # Pergola is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Pergola is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Pergola. If not, see <http://www.gnu.org/licenses/>. """ 30 oct 2014 Script to run pergola from the command line """ from __future__ import print_function # from pergola import tracks # import os def main(args=None): <|code_end|> . Use current file imports: from pergola import intervals from pergola import mapping from argparse import ArgumentParser from sys import stderr, exit from os.path import basename, splitext from pergola import parsers and context (classes, functions, or code) from other files: # Path: pergola/intervals.py # class IntData(object): # def __init__(self, path, map_dict, header=True, **kwargs): # def _check_delimiter (self, path, delimiter): # def _reader_data(self): # def _pandas_df_reader(self, df): # def _set_fields_b(self, fields=None): # def _set_fields_g (self, map_dict): # def _simple_read(self): # def get_field_items(self, data, field="data_types", default=None): # def read(self, fields=None, relative_coord=False, intervals=False, int_step=None, fields2rel=None, multiply_t=None, # **kwargs): # def _min_max(self, list_data, f_start="start", f_end="end"): # def _time2rel_time(self, i_fields): # def _multiply_values(self, i_fields, factor=1): # def _create_int(self, start_int, int_step=None): # def _create_int_add_integ(self, start_int, integer=1): # def __del__(self): # def is_number(var): # def num(s): # # Path: pergola/mapping.py # class MappingInfo(): # def __init__(self, path, **kwargs): # def _correspondence_from_config(self, path): # def _tab_config(self, file_tab): # def _mapping_config(self, file_map): # def write(self, indent=0): # def check_path(path): # def write_chr(self, mode="w", path_w=None, min_c=None, max_c=None): # def write_chr_sizes(self, mode="w", path_w=None, file_n=None, min_c=None, max_c=None): # def write_cytoband(end, start=0, delta=43200, start_phase="light", mode="w", path_w=None, lab_bed=True, track_line=True): # def write_period_seq (end, start=0, delta=43200, tag="day", mode="w", path_w=None, name_file="period_seq", lab_bed=True, track_line=True): # # Path: pergola/parsers.py # PATH = abspath(split(realpath(__file__))[0]) # def parse_num_range(string): # def read_track_actions (tracks, track_action = "split_all"): # def read_colors (path_color_file): . Output only the next line.
parser_pergola_rules = ArgumentParser(parents=[parsers.parent_parser])
Next line prediction: <|code_start|># Pergola is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Pergola. If not, see <http://www.gnu.org/licenses/>. # example execution # ./celegans_speed_i_motion.py -p midbody.phenotypic_feature.bed -m motion.bed -b bed_map.txt -t "N2" # Loading libraries parser = ArgumentParser(description='File input arguments') parser.add_argument('-p','--phenotypic_file', help='Bed file containing a phenotypic feature of the worn', required=True) # parser.add_argument('-m','--motion_file', help='Bed file containing worm motion (forward, backward or paused)', required=True) parser.add_argument('-m','--bed_mapping_file', help='Mapping pergola file for bed files', required=True) parser.add_argument('-t', '--tag_out', required=False, type=str, help='Tag output file') args = parser.parse_args() if args.tag_out: tag_file = args.tag_out else: tag_file = "mean_speed_i_motionDir" print >> stderr, "Bed speed file: %s" % args.phenotypic_file print >> stderr, "Mapping bed to Pergola file: %s" % args.bed_mapping_file print >> stderr, "Output tag file: %s" % tag_file <|code_end|> . Use current file imports: (from argparse import ArgumentParser from os import path, getcwd from csv import writer from pergola import mapping from pergola import intervals from sys import stderr, exit import pybedtools) and context including class names, function names, or small code snippets from other files: # Path: pergola/mapping.py # class MappingInfo(): # def __init__(self, path, **kwargs): # def _correspondence_from_config(self, path): # def _tab_config(self, file_tab): # def _mapping_config(self, file_map): # def write(self, indent=0): # def check_path(path): # def write_chr(self, mode="w", path_w=None, min_c=None, max_c=None): # def write_chr_sizes(self, mode="w", path_w=None, file_n=None, min_c=None, max_c=None): # def write_cytoband(end, start=0, delta=43200, start_phase="light", mode="w", path_w=None, lab_bed=True, track_line=True): # def write_period_seq (end, start=0, delta=43200, tag="day", mode="w", path_w=None, name_file="period_seq", lab_bed=True, track_line=True): # # Path: pergola/intervals.py # class IntData(object): # def __init__(self, path, map_dict, header=True, **kwargs): # def _check_delimiter (self, path, delimiter): # def _reader_data(self): # def _pandas_df_reader(self, df): # def _set_fields_b(self, fields=None): # def _set_fields_g (self, map_dict): # def _simple_read(self): # def get_field_items(self, data, field="data_types", default=None): # def read(self, fields=None, relative_coord=False, intervals=False, int_step=None, fields2rel=None, multiply_t=None, # **kwargs): # def _min_max(self, list_data, f_start="start", f_end="end"): # def _time2rel_time(self, i_fields): # def _multiply_values(self, i_fields, factor=1): # def _create_int(self, start_int, int_step=None): # def _create_int_add_integ(self, start_int, integer=1): # def __del__(self): # def is_number(var): # def num(s): . Output only the next line.
mapping_bed = mapping.MappingInfo(args.bed_mapping_file)
Based on the snippet: <|code_start|># along with Pergola. If not, see <http://www.gnu.org/licenses/>. # example execution # ./celegans_speed_i_motion.py -p midbody.phenotypic_feature.bed -m motion.bed -b bed_map.txt -t "N2" # Loading libraries parser = ArgumentParser(description='File input arguments') parser.add_argument('-p','--phenotypic_file', help='Bed file containing a phenotypic feature of the worn', required=True) # parser.add_argument('-m','--motion_file', help='Bed file containing worm motion (forward, backward or paused)', required=True) parser.add_argument('-m','--bed_mapping_file', help='Mapping pergola file for bed files', required=True) parser.add_argument('-t', '--tag_out', required=False, type=str, help='Tag output file') args = parser.parse_args() if args.tag_out: tag_file = args.tag_out else: tag_file = "mean_speed_i_motionDir" print >> stderr, "Bed speed file: %s" % args.phenotypic_file print >> stderr, "Mapping bed to Pergola file: %s" % args.bed_mapping_file print >> stderr, "Output tag file: %s" % tag_file mapping_bed = mapping.MappingInfo(args.bed_mapping_file) # mapping_bed = mapping.MappingInfo("/Users/jespinosa/git/pergola/test/c_elegans_data_test/bed2pergola.txt") bed_ph_file = args.phenotypic_file # bed_ph_file = '/Users/jespinosa/git/pergola/examples/N2_hourly_mean_measures/bin/bed_debug.bed' <|code_end|> , predict the immediate next line with the help of imports: from argparse import ArgumentParser from os import path, getcwd from csv import writer from pergola import mapping from pergola import intervals from sys import stderr, exit import pybedtools and context (classes, functions, sometimes code) from other files: # Path: pergola/mapping.py # class MappingInfo(): # def __init__(self, path, **kwargs): # def _correspondence_from_config(self, path): # def _tab_config(self, file_tab): # def _mapping_config(self, file_map): # def write(self, indent=0): # def check_path(path): # def write_chr(self, mode="w", path_w=None, min_c=None, max_c=None): # def write_chr_sizes(self, mode="w", path_w=None, file_n=None, min_c=None, max_c=None): # def write_cytoband(end, start=0, delta=43200, start_phase="light", mode="w", path_w=None, lab_bed=True, track_line=True): # def write_period_seq (end, start=0, delta=43200, tag="day", mode="w", path_w=None, name_file="period_seq", lab_bed=True, track_line=True): # # Path: pergola/intervals.py # class IntData(object): # def __init__(self, path, map_dict, header=True, **kwargs): # def _check_delimiter (self, path, delimiter): # def _reader_data(self): # def _pandas_df_reader(self, df): # def _set_fields_b(self, fields=None): # def _set_fields_g (self, map_dict): # def _simple_read(self): # def get_field_items(self, data, field="data_types", default=None): # def read(self, fields=None, relative_coord=False, intervals=False, int_step=None, fields2rel=None, multiply_t=None, # **kwargs): # def _min_max(self, list_data, f_start="start", f_end="end"): # def _time2rel_time(self, i_fields): # def _multiply_values(self, i_fields, factor=1): # def _create_int(self, start_int, int_step=None): # def _create_int_add_integ(self, start_int, integer=1): # def __del__(self): # def is_number(var): # def num(s): . Output only the next line.
int_data_phenotypic = intervals.IntData(bed_ph_file, map_dict=mapping_bed.correspondence, header=False,
Predict the next line after this snippet: <|code_start|> required=True, choices=_behaviors_available) args = parser.parse_args() print >> stderr, "Statistic to be calculated: %s" % args.statistic print >> stderr, "Working with mice %s behavioral data" % args.behavioral_type # Statistic to calculate # statistic = "count" statistic = args.statistic ## Dictionary to set colors of each type of food # food_sc orange # food_fat black # water blue # saccharin red ### Feeding data if args.behavioral_type == "feeding": data_type_1 = "food_sc" data_type_2 = "food_fat" data_type_col = {data_type_1: 'orange', data_type_2:'black'} ### Drinking data elif args.behavioral_type == 'drinking': data_type_1 = "water" data_type_2 = "saccharin" data_type_col = {data_type_1: 'blue', data_type_2:'red'} else: print >> stderr, "Behavioral data type not available in script, please try again with \"drinking\" or \"feeding\"" <|code_end|> using the current file's imports: from argparse import ArgumentParser from os import path, getcwd, makedirs, chdir from sys import stderr from pergola import mapping from pergola import intervals from pergola import tracks import subprocess import pybedtools and any relevant context from other files: # Path: pergola/mapping.py # class MappingInfo(): # def __init__(self, path, **kwargs): # def _correspondence_from_config(self, path): # def _tab_config(self, file_tab): # def _mapping_config(self, file_map): # def write(self, indent=0): # def check_path(path): # def write_chr(self, mode="w", path_w=None, min_c=None, max_c=None): # def write_chr_sizes(self, mode="w", path_w=None, file_n=None, min_c=None, max_c=None): # def write_cytoband(end, start=0, delta=43200, start_phase="light", mode="w", path_w=None, lab_bed=True, track_line=True): # def write_period_seq (end, start=0, delta=43200, tag="day", mode="w", path_w=None, name_file="period_seq", lab_bed=True, track_line=True): # # Path: pergola/intervals.py # class IntData(object): # def __init__(self, path, map_dict, header=True, **kwargs): # def _check_delimiter (self, path, delimiter): # def _reader_data(self): # def _pandas_df_reader(self, df): # def _set_fields_b(self, fields=None): # def _set_fields_g (self, map_dict): # def _simple_read(self): # def get_field_items(self, data, field="data_types", default=None): # def read(self, fields=None, relative_coord=False, intervals=False, int_step=None, fields2rel=None, multiply_t=None, # **kwargs): # def _min_max(self, list_data, f_start="start", f_end="end"): # def _time2rel_time(self, i_fields): # def _multiply_values(self, i_fields, factor=1): # def _create_int(self, start_int, int_step=None): # def _create_int_add_integ(self, start_int, integer=1): # def __del__(self): # def is_number(var): # def num(s): # # Path: pergola/tracks.py # class GenomicContainer(object): # class Track(GenomicContainer): # class BedToolConvertible(GenomicContainer): # class Bed(BedToolConvertible): # class BedGraph(BedToolConvertible): # class Gff(BedToolConvertible): # def __init__(self, data, fields=None, data_types=None, **kwargs): # def __iter__(self): # def next(self): # def save_track(self, mode="w", path=None, name_file=None, track_line=True, bed_label=False, gff_label=False): # def __init__(self, data, fields=None, data_types=None, list_tracks=None, min=0, max=0, **kwargs): # def convert(self, mode='bed', range_color=None, **kwargs): # def _convert2single_track(self, data_tuples, mode=None, **kwargs): # def _get_range(self, data_tr): # def remove(self, dict_t, tracks2remove): # def join_by_track(self, dict_t, tracks2join): # def join_by_dataType (self, dict_d, mode): # def track_convert2bed(self, track, in_call=False, **kwargs): # def track_convert2gff(self, track, in_call=False, **kwargs): # def track_convert2bedGraph(self, track, in_call=False, window=300, mean_win=False, mean_value=False, **kwargs): # def __init__(self, data, **kwargs): # def create_pybedtools(self): # def _tmp_track(self): # def __init__(self, data, **kwargs): # def __init__(self, data, **kwargs): # def win_mean (self): # def _win_mean (self, data, n_tracks): # def __init__(self, data, **kwargs): # def assign_color(set_data_types, color_restrictions=None): # def merge_tracks (tr_1, tr_2): . Output only the next line.
mapping_data = mapping.MappingInfo("../../sample_data/feeding_behavior/b2g.txt")
Based on the snippet: <|code_start|>args = parser.parse_args() print >> stderr, "Statistic to be calculated: %s" % args.statistic print >> stderr, "Working with mice %s behavioral data" % args.behavioral_type # Statistic to calculate # statistic = "count" statistic = args.statistic ## Dictionary to set colors of each type of food # food_sc orange # food_fat black # water blue # saccharin red ### Feeding data if args.behavioral_type == "feeding": data_type_1 = "food_sc" data_type_2 = "food_fat" data_type_col = {data_type_1: 'orange', data_type_2:'black'} ### Drinking data elif args.behavioral_type == 'drinking': data_type_1 = "water" data_type_2 = "saccharin" data_type_col = {data_type_1: 'blue', data_type_2:'red'} else: print >> stderr, "Behavioral data type not available in script, please try again with \"drinking\" or \"feeding\"" mapping_data = mapping.MappingInfo("../../sample_data/feeding_behavior/b2g.txt") <|code_end|> , predict the immediate next line with the help of imports: from argparse import ArgumentParser from os import path, getcwd, makedirs, chdir from sys import stderr from pergola import mapping from pergola import intervals from pergola import tracks import subprocess import pybedtools and context (classes, functions, sometimes code) from other files: # Path: pergola/mapping.py # class MappingInfo(): # def __init__(self, path, **kwargs): # def _correspondence_from_config(self, path): # def _tab_config(self, file_tab): # def _mapping_config(self, file_map): # def write(self, indent=0): # def check_path(path): # def write_chr(self, mode="w", path_w=None, min_c=None, max_c=None): # def write_chr_sizes(self, mode="w", path_w=None, file_n=None, min_c=None, max_c=None): # def write_cytoband(end, start=0, delta=43200, start_phase="light", mode="w", path_w=None, lab_bed=True, track_line=True): # def write_period_seq (end, start=0, delta=43200, tag="day", mode="w", path_w=None, name_file="period_seq", lab_bed=True, track_line=True): # # Path: pergola/intervals.py # class IntData(object): # def __init__(self, path, map_dict, header=True, **kwargs): # def _check_delimiter (self, path, delimiter): # def _reader_data(self): # def _pandas_df_reader(self, df): # def _set_fields_b(self, fields=None): # def _set_fields_g (self, map_dict): # def _simple_read(self): # def get_field_items(self, data, field="data_types", default=None): # def read(self, fields=None, relative_coord=False, intervals=False, int_step=None, fields2rel=None, multiply_t=None, # **kwargs): # def _min_max(self, list_data, f_start="start", f_end="end"): # def _time2rel_time(self, i_fields): # def _multiply_values(self, i_fields, factor=1): # def _create_int(self, start_int, int_step=None): # def _create_int_add_integ(self, start_int, integer=1): # def __del__(self): # def is_number(var): # def num(s): # # Path: pergola/tracks.py # class GenomicContainer(object): # class Track(GenomicContainer): # class BedToolConvertible(GenomicContainer): # class Bed(BedToolConvertible): # class BedGraph(BedToolConvertible): # class Gff(BedToolConvertible): # def __init__(self, data, fields=None, data_types=None, **kwargs): # def __iter__(self): # def next(self): # def save_track(self, mode="w", path=None, name_file=None, track_line=True, bed_label=False, gff_label=False): # def __init__(self, data, fields=None, data_types=None, list_tracks=None, min=0, max=0, **kwargs): # def convert(self, mode='bed', range_color=None, **kwargs): # def _convert2single_track(self, data_tuples, mode=None, **kwargs): # def _get_range(self, data_tr): # def remove(self, dict_t, tracks2remove): # def join_by_track(self, dict_t, tracks2join): # def join_by_dataType (self, dict_d, mode): # def track_convert2bed(self, track, in_call=False, **kwargs): # def track_convert2gff(self, track, in_call=False, **kwargs): # def track_convert2bedGraph(self, track, in_call=False, window=300, mean_win=False, mean_value=False, **kwargs): # def __init__(self, data, **kwargs): # def create_pybedtools(self): # def _tmp_track(self): # def __init__(self, data, **kwargs): # def __init__(self, data, **kwargs): # def win_mean (self): # def _win_mean (self, data, n_tracks): # def __init__(self, data, **kwargs): # def assign_color(set_data_types, color_restrictions=None): # def merge_tracks (tr_1, tr_2): . Output only the next line.
int_data_b1 = intervals.IntData ("../../sample_data/feeding_beh_CB1_mice/intake_CB1_B1.csv", map_dict=mapping_data.correspondence)
Predict the next line for this snippet: <|code_start|>int_data_b1 = intervals.IntData ("../../sample_data/feeding_beh_CB1_mice/intake_CB1_B1.csv", map_dict=mapping_data.correspondence) int_data_b2 = intervals.IntData ("../../sample_data/feeding_beh_CB1_mice/intake_CB1_B2.csv", map_dict=mapping_data.correspondence) int_data_b3 = intervals.IntData ("../../sample_data/feeding_beh_CB1_mice/intake_CB1_B3.csv", map_dict=mapping_data.correspondence) int_data_b4 = intervals.IntData ("../../sample_data/feeding_beh_CB1_mice/intake_CB1_B4.csv", map_dict=mapping_data.correspondence) mapping_bed = mapping.MappingInfo("../../test/pybed2perg.txt") # base_dir = path.dirname(getcwd()) base_dir = getcwd() # out_dir = base_dir + "/results/" + statistic + "/" out_dir = base_dir + "/results/" + args.behavioral_type + "/" + statistic + "/" if path.exists(out_dir): rmtree(out_dir) makedirs(out_dir) chdir(out_dir) data_read_b1 = int_data_b1.read(relative_coord=True) data_read_b2 = int_data_b2.read(relative_coord=True) data_read_b3 = int_data_b3.read(relative_coord=True) data_read_b4 = int_data_b4.read(relative_coord=True) # Check the longest period of time of any batches end_time = max (int_data_b1.max - int_data_b1.min, int_data_b2.max - int_data_b2.min, int_data_b3.max - int_data_b3.min, int_data_b4.max - int_data_b4.min) <|code_end|> with the help of current file imports: from argparse import ArgumentParser from os import path, getcwd, makedirs, chdir from sys import stderr from pergola import mapping from pergola import intervals from pergola import tracks import subprocess import pybedtools and context from other files: # Path: pergola/mapping.py # class MappingInfo(): # def __init__(self, path, **kwargs): # def _correspondence_from_config(self, path): # def _tab_config(self, file_tab): # def _mapping_config(self, file_map): # def write(self, indent=0): # def check_path(path): # def write_chr(self, mode="w", path_w=None, min_c=None, max_c=None): # def write_chr_sizes(self, mode="w", path_w=None, file_n=None, min_c=None, max_c=None): # def write_cytoband(end, start=0, delta=43200, start_phase="light", mode="w", path_w=None, lab_bed=True, track_line=True): # def write_period_seq (end, start=0, delta=43200, tag="day", mode="w", path_w=None, name_file="period_seq", lab_bed=True, track_line=True): # # Path: pergola/intervals.py # class IntData(object): # def __init__(self, path, map_dict, header=True, **kwargs): # def _check_delimiter (self, path, delimiter): # def _reader_data(self): # def _pandas_df_reader(self, df): # def _set_fields_b(self, fields=None): # def _set_fields_g (self, map_dict): # def _simple_read(self): # def get_field_items(self, data, field="data_types", default=None): # def read(self, fields=None, relative_coord=False, intervals=False, int_step=None, fields2rel=None, multiply_t=None, # **kwargs): # def _min_max(self, list_data, f_start="start", f_end="end"): # def _time2rel_time(self, i_fields): # def _multiply_values(self, i_fields, factor=1): # def _create_int(self, start_int, int_step=None): # def _create_int_add_integ(self, start_int, integer=1): # def __del__(self): # def is_number(var): # def num(s): # # Path: pergola/tracks.py # class GenomicContainer(object): # class Track(GenomicContainer): # class BedToolConvertible(GenomicContainer): # class Bed(BedToolConvertible): # class BedGraph(BedToolConvertible): # class Gff(BedToolConvertible): # def __init__(self, data, fields=None, data_types=None, **kwargs): # def __iter__(self): # def next(self): # def save_track(self, mode="w", path=None, name_file=None, track_line=True, bed_label=False, gff_label=False): # def __init__(self, data, fields=None, data_types=None, list_tracks=None, min=0, max=0, **kwargs): # def convert(self, mode='bed', range_color=None, **kwargs): # def _convert2single_track(self, data_tuples, mode=None, **kwargs): # def _get_range(self, data_tr): # def remove(self, dict_t, tracks2remove): # def join_by_track(self, dict_t, tracks2join): # def join_by_dataType (self, dict_d, mode): # def track_convert2bed(self, track, in_call=False, **kwargs): # def track_convert2gff(self, track, in_call=False, **kwargs): # def track_convert2bedGraph(self, track, in_call=False, window=300, mean_win=False, mean_value=False, **kwargs): # def __init__(self, data, **kwargs): # def create_pybedtools(self): # def _tmp_track(self): # def __init__(self, data, **kwargs): # def __init__(self, data, **kwargs): # def win_mean (self): # def _win_mean (self, data, n_tracks): # def __init__(self, data, **kwargs): # def assign_color(set_data_types, color_restrictions=None): # def merge_tracks (tr_1, tr_2): , which may contain function names, class names, or code. Output only the next line.
data_read_all_batches = tracks.merge_tracks (tracks.merge_tracks (tracks.merge_tracks (data_read_b1, data_read_b2), data_read_b3), data_read_b4)
Given the following code snippet before the placeholder: <|code_start|># but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Pergola. If not, see <http://www.gnu.org/licenses/>. # example execution # ./celegans_speed_i_motion.py -p midbody.phenotypic_feature.bed -m motion.bed -b bed_map.txt -t "N2" # Loading libraries parser = ArgumentParser(description='File input arguments') parser.add_argument('-p','--phenotypic_file', help='Bed file containing a phenotypic feature of the worn', required=True) parser.add_argument('-m','--motion_file', help='Bed file containing worm motion (forward, backward or paused)', required=True) parser.add_argument('-b','--bed_mapping_file', help='Mapping pergola file for bed files', required=True) parser.add_argument('-t', '--tag_out', required=False, type=str, help='Tag output file') args = parser.parse_args() if args.tag_out: tag_file = args.tag_out else: tag_file = "mean_speed_i_motionDir" print >> stderr, "Bed speed file: %s" % args.phenotypic_file print >> stderr, "Bed motion file: %s" % args.motion_file print >> stderr, "Mapping bed to Pergola file: %s" % args.bed_mapping_file print >> stderr, "Output tag file: %s" % tag_file <|code_end|> , predict the next line using imports from the current file: from argparse import ArgumentParser from os import path, getcwd from csv import writer from pergola import mapping from pergola import intervals from sys import stderr, exit import pybedtools and context including class names, function names, and sometimes code from other files: # Path: pergola/mapping.py # class MappingInfo(): # def __init__(self, path, **kwargs): # def _correspondence_from_config(self, path): # def _tab_config(self, file_tab): # def _mapping_config(self, file_map): # def write(self, indent=0): # def check_path(path): # def write_chr(self, mode="w", path_w=None, min_c=None, max_c=None): # def write_chr_sizes(self, mode="w", path_w=None, file_n=None, min_c=None, max_c=None): # def write_cytoband(end, start=0, delta=43200, start_phase="light", mode="w", path_w=None, lab_bed=True, track_line=True): # def write_period_seq (end, start=0, delta=43200, tag="day", mode="w", path_w=None, name_file="period_seq", lab_bed=True, track_line=True): # # Path: pergola/intervals.py # class IntData(object): # def __init__(self, path, map_dict, header=True, **kwargs): # def _check_delimiter (self, path, delimiter): # def _reader_data(self): # def _pandas_df_reader(self, df): # def _set_fields_b(self, fields=None): # def _set_fields_g (self, map_dict): # def _simple_read(self): # def get_field_items(self, data, field="data_types", default=None): # def read(self, fields=None, relative_coord=False, intervals=False, int_step=None, fields2rel=None, multiply_t=None, # **kwargs): # def _min_max(self, list_data, f_start="start", f_end="end"): # def _time2rel_time(self, i_fields): # def _multiply_values(self, i_fields, factor=1): # def _create_int(self, start_int, int_step=None): # def _create_int_add_integ(self, start_int, integer=1): # def __del__(self): # def is_number(var): # def num(s): . Output only the next line.
mapping_bed = mapping.MappingInfo(args.bed_mapping_file)
Given snippet: <|code_start|># along with Pergola. If not, see <http://www.gnu.org/licenses/>. # example execution # ./celegans_speed_i_motion.py -p midbody.phenotypic_feature.bed -m motion.bed -b bed_map.txt -t "N2" # Loading libraries parser = ArgumentParser(description='File input arguments') parser.add_argument('-p','--phenotypic_file', help='Bed file containing a phenotypic feature of the worn', required=True) parser.add_argument('-m','--motion_file', help='Bed file containing worm motion (forward, backward or paused)', required=True) parser.add_argument('-b','--bed_mapping_file', help='Mapping pergola file for bed files', required=True) parser.add_argument('-t', '--tag_out', required=False, type=str, help='Tag output file') args = parser.parse_args() if args.tag_out: tag_file = args.tag_out else: tag_file = "mean_speed_i_motionDir" print >> stderr, "Bed speed file: %s" % args.phenotypic_file print >> stderr, "Bed motion file: %s" % args.motion_file print >> stderr, "Mapping bed to Pergola file: %s" % args.bed_mapping_file print >> stderr, "Output tag file: %s" % tag_file mapping_bed = mapping.MappingInfo(args.bed_mapping_file) ## mapping_bed = mapping.MappingInfo("/Users/jespinosa/git/pergola/test/c_elegans_data_test/bed2pergola.txt") bed_ph_file = args.phenotypic_file <|code_end|> , continue by predicting the next line. Consider current file imports: from argparse import ArgumentParser from os import path, getcwd from csv import writer from pergola import mapping from pergola import intervals from sys import stderr, exit import pybedtools and context: # Path: pergola/mapping.py # class MappingInfo(): # def __init__(self, path, **kwargs): # def _correspondence_from_config(self, path): # def _tab_config(self, file_tab): # def _mapping_config(self, file_map): # def write(self, indent=0): # def check_path(path): # def write_chr(self, mode="w", path_w=None, min_c=None, max_c=None): # def write_chr_sizes(self, mode="w", path_w=None, file_n=None, min_c=None, max_c=None): # def write_cytoband(end, start=0, delta=43200, start_phase="light", mode="w", path_w=None, lab_bed=True, track_line=True): # def write_period_seq (end, start=0, delta=43200, tag="day", mode="w", path_w=None, name_file="period_seq", lab_bed=True, track_line=True): # # Path: pergola/intervals.py # class IntData(object): # def __init__(self, path, map_dict, header=True, **kwargs): # def _check_delimiter (self, path, delimiter): # def _reader_data(self): # def _pandas_df_reader(self, df): # def _set_fields_b(self, fields=None): # def _set_fields_g (self, map_dict): # def _simple_read(self): # def get_field_items(self, data, field="data_types", default=None): # def read(self, fields=None, relative_coord=False, intervals=False, int_step=None, fields2rel=None, multiply_t=None, # **kwargs): # def _min_max(self, list_data, f_start="start", f_end="end"): # def _time2rel_time(self, i_fields): # def _multiply_values(self, i_fields, factor=1): # def _create_int(self, start_int, int_step=None): # def _create_int_add_integ(self, start_int, integer=1): # def __del__(self): # def is_number(var): # def num(s): which might include code, classes, or functions. Output only the next line.
int_data_phenotypic = intervals.IntData(bed_ph_file, map_dict=mapping_bed.correspondence, header=False,
Here is a snippet: <|code_start|>parser.add_argument('-b','--behavioral_type', help='Choose whether to work with drinking or feeding mice behavioral data', required=True, choices=_behaviors_available) args = parser.parse_args() print >> stderr, "Statistic to be calculated: %s" % args.statistic print >> stderr, "Working with mice %s behavioral data" % args.behavioral_type # Statistic to calculate statistic = args.statistic ## Dictionary to set colors of each type of food # food_sc orange # food_fat black # water blue # saccharin red ### Feeding data if args.behavioral_type == "feeding": data_type_1 = "food_sc" data_type_2 = "food_fat" data_type_col = {data_type_1: 'orange', data_type_2:'black'} ### Drinking data elif args.behavioral_type == 'drinking': data_type_1 = "water" data_type_2 = "saccharin" data_type_col = {data_type_1: 'blue', data_type_2:'red'} else: print >> stderr, "Behavioral data type not available in script, please try again with \"drinking\" or \"feeding\"" <|code_end|> . Write the next line using the current file imports: from argparse import ArgumentParser from os import path, getcwd, makedirs, chdir from shutil import rmtree from sys import stderr from pergola import mapping from pergola import intervals from pergola import tracks import subprocess import pybedtools and context from other files: # Path: pergola/mapping.py # class MappingInfo(): # def __init__(self, path, **kwargs): # def _correspondence_from_config(self, path): # def _tab_config(self, file_tab): # def _mapping_config(self, file_map): # def write(self, indent=0): # def check_path(path): # def write_chr(self, mode="w", path_w=None, min_c=None, max_c=None): # def write_chr_sizes(self, mode="w", path_w=None, file_n=None, min_c=None, max_c=None): # def write_cytoband(end, start=0, delta=43200, start_phase="light", mode="w", path_w=None, lab_bed=True, track_line=True): # def write_period_seq (end, start=0, delta=43200, tag="day", mode="w", path_w=None, name_file="period_seq", lab_bed=True, track_line=True): # # Path: pergola/intervals.py # class IntData(object): # def __init__(self, path, map_dict, header=True, **kwargs): # def _check_delimiter (self, path, delimiter): # def _reader_data(self): # def _pandas_df_reader(self, df): # def _set_fields_b(self, fields=None): # def _set_fields_g (self, map_dict): # def _simple_read(self): # def get_field_items(self, data, field="data_types", default=None): # def read(self, fields=None, relative_coord=False, intervals=False, int_step=None, fields2rel=None, multiply_t=None, # **kwargs): # def _min_max(self, list_data, f_start="start", f_end="end"): # def _time2rel_time(self, i_fields): # def _multiply_values(self, i_fields, factor=1): # def _create_int(self, start_int, int_step=None): # def _create_int_add_integ(self, start_int, integer=1): # def __del__(self): # def is_number(var): # def num(s): # # Path: pergola/tracks.py # class GenomicContainer(object): # class Track(GenomicContainer): # class BedToolConvertible(GenomicContainer): # class Bed(BedToolConvertible): # class BedGraph(BedToolConvertible): # class Gff(BedToolConvertible): # def __init__(self, data, fields=None, data_types=None, **kwargs): # def __iter__(self): # def next(self): # def save_track(self, mode="w", path=None, name_file=None, track_line=True, bed_label=False, gff_label=False): # def __init__(self, data, fields=None, data_types=None, list_tracks=None, min=0, max=0, **kwargs): # def convert(self, mode='bed', range_color=None, **kwargs): # def _convert2single_track(self, data_tuples, mode=None, **kwargs): # def _get_range(self, data_tr): # def remove(self, dict_t, tracks2remove): # def join_by_track(self, dict_t, tracks2join): # def join_by_dataType (self, dict_d, mode): # def track_convert2bed(self, track, in_call=False, **kwargs): # def track_convert2gff(self, track, in_call=False, **kwargs): # def track_convert2bedGraph(self, track, in_call=False, window=300, mean_win=False, mean_value=False, **kwargs): # def __init__(self, data, **kwargs): # def create_pybedtools(self): # def _tmp_track(self): # def __init__(self, data, **kwargs): # def __init__(self, data, **kwargs): # def win_mean (self): # def _win_mean (self, data, n_tracks): # def __init__(self, data, **kwargs): # def assign_color(set_data_types, color_restrictions=None): # def merge_tracks (tr_1, tr_2): , which may include functions, classes, or code. Output only the next line.
mapping_data = mapping.MappingInfo("../../sample_data/feeding_behavior/b2g.txt")
Given the following code snippet before the placeholder: <|code_start|> args = parser.parse_args() print >> stderr, "Statistic to be calculated: %s" % args.statistic print >> stderr, "Working with mice %s behavioral data" % args.behavioral_type # Statistic to calculate statistic = args.statistic ## Dictionary to set colors of each type of food # food_sc orange # food_fat black # water blue # saccharin red ### Feeding data if args.behavioral_type == "feeding": data_type_1 = "food_sc" data_type_2 = "food_fat" data_type_col = {data_type_1: 'orange', data_type_2:'black'} ### Drinking data elif args.behavioral_type == 'drinking': data_type_1 = "water" data_type_2 = "saccharin" data_type_col = {data_type_1: 'blue', data_type_2:'red'} else: print >> stderr, "Behavioral data type not available in script, please try again with \"drinking\" or \"feeding\"" mapping_data = mapping.MappingInfo("../../sample_data/feeding_behavior/b2g.txt") <|code_end|> , predict the next line using imports from the current file: from argparse import ArgumentParser from os import path, getcwd, makedirs, chdir from shutil import rmtree from sys import stderr from pergola import mapping from pergola import intervals from pergola import tracks import subprocess import pybedtools and context including class names, function names, and sometimes code from other files: # Path: pergola/mapping.py # class MappingInfo(): # def __init__(self, path, **kwargs): # def _correspondence_from_config(self, path): # def _tab_config(self, file_tab): # def _mapping_config(self, file_map): # def write(self, indent=0): # def check_path(path): # def write_chr(self, mode="w", path_w=None, min_c=None, max_c=None): # def write_chr_sizes(self, mode="w", path_w=None, file_n=None, min_c=None, max_c=None): # def write_cytoband(end, start=0, delta=43200, start_phase="light", mode="w", path_w=None, lab_bed=True, track_line=True): # def write_period_seq (end, start=0, delta=43200, tag="day", mode="w", path_w=None, name_file="period_seq", lab_bed=True, track_line=True): # # Path: pergola/intervals.py # class IntData(object): # def __init__(self, path, map_dict, header=True, **kwargs): # def _check_delimiter (self, path, delimiter): # def _reader_data(self): # def _pandas_df_reader(self, df): # def _set_fields_b(self, fields=None): # def _set_fields_g (self, map_dict): # def _simple_read(self): # def get_field_items(self, data, field="data_types", default=None): # def read(self, fields=None, relative_coord=False, intervals=False, int_step=None, fields2rel=None, multiply_t=None, # **kwargs): # def _min_max(self, list_data, f_start="start", f_end="end"): # def _time2rel_time(self, i_fields): # def _multiply_values(self, i_fields, factor=1): # def _create_int(self, start_int, int_step=None): # def _create_int_add_integ(self, start_int, integer=1): # def __del__(self): # def is_number(var): # def num(s): # # Path: pergola/tracks.py # class GenomicContainer(object): # class Track(GenomicContainer): # class BedToolConvertible(GenomicContainer): # class Bed(BedToolConvertible): # class BedGraph(BedToolConvertible): # class Gff(BedToolConvertible): # def __init__(self, data, fields=None, data_types=None, **kwargs): # def __iter__(self): # def next(self): # def save_track(self, mode="w", path=None, name_file=None, track_line=True, bed_label=False, gff_label=False): # def __init__(self, data, fields=None, data_types=None, list_tracks=None, min=0, max=0, **kwargs): # def convert(self, mode='bed', range_color=None, **kwargs): # def _convert2single_track(self, data_tuples, mode=None, **kwargs): # def _get_range(self, data_tr): # def remove(self, dict_t, tracks2remove): # def join_by_track(self, dict_t, tracks2join): # def join_by_dataType (self, dict_d, mode): # def track_convert2bed(self, track, in_call=False, **kwargs): # def track_convert2gff(self, track, in_call=False, **kwargs): # def track_convert2bedGraph(self, track, in_call=False, window=300, mean_win=False, mean_value=False, **kwargs): # def __init__(self, data, **kwargs): # def create_pybedtools(self): # def _tmp_track(self): # def __init__(self, data, **kwargs): # def __init__(self, data, **kwargs): # def win_mean (self): # def _win_mean (self, data, n_tracks): # def __init__(self, data, **kwargs): # def assign_color(set_data_types, color_restrictions=None): # def merge_tracks (tr_1, tr_2): . Output only the next line.
int_data_b1 = intervals.IntData ("../../sample_data/feeding_beh_CB1_mice/intake_CB1_B1.csv", map_dict=mapping_data.correspondence)
Predict the next line after this snippet: <|code_start|> int_data_b1 = intervals.IntData ("../../sample_data/feeding_beh_CB1_mice/intake_CB1_B1.csv", map_dict=mapping_data.correspondence) int_data_b2 = intervals.IntData ("../../sample_data/feeding_beh_CB1_mice/intake_CB1_B2.csv", map_dict=mapping_data.correspondence) int_data_b3 = intervals.IntData ("../../sample_data/feeding_beh_CB1_mice/intake_CB1_B3.csv", map_dict=mapping_data.correspondence) int_data_b4 = intervals.IntData ("../../sample_data/feeding_beh_CB1_mice/intake_CB1_B4.csv", map_dict=mapping_data.correspondence) mapping_bed = mapping.MappingInfo("../../test/pybed2perg.txt") # base_dir = path.dirname(getcwd()) base_dir = getcwd() results_dir = "/results_by_tt/" out_dir = base_dir + results_dir + args.behavioral_type + "_by_phases/" + statistic + "/" if path.exists(out_dir): rmtree(out_dir) makedirs(out_dir) chdir(out_dir) data_read_b1 = int_data_b1.read(relative_coord=True) data_read_b2 = int_data_b2.read(relative_coord=True) data_read_b3 = int_data_b3.read(relative_coord=True) data_read_b4 = int_data_b4.read(relative_coord=True) # Check the longest period of time of any batches end_time = max (int_data_b1.max - int_data_b1.min, int_data_b2.max - int_data_b2.min, int_data_b3.max - int_data_b3.min, int_data_b4.max - int_data_b4.min) <|code_end|> using the current file's imports: from argparse import ArgumentParser from os import path, getcwd, makedirs, chdir from shutil import rmtree from sys import stderr from pergola import mapping from pergola import intervals from pergola import tracks import subprocess import pybedtools and any relevant context from other files: # Path: pergola/mapping.py # class MappingInfo(): # def __init__(self, path, **kwargs): # def _correspondence_from_config(self, path): # def _tab_config(self, file_tab): # def _mapping_config(self, file_map): # def write(self, indent=0): # def check_path(path): # def write_chr(self, mode="w", path_w=None, min_c=None, max_c=None): # def write_chr_sizes(self, mode="w", path_w=None, file_n=None, min_c=None, max_c=None): # def write_cytoband(end, start=0, delta=43200, start_phase="light", mode="w", path_w=None, lab_bed=True, track_line=True): # def write_period_seq (end, start=0, delta=43200, tag="day", mode="w", path_w=None, name_file="period_seq", lab_bed=True, track_line=True): # # Path: pergola/intervals.py # class IntData(object): # def __init__(self, path, map_dict, header=True, **kwargs): # def _check_delimiter (self, path, delimiter): # def _reader_data(self): # def _pandas_df_reader(self, df): # def _set_fields_b(self, fields=None): # def _set_fields_g (self, map_dict): # def _simple_read(self): # def get_field_items(self, data, field="data_types", default=None): # def read(self, fields=None, relative_coord=False, intervals=False, int_step=None, fields2rel=None, multiply_t=None, # **kwargs): # def _min_max(self, list_data, f_start="start", f_end="end"): # def _time2rel_time(self, i_fields): # def _multiply_values(self, i_fields, factor=1): # def _create_int(self, start_int, int_step=None): # def _create_int_add_integ(self, start_int, integer=1): # def __del__(self): # def is_number(var): # def num(s): # # Path: pergola/tracks.py # class GenomicContainer(object): # class Track(GenomicContainer): # class BedToolConvertible(GenomicContainer): # class Bed(BedToolConvertible): # class BedGraph(BedToolConvertible): # class Gff(BedToolConvertible): # def __init__(self, data, fields=None, data_types=None, **kwargs): # def __iter__(self): # def next(self): # def save_track(self, mode="w", path=None, name_file=None, track_line=True, bed_label=False, gff_label=False): # def __init__(self, data, fields=None, data_types=None, list_tracks=None, min=0, max=0, **kwargs): # def convert(self, mode='bed', range_color=None, **kwargs): # def _convert2single_track(self, data_tuples, mode=None, **kwargs): # def _get_range(self, data_tr): # def remove(self, dict_t, tracks2remove): # def join_by_track(self, dict_t, tracks2join): # def join_by_dataType (self, dict_d, mode): # def track_convert2bed(self, track, in_call=False, **kwargs): # def track_convert2gff(self, track, in_call=False, **kwargs): # def track_convert2bedGraph(self, track, in_call=False, window=300, mean_win=False, mean_value=False, **kwargs): # def __init__(self, data, **kwargs): # def create_pybedtools(self): # def _tmp_track(self): # def __init__(self, data, **kwargs): # def __init__(self, data, **kwargs): # def win_mean (self): # def _win_mean (self, data, n_tracks): # def __init__(self, data, **kwargs): # def assign_color(set_data_types, color_restrictions=None): # def merge_tracks (tr_1, tr_2): . Output only the next line.
data_read_all_batches = tracks.merge_tracks (tracks.merge_tracks (tracks.merge_tracks (data_read_b1, data_read_b2), data_read_b3), data_read_b4)
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python """ 5 feb 2015 Script to transform Jaaba files in matlab format into pergola files Example of how to run this file: python jaaba2pergola_dev.py ./jaaba2pergola_dev.py """ # from os import getcwd # from sys import stderr # from os.path import join, exists # from scipy import io #parsers # from scipy import nditer # from pergola import mapping#parsers # from pergola import intervals#parsers # from tempfile import NamedTemporaryFile#parsers # This part has been included in the function # jaaba_data = io.loadmat('/Users/jespinosa/JAABA_MAC_0.5.1/sampledata/Chase1_TrpA_Rig1Plate15BowlA_20120404T141155/scores_chase.mat') <|code_end|> using the current file's imports: from numpy import hstack#parsers from numpy import mean#parsers from pergola import parsers from pergola import jaaba_parsers and any relevant context from other files: # Path: pergola/parsers.py # PATH = abspath(split(realpath(__file__))[0]) # def parse_num_range(string): # def read_track_actions (tracks, track_action = "split_all"): # def read_colors (path_color_file): # # Path: pergola/jaaba_parsers.py # def jaaba_scores_to_csv(input_file, name_file="JAABA_scores", mode="w", delimiter="\t", path_w=None, norm=False, data_type="a"): # def jaaba_scores_to_intData(input_file, map_jaaba, name_file="JAABA_scores", delimiter="\t", norm=False, data_type="a"): # def extract_jaaba_features(dir_perframe, output="csv", map_jaaba=False, delimiter="\t", feature="velmag", path_w=""): . Output only the next line.
jaaba_parsers.jaaba_scores_to_csv(input_file='/Users/jespinosa/JAABA_MAC_0.5.1/sampledata_v0.5/Chase1_TrpA_Rig1Plate15BowlA_20120404T141155/scores_chase.mat',
Given snippet: <|code_start|># In the cluster I use bedtools Pablo installation, because default cluster version has not map if home == "/users/cn/jespinosa" : pybedtools.helpers.set_bedtools_path('/users/cn/pprieto/soft/bedtools/bedtools2-2.19.1/bin') parser = ArgumentParser(description='File input arguments') parser.add_argument('-s','--speed', help='Bed file containing speed for one body part of the worn', required=True) parser.add_argument('-m','--motion', help='Bed file containing worm motion (forward, backward or paused)', required=True) parser.add_argument('-b','--bed_mapping', help='Mapping pergola file for bed files', required=True) parser.add_argument('-t', '--tag_out', required=False, type=str, help='Tag output file') args = parser.parse_args() if args.tag_out: tag_file = args.tag_out else: tag_file = "mean_speed_i_motionDir" print >> stderr, "Bed speed file: %s" % args.speed print >> stderr, "Bed motion file: %s" % args.motion print >> stderr, "Mapping bed to Pergola file: %s" % args.bed_mapping print >> stderr, "Output tag file: %s" % tag_file # base_dir = path.dirname(getcwd()) # dir_development = base_dir + "/c_elegans_data_test/" # # out_dir = base_dir + "/test/" # out_dir = base_dir + "/c_elegans_data_test/" # # mapping_bed = mapping.MappingInfo(base_dir + "/test/" + "bed2pergola.txt") <|code_end|> , continue by predicting the next line. Consider current file imports: from argparse import ArgumentParser from os import path, getcwd from csv import writer from os.path import expanduser from pergola import mapping from pergola import intervals from sys import stderr, exit import pybedtools and context: # Path: pergola/mapping.py # class MappingInfo(): # def __init__(self, path, **kwargs): # def _correspondence_from_config(self, path): # def _tab_config(self, file_tab): # def _mapping_config(self, file_map): # def write(self, indent=0): # def check_path(path): # def write_chr(self, mode="w", path_w=None, min_c=None, max_c=None): # def write_chr_sizes(self, mode="w", path_w=None, file_n=None, min_c=None, max_c=None): # def write_cytoband(end, start=0, delta=43200, start_phase="light", mode="w", path_w=None, lab_bed=True, track_line=True): # def write_period_seq (end, start=0, delta=43200, tag="day", mode="w", path_w=None, name_file="period_seq", lab_bed=True, track_line=True): # # Path: pergola/intervals.py # class IntData(object): # def __init__(self, path, map_dict, header=True, **kwargs): # def _check_delimiter (self, path, delimiter): # def _reader_data(self): # def _pandas_df_reader(self, df): # def _set_fields_b(self, fields=None): # def _set_fields_g (self, map_dict): # def _simple_read(self): # def get_field_items(self, data, field="data_types", default=None): # def read(self, fields=None, relative_coord=False, intervals=False, int_step=None, fields2rel=None, multiply_t=None, # **kwargs): # def _min_max(self, list_data, f_start="start", f_end="end"): # def _time2rel_time(self, i_fields): # def _multiply_values(self, i_fields, factor=1): # def _create_int(self, start_int, int_step=None): # def _create_int_add_integ(self, start_int, integer=1): # def __del__(self): # def is_number(var): # def num(s): which might include code, classes, or functions. Output only the next line.
mapping_bed = mapping.MappingInfo(args.bed_mapping)
Continue the code snippet: <|code_start|> tag_file = args.tag_out else: tag_file = "mean_speed_i_motionDir" print >> stderr, "Bed speed file: %s" % args.speed print >> stderr, "Bed motion file: %s" % args.motion print >> stderr, "Mapping bed to Pergola file: %s" % args.bed_mapping print >> stderr, "Output tag file: %s" % tag_file # base_dir = path.dirname(getcwd()) # dir_development = base_dir + "/c_elegans_data_test/" # # out_dir = base_dir + "/test/" # out_dir = base_dir + "/c_elegans_data_test/" # # mapping_bed = mapping.MappingInfo(base_dir + "/test/" + "bed2pergola.txt") mapping_bed = mapping.MappingInfo(args.bed_mapping) ## mapping_bed = mapping.MappingInfo("/Users/jespinosa/git/pergola/test/c_elegans_data_test/bed2pergola.txt") # speed bed file ## read file from input args # bed_speed_file = dir_development + "midbody.575_JU440_on_food_L_2011_02_17__16_43___3___11_features_speed.csv.bed" # bed_speed_file ='/Users/jespinosa/git/pergola/test/c_elegans_data_test/results_GB/midbody.575_JU440_on_food_L_2011_02_17__11_00___3___1_features.mat.GB.bed' ## bed_speed_file = '/Users/jespinosa/git/pergola/test/c_elegans_data_test/work/be/c8a7942756ee7053d0f9856e1caa88/bed_speed_no_tr' ## error to debug nextflow Paolo # bed_speed_file = dir_development + args.speed bed_speed_file = args.speed <|code_end|> . Use current file imports: from argparse import ArgumentParser from os import path, getcwd from csv import writer from os.path import expanduser from pergola import mapping from pergola import intervals from sys import stderr, exit import pybedtools and context (classes, functions, or code) from other files: # Path: pergola/mapping.py # class MappingInfo(): # def __init__(self, path, **kwargs): # def _correspondence_from_config(self, path): # def _tab_config(self, file_tab): # def _mapping_config(self, file_map): # def write(self, indent=0): # def check_path(path): # def write_chr(self, mode="w", path_w=None, min_c=None, max_c=None): # def write_chr_sizes(self, mode="w", path_w=None, file_n=None, min_c=None, max_c=None): # def write_cytoband(end, start=0, delta=43200, start_phase="light", mode="w", path_w=None, lab_bed=True, track_line=True): # def write_period_seq (end, start=0, delta=43200, tag="day", mode="w", path_w=None, name_file="period_seq", lab_bed=True, track_line=True): # # Path: pergola/intervals.py # class IntData(object): # def __init__(self, path, map_dict, header=True, **kwargs): # def _check_delimiter (self, path, delimiter): # def _reader_data(self): # def _pandas_df_reader(self, df): # def _set_fields_b(self, fields=None): # def _set_fields_g (self, map_dict): # def _simple_read(self): # def get_field_items(self, data, field="data_types", default=None): # def read(self, fields=None, relative_coord=False, intervals=False, int_step=None, fields2rel=None, multiply_t=None, # **kwargs): # def _min_max(self, list_data, f_start="start", f_end="end"): # def _time2rel_time(self, i_fields): # def _multiply_values(self, i_fields, factor=1): # def _create_int(self, start_int, int_step=None): # def _create_int_add_integ(self, start_int, integer=1): # def __del__(self): # def is_number(var): # def num(s): . Output only the next line.
int_data_speed = intervals.IntData(bed_speed_file, map_dict=mapping_bed.correspondence, header=False,
Next line prediction: <|code_start|> voidp = ctypes.c_void_p stp = ctypes.POINTER(St) stpvoid = ctypes.POINTER(None) arra1 = (ctypes.c_long * 4) arra2 = (St * 4) arra3 = (ctypes.POINTER(St) * 4) charp = ctypes.c_char_p string = ctypes.CString fptr = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_uint) arra4 = (fptr * 256) double = ctypes.c_longdouble arra5 = ctypes.c_ubyte * 8 arra6 = ctypes.c_char * 32 ptrUnion = ctypes.POINTER(Union) return locals() class TestReload(unittest.TestCase): """Tests sizes after ctypes changes.""" def setUp(self): pass # test ctypes._pointer_type_cache def test_pointer_type_cache(self): """test the comportment of _pointer_type_cache""" # between reset(), we keep the reference to the ctypes modules # and we don't the pointer cache, that we only share with the default # ctypes proxy instance <|code_end|> . Use current file imports: (import logging import unittest import ctypes from haystack import types from haystack import basicmodel from haystack import basicmodel from haystack import basicmodel from haystack import basicmodel) and context including class names, function names, or small code snippets from other files: # Path: haystack/types.py # __PROXIES = {} # SIZE = self.__longdoublesize # HOSTSIZE = self.sizeof(self.__real_ctypes.c_longdouble) # HOSTDOUBLESIZE = self.sizeof(self.__real_ctypes.c_double) # POINTERSIZE = self.__pointersize # def load_ctypes_default(): # def build_ctypes_proxy(longsize, pointersize, longdoublesize): # def is_ctypes_instance(obj): # def check_arg_is_type(func): # def check_arg(self, objtype): # def __init__(self, longsize, pointersize, longdoublesize): # def __init_types(self): # def __set_void(self): # def __set_int128(self): # def __set_long(self): # def __set_float(self): # def __eq__(thisself, other): # def __repr__(thisself): # def value(thisself): # def __eq__(thisself, other): # def __repr__(thisself): # def value(thisself): # def __set_pointer(self): # def _sub_addr_(myself): # def __init__(myself, value): # def __repr__(myself): # def POINTER_T(pointee): # def __repr__(myself): # def contents(myself): # def __init__(myself, _value=None): # def __set_records(self): # def read_string(self, memoryMap, address, max_size, chunk_length=256): # def read_string(self, memoryMap, address, max_size, chunk_length=256): # def __set_utils_types(self): # def __cast(self, obj, next_type): # def __set_CFUNCTYPE(self): # def __init__(myself, *a, **args): # def fn_FUNC_T(*args): # def _p_type(self): # def get_real_ctypes_member(self, typename): # def get_pack_format(self): # def get_bytes_for_record_field(self, record, fieldname): # def is_array_of_basic_instance(self, obj): # def is_array_type(self, objtype): # def is_array_of_basic_type(self, objtype): # def is_basic_type(self, objtype): # def is_basic_ctype(self, objtype): # def is_cstring_type(self, objtype): # def is_function_type(self, objtype): # def is_pointer_type(self, objtype): # def get_pointee_type(self, objtype): # def is_pointer_to_array_type(self, objtype): # def is_pointer_to_basic_type(self, objtype): # def is_pointer_to_struct_type(self, objtype): # def is_pointer_to_union_type(self, objtype): # def is_pointer_to_void_type(self, objtype): # def is_struct_type(self, objtype): # def is_union_type(self, objtype): # def __str__(self): # class CTypesProxy(object): # class c_longdouble(self.__real_ctypes.Union): # class _T_Simple(_ctypes._SimpleCData,): # class _T(_T_Simple,): # class CString(self.__real_ctypes.Union): # class CWString(self.__real_ctypes.Union): # class _FUNC_T(self._T_Simple,): . Output only the next line.
ctypes = types.load_ctypes_default()
Based on the snippet: <|code_start|> try: # i'm lazy. Heap validation could be 10 chunks deep. # but we validate _is_heap by looking at the mapping size sizes = [ size for ( addr, size) in validator.iter_user_allocations( mapping)] size = sum(sizes) except ValueError as e: log.debug(e) return False except NotImplementedError as e: # file absent log.debug(e) return False # FIXME: is malloc word size dependent if size != (len(mapping) - target_platform.get_word_size() * len(sizes)): log.debug( 'expected %d/%d bytes, got %d' % (len(mapping), len(mapping) - 2 * target_platform.get_word_size() * len(sizes), size)) return False return True <|code_end|> , predict the immediate next line with the help of imports: import ctypes import logging import sys from haystack import listmodel and context (classes, functions, sometimes code) from other files: # Path: haystack/listmodel.py # class ListModel(basicmodel.CTypesRecordConstraintValidator): # def is_single_linked_list_type(self, record_type): # def is_double_linked_list_type(self, record_type): # def get_single_linked_list_type(self, record_type): # def get_double_linked_list_type(self, record_type): # def register_single_linked_list_record_type(self, record_type, forward, sentinels=None): # def register_double_linked_list_record_type(self, record_type, forward, backward, sentinels=None): # def register_linked_list_field_and_type(self, record_type, field_name, list_entry_type, list_entry_field_name): # def _get_list_info_for_field_for(self, record_type, fieldname): # def _get_list_fields(self, record_type): # def iterate_list_from_field(self, record, fieldname, sentinels=None, ignore_head=True): # def iterate_list_from_pointer_field(self, pointer_field, target_fieldname, sentinels=None): # def _iterate_list_from_field_with_link_info(self, record, link_info, sentinels=None, ignore_head=True): # def _iterate_list_from_field_inner(self, iterator_fn, head, pointee_record_type, offset, sentinels): # def _iterate_double_linked_list(self, record, sentinels=None): # def _iterate_single_linked_list(self, record, sentinels=None): # def is_valid(self, record): # def load_members(self, record, max_depth): # def _load_list_entries(self, record, link_iterator, max_depth): . Output only the next line.
class LibcHeapValidator(listmodel.ListModel):
Given snippet: <|code_start|> register_linked_list_field_and_type(struct_Items, 'list_of_items', struct_Items, 'list_of_items') register_linked_list_field_and_type(struct_Items2, 'list_of_items', struct_Items2, 'list_of_items') In case of a single link list: register_single_linked_list_record_type(struct_SListEntry, 'next') register_linked_list_field_and_type(struct_Items, 'list_of_items', struct_SubItems, 'siblings') register_linked_list_field_and_type(struct_SubItems, 'siblings', struct_SubItems, 'siblings') In the case of a double linked list of siblings: register_double_linked_list_record_type(struct_DoubleListEntry, 'next', 'previous') register_linked_list_field_and_type(struct_Node, 'list_of_nodes', struct_DoubleListEntry, 'list_of_nodes') In the case of a double linked list of child elements with siblings: register_double_linked_list_record_type(struct_DoubleListEntry, 'next', 'previous') register_linked_list_field_and_type(struct_Root, 'children', struct_Child, 'siblings') register_linked_list_field_and_type(struct_Child, 'siblings', struct_Child, 'siblings') In code usage: use _iterate_list_from_field_with_link_info(record, fieldname, sentinel_values) to iterate on elements of the list. """ log = logging.getLogger('listmodel') <|code_end|> , continue by predicting the next line. Consider current file imports: import ctypes import logging import traceback from haystack import basicmodel from haystack import constraints and context: # Path: haystack/basicmodel.py # def get_field_type(record, fieldname): # def get_fields(record): # def get_record_type_fields(record_type): # def __init__(self, memory_handler, my_constraints, target_ctypes=None): # def _get_constraints_for(self, record): # def _get_dynamic_constraints_for(self, record): # def get_orig_addr(self, record): # def is_valid(self, record): # def _is_valid_dynamic_constraints(self, record): # def _is_valid(self, record, record_constraints): # def _is_valid_attr(self, attr, attrname, attrtype, record_constraints): # def _is_loadable_member(self, attr, attrname, attrtype): # def load_members(self, record, max_depth): # def _load_member(self, record, attr, attrname, attrtype, record_constraints, max_depth): # def is_valid_address(self, obj, structType=None): # def is_valid_address_value(self, addr, structType=None): # def __str__(self): # class CTypesRecordConstraintValidator(interfaces.IRecordConstraintsValidator): # MAX_CSTRING_SIZE = 1024 # # Path: haystack/constraints.py # class ConstraintsConfigHandler(interfaces.IConstraintsConfigHandler): # class ModuleConstraints(interfaces.IModuleConstraints): # class RecordConstraints(interfaces.IRecordConstraints, dict): # class IgnoreMember(interfaces.IConstraint): # class ListLimitDepthValidation(interfaces.IConstraint): # class RangeValue(interfaces.IConstraint): # class NotValue(interfaces.IConstraint): # class NotNullComparable(interfaces.IConstraint): # class BytesComparable(interfaces.IConstraint): # def read(self, filename): # def _parse(self, value): # def _parse_c(self, value): # def _try_numbers(self, _arg): # def __init__(self): # def get_constraints(self): # def set_constraints(self, record_type_name, record_constraints): # def get_dynamic_constraints(self): # def set_dynamic_constraints(self, record_type_name, record_constraints): # def get_fields(self): # def get_constraints_for_field(self, field_name): # def __contains__(self, obj): # def __init__(self, max_depth): # def __contains__(self, obj): # def __init__(self, low, high): # def __contains__(self, obj): # def __eq__(self, obj): # def __init__(self, not_value): # def __contains__(self, obj): # def __eq__(self, obj): # def __contains__(self, obj): # def __eq__(self, obj): # def __init__(self, seq): # def __contains__(self, obj): # def __cmp__(self, obj): which might include code, classes, or functions. Output only the next line.
class ListModel(basicmodel.CTypesRecordConstraintValidator):
Predict the next line after this snippet: <|code_start|> if not isinstance(record, ctypes.Structure) and not isinstance(record, ctypes.Union): raise TypeError('Feed me a ctypes record instance') if max_depth <= 0: log.debug('Maximum depth reach. Not loading any deeper members.') log.debug('Struct partially LOADED. %s not loaded', record.__class__.__name__) return True if max_depth > 100: raise RuntimeError('max_depth') log.debug('-+ <%s> ListModel load_members +- @%x', record.__class__.__name__, record._orig_address_) if not super(ListModel, self).load_members(record, max_depth): log.debug('basicmodel returned False') return False # now try to load the list members log.debug('d:%d load list elements members recursively on %s @%x ', max_depth, type(record).__name__, record._orig_address_) if self.is_single_linked_list_type(type(record)): # we cannot devine what the element of the list are gonna be. return True elif self.is_double_linked_list_type(type(record)): # we cannot devine what the element of the list are gonna be. return True try: record_constraints = self._get_constraints_for(record) # we look at the list we know about for link_info in self._get_list_fields(type(record)): attrname = link_info[0] ignore = False # shorcut ignores if attrname in record_constraints: for constraint in record_constraints[attrname]: <|code_end|> using the current file's imports: import ctypes import logging import traceback from haystack import basicmodel from haystack import constraints and any relevant context from other files: # Path: haystack/basicmodel.py # def get_field_type(record, fieldname): # def get_fields(record): # def get_record_type_fields(record_type): # def __init__(self, memory_handler, my_constraints, target_ctypes=None): # def _get_constraints_for(self, record): # def _get_dynamic_constraints_for(self, record): # def get_orig_addr(self, record): # def is_valid(self, record): # def _is_valid_dynamic_constraints(self, record): # def _is_valid(self, record, record_constraints): # def _is_valid_attr(self, attr, attrname, attrtype, record_constraints): # def _is_loadable_member(self, attr, attrname, attrtype): # def load_members(self, record, max_depth): # def _load_member(self, record, attr, attrname, attrtype, record_constraints, max_depth): # def is_valid_address(self, obj, structType=None): # def is_valid_address_value(self, addr, structType=None): # def __str__(self): # class CTypesRecordConstraintValidator(interfaces.IRecordConstraintsValidator): # MAX_CSTRING_SIZE = 1024 # # Path: haystack/constraints.py # class ConstraintsConfigHandler(interfaces.IConstraintsConfigHandler): # class ModuleConstraints(interfaces.IModuleConstraints): # class RecordConstraints(interfaces.IRecordConstraints, dict): # class IgnoreMember(interfaces.IConstraint): # class ListLimitDepthValidation(interfaces.IConstraint): # class RangeValue(interfaces.IConstraint): # class NotValue(interfaces.IConstraint): # class NotNullComparable(interfaces.IConstraint): # class BytesComparable(interfaces.IConstraint): # def read(self, filename): # def _parse(self, value): # def _parse_c(self, value): # def _try_numbers(self, _arg): # def __init__(self): # def get_constraints(self): # def set_constraints(self, record_type_name, record_constraints): # def get_dynamic_constraints(self): # def set_dynamic_constraints(self, record_type_name, record_constraints): # def get_fields(self): # def get_constraints_for_field(self, field_name): # def __contains__(self, obj): # def __init__(self, max_depth): # def __contains__(self, obj): # def __init__(self, low, high): # def __contains__(self, obj): # def __eq__(self, obj): # def __init__(self, not_value): # def __contains__(self, obj): # def __eq__(self, obj): # def __contains__(self, obj): # def __eq__(self, obj): # def __init__(self, seq): # def __contains__(self, obj): # def __cmp__(self, obj): . Output only the next line.
if constraint is constraints.IgnoreMember:
Given snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- log = logging.getLogger('testwinxpheap') class TestWinXPHeapValidator(unittest.TestCase): @classmethod def setUpClass(cls): cls._memory_handler = folder.load(zeus_1668_vmtoolsd_exe.dumpname) cls._utils = cls._memory_handler.get_target_platform().get_target_ctypes_utils() return @classmethod def tearDownClass(cls): cls._utils = None cls._memory_handler.reset_mappings() cls._memory_handler = None return def setUp(self): self._heap_finder = self._memory_handler.get_heap_finder() <|code_end|> , continue by predicting the next line. Consider current file imports: import logging import unittest from haystack.outputters import text from haystack.mappings import folder from test.testfiles import zeus_1668_vmtoolsd_exe and context: # Path: haystack/outputters/text.py # class RecursiveTextOutputter(Outputter): # def parse(self, obj, prefix='', depth=10, addr_was=None): # def _attrToString(self, attr, field, attrtype, prefix, addr, depth=-1): # # Path: haystack/mappings/folder.py # MMAP_HACK_ACTIVE = True # MAX_MAPPING_SIZE_FOR_MMAP = 1024 * 1024 * 20 # class LazyLoadingException(Exception): # class MemoryDumpLoader(interfaces.IMemoryLoader): # class ProcessMemoryDumpLoader(MemoryDumpLoader): # class LazyProcessMemoryDumpLoader(ProcessMemoryDumpLoader): # class VeryLazyProcessMemoryDumpLoader(LazyProcessMemoryDumpLoader): # class FolderLoader(interfaces.IMemoryLoader): # def __init__(self, filename): # def __init__(self, dumpname, bits=None, os_name=None): # def make_memory_handler(self): # def _is_valid(self): # def _load_mappings(self): # def _is_valid(self): # def _test_dir(self): # def _protected_open_file(self, mmap_fname, mmap_pathname): # def _load_mappings(self): # def _load_metadata(self): # def _load_memory_mappings(self): # def __init__(self, dumpname, maps_to_load=None, bits=None, os_name=None): # def _protected_open_file(self, mmap_fname, mmap_pathname): # def _load_memory_mappings(self): # def load(dumpname, bits=None, os_name=None): # def __init__(self, opts): # def make_memory_handler(self): which might include code, classes, or functions. Output only the next line.
self.parser = text.RecursiveTextOutputter(self._memory_handler)
Using the snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- log = logging.getLogger('testwinxpheap') class TestWinXPHeapValidator(unittest.TestCase): @classmethod def setUpClass(cls): <|code_end|> , determine the next line of code. You have imports: import logging import unittest from haystack.outputters import text from haystack.mappings import folder from test.testfiles import zeus_1668_vmtoolsd_exe and context (class names, function names, or code) available: # Path: haystack/outputters/text.py # class RecursiveTextOutputter(Outputter): # def parse(self, obj, prefix='', depth=10, addr_was=None): # def _attrToString(self, attr, field, attrtype, prefix, addr, depth=-1): # # Path: haystack/mappings/folder.py # MMAP_HACK_ACTIVE = True # MAX_MAPPING_SIZE_FOR_MMAP = 1024 * 1024 * 20 # class LazyLoadingException(Exception): # class MemoryDumpLoader(interfaces.IMemoryLoader): # class ProcessMemoryDumpLoader(MemoryDumpLoader): # class LazyProcessMemoryDumpLoader(ProcessMemoryDumpLoader): # class VeryLazyProcessMemoryDumpLoader(LazyProcessMemoryDumpLoader): # class FolderLoader(interfaces.IMemoryLoader): # def __init__(self, filename): # def __init__(self, dumpname, bits=None, os_name=None): # def make_memory_handler(self): # def _is_valid(self): # def _load_mappings(self): # def _is_valid(self): # def _test_dir(self): # def _protected_open_file(self, mmap_fname, mmap_pathname): # def _load_mappings(self): # def _load_metadata(self): # def _load_memory_mappings(self): # def __init__(self, dumpname, maps_to_load=None, bits=None, os_name=None): # def _protected_open_file(self, mmap_fname, mmap_pathname): # def _load_memory_mappings(self): # def load(dumpname, bits=None, os_name=None): # def __init__(self, opts): # def make_memory_handler(self): . Output only the next line.
cls._memory_handler = folder.load(zeus_1668_vmtoolsd_exe.dumpname)
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for haystack.reverse.structure.""" __author__ = "Loic Jaquemet" __copyright__ = "Copyright (C) 2012 Loic Jaquemet" __license__ = "GPL" __maintainer__ = "Loic Jaquemet" __email__ = "loic.jaquemet+python@gmail.com" __status__ = "Production" log = logging.getLogger("test_libcheapwalker") class TestLibcHeapFinder(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_list_heap_walkers(self): <|code_end|> with the help of current file imports: import logging import unittest from haystack.mappings import folder and context from other files: # Path: haystack/mappings/folder.py # MMAP_HACK_ACTIVE = True # MAX_MAPPING_SIZE_FOR_MMAP = 1024 * 1024 * 20 # class LazyLoadingException(Exception): # class MemoryDumpLoader(interfaces.IMemoryLoader): # class ProcessMemoryDumpLoader(MemoryDumpLoader): # class LazyProcessMemoryDumpLoader(ProcessMemoryDumpLoader): # class VeryLazyProcessMemoryDumpLoader(LazyProcessMemoryDumpLoader): # class FolderLoader(interfaces.IMemoryLoader): # def __init__(self, filename): # def __init__(self, dumpname, bits=None, os_name=None): # def make_memory_handler(self): # def _is_valid(self): # def _load_mappings(self): # def _is_valid(self): # def _test_dir(self): # def _protected_open_file(self, mmap_fname, mmap_pathname): # def _load_mappings(self): # def _load_metadata(self): # def _load_memory_mappings(self): # def __init__(self, dumpname, maps_to_load=None, bits=None, os_name=None): # def _protected_open_file(self, mmap_fname, mmap_pathname): # def _load_memory_mappings(self): # def load(dumpname, bits=None, os_name=None): # def __init__(self, opts): # def make_memory_handler(self): , which may contain function names, class names, or code. Output only the next line.
memory_handler = folder.load('test/src/test-ctypes1.64.dump')
Continue the code snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests haystack.model .""" class TestCopyModule(unittest.TestCase): @classmethod def setUpClass(cls): cls.memory_handler = process.make_local_memory_handler() cls.my_target = cls.memory_handler.get_target_platform() <|code_end|> . Use current file imports: import logging import unittest from haystack import model from haystack.mappings import process and context (classes, functions, or code) from other files: # Path: haystack/model.py # class NotValid(Exception): # class LoadException(Exception): # class Model(object): # def __init__(self, ctypes_module): # def reset(self): # def __create_POPO_classes(self, targetmodule): # def build_python_class_clones(self, targetmodule): # def get_pythoned_modules(self): # def get_pythoned_module(self, name): # def import_module(self, module_name): # def get_imported_modules(self): # def get_imported_module(self, name): # def copy_generated_classes(src_module, dst_module): # def import_module_for_target_ctypes(module_name, target_ctypes): # # Path: haystack/mappings/process.py # PROC_MAP_REGEX = re.compile( # # Address range: '08048000-080b0000 ' # r'([0-9a-f]+)-([0-9a-f]+) ' # # Permission: 'r-xp ' # r'(.{4}) ' # # Offset: '0804d000' # r'([0-9a-f]+) ' # # Device (major:minor): 'fe:01 ' # r'([0-9a-f]{2}):([0-9a-f]{2}) ' # # Inode: '3334030' # r'([0-9]+)' # # Filename: ' /usr/bin/synergyc' # r'(?: +(.*))?') # __LOCAL_MAPPINGS = None # __LOCAL_MAPPINGS = make_process_memory_handler(dbg.MyPTraceProcess(os.getpid(), None)) # class ProcessMemoryMapping(AMemoryMapping): # class ProcessLoader(interfaces.IMemoryLoader): # def __init__(self, process, start, end, permissions, offset, # major_device, minor_device, inode, pathname): # def read_word(self, address): # def read_bytes(self, address, size): # def read_struct(self, address, _struct): # def read_array(self, address, basetype, count): # def is_mmaped(self): # def mmap(self): # def rebase(self, new_start_address): # def reset(self): # def __getstate__(self): # def make_process_memory_handler(process): # def make_local_memory_handler(force=False): # def __init__(self, opts): # def make_memory_handler(self): . Output only the next line.
cls.my_model = model.Model(cls.my_target.get_target_ctypes())
Given snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests haystack.model .""" class TestCopyModule(unittest.TestCase): @classmethod def setUpClass(cls): <|code_end|> , continue by predicting the next line. Consider current file imports: import logging import unittest from haystack import model from haystack.mappings import process and context: # Path: haystack/model.py # class NotValid(Exception): # class LoadException(Exception): # class Model(object): # def __init__(self, ctypes_module): # def reset(self): # def __create_POPO_classes(self, targetmodule): # def build_python_class_clones(self, targetmodule): # def get_pythoned_modules(self): # def get_pythoned_module(self, name): # def import_module(self, module_name): # def get_imported_modules(self): # def get_imported_module(self, name): # def copy_generated_classes(src_module, dst_module): # def import_module_for_target_ctypes(module_name, target_ctypes): # # Path: haystack/mappings/process.py # PROC_MAP_REGEX = re.compile( # # Address range: '08048000-080b0000 ' # r'([0-9a-f]+)-([0-9a-f]+) ' # # Permission: 'r-xp ' # r'(.{4}) ' # # Offset: '0804d000' # r'([0-9a-f]+) ' # # Device (major:minor): 'fe:01 ' # r'([0-9a-f]{2}):([0-9a-f]{2}) ' # # Inode: '3334030' # r'([0-9]+)' # # Filename: ' /usr/bin/synergyc' # r'(?: +(.*))?') # __LOCAL_MAPPINGS = None # __LOCAL_MAPPINGS = make_process_memory_handler(dbg.MyPTraceProcess(os.getpid(), None)) # class ProcessMemoryMapping(AMemoryMapping): # class ProcessLoader(interfaces.IMemoryLoader): # def __init__(self, process, start, end, permissions, offset, # major_device, minor_device, inode, pathname): # def read_word(self, address): # def read_bytes(self, address, size): # def read_struct(self, address, _struct): # def read_array(self, address, basetype, count): # def is_mmaped(self): # def mmap(self): # def rebase(self, new_start_address): # def reset(self): # def __getstate__(self): # def make_process_memory_handler(process): # def make_local_memory_handler(force=False): # def __init__(self, opts): # def make_memory_handler(self): which might include code, classes, or functions. Output only the next line.
cls.memory_handler = process.make_local_memory_handler()
Here is a snippet: <|code_start|># Copyright (C) 2011 Loic Jaquemet loic.jaquemet+python@gmail.com # from __future__ import print_function log = logging.getLogger('libdl') class Dl_info(ctypes.Structure): _fields_ = [ # Pathname of shared object that contains address ('dli_fname', ctypes.c_char_p), # Address at which shared object is loaded ('dli_fbase', ctypes.c_void_p), # Name of nearest symbol with address lower than addr ('dli_sname', ctypes.c_char_p), # Exact address of symbol named in dli_sname ('dli_saddr', ctypes.c_void_p) ] class Dummy(): pass def getMappings(): me = Dummy() me.pid = os.getpid() <|code_end|> . Write the next line using the current file imports: import ctypes import logging import os import pickle import pickle from haystack.mappings.process import make_process_memory_handler and context from other files: # Path: haystack/mappings/process.py # def make_process_memory_handler(process): # """ # Read all memory mappings of the specified process. # # Return a list of MemoryMapping objects, or empty list if it's not possible # to read the memory mappings. # # May raise a ProcessError. # """ # if not isinstance(process, dbg.IProcess): # raise TypeError('dbg.IProcess expected') # mapsfile = process.get_mappings_line() # # mappings = [] # is_64 = False # # read the mappings # for line in mapsfile: # line = line.rstrip() # match = PROC_MAP_REGEX.match(line) # if not match: # raise IOError(process, "Unable to parse memory mapping: %r" % line) # if not is_64 and len(match.group(1)) > 8: # is_64 = True # # # log.debug('readProcessMappings %s' % (str(match.groups()))) # _map = ProcessMemoryMapping(process, int(match.group(1), 16), int(match.group(2), 16), # match.group(3), int(match.group(4), 16), int(match.group(5), 16), # int(match.group(6), 16), int(match.group(7)), match.group(8)) # mappings.append(_map) # # create the memory_handler for self # import sys # if 'linux' in sys.platform: # os_name = target.TargetPlatform.LINUX # else: # sys.platform.startswith('win'): # os_name = target.TargetPlatform.WIN7 # _target_platform = None # if is_64: # if os_name in [target.TargetPlatform.WINXP, target.TargetPlatform.WIN7]: # _target_platform = target.TargetPlatform.make_target_win_64(os_name) # elif os_name == target.TargetPlatform.LINUX: # _target_platform = target.TargetPlatform.make_target_linux_64() # else: # if os_name in [target.TargetPlatform.WINXP, target.TargetPlatform.WIN7]: # _target_platform = target.TargetPlatform.make_target_win_32(os_name) # elif os_name == target.TargetPlatform.LINUX: # _target_platform = target.TargetPlatform.make_target_linux_32() # _memory_handler = MemoryHandler(mappings, _target_platform, 'localhost-%d' % process.get_pid()) # return _memory_handler , which may include functions, classes, or code. Output only the next line.
return make_process_memory_handler(me)
Given snippet: <|code_start|> # output handling output = api.output_to_python(memory_handler, results) py_obj = output[0][0] def base_argparser(program_name, description): """ Base options shared by all console scripts """ rootparser = argparse.ArgumentParser(prog=program_name, description=description) verbosity = rootparser.add_mutually_exclusive_group(required=False) verbosity.add_argument('--debug', dest='debug', action='store_true', help='Set verbosity to DEBUG') verbosity.add_argument('--quiet', dest='quiet', action='store_true', help='Set verbosity to ERROR only') rootparser.add_argument('--interactive', dest='interactive', action='store_true', help='drop to python command line after action') rootparser.add_argument('--nommap', dest='mmap', action='store_false', help='disable mmap()-ing') rootparser.add_argument('--osname', '-n', action='store', default=None, choices=['linux', 'winxp', 'win7'], help='Force a specific OS') rootparser.add_argument('--bits', '-b', type=int, action='store', default=None, choices=[32, 64], help='Force a specific word size') text = '://, '.join(sorted(SUPPORTED_DUMP_URI.keys())) + '://' help_desc = 'target file or process. Supported URL types: %s' % text rootparser.add_argument('target', type=url, help=help_desc) return rootparser def search_argparser(search_parser): """ Search function options argument parser """ search_parser.add_argument('record_type_name', type=str, help='Python record type name. Module must be in Python path') search_parser.add_argument('--constraints_file', type=argparse.FileType('r'), help='Filename that contains Constraints for the record types in the module') search_parser.add_argument('--extended', action='store_true', help='Do not restrict the search to allocated chunks') <|code_end|> , continue by predicting the next line. Consider current file imports: import argparse import logging import os import sys import time import pkg_resources import code import code from urllib.parse import urlparse from urlparse import urlparse from haystack import argparse_utils from haystack import basicmodel from haystack import constraints from haystack.search import api from haystack.mappings import rek and context: # Path: haystack/argparse_utils.py # def readable(f): # def writeable(f): # def int16(s): # # Path: haystack/basicmodel.py # def get_field_type(record, fieldname): # def get_fields(record): # def get_record_type_fields(record_type): # def __init__(self, memory_handler, my_constraints, target_ctypes=None): # def _get_constraints_for(self, record): # def _get_dynamic_constraints_for(self, record): # def get_orig_addr(self, record): # def is_valid(self, record): # def _is_valid_dynamic_constraints(self, record): # def _is_valid(self, record, record_constraints): # def _is_valid_attr(self, attr, attrname, attrtype, record_constraints): # def _is_loadable_member(self, attr, attrname, attrtype): # def load_members(self, record, max_depth): # def _load_member(self, record, attr, attrname, attrtype, record_constraints, max_depth): # def is_valid_address(self, obj, structType=None): # def is_valid_address_value(self, addr, structType=None): # def __str__(self): # class CTypesRecordConstraintValidator(interfaces.IRecordConstraintsValidator): # MAX_CSTRING_SIZE = 1024 # # Path: haystack/constraints.py # class ConstraintsConfigHandler(interfaces.IConstraintsConfigHandler): # class ModuleConstraints(interfaces.IModuleConstraints): # class RecordConstraints(interfaces.IRecordConstraints, dict): # class IgnoreMember(interfaces.IConstraint): # class ListLimitDepthValidation(interfaces.IConstraint): # class RangeValue(interfaces.IConstraint): # class NotValue(interfaces.IConstraint): # class NotNullComparable(interfaces.IConstraint): # class BytesComparable(interfaces.IConstraint): # def read(self, filename): # def _parse(self, value): # def _parse_c(self, value): # def _try_numbers(self, _arg): # def __init__(self): # def get_constraints(self): # def set_constraints(self, record_type_name, record_constraints): # def get_dynamic_constraints(self): # def set_dynamic_constraints(self, record_type_name, record_constraints): # def get_fields(self): # def get_constraints_for_field(self, field_name): # def __contains__(self, obj): # def __init__(self, max_depth): # def __contains__(self, obj): # def __init__(self, low, high): # def __contains__(self, obj): # def __eq__(self, obj): # def __init__(self, not_value): # def __contains__(self, obj): # def __eq__(self, obj): # def __contains__(self, obj): # def __eq__(self, obj): # def __init__(self, seq): # def __contains__(self, obj): # def __cmp__(self, obj): # # Path: haystack/search/api.py # class HaystackError(Exception): # def search_record(memory_handler, record_type, search_constraints=None, extended_search=False): # def search_record_hint(memory_handler, record_type, hint, search_constraints=None, extended_search=False): # def output_to_string(memory_handler, results): # def output_to_python(memory_handler, results): # def output_to_json(memory_handler, results): # def output_to_pickle(memory_handler, results): # def load_record(memory_handler, struct_type, memory_address, load_constraints=None): # def validate_record(memory_handler, instance, record_constraints=None, max_depth=10): which might include code, classes, or functions. Output only the next line.
search_parser.add_argument('--hint', type=argparse_utils.int16,
Using the snippet: <|code_start|> # validate if required validation = None if args.constraints_file: handler = constraints.ConstraintsConfigHandler() my_constraints = handler.read(args.constraints_file.name) validation = api.validate_record(memory_handler, result[0], my_constraints) # output handling ret = None try: ret = get_output(memory_handler, results, args.output) # print output on stdout print(ret) if args.constraints_file: print('Validated', validation) except Exception as e: log.error(e) finally: if args.interactive: print('results are local variable "results"') code.interact(local=locals()) return def check_varname_for_type(memory_handler, varname, struct_type): done = [] st = struct_type model = memory_handler.get_model() ctypes = memory_handler.get_target_platform().get_target_ctypes() for v in varname: if not hasattr(st, v): <|code_end|> , determine the next line of code. You have imports: import argparse import logging import os import sys import time import pkg_resources import code import code from urllib.parse import urlparse from urlparse import urlparse from haystack import argparse_utils from haystack import basicmodel from haystack import constraints from haystack.search import api from haystack.mappings import rek and context (class names, function names, or code) available: # Path: haystack/argparse_utils.py # def readable(f): # def writeable(f): # def int16(s): # # Path: haystack/basicmodel.py # def get_field_type(record, fieldname): # def get_fields(record): # def get_record_type_fields(record_type): # def __init__(self, memory_handler, my_constraints, target_ctypes=None): # def _get_constraints_for(self, record): # def _get_dynamic_constraints_for(self, record): # def get_orig_addr(self, record): # def is_valid(self, record): # def _is_valid_dynamic_constraints(self, record): # def _is_valid(self, record, record_constraints): # def _is_valid_attr(self, attr, attrname, attrtype, record_constraints): # def _is_loadable_member(self, attr, attrname, attrtype): # def load_members(self, record, max_depth): # def _load_member(self, record, attr, attrname, attrtype, record_constraints, max_depth): # def is_valid_address(self, obj, structType=None): # def is_valid_address_value(self, addr, structType=None): # def __str__(self): # class CTypesRecordConstraintValidator(interfaces.IRecordConstraintsValidator): # MAX_CSTRING_SIZE = 1024 # # Path: haystack/constraints.py # class ConstraintsConfigHandler(interfaces.IConstraintsConfigHandler): # class ModuleConstraints(interfaces.IModuleConstraints): # class RecordConstraints(interfaces.IRecordConstraints, dict): # class IgnoreMember(interfaces.IConstraint): # class ListLimitDepthValidation(interfaces.IConstraint): # class RangeValue(interfaces.IConstraint): # class NotValue(interfaces.IConstraint): # class NotNullComparable(interfaces.IConstraint): # class BytesComparable(interfaces.IConstraint): # def read(self, filename): # def _parse(self, value): # def _parse_c(self, value): # def _try_numbers(self, _arg): # def __init__(self): # def get_constraints(self): # def set_constraints(self, record_type_name, record_constraints): # def get_dynamic_constraints(self): # def set_dynamic_constraints(self, record_type_name, record_constraints): # def get_fields(self): # def get_constraints_for_field(self, field_name): # def __contains__(self, obj): # def __init__(self, max_depth): # def __contains__(self, obj): # def __init__(self, low, high): # def __contains__(self, obj): # def __eq__(self, obj): # def __init__(self, not_value): # def __contains__(self, obj): # def __eq__(self, obj): # def __contains__(self, obj): # def __eq__(self, obj): # def __init__(self, seq): # def __contains__(self, obj): # def __cmp__(self, obj): # # Path: haystack/search/api.py # class HaystackError(Exception): # def search_record(memory_handler, record_type, search_constraints=None, extended_search=False): # def search_record_hint(memory_handler, record_type, hint, search_constraints=None, extended_search=False): # def output_to_string(memory_handler, results): # def output_to_python(memory_handler, results): # def output_to_json(memory_handler, results): # def output_to_pickle(memory_handler, results): # def load_record(memory_handler, struct_type, memory_address, load_constraints=None): # def validate_record(memory_handler, instance, record_constraints=None, max_depth=10): . Output only the next line.
fields = ["%s: %s" % (n, t) for n, t in basicmodel.get_fields(st)]
Predict the next line after this snippet: <|code_start|> if rtype == 'string': ret = api.output_to_string(memory_handler, results) elif rtype == 'python': # useful in interactive mode ret = api.output_to_python(memory_handler, results) elif rtype == 'json': ret = api.output_to_json(memory_handler, results) elif rtype == 'pickled': ret = api.output_to_pickle(memory_handler, results) else: raise ValueError('unknown output format') return ret def dump_process(opts): """ Extract the process dump from the OS memory dump in haystack format. """ if opts.dumptype == DUMPTYPE_VOLATILITY: pass elif opts.dumptype == DUMPTYPE_REKALL: rek.rekall_dump_to_haystack(opts.dump_filename, opts.pid, opts.output_folder_name) return def search_cmdline(args): """ Search for instance of a record_type in the allocated memory of a process. """ # get the memory handler adequate for the type requested memory_handler = make_memory_handler(args) # try to load constraints my_constraints = None if args.constraints_file: <|code_end|> using the current file's imports: import argparse import logging import os import sys import time import pkg_resources import code import code from urllib.parse import urlparse from urlparse import urlparse from haystack import argparse_utils from haystack import basicmodel from haystack import constraints from haystack.search import api from haystack.mappings import rek and any relevant context from other files: # Path: haystack/argparse_utils.py # def readable(f): # def writeable(f): # def int16(s): # # Path: haystack/basicmodel.py # def get_field_type(record, fieldname): # def get_fields(record): # def get_record_type_fields(record_type): # def __init__(self, memory_handler, my_constraints, target_ctypes=None): # def _get_constraints_for(self, record): # def _get_dynamic_constraints_for(self, record): # def get_orig_addr(self, record): # def is_valid(self, record): # def _is_valid_dynamic_constraints(self, record): # def _is_valid(self, record, record_constraints): # def _is_valid_attr(self, attr, attrname, attrtype, record_constraints): # def _is_loadable_member(self, attr, attrname, attrtype): # def load_members(self, record, max_depth): # def _load_member(self, record, attr, attrname, attrtype, record_constraints, max_depth): # def is_valid_address(self, obj, structType=None): # def is_valid_address_value(self, addr, structType=None): # def __str__(self): # class CTypesRecordConstraintValidator(interfaces.IRecordConstraintsValidator): # MAX_CSTRING_SIZE = 1024 # # Path: haystack/constraints.py # class ConstraintsConfigHandler(interfaces.IConstraintsConfigHandler): # class ModuleConstraints(interfaces.IModuleConstraints): # class RecordConstraints(interfaces.IRecordConstraints, dict): # class IgnoreMember(interfaces.IConstraint): # class ListLimitDepthValidation(interfaces.IConstraint): # class RangeValue(interfaces.IConstraint): # class NotValue(interfaces.IConstraint): # class NotNullComparable(interfaces.IConstraint): # class BytesComparable(interfaces.IConstraint): # def read(self, filename): # def _parse(self, value): # def _parse_c(self, value): # def _try_numbers(self, _arg): # def __init__(self): # def get_constraints(self): # def set_constraints(self, record_type_name, record_constraints): # def get_dynamic_constraints(self): # def set_dynamic_constraints(self, record_type_name, record_constraints): # def get_fields(self): # def get_constraints_for_field(self, field_name): # def __contains__(self, obj): # def __init__(self, max_depth): # def __contains__(self, obj): # def __init__(self, low, high): # def __contains__(self, obj): # def __eq__(self, obj): # def __init__(self, not_value): # def __contains__(self, obj): # def __eq__(self, obj): # def __contains__(self, obj): # def __eq__(self, obj): # def __init__(self, seq): # def __contains__(self, obj): # def __cmp__(self, obj): # # Path: haystack/search/api.py # class HaystackError(Exception): # def search_record(memory_handler, record_type, search_constraints=None, extended_search=False): # def search_record_hint(memory_handler, record_type, hint, search_constraints=None, extended_search=False): # def output_to_string(memory_handler, results): # def output_to_python(memory_handler, results): # def output_to_json(memory_handler, results): # def output_to_pickle(memory_handler, results): # def load_record(memory_handler, struct_type, memory_address, load_constraints=None): # def validate_record(memory_handler, instance, record_constraints=None, max_depth=10): . Output only the next line.
handler = constraints.ConstraintsConfigHandler()
Based on the snippet: <|code_start|> path = _url.path.split(':')[0] if scheme in ['dir', 'volatility', 'rekall', 'dmp']: if not os.path.exists(path): raise argparse.ArgumentTypeError("Target {p} does not exists".format(p=path)) # see url.netloc for host name, frida ? live ? return _url # the description of the dump type DUMPTYPE_BASE_DESC = 'The process dump is a folder produced by a haystack-dump script.' DUMPTYPE_VOL_DESC = 'The process dump is a volatility OS dump. The PID is the targeted process.' DUMPTYPE_REKALL_DESC = 'The process dump is a rekall OS dump. The PID is the targeted process.' DUMPTYPE_LIVE_DESC = 'The PID must be a running process.' DUMPTYPE_MINIDUMP_DESC = 'The process dump is a Minidump (MDMP) process dump.' class HaystackError(Exception): pass def make_memory_handler(opts): dumptype = opts.target.scheme.lower() if dumptype not in SUPPORTED_DUMP_URI.keys(): raise TypeError('dump type has no case support. %s' % dumptype) loader = SUPPORTED_DUMP_URI[dumptype](opts) return loader.make_memory_handler() def get_output(memory_handler, results, rtype): if rtype == 'string': <|code_end|> , predict the immediate next line with the help of imports: import argparse import logging import os import sys import time import pkg_resources import code import code from urllib.parse import urlparse from urlparse import urlparse from haystack import argparse_utils from haystack import basicmodel from haystack import constraints from haystack.search import api from haystack.mappings import rek and context (classes, functions, sometimes code) from other files: # Path: haystack/argparse_utils.py # def readable(f): # def writeable(f): # def int16(s): # # Path: haystack/basicmodel.py # def get_field_type(record, fieldname): # def get_fields(record): # def get_record_type_fields(record_type): # def __init__(self, memory_handler, my_constraints, target_ctypes=None): # def _get_constraints_for(self, record): # def _get_dynamic_constraints_for(self, record): # def get_orig_addr(self, record): # def is_valid(self, record): # def _is_valid_dynamic_constraints(self, record): # def _is_valid(self, record, record_constraints): # def _is_valid_attr(self, attr, attrname, attrtype, record_constraints): # def _is_loadable_member(self, attr, attrname, attrtype): # def load_members(self, record, max_depth): # def _load_member(self, record, attr, attrname, attrtype, record_constraints, max_depth): # def is_valid_address(self, obj, structType=None): # def is_valid_address_value(self, addr, structType=None): # def __str__(self): # class CTypesRecordConstraintValidator(interfaces.IRecordConstraintsValidator): # MAX_CSTRING_SIZE = 1024 # # Path: haystack/constraints.py # class ConstraintsConfigHandler(interfaces.IConstraintsConfigHandler): # class ModuleConstraints(interfaces.IModuleConstraints): # class RecordConstraints(interfaces.IRecordConstraints, dict): # class IgnoreMember(interfaces.IConstraint): # class ListLimitDepthValidation(interfaces.IConstraint): # class RangeValue(interfaces.IConstraint): # class NotValue(interfaces.IConstraint): # class NotNullComparable(interfaces.IConstraint): # class BytesComparable(interfaces.IConstraint): # def read(self, filename): # def _parse(self, value): # def _parse_c(self, value): # def _try_numbers(self, _arg): # def __init__(self): # def get_constraints(self): # def set_constraints(self, record_type_name, record_constraints): # def get_dynamic_constraints(self): # def set_dynamic_constraints(self, record_type_name, record_constraints): # def get_fields(self): # def get_constraints_for_field(self, field_name): # def __contains__(self, obj): # def __init__(self, max_depth): # def __contains__(self, obj): # def __init__(self, low, high): # def __contains__(self, obj): # def __eq__(self, obj): # def __init__(self, not_value): # def __contains__(self, obj): # def __eq__(self, obj): # def __contains__(self, obj): # def __eq__(self, obj): # def __init__(self, seq): # def __contains__(self, obj): # def __cmp__(self, obj): # # Path: haystack/search/api.py # class HaystackError(Exception): # def search_record(memory_handler, record_type, search_constraints=None, extended_search=False): # def search_record_hint(memory_handler, record_type, hint, search_constraints=None, extended_search=False): # def output_to_string(memory_handler, results): # def output_to_python(memory_handler, results): # def output_to_json(memory_handler, results): # def output_to_pickle(memory_handler, results): # def load_record(memory_handler, struct_type, memory_address, load_constraints=None): # def validate_record(memory_handler, instance, record_constraints=None, max_depth=10): . Output only the next line.
ret = api.output_to_string(memory_handler, results)
Here is a snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2011 Loic Jaquemet loic.jaquemet+python@gmail.com # try: except ImportError as e: """ This module holds some basic constraint class for the Haystack model. """ __author__ = "Loic Jaquemet loic.jaquemet+python@gmail.com" log = logging.getLogger('constraints') <|code_end|> . Write the next line using the current file imports: import ConfigParser as configparser import configparser import logging import numbers import os import re import sys import ctypes from haystack.abc import interfaces and context from other files: # Path: haystack/abc/interfaces.py # class IMemoryMapping(object): # class IMemoryLoader(object): # class IMemoryHandler(object): # class IMemoryCache(object): # class ITargetPlatform(object): # class IHeapFinder(object): # class IHeapWalker(object): # class ICTypesUtils(object): # class IConstraintsConfigHandler(object): # class IModuleConstraints(object): # class IRecordConstraints(object): # class IConstraint(object): # class IRecordConstraintsValidator(object): # class IRecordTypeDynamicConstraintsValidator(object): # def _vtop(self, vaddr): # def _ptov(self, paddr): # def read_array(self, address, basetype, count): # def read_bytes(self, address, size): # def read_cstring(self, address, max_size, chunk_length=256): # def read_struct(self, address, struct): # def read_word(self, address): # def search(self, bytestr): # def __contains__(self, address): # def __len__(self): # def make_memory_handler(self): # def get_name(self): # def get_target_platform(self): # def get_heap_finder(self): # def get_model(self): # def get_mappings(self): # def reset_mappings(self): # def get_reverse_context(self): # def get_mapping_for_address(self, vaddr): # def iter_mapping_with_name(self, pathname): # def is_valid_address(self, obj, struct_type=None): # def is_valid_address_value(self, addr, struct_type=None): # def __contains__(self, vaddr): # def __len__(self): # def __getitem__(self, i): # def __setitem__(self, i, val): # def __iter__(self): # def reset(self): # def getRefs(self): # def printRefs(self): # def printRefsLite(self): # def hasRef(self, typ, orig_addr): # def getRef(self, typ, orig_addr): # def getRefByAddr(self, addr): # def keepRef(self, obj, typ=None, orig_addr=None): # def delRef(self, typ, orig_addr): # def get_word_type(self): # def get_word_type_char(self): # def get_word_size(self): # def get_target_ctypes(self): # def get_target_ctypes_utils(self): # def get_os_name(self): # def get_cpu_bits(self): # def list_heap_walkers(self): # def get_heap_module(self): # def get_heap_walker(self, heap): # def get_target_platform(self): # def get_heap_address(self): # def get_user_allocations(self): # def get_free_chunks(self): # def formatAddress(self, addr): # def unpackWord(self, bytes, endianess): # def is_address_local(self, obj, structType): # def get_pointee_address(self, obj): # def container_of(self, memberaddr, typ, membername): # def offsetof(self, typ, membername): # def ctypes_to_python_array(self, array): # def array2bytes(self, array): # def bytes2array(self, bytes, typ): # def pointer2bytes(self, attr, nbElement): # def get_subtype(self, cls): # def read(self, filename): # def get_constraints(self): # def set_constraints(self, record_type_name, record_constraints): # def get_dynamic_constraints(self): # def set_dynamic_constraints(self, record_type_name, record_constraints): # def get_fields(self): # def get_constraints_for_field(self, field_name): # def __contains__(self, obj): # def is_valid(self, record): # def load_members(self, record, max_depth): # def get_record_type_name(self): # def is_valid(self, record): , which may include functions, classes, or code. Output only the next line.
class ConstraintsConfigHandler(interfaces.IConstraintsConfigHandler):
Here is a snippet: <|code_start|>b6efa000-b6f01000 r--p 00296000 08:04 3426931 /usr/lib/i386-linux-gnu/libQtCore.so.4.7.4 b6f01000-b6f04000 rw-p 0029d000 08:04 3426931 /usr/lib/i386-linux-gnu/libQtCore.so.4.7.4 ''' offset = 0xb6b3ef68 - 0xb68b1000 class Dummy(): pass class Dl_info(ctypes.Structure): _fields_ = [ # Pathname of shared object that contains address ('dli_fname', ctypes.c_char_p), # Address at which shared object is loaded ('dli_fbase', ctypes.c_void_p), # Name of nearest symbol with address lower than addr ('dli_sname', ctypes.c_char_p), # Exact address of symbol named in dli_sname ('dli_saddr', ctypes.c_void_p) ] def getMappings(): me = Dummy() me.pid = os.getpid() <|code_end|> . Write the next line using the current file imports: import struct import sys import ctypes import os from haystack.mappings.process import make_process_memory_handler from haystack.reverse import context and context from other files: # Path: haystack/mappings/process.py # def make_process_memory_handler(process): # """ # Read all memory mappings of the specified process. # # Return a list of MemoryMapping objects, or empty list if it's not possible # to read the memory mappings. # # May raise a ProcessError. # """ # if not isinstance(process, dbg.IProcess): # raise TypeError('dbg.IProcess expected') # mapsfile = process.get_mappings_line() # # mappings = [] # is_64 = False # # read the mappings # for line in mapsfile: # line = line.rstrip() # match = PROC_MAP_REGEX.match(line) # if not match: # raise IOError(process, "Unable to parse memory mapping: %r" % line) # if not is_64 and len(match.group(1)) > 8: # is_64 = True # # # log.debug('readProcessMappings %s' % (str(match.groups()))) # _map = ProcessMemoryMapping(process, int(match.group(1), 16), int(match.group(2), 16), # match.group(3), int(match.group(4), 16), int(match.group(5), 16), # int(match.group(6), 16), int(match.group(7)), match.group(8)) # mappings.append(_map) # # create the memory_handler for self # import sys # if 'linux' in sys.platform: # os_name = target.TargetPlatform.LINUX # else: # sys.platform.startswith('win'): # os_name = target.TargetPlatform.WIN7 # _target_platform = None # if is_64: # if os_name in [target.TargetPlatform.WINXP, target.TargetPlatform.WIN7]: # _target_platform = target.TargetPlatform.make_target_win_64(os_name) # elif os_name == target.TargetPlatform.LINUX: # _target_platform = target.TargetPlatform.make_target_linux_64() # else: # if os_name in [target.TargetPlatform.WINXP, target.TargetPlatform.WIN7]: # _target_platform = target.TargetPlatform.make_target_win_32(os_name) # elif os_name == target.TargetPlatform.LINUX: # _target_platform = target.TargetPlatform.make_target_linux_32() # _memory_handler = MemoryHandler(mappings, _target_platform, 'localhost-%d' % process.get_pid()) # return _memory_handler , which may include functions, classes, or code. Output only the next line.
return make_process_memory_handler(me)
Using the snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- class Test(unittest.TestCase): def test_readable(self): """test the readable helper.""" invalid = '/345678ui0d9t921giv9' <|code_end|> , determine the next line of code. You have imports: import logging import unittest import sys import argparse from haystack import argparse_utils and context (class names, function names, or code) available: # Path: haystack/argparse_utils.py # def readable(f): # def writeable(f): # def int16(s): . Output only the next line.
self.assertRaises(argparse.ArgumentTypeError, argparse_utils.readable, invalid)
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- log = logging.getLogger('heapwalker') SUPPORTED_ALLOCATORS = {} def _discover_supported_allocators(): # TODO use it in memory dump discovery. Maybe add platform selectors to Finder interface for entry_point in pkg_resources.iter_entry_points("haystack.heap_finder"): SUPPORTED_ALLOCATORS[entry_point.name] = entry_point.resolve() <|code_end|> , predict the next line using imports from the current file: import logging import pkg_resources from haystack.abc import interfaces from haystack.allocators.libc import libcheapwalker from haystack.allocators.win32 import winxpheapwalker from haystack.allocators.win32 import win7heapwalker and context including class names, function names, and sometimes code from other files: # Path: haystack/abc/interfaces.py # class IMemoryMapping(object): # class IMemoryLoader(object): # class IMemoryHandler(object): # class IMemoryCache(object): # class ITargetPlatform(object): # class IHeapFinder(object): # class IHeapWalker(object): # class ICTypesUtils(object): # class IConstraintsConfigHandler(object): # class IModuleConstraints(object): # class IRecordConstraints(object): # class IConstraint(object): # class IRecordConstraintsValidator(object): # class IRecordTypeDynamicConstraintsValidator(object): # def _vtop(self, vaddr): # def _ptov(self, paddr): # def read_array(self, address, basetype, count): # def read_bytes(self, address, size): # def read_cstring(self, address, max_size, chunk_length=256): # def read_struct(self, address, struct): # def read_word(self, address): # def search(self, bytestr): # def __contains__(self, address): # def __len__(self): # def make_memory_handler(self): # def get_name(self): # def get_target_platform(self): # def get_heap_finder(self): # def get_model(self): # def get_mappings(self): # def reset_mappings(self): # def get_reverse_context(self): # def get_mapping_for_address(self, vaddr): # def iter_mapping_with_name(self, pathname): # def is_valid_address(self, obj, struct_type=None): # def is_valid_address_value(self, addr, struct_type=None): # def __contains__(self, vaddr): # def __len__(self): # def __getitem__(self, i): # def __setitem__(self, i, val): # def __iter__(self): # def reset(self): # def getRefs(self): # def printRefs(self): # def printRefsLite(self): # def hasRef(self, typ, orig_addr): # def getRef(self, typ, orig_addr): # def getRefByAddr(self, addr): # def keepRef(self, obj, typ=None, orig_addr=None): # def delRef(self, typ, orig_addr): # def get_word_type(self): # def get_word_type_char(self): # def get_word_size(self): # def get_target_ctypes(self): # def get_target_ctypes_utils(self): # def get_os_name(self): # def get_cpu_bits(self): # def list_heap_walkers(self): # def get_heap_module(self): # def get_heap_walker(self, heap): # def get_target_platform(self): # def get_heap_address(self): # def get_user_allocations(self): # def get_free_chunks(self): # def formatAddress(self, addr): # def unpackWord(self, bytes, endianess): # def is_address_local(self, obj, structType): # def get_pointee_address(self, obj): # def container_of(self, memberaddr, typ, membername): # def offsetof(self, typ, membername): # def ctypes_to_python_array(self, array): # def array2bytes(self, array): # def bytes2array(self, bytes, typ): # def pointer2bytes(self, attr, nbElement): # def get_subtype(self, cls): # def read(self, filename): # def get_constraints(self): # def set_constraints(self, record_type_name, record_constraints): # def get_dynamic_constraints(self): # def set_dynamic_constraints(self, record_type_name, record_constraints): # def get_fields(self): # def get_constraints_for_field(self, field_name): # def __contains__(self, obj): # def is_valid(self, record): # def load_members(self, record, max_depth): # def get_record_type_name(self): # def is_valid(self, record): . Output only the next line.
class HeapWalker(interfaces.IHeapWalker):
Based on the snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for haystack.reverse.structure.""" log = logging.getLogger('testwin7heap') class TestWin7Heap(unittest.TestCase): @classmethod def setUpClass(cls): cls.memory_handler = folder.load(putty_1_win7.dumpname) return @classmethod def tearDownClass(cls): cls.memory_handler.reset_mappings() cls.memory_handler = None return def test_ctypes_sizes(self): """putty.1.dump is a win7 32 bits memory dump""" <|code_end|> , predict the immediate next line with the help of imports: import logging import sys import unittest from haystack.allocators.win32 import win7heapwalker from haystack.mappings import folder from test.testfiles import putty_1_win7 and context (classes, functions, sometimes code) from other files: # Path: haystack/allocators/win32/win7heapwalker.py # class Win7HeapWalker(winheapwalker.WinHeapWalker): # class Win7HeapFinder(winheapwalker.WinHeapFinder): # def _create_validator(self): # def _validator_type(self): # def _walker_type(self): # def _make_dual_arch_ctypes(self): # def _get_heap_possible_kernel_pointer_from_heap(self, target_platform, heap): # # Path: haystack/mappings/folder.py # MMAP_HACK_ACTIVE = True # MAX_MAPPING_SIZE_FOR_MMAP = 1024 * 1024 * 20 # class LazyLoadingException(Exception): # class MemoryDumpLoader(interfaces.IMemoryLoader): # class ProcessMemoryDumpLoader(MemoryDumpLoader): # class LazyProcessMemoryDumpLoader(ProcessMemoryDumpLoader): # class VeryLazyProcessMemoryDumpLoader(LazyProcessMemoryDumpLoader): # class FolderLoader(interfaces.IMemoryLoader): # def __init__(self, filename): # def __init__(self, dumpname, bits=None, os_name=None): # def make_memory_handler(self): # def _is_valid(self): # def _load_mappings(self): # def _is_valid(self): # def _test_dir(self): # def _protected_open_file(self, mmap_fname, mmap_pathname): # def _load_mappings(self): # def _load_metadata(self): # def _load_memory_mappings(self): # def __init__(self, dumpname, maps_to_load=None, bits=None, os_name=None): # def _protected_open_file(self, mmap_fname, mmap_pathname): # def _load_memory_mappings(self): # def load(dumpname, bits=None, os_name=None): # def __init__(self, opts): # def make_memory_handler(self): . Output only the next line.
finder = win7heapwalker.Win7HeapFinder(self.memory_handler)
Using the snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for haystack.reverse.structure.""" log = logging.getLogger('testwin7heap') class TestWin7Heap(unittest.TestCase): @classmethod def setUpClass(cls): <|code_end|> , determine the next line of code. You have imports: import logging import sys import unittest from haystack.allocators.win32 import win7heapwalker from haystack.mappings import folder from test.testfiles import putty_1_win7 and context (class names, function names, or code) available: # Path: haystack/allocators/win32/win7heapwalker.py # class Win7HeapWalker(winheapwalker.WinHeapWalker): # class Win7HeapFinder(winheapwalker.WinHeapFinder): # def _create_validator(self): # def _validator_type(self): # def _walker_type(self): # def _make_dual_arch_ctypes(self): # def _get_heap_possible_kernel_pointer_from_heap(self, target_platform, heap): # # Path: haystack/mappings/folder.py # MMAP_HACK_ACTIVE = True # MAX_MAPPING_SIZE_FOR_MMAP = 1024 * 1024 * 20 # class LazyLoadingException(Exception): # class MemoryDumpLoader(interfaces.IMemoryLoader): # class ProcessMemoryDumpLoader(MemoryDumpLoader): # class LazyProcessMemoryDumpLoader(ProcessMemoryDumpLoader): # class VeryLazyProcessMemoryDumpLoader(LazyProcessMemoryDumpLoader): # class FolderLoader(interfaces.IMemoryLoader): # def __init__(self, filename): # def __init__(self, dumpname, bits=None, os_name=None): # def make_memory_handler(self): # def _is_valid(self): # def _load_mappings(self): # def _is_valid(self): # def _test_dir(self): # def _protected_open_file(self, mmap_fname, mmap_pathname): # def _load_mappings(self): # def _load_metadata(self): # def _load_memory_mappings(self): # def __init__(self, dumpname, maps_to_load=None, bits=None, os_name=None): # def _protected_open_file(self, mmap_fname, mmap_pathname): # def _load_memory_mappings(self): # def load(dumpname, bits=None, os_name=None): # def __init__(self, opts): # def make_memory_handler(self): . Output only the next line.
cls.memory_handler = folder.load(putty_1_win7.dumpname)
Next line prediction: <|code_start|> def tearDown(self): if self.process is not None: try: self.process.kill() except OSError as e: pass for f in self.tgts: if os.path.isfile(f): os.remove(f) elif os.path.isdir(f): shutil.rmtree(f) def _make_tgt_dir(self): tgt = tempfile.mkdtemp() self.tgts.append(tgt) return tgt def _renew_process(self): self.process.kill() self.process = self.run_app_test('test3', stdout=self.devnull.fileno()) time.sleep(0.1) def test_mappings_file(self): '''Checks if memory_dumper make a _memory_handler index file''' tgt1 = self._make_tgt_dir() self.devnull = open('/dev/null') self.process = self.run_app_test('test1', stdout=self.devnull.fileno()) time.sleep(0.1) # FIXME, heaponly is breaking machine detection. <|code_end|> . Use current file imports: (import logging import os import shutil import subprocess import sys import tempfile import time import unittest import os import haystack.api import haystack.api import haystack.api from haystack import memory_dumper from haystack import types from haystack.mappings import folder from haystack.mappings.base import MemoryHandler) and context including class names, function names, or small code snippets from other files: # Path: haystack/memory_dumper.py # class MemoryDumper: # ARCHIVE_TYPES = ["dir", "tar", "gztar"] # def __init__(self, pid, dest): # def make_mappings(self): # def dump(self, dest=None): # def _dump_all_mappings_winapp(self, destdir): # def _dump_all_mappings(self, destdir): # def _free_process(self): # def _dump_mapping(self, m, tmpdir): # def dump(pid, outfile): # def _dump(opt): # def argparser(): # def main(): . Output only the next line.
out1 = memory_dumper.dump(self.process.pid, tgt1, "dir", True)