Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Given snippet: <|code_start|>""" Description: Test module for module src/factory/simple_factory.py @author: Paul Bodean @date: 10/08/2017 """ class TestSimpleFactory(TestCase): """ Check simple factory functionality """ def setUp(self): """ Driver + factory setup :return: driver :rtype: object """ driver = get_selenium_driver('chrome') driver.set_window_size(1200, 800) driver.get('https://www.youtube.com/') <|code_end|> , continue by predicting the next line. Consider current file imports: from unittest import TestCase from src.factory.simple_factory import App from src.utils import get_selenium_driver and context: # Path: src/factory/simple_factory.py # class App(object): # """ # # """ # # def __init__(self, driver: Union[Chrome, Firefox]): # """ # # :param driver: browser driver # :type driver: object # """ # self.__driver = driver # # def factory(self, page: str): # """ # The access method which handles pages selection # :type page: str # """ # if page == 'Menu': # return Menu(self.__driver) # elif page == 'Search': # return Search(self.__driver) # else: # raise NotImplemented # # Path: src/utils.py # def get_selenium_driver(browser_name: str) -> Union[Chrome, Firefox]: # """ # Return the same instance to the Selenium driver. # # :param browser_name: the name of the browser: chrome or mozilla # :type browser_name: str # :return: an instance of the required driver. # :rtype: Union[Chrome, Mozilla] # """ # if browser_name.upper() == 'CHROME': # return SingletonFactory.build(Chrome) # # elif browser_name.upper() == 'Mozilla': # return SingletonFactory.build(Firefox) # # else: # raise NotImplementedError which might include code, classes, or functions. Output only the next line.
return driver, App(driver)
Based on the snippet: <|code_start|>""" Description: Test module for module src/factory/simple_factory.py @author: Paul Bodean @date: 10/08/2017 """ class TestSimpleFactory(TestCase): """ Check simple factory functionality """ def setUp(self): """ Driver + factory setup :return: driver :rtype: object """ <|code_end|> , predict the immediate next line with the help of imports: from unittest import TestCase from src.factory.simple_factory import App from src.utils import get_selenium_driver and context (classes, functions, sometimes code) from other files: # Path: src/factory/simple_factory.py # class App(object): # """ # # """ # # def __init__(self, driver: Union[Chrome, Firefox]): # """ # # :param driver: browser driver # :type driver: object # """ # self.__driver = driver # # def factory(self, page: str): # """ # The access method which handles pages selection # :type page: str # """ # if page == 'Menu': # return Menu(self.__driver) # elif page == 'Search': # return Search(self.__driver) # else: # raise NotImplemented # # Path: src/utils.py # def get_selenium_driver(browser_name: str) -> Union[Chrome, Firefox]: # """ # Return the same instance to the Selenium driver. # # :param browser_name: the name of the browser: chrome or mozilla # :type browser_name: str # :return: an instance of the required driver. # :rtype: Union[Chrome, Mozilla] # """ # if browser_name.upper() == 'CHROME': # return SingletonFactory.build(Chrome) # # elif browser_name.upper() == 'Mozilla': # return SingletonFactory.build(Firefox) # # else: # raise NotImplementedError . Output only the next line.
driver = get_selenium_driver('chrome')
Given snippet: <|code_start|> self.__builder.get_flow() # Make comparison if self.__builder.get_post_validation(): self.__status = True else: self.__status = False else: self.__status = False # Post results self.__builder.get_report(self.__status) # Close driver self.__builder.close() class Test: """ Represent the complex object under construction. """ def __init__(self): pass class Builder(metaclass=abc.ABCMeta): """ Abstract interface for defining parts of the Product """ def __init__(self): <|code_end|> , continue by predicting the next line. Consider current file imports: import abc from src.utils import get_selenium_driver and context: # Path: src/utils.py # def get_selenium_driver(browser_name: str) -> Union[Chrome, Firefox]: # """ # Return the same instance to the Selenium driver. # # :param browser_name: the name of the browser: chrome or mozilla # :type browser_name: str # :return: an instance of the required driver. # :rtype: Union[Chrome, Mozilla] # """ # if browser_name.upper() == 'CHROME': # return SingletonFactory.build(Chrome) # # elif browser_name.upper() == 'Mozilla': # return SingletonFactory.build(Firefox) # # else: # raise NotImplementedError which might include code, classes, or functions. Output only the next line.
self._driver = get_selenium_driver('chrome')
Next line prediction: <|code_start|>""" Description: - Check Driver connection following both singleton approaches @author: Paul Bodean @date: 26/12/2017 """ class TestDecoratorSingleton(TestCase): def test_singleton(self): dr1 = Driver() dr1.get_driver().get('https://en.wikipedia.org/') dr2 = Driver() self.assertEqual(dr1, dr2) def test_my_singleton(self): <|code_end|> . Use current file imports: (from unittest import TestCase from src.singleton.singleton_decor import MyDriver, Driver) and context including class names, function names, or small code snippets from other files: # Path: src/singleton/singleton_decor.py # class MyDriver: # @staticmethod # def get_driver(): # return webdriver.Chrome() # # class Driver: # @staticmethod # def get_driver(): # return webdriver.Chrome() . Output only the next line.
dr1 = MyDriver()
Continue the code snippet: <|code_start|>""" Description: - Check Driver connection following both singleton approaches @author: Paul Bodean @date: 26/12/2017 """ class TestDecoratorSingleton(TestCase): def test_singleton(self): <|code_end|> . Use current file imports: from unittest import TestCase from src.singleton.singleton_decor import MyDriver, Driver and context (classes, functions, or code) from other files: # Path: src/singleton/singleton_decor.py # class MyDriver: # @staticmethod # def get_driver(): # return webdriver.Chrome() # # class Driver: # @staticmethod # def get_driver(): # return webdriver.Chrome() . Output only the next line.
dr1 = Driver()
Continue the code snippet: <|code_start|>Description: Test module for module src/factory/simple_factory.py @author: Paul Bodean @date: 12/08/2017 """ class TestFactoryMethod(TestCase): """ Check simple factory functionality """ def setUp(self): """ Driver + factory setup :return: driver :rtype: object """ self.dr = get_selenium_driver('chrome') self.dr.set_window_size(1200, 800) self.dr.get('https://www.youtube.com/') def test_menu_and_search(self): """ Perform some clicks and search for a song """ # driver = self.setUp() <|code_end|> . Use current file imports: from unittest import TestCase from src.factory.factory_method import MenuAndSearchTest from src.utils import get_selenium_driver import time and context (classes, functions, or code) from other files: # Path: src/factory/factory_method.py # class MenuAndSearchTest(TemplateTest): # """ # Implement a test case for checking menu and search # """ # # def __init__(self, driver: Union[Chrome, Firefox]): # """ # # :param driver: browser driver # :type driver: object # """ # self.__driver = driver # super().__init__() # # def create_test(self): # """ # # :return: sections to be tested # :rtype: dict # """ # self.add_sections('menu', MenuComponent(self.__driver)) # self.add_sections('search', SearchComponent(self.__driver)) # # Path: src/utils.py # def get_selenium_driver(browser_name: str) -> Union[Chrome, Firefox]: # """ # Return the same instance to the Selenium driver. # # :param browser_name: the name of the browser: chrome or mozilla # :type browser_name: str # :return: an instance of the required driver. # :rtype: Union[Chrome, Mozilla] # """ # if browser_name.upper() == 'CHROME': # return SingletonFactory.build(Chrome) # # elif browser_name.upper() == 'Mozilla': # return SingletonFactory.build(Firefox) # # else: # raise NotImplementedError . Output only the next line.
demo = MenuAndSearchTest(self.dr)
Here is a snippet: <|code_start|>""" Description: Test module for module src/factory/simple_factory.py @author: Paul Bodean @date: 12/08/2017 """ class TestFactoryMethod(TestCase): """ Check simple factory functionality """ def setUp(self): """ Driver + factory setup :return: driver :rtype: object """ <|code_end|> . Write the next line using the current file imports: from unittest import TestCase from src.factory.factory_method import MenuAndSearchTest from src.utils import get_selenium_driver import time and context from other files: # Path: src/factory/factory_method.py # class MenuAndSearchTest(TemplateTest): # """ # Implement a test case for checking menu and search # """ # # def __init__(self, driver: Union[Chrome, Firefox]): # """ # # :param driver: browser driver # :type driver: object # """ # self.__driver = driver # super().__init__() # # def create_test(self): # """ # # :return: sections to be tested # :rtype: dict # """ # self.add_sections('menu', MenuComponent(self.__driver)) # self.add_sections('search', SearchComponent(self.__driver)) # # Path: src/utils.py # def get_selenium_driver(browser_name: str) -> Union[Chrome, Firefox]: # """ # Return the same instance to the Selenium driver. # # :param browser_name: the name of the browser: chrome or mozilla # :type browser_name: str # :return: an instance of the required driver. # :rtype: Union[Chrome, Mozilla] # """ # if browser_name.upper() == 'CHROME': # return SingletonFactory.build(Chrome) # # elif browser_name.upper() == 'Mozilla': # return SingletonFactory.build(Firefox) # # else: # raise NotImplementedError , which may include functions, classes, or code. Output only the next line.
self.dr = get_selenium_driver('chrome')
Predict the next line for this snippet: <|code_start|>""" Implement a test flow using facade pattern. The flow will be a unified high-level interface for all the pages which composes the test app """ class FacadePage: """ Facade class delegates the client requests to the actual subsystems """ __driver = get_selenium_driver('chrome') def get_driver(self): """ :return: selenium driver """ return self.__driver @staticmethod def get_home_page(): """ Implement home page sub-system :return: HomePage class """ <|code_end|> with the help of current file imports: from src.page_object_pattern.home_page import HomePage from src.page_object_pattern.search_page import SearchPage from src.utils import get_selenium_driver and context from other files: # Path: src/page_object_pattern/home_page.py # class HomePage(BasePage): # """ # Home page # """ # SEARCH_CONTAINER = 'searchInput' # SEARCH_BUTTON = 'searchButton' # CREATE_ACCOUNT = 'pt-createaccount' # LOGIN = 'pt-login' # # def set_search_query(self, query: str): # """ # Search for a string # :param query: string you are looking for # """ # self._driver.find_element_by_id(HomePage.SEARCH_CONTAINER).send_keys(query) # # def check_search(self): # """ # Check search button is visible # """ # return self._driver.find_element_by_id(HomePage.SEARCH_BUTTON).is_displayed() # # def search(self): # """ # Click on search button # """ # self._driver.find_element_by_id(HomePage.SEARCH_BUTTON).click() # # def check_login(self): # """ # Check Login button is visible # """ # return self._driver.find_element_by_id(HomePage.LOGIN).is_displayed() # # def login(self): # """ # Press login button # """ # self._driver.find_element_by_id(HomePage.LOGIN).click() # # def check_create_account(self): # """ # Check create account button available # """ # return self._driver.find_element_by_id(HomePage.CREATE_ACCOUNT).is_displayed() # # def create_account(self): # """ # Press create account button # """ # self._driver.find_element_by_id(HomePage.CREATE_ACCOUNT).click() # # Path: src/page_object_pattern/search_page.py # class SearchPage(BasePage): # """ # Search page # """ # HEADING = 'firstHeading' # SEE_ALSO = 'See_also' # DOMAIN_ARTICLES = 'Domain-specific_articles' # READING = 'Further_reading' # REF = 'References' # EXTERNAL_LINKS = 'External_links' # # def heading_text(self): # """ # :return: Get the heading text # """ # return self._driver.find_element_by_id(SearchPage.HEADING).text # # def see_also_text(self): # """ # :return: see also text # """ # return self._driver.find_element_by_xpath(SearchPage.SEE_ALSO).text # # def domain_articles_text(self): # """ # :return: domain article title # """ # return self._driver.find_element_by_xpath(SearchPage.DOMAIN_ARTICLES).text # # def reading_text(self): # """ # :return: reading text # """ # return self._driver.find_element_by_xpath(SearchPage.READING).text # # def ref_text(self): # """ # :return: reference text value # """ # return self._driver.find_element_by_xpath(SearchPage.REF).text # # def external_links_text(self): # """ # :return: external links text value # """ # return self._driver.find_element_by_xpath(SearchPage.EXTERNAL_LINKS).text # # Path: src/utils.py # def get_selenium_driver(browser_name: str) -> Union[Chrome, Firefox]: # """ # Return the same instance to the Selenium driver. # # :param browser_name: the name of the browser: chrome or mozilla # :type browser_name: str # :return: an instance of the required driver. # :rtype: Union[Chrome, Mozilla] # """ # if browser_name.upper() == 'CHROME': # return SingletonFactory.build(Chrome) # # elif browser_name.upper() == 'Mozilla': # return SingletonFactory.build(Firefox) # # else: # raise NotImplementedError , which may contain function names, class names, or code. Output only the next line.
return HomePage(FacadePage.__driver)
Here is a snippet: <|code_start|>""" class FacadePage: """ Facade class delegates the client requests to the actual subsystems """ __driver = get_selenium_driver('chrome') def get_driver(self): """ :return: selenium driver """ return self.__driver @staticmethod def get_home_page(): """ Implement home page sub-system :return: HomePage class """ return HomePage(FacadePage.__driver) @staticmethod def get_search_page(): """ Implement search page sub-system :return: SearchPage class """ <|code_end|> . Write the next line using the current file imports: from src.page_object_pattern.home_page import HomePage from src.page_object_pattern.search_page import SearchPage from src.utils import get_selenium_driver and context from other files: # Path: src/page_object_pattern/home_page.py # class HomePage(BasePage): # """ # Home page # """ # SEARCH_CONTAINER = 'searchInput' # SEARCH_BUTTON = 'searchButton' # CREATE_ACCOUNT = 'pt-createaccount' # LOGIN = 'pt-login' # # def set_search_query(self, query: str): # """ # Search for a string # :param query: string you are looking for # """ # self._driver.find_element_by_id(HomePage.SEARCH_CONTAINER).send_keys(query) # # def check_search(self): # """ # Check search button is visible # """ # return self._driver.find_element_by_id(HomePage.SEARCH_BUTTON).is_displayed() # # def search(self): # """ # Click on search button # """ # self._driver.find_element_by_id(HomePage.SEARCH_BUTTON).click() # # def check_login(self): # """ # Check Login button is visible # """ # return self._driver.find_element_by_id(HomePage.LOGIN).is_displayed() # # def login(self): # """ # Press login button # """ # self._driver.find_element_by_id(HomePage.LOGIN).click() # # def check_create_account(self): # """ # Check create account button available # """ # return self._driver.find_element_by_id(HomePage.CREATE_ACCOUNT).is_displayed() # # def create_account(self): # """ # Press create account button # """ # self._driver.find_element_by_id(HomePage.CREATE_ACCOUNT).click() # # Path: src/page_object_pattern/search_page.py # class SearchPage(BasePage): # """ # Search page # """ # HEADING = 'firstHeading' # SEE_ALSO = 'See_also' # DOMAIN_ARTICLES = 'Domain-specific_articles' # READING = 'Further_reading' # REF = 'References' # EXTERNAL_LINKS = 'External_links' # # def heading_text(self): # """ # :return: Get the heading text # """ # return self._driver.find_element_by_id(SearchPage.HEADING).text # # def see_also_text(self): # """ # :return: see also text # """ # return self._driver.find_element_by_xpath(SearchPage.SEE_ALSO).text # # def domain_articles_text(self): # """ # :return: domain article title # """ # return self._driver.find_element_by_xpath(SearchPage.DOMAIN_ARTICLES).text # # def reading_text(self): # """ # :return: reading text # """ # return self._driver.find_element_by_xpath(SearchPage.READING).text # # def ref_text(self): # """ # :return: reference text value # """ # return self._driver.find_element_by_xpath(SearchPage.REF).text # # def external_links_text(self): # """ # :return: external links text value # """ # return self._driver.find_element_by_xpath(SearchPage.EXTERNAL_LINKS).text # # Path: src/utils.py # def get_selenium_driver(browser_name: str) -> Union[Chrome, Firefox]: # """ # Return the same instance to the Selenium driver. # # :param browser_name: the name of the browser: chrome or mozilla # :type browser_name: str # :return: an instance of the required driver. # :rtype: Union[Chrome, Mozilla] # """ # if browser_name.upper() == 'CHROME': # return SingletonFactory.build(Chrome) # # elif browser_name.upper() == 'Mozilla': # return SingletonFactory.build(Firefox) # # else: # raise NotImplementedError , which may include functions, classes, or code. Output only the next line.
return SearchPage(FacadePage.__driver)
Based on the snippet: <|code_start|>""" Implement a test flow using facade pattern. The flow will be a unified high-level interface for all the pages which composes the test app """ class FacadePage: """ Facade class delegates the client requests to the actual subsystems """ <|code_end|> , predict the immediate next line with the help of imports: from src.page_object_pattern.home_page import HomePage from src.page_object_pattern.search_page import SearchPage from src.utils import get_selenium_driver and context (classes, functions, sometimes code) from other files: # Path: src/page_object_pattern/home_page.py # class HomePage(BasePage): # """ # Home page # """ # SEARCH_CONTAINER = 'searchInput' # SEARCH_BUTTON = 'searchButton' # CREATE_ACCOUNT = 'pt-createaccount' # LOGIN = 'pt-login' # # def set_search_query(self, query: str): # """ # Search for a string # :param query: string you are looking for # """ # self._driver.find_element_by_id(HomePage.SEARCH_CONTAINER).send_keys(query) # # def check_search(self): # """ # Check search button is visible # """ # return self._driver.find_element_by_id(HomePage.SEARCH_BUTTON).is_displayed() # # def search(self): # """ # Click on search button # """ # self._driver.find_element_by_id(HomePage.SEARCH_BUTTON).click() # # def check_login(self): # """ # Check Login button is visible # """ # return self._driver.find_element_by_id(HomePage.LOGIN).is_displayed() # # def login(self): # """ # Press login button # """ # self._driver.find_element_by_id(HomePage.LOGIN).click() # # def check_create_account(self): # """ # Check create account button available # """ # return self._driver.find_element_by_id(HomePage.CREATE_ACCOUNT).is_displayed() # # def create_account(self): # """ # Press create account button # """ # self._driver.find_element_by_id(HomePage.CREATE_ACCOUNT).click() # # Path: src/page_object_pattern/search_page.py # class SearchPage(BasePage): # """ # Search page # """ # HEADING = 'firstHeading' # SEE_ALSO = 'See_also' # DOMAIN_ARTICLES = 'Domain-specific_articles' # READING = 'Further_reading' # REF = 'References' # EXTERNAL_LINKS = 'External_links' # # def heading_text(self): # """ # :return: Get the heading text # """ # return self._driver.find_element_by_id(SearchPage.HEADING).text # # def see_also_text(self): # """ # :return: see also text # """ # return self._driver.find_element_by_xpath(SearchPage.SEE_ALSO).text # # def domain_articles_text(self): # """ # :return: domain article title # """ # return self._driver.find_element_by_xpath(SearchPage.DOMAIN_ARTICLES).text # # def reading_text(self): # """ # :return: reading text # """ # return self._driver.find_element_by_xpath(SearchPage.READING).text # # def ref_text(self): # """ # :return: reference text value # """ # return self._driver.find_element_by_xpath(SearchPage.REF).text # # def external_links_text(self): # """ # :return: external links text value # """ # return self._driver.find_element_by_xpath(SearchPage.EXTERNAL_LINKS).text # # Path: src/utils.py # def get_selenium_driver(browser_name: str) -> Union[Chrome, Firefox]: # """ # Return the same instance to the Selenium driver. # # :param browser_name: the name of the browser: chrome or mozilla # :type browser_name: str # :return: an instance of the required driver. # :rtype: Union[Chrome, Mozilla] # """ # if browser_name.upper() == 'CHROME': # return SingletonFactory.build(Chrome) # # elif browser_name.upper() == 'Mozilla': # return SingletonFactory.build(Firefox) # # else: # raise NotImplementedError . Output only the next line.
__driver = get_selenium_driver('chrome')
Predict the next line after this snippet: <|code_start|>""" Description: Test case implementation based on builder pattern and unittest """ class TestSearchFlow(TestTemplate): """ Test class for testing a search on Wikipedia """ def test_flow(self): """ Test Steps """ <|code_end|> using the current file's imports: from src.builder.builder import SearchFlow, TestManager from src.page_object_pattern.test_template import TestTemplate and any relevant context from other files: # Path: src/builder/builder.py # class SearchFlow(Builder): # """ # Definition of a concrete builder # """ # SEARCH_CONTAINER = 'searchInput' # SEARCH_BUTTON = 'searchButton' # CREATE_ACCOUNT = 'pt-createaccount' # LOGIN = 'pt-login' # HEADING = 'firstHeading' # # def get_pre_validation(self): # """ # Validate if UI is available for the environment to be tested # :return: True or False # """ # return self._driver.find_element_by_id('p-search').is_displayed() # # def get_flow(self): # """ # # :return: True if validation succeeded # """ # self._driver.find_element_by_id(SearchFlow.SEARCH_CONTAINER).send_keys('Design patterns') # self._driver.find_element_by_id(SearchFlow.SEARCH_BUTTON).click() # # def get_post_validation(self): # """ # # :return: True if flow was executed # """ # return self._driver.find_element_by_id(SearchFlow.HEADING).text == 'Design pattern' # # def get_report(self, status): # print("Test execution:", status) # # class TestManager: # """ # Control the construction process, having a builder associated with it # It delegates to the builder the implementation details, # and deliver the already implemented functionality to the client # """ # # __builder = None # __status = True # # def set_manager(self, builder): # """ # Selection of the builder which will construct the product # :param builder: concrete builder which will implement the product # """ # # self.__builder = builder # # def get_test(self): # """ # Prepare the test product to be delivered to a client # """ # # # Pre validation # pre_validation = self.__builder.get_pre_validation() # # Set flow # if pre_validation: # self.__builder.get_flow() # # Make comparison # if self.__builder.get_post_validation(): # self.__status = True # else: # self.__status = False # # else: # self.__status = False # # Post results # self.__builder.get_report(self.__status) # # Close driver # self.__builder.close() # # Path: src/page_object_pattern/test_template.py # class TestTemplate(unittest.TestCase): # def setUp(self): # """ # Open the page to be tested # :return: the driver implementation # """ # # self.driver = webdriver.Chrome() # self.driver.get("https://en.wikipedia.org/wiki/Main_Page") # # def tearDown(self): # """ # Quit the browser # """ # self.driver.quit() . Output only the next line.
home_builder = SearchFlow()
Given the code snippet: <|code_start|>""" Description: Test case implementation based on builder pattern and unittest """ class TestSearchFlow(TestTemplate): """ Test class for testing a search on Wikipedia """ def test_flow(self): """ Test Steps """ home_builder = SearchFlow() <|code_end|> , generate the next line using the imports in this file: from src.builder.builder import SearchFlow, TestManager from src.page_object_pattern.test_template import TestTemplate and context (functions, classes, or occasionally code) from other files: # Path: src/builder/builder.py # class SearchFlow(Builder): # """ # Definition of a concrete builder # """ # SEARCH_CONTAINER = 'searchInput' # SEARCH_BUTTON = 'searchButton' # CREATE_ACCOUNT = 'pt-createaccount' # LOGIN = 'pt-login' # HEADING = 'firstHeading' # # def get_pre_validation(self): # """ # Validate if UI is available for the environment to be tested # :return: True or False # """ # return self._driver.find_element_by_id('p-search').is_displayed() # # def get_flow(self): # """ # # :return: True if validation succeeded # """ # self._driver.find_element_by_id(SearchFlow.SEARCH_CONTAINER).send_keys('Design patterns') # self._driver.find_element_by_id(SearchFlow.SEARCH_BUTTON).click() # # def get_post_validation(self): # """ # # :return: True if flow was executed # """ # return self._driver.find_element_by_id(SearchFlow.HEADING).text == 'Design pattern' # # def get_report(self, status): # print("Test execution:", status) # # class TestManager: # """ # Control the construction process, having a builder associated with it # It delegates to the builder the implementation details, # and deliver the already implemented functionality to the client # """ # # __builder = None # __status = True # # def set_manager(self, builder): # """ # Selection of the builder which will construct the product # :param builder: concrete builder which will implement the product # """ # # self.__builder = builder # # def get_test(self): # """ # Prepare the test product to be delivered to a client # """ # # # Pre validation # pre_validation = self.__builder.get_pre_validation() # # Set flow # if pre_validation: # self.__builder.get_flow() # # Make comparison # if self.__builder.get_post_validation(): # self.__status = True # else: # self.__status = False # # else: # self.__status = False # # Post results # self.__builder.get_report(self.__status) # # Close driver # self.__builder.close() # # Path: src/page_object_pattern/test_template.py # class TestTemplate(unittest.TestCase): # def setUp(self): # """ # Open the page to be tested # :return: the driver implementation # """ # # self.driver = webdriver.Chrome() # self.driver.get("https://en.wikipedia.org/wiki/Main_Page") # # def tearDown(self): # """ # Quit the browser # """ # self.driver.quit() . Output only the next line.
manager = TestManager()
Given the following code snippet before the placeholder: <|code_start|> class Manager: """ State machine manager. Acting as an interface to the client and providing the actual state of the object """ def __init__(self, state): """ :param state: current object state """ self._state = state def get_state(self): """ :return: state getter """ self._state.run() class State(metaclass=abc.ABCMeta): """ Interface definition for behaviour encapsulation """ def __init__(self): <|code_end|> , predict the next line using imports from the current file: import abc from src.utils import get_selenium_driver and context including class names, function names, and sometimes code from other files: # Path: src/utils.py # def get_selenium_driver(browser_name: str) -> Union[Chrome, Firefox]: # """ # Return the same instance to the Selenium driver. # # :param browser_name: the name of the browser: chrome or mozilla # :type browser_name: str # :return: an instance of the required driver. # :rtype: Union[Chrome, Mozilla] # """ # if browser_name.upper() == 'CHROME': # return SingletonFactory.build(Chrome) # # elif browser_name.upper() == 'Mozilla': # return SingletonFactory.build(Firefox) # # else: # raise NotImplementedError . Output only the next line.
self._driver = get_selenium_driver('chrome')
Predict the next line after this snippet: <|code_start|>""" Description: module providing the implementation of the search class of the object pattern pattern class declaration. @author: Paul Bodean @date: 25/07/2017 """ <|code_end|> using the current file's imports: from src.page_object_pattern.base_page import BasePage and any relevant context from other files: # Path: src/page_object_pattern/base_page.py # class BasePage(object): # """ # Base class to initialize the base page that will be called from all pages # """ # # def __init__(self, driver): # self._driver = driver . Output only the next line.
class HomePage(BasePage):
Next line prediction: <|code_start|>""" Different project related utilities like Selenium driver connection """ def get_appium_driver(url, desired_capabilities) -> Remote: """ Return the same instance to the Appium driver. :param url: the URL (address and port) where the service runs. :param desired_capabilities: session configuration data. :return: returns the SAME instance of the driver """ <|code_end|> . Use current file imports: (from typing import Union from selenium.webdriver import Chrome, Firefox from selenium.webdriver import Remote from src.singleton.singleton_factory import SingletonFactory import psutil) and context including class names, function names, or small code snippets from other files: # Path: src/singleton/singleton_factory.py # class SingletonFactory(object): # """ # A factory of the same instances of injected classes. # """ # # # a mapping between the name of a class and the instance. # __mappings = {} # # @staticmethod # def build(class_, **constructor_args): # """ # Builds an instance of the given class pointer together with the provided constructor arguments. # Returns the SAME instance for a given class. # # :param class_: A pointer to the definition of the class. # :param constructor_args: The arguments for the class instance. # :return: An instance of the provided class. # """ # # # if the class instance is mapped, then retrieve it. # if str(class_) in SingletonFactory.__mappings: # instance_ = SingletonFactory.__mappings[str(class_)] # # # else create the instance and map it to the class name. # else: # instance_ = class_(**constructor_args) # SingletonFactory.__mappings[str(class_)] = instance_ # # return instance_ . Output only the next line.
return SingletonFactory.build(Remote,
Given snippet: <|code_start|> def subscribe(self, who): self._observers.add(who) def un_subscribe(self, who): self._observers.discard(who) def dispatch(self,test_func, message): for subscriber in self._observers: if get_process_info_spike(message) >= 50: subscriber.update(test_func, 'CPU usage warning: ' + str(get_process_info_spike(message))) else: subscriber.update(test_func, 'CPU usage normal: ' + str(get_process_info_spike(message))) class Tests: """ Define the observant class """ def __init__(self, name): self.name = name def update(self, test_func, message): test_func() print('{} test measurement - "{}"'.format(self.name, message)) def search_test(): driver = get_selenium_driver('CHROME') driver.get("https://en.wikipedia.org/wiki/Main_Page") <|code_end|> , continue by predicting the next line. Consider current file imports: from src.page_object_pattern.home_page import HomePage from src.utils import get_selenium_driver, get_process_info_spike and context: # Path: src/page_object_pattern/home_page.py # class HomePage(BasePage): # """ # Home page # """ # SEARCH_CONTAINER = 'searchInput' # SEARCH_BUTTON = 'searchButton' # CREATE_ACCOUNT = 'pt-createaccount' # LOGIN = 'pt-login' # # def set_search_query(self, query: str): # """ # Search for a string # :param query: string you are looking for # """ # self._driver.find_element_by_id(HomePage.SEARCH_CONTAINER).send_keys(query) # # def check_search(self): # """ # Check search button is visible # """ # return self._driver.find_element_by_id(HomePage.SEARCH_BUTTON).is_displayed() # # def search(self): # """ # Click on search button # """ # self._driver.find_element_by_id(HomePage.SEARCH_BUTTON).click() # # def check_login(self): # """ # Check Login button is visible # """ # return self._driver.find_element_by_id(HomePage.LOGIN).is_displayed() # # def login(self): # """ # Press login button # """ # self._driver.find_element_by_id(HomePage.LOGIN).click() # # def check_create_account(self): # """ # Check create account button available # """ # return self._driver.find_element_by_id(HomePage.CREATE_ACCOUNT).is_displayed() # # def create_account(self): # """ # Press create account button # """ # self._driver.find_element_by_id(HomePage.CREATE_ACCOUNT).click() # # Path: src/utils.py # def get_selenium_driver(browser_name: str) -> Union[Chrome, Firefox]: # """ # Return the same instance to the Selenium driver. # # :param browser_name: the name of the browser: chrome or mozilla # :type browser_name: str # :return: an instance of the required driver. # :rtype: Union[Chrome, Mozilla] # """ # if browser_name.upper() == 'CHROME': # return SingletonFactory.build(Chrome) # # elif browser_name.upper() == 'Mozilla': # return SingletonFactory.build(Firefox) # # else: # raise NotImplementedError # # def get_process_info_spike(process): # """ # # :param process: get system information like memory consumption, cpu usage # :return: # """ # for process_id in psutil.pids(): # p = psutil.Process(process_id) # if p.name() == 'pycharm': # if process == 'memory': # return p.memory_percent() # elif process == 'cpu': # return p.cpu_percent(interval=1) # else: # return p which might include code, classes, or functions. Output only the next line.
main_page = HomePage(driver)
Given snippet: <|code_start|> def __init__(self): self._observers = set() def subscribe(self, who): self._observers.add(who) def un_subscribe(self, who): self._observers.discard(who) def dispatch(self,test_func, message): for subscriber in self._observers: if get_process_info_spike(message) >= 50: subscriber.update(test_func, 'CPU usage warning: ' + str(get_process_info_spike(message))) else: subscriber.update(test_func, 'CPU usage normal: ' + str(get_process_info_spike(message))) class Tests: """ Define the observant class """ def __init__(self, name): self.name = name def update(self, test_func, message): test_func() print('{} test measurement - "{}"'.format(self.name, message)) def search_test(): <|code_end|> , continue by predicting the next line. Consider current file imports: from src.page_object_pattern.home_page import HomePage from src.utils import get_selenium_driver, get_process_info_spike and context: # Path: src/page_object_pattern/home_page.py # class HomePage(BasePage): # """ # Home page # """ # SEARCH_CONTAINER = 'searchInput' # SEARCH_BUTTON = 'searchButton' # CREATE_ACCOUNT = 'pt-createaccount' # LOGIN = 'pt-login' # # def set_search_query(self, query: str): # """ # Search for a string # :param query: string you are looking for # """ # self._driver.find_element_by_id(HomePage.SEARCH_CONTAINER).send_keys(query) # # def check_search(self): # """ # Check search button is visible # """ # return self._driver.find_element_by_id(HomePage.SEARCH_BUTTON).is_displayed() # # def search(self): # """ # Click on search button # """ # self._driver.find_element_by_id(HomePage.SEARCH_BUTTON).click() # # def check_login(self): # """ # Check Login button is visible # """ # return self._driver.find_element_by_id(HomePage.LOGIN).is_displayed() # # def login(self): # """ # Press login button # """ # self._driver.find_element_by_id(HomePage.LOGIN).click() # # def check_create_account(self): # """ # Check create account button available # """ # return self._driver.find_element_by_id(HomePage.CREATE_ACCOUNT).is_displayed() # # def create_account(self): # """ # Press create account button # """ # self._driver.find_element_by_id(HomePage.CREATE_ACCOUNT).click() # # Path: src/utils.py # def get_selenium_driver(browser_name: str) -> Union[Chrome, Firefox]: # """ # Return the same instance to the Selenium driver. # # :param browser_name: the name of the browser: chrome or mozilla # :type browser_name: str # :return: an instance of the required driver. # :rtype: Union[Chrome, Mozilla] # """ # if browser_name.upper() == 'CHROME': # return SingletonFactory.build(Chrome) # # elif browser_name.upper() == 'Mozilla': # return SingletonFactory.build(Firefox) # # else: # raise NotImplementedError # # def get_process_info_spike(process): # """ # # :param process: get system information like memory consumption, cpu usage # :return: # """ # for process_id in psutil.pids(): # p = psutil.Process(process_id) # if p.name() == 'pycharm': # if process == 'memory': # return p.memory_percent() # elif process == 'cpu': # return p.cpu_percent(interval=1) # else: # return p which might include code, classes, or functions. Output only the next line.
driver = get_selenium_driver('CHROME')
Given the following code snippet before the placeholder: <|code_start|>""" Define a one to many relationship between objects. If the state of an object is changed, all the others are notified """ class Process: """ - is aware of observers - send a notification to the observers if its state is changed """ def __init__(self): self._observers = set() def subscribe(self, who): self._observers.add(who) def un_subscribe(self, who): self._observers.discard(who) def dispatch(self,test_func, message): for subscriber in self._observers: <|code_end|> , predict the next line using imports from the current file: from src.page_object_pattern.home_page import HomePage from src.utils import get_selenium_driver, get_process_info_spike and context including class names, function names, and sometimes code from other files: # Path: src/page_object_pattern/home_page.py # class HomePage(BasePage): # """ # Home page # """ # SEARCH_CONTAINER = 'searchInput' # SEARCH_BUTTON = 'searchButton' # CREATE_ACCOUNT = 'pt-createaccount' # LOGIN = 'pt-login' # # def set_search_query(self, query: str): # """ # Search for a string # :param query: string you are looking for # """ # self._driver.find_element_by_id(HomePage.SEARCH_CONTAINER).send_keys(query) # # def check_search(self): # """ # Check search button is visible # """ # return self._driver.find_element_by_id(HomePage.SEARCH_BUTTON).is_displayed() # # def search(self): # """ # Click on search button # """ # self._driver.find_element_by_id(HomePage.SEARCH_BUTTON).click() # # def check_login(self): # """ # Check Login button is visible # """ # return self._driver.find_element_by_id(HomePage.LOGIN).is_displayed() # # def login(self): # """ # Press login button # """ # self._driver.find_element_by_id(HomePage.LOGIN).click() # # def check_create_account(self): # """ # Check create account button available # """ # return self._driver.find_element_by_id(HomePage.CREATE_ACCOUNT).is_displayed() # # def create_account(self): # """ # Press create account button # """ # self._driver.find_element_by_id(HomePage.CREATE_ACCOUNT).click() # # Path: src/utils.py # def get_selenium_driver(browser_name: str) -> Union[Chrome, Firefox]: # """ # Return the same instance to the Selenium driver. # # :param browser_name: the name of the browser: chrome or mozilla # :type browser_name: str # :return: an instance of the required driver. # :rtype: Union[Chrome, Mozilla] # """ # if browser_name.upper() == 'CHROME': # return SingletonFactory.build(Chrome) # # elif browser_name.upper() == 'Mozilla': # return SingletonFactory.build(Firefox) # # else: # raise NotImplementedError # # def get_process_info_spike(process): # """ # # :param process: get system information like memory consumption, cpu usage # :return: # """ # for process_id in psutil.pids(): # p = psutil.Process(process_id) # if p.name() == 'pycharm': # if process == 'memory': # return p.memory_percent() # elif process == 'cpu': # return p.cpu_percent(interval=1) # else: # return p . Output only the next line.
if get_process_info_spike(message) >= 50:
Predict the next line for this snippet: <|code_start|>- Simple Factory Pattern implementation - To notice them main idea a base class App was created and two other subclasses @author: Paul Bodean @date: 10/08/2017 """ class App(object): """ """ def __init__(self, driver: Union[Chrome, Firefox]): """ :param driver: browser driver :type driver: object """ self.__driver = driver def factory(self, page: str): """ The access method which handles pages selection :type page: str """ if page == 'Menu': <|code_end|> with the help of current file imports: from typing import Union from selenium.webdriver import Chrome, Firefox from src.factory.pages.menu import Menu from src.factory.pages.search import Search and context from other files: # Path: src/factory/pages/menu.py # class Menu(object): # """ # A couple of menu actions are implemented in Menu class # """ # MENU_BUTTON = '#appbar-guide-button > span > span' # TREND_BUTTON = '//*[@id="trending-guide-item"]/a/span/span[2]/span' # HISTORY_BUTTON = '//*[@id="history-guide-item"]/a/span/span[2]' # BROWSE = '//*[@id="guide_builder-guide-item"]/a/span/span[2]/span' # # def __init__(self, driver: Union[Chrome, Firefox]): # """ # # :param driver: browser driver # :type driver: object # """ # self.__driver = driver # # def menu_button(self): # """ # Click on menu # """ # click_retry(self.__driver, self.MENU_BUTTON, 'css_selector') # # def filter_by_trend(self): # """ # Sort results by trend # """ # click_retry(self.__driver, self.TREND_BUTTON, 'xpath') # # def filter_by_history(self): # """ # Sort results by history # """ # click_retry(self.__driver, self.HISTORY_BUTTON, 'xpath') # # def browse(self): # """ # Browse channels # """ # click_retry(self.__driver, self.BROWSE, 'xpath') # # Path: src/factory/pages/search.py # class Search(object): # """ # Search page methods implementation # """ # SEARCH_CONTAINER = '//*[@id="masthead-search-term"]' # SEARCH_BUTTON = '//*[@id="search-btn"]' # # def __init__(self, driver: Union[Chrome, Firefox]): # """ # # :param driver: browser driver # :type driver: object # """ # self.__driver = driver # # def search(self): # """ # Click on search button # """ # self.__driver.find_element_by_xpath(Search.SEARCH_BUTTON).click() # # def set_query(self, query): # """ # Set query # :return: # :rtype: # """ # self.__driver.find_element_by_xpath(Search.SEARCH_CONTAINER).send_keys(query) , which may contain function names, class names, or code. Output only the next line.
return Menu(self.__driver)
Here is a snippet: <|code_start|> @author: Paul Bodean @date: 10/08/2017 """ class App(object): """ """ def __init__(self, driver: Union[Chrome, Firefox]): """ :param driver: browser driver :type driver: object """ self.__driver = driver def factory(self, page: str): """ The access method which handles pages selection :type page: str """ if page == 'Menu': return Menu(self.__driver) elif page == 'Search': <|code_end|> . Write the next line using the current file imports: from typing import Union from selenium.webdriver import Chrome, Firefox from src.factory.pages.menu import Menu from src.factory.pages.search import Search and context from other files: # Path: src/factory/pages/menu.py # class Menu(object): # """ # A couple of menu actions are implemented in Menu class # """ # MENU_BUTTON = '#appbar-guide-button > span > span' # TREND_BUTTON = '//*[@id="trending-guide-item"]/a/span/span[2]/span' # HISTORY_BUTTON = '//*[@id="history-guide-item"]/a/span/span[2]' # BROWSE = '//*[@id="guide_builder-guide-item"]/a/span/span[2]/span' # # def __init__(self, driver: Union[Chrome, Firefox]): # """ # # :param driver: browser driver # :type driver: object # """ # self.__driver = driver # # def menu_button(self): # """ # Click on menu # """ # click_retry(self.__driver, self.MENU_BUTTON, 'css_selector') # # def filter_by_trend(self): # """ # Sort results by trend # """ # click_retry(self.__driver, self.TREND_BUTTON, 'xpath') # # def filter_by_history(self): # """ # Sort results by history # """ # click_retry(self.__driver, self.HISTORY_BUTTON, 'xpath') # # def browse(self): # """ # Browse channels # """ # click_retry(self.__driver, self.BROWSE, 'xpath') # # Path: src/factory/pages/search.py # class Search(object): # """ # Search page methods implementation # """ # SEARCH_CONTAINER = '//*[@id="masthead-search-term"]' # SEARCH_BUTTON = '//*[@id="search-btn"]' # # def __init__(self, driver: Union[Chrome, Firefox]): # """ # # :param driver: browser driver # :type driver: object # """ # self.__driver = driver # # def search(self): # """ # Click on search button # """ # self.__driver.find_element_by_xpath(Search.SEARCH_BUTTON).click() # # def set_query(self, query): # """ # Set query # :return: # :rtype: # """ # self.__driver.find_element_by_xpath(Search.SEARCH_CONTAINER).send_keys(query) , which may include functions, classes, or code. Output only the next line.
return Search(self.__driver)
Continue the code snippet: <|code_start|> class TestTemplateTestBuilder(TestCase): def setUp(self): self.driver = get_selenium_driver('chrome') self.driver.get('https://www.youtube.com/') def test_one(self): <|code_end|> . Use current file imports: from unittest import TestCase from src.builder.template_test_case import TemplateTestBuilder from src.utils import get_selenium_driver and context (classes, functions, or code) from other files: # Path: src/builder/template_test_case.py # class TemplateTestBuilder(object): # # class _TestTemplate(object): # """ # Generic test case template. # It exposes a set of actions that are required for the most basic interactions. # # All the methods are designed to add an action to the instance attribute 'actions' # The list contains tuples of 2, where the first position represents a callback to a driver method # and the second position is a list of method arguments. # """ # # def __init__(self, driver: Chrome): # """ # Constructor. # :param driver: a connection driver from the Selenium package. # :type driver: Chrome # """ # self.__driver = driver # self.__actions = [] # # def _click(self, element_xpath): # """ # Generic method for clicking an element given by xpath. # :param element_xpath: the xpath identifier for the element. # :type element_xpath: str # # It appends a tuple with the 'click' method of the retrieved element and an empty list of args. # """ # self.__actions.append((self.__driver.find_element_by_xpath(element_xpath).click, [])) # # def _type(self, element_xpath, text): # """ # Generic method used for typing text in a text box. # :param element_xpath: the xpath identifier of the text box. # :type element_xpath: str # :param text: the text to type. # :type text: str # # It appends a tuple with the 'send_keys' method of the retrieved element and a list with the args # in this case the text value. # """ # self.__actions.append((self.__driver.find_element_by_xpath(element_xpath).send_keys, [text])) # # def _wait(self, seconds): # """ # Generic method to wait. # :param seconds: the amount of time to wait in seconds. # :type seconds: int # """ # self.__actions.append((sleep, [seconds])) # # def _compare(self, element_xpath, text): # """ # Generic method to assert the text of an element. # :param element_xpath: the xpath identifier of the element. # :type element_xpath: str # :param text: the reference text # :type text: str # """ # self.__actions.append((TemplateTestBuilder._TestTemplate.__is_equal, # [self.__driver.find_element_by_xpath(element_xpath).text, text])) # # def execute(self): # """ # Terminal method that executes all the added methods. # :return: # :rtype: # """ # for action, args in self.__actions: # action(*args) # # self.__actions = [] # # @staticmethod # def __is_equal(actual, reference): # assert actual == reference # # def __init__(self, driver): # self.__test = self._TestTemplate(driver) # # def click_element(self, element_xpath: str): # self.__test._click(element_xpath) # return self # # def type_text(self, element_xpath: str, text: str): # self.__test._type(element_xpath, text) # return self # # def wait(self, time: int): # self.__test._wait(time) # return self # # def compare(self, element_xpath, text): # self.__test._compare(element_xpath, text) # return self # # def build(self): # return self.__test # # Path: src/utils.py # def get_selenium_driver(browser_name: str) -> Union[Chrome, Firefox]: # """ # Return the same instance to the Selenium driver. # # :param browser_name: the name of the browser: chrome or mozilla # :type browser_name: str # :return: an instance of the required driver. # :rtype: Union[Chrome, Mozilla] # """ # if browser_name.upper() == 'CHROME': # return SingletonFactory.build(Chrome) # # elif browser_name.upper() == 'Mozilla': # return SingletonFactory.build(Firefox) # # else: # raise NotImplementedError . Output only the next line.
test_case = TemplateTestBuilder(self.driver)\
Continue the code snippet: <|code_start|>""" Description: Test case implementation based on page object pattern and unittest """ class TestSearchPage(TestTemplate): """ Test class for testing a search on Youtube """ def test_result_found(self): """ Perform searches """ <|code_end|> . Use current file imports: from src.page_object_pattern.home_page import HomePage from src.page_object_pattern.search_page import SearchPage from src.page_object_pattern.test_template import TestTemplate and context (classes, functions, or code) from other files: # Path: src/page_object_pattern/home_page.py # class HomePage(BasePage): # """ # Home page # """ # SEARCH_CONTAINER = 'searchInput' # SEARCH_BUTTON = 'searchButton' # CREATE_ACCOUNT = 'pt-createaccount' # LOGIN = 'pt-login' # # def set_search_query(self, query: str): # """ # Search for a string # :param query: string you are looking for # """ # self._driver.find_element_by_id(HomePage.SEARCH_CONTAINER).send_keys(query) # # def check_search(self): # """ # Check search button is visible # """ # return self._driver.find_element_by_id(HomePage.SEARCH_BUTTON).is_displayed() # # def search(self): # """ # Click on search button # """ # self._driver.find_element_by_id(HomePage.SEARCH_BUTTON).click() # # def check_login(self): # """ # Check Login button is visible # """ # return self._driver.find_element_by_id(HomePage.LOGIN).is_displayed() # # def login(self): # """ # Press login button # """ # self._driver.find_element_by_id(HomePage.LOGIN).click() # # def check_create_account(self): # """ # Check create account button available # """ # return self._driver.find_element_by_id(HomePage.CREATE_ACCOUNT).is_displayed() # # def create_account(self): # """ # Press create account button # """ # self._driver.find_element_by_id(HomePage.CREATE_ACCOUNT).click() # # Path: src/page_object_pattern/search_page.py # class SearchPage(BasePage): # """ # Search page # """ # HEADING = 'firstHeading' # SEE_ALSO = 'See_also' # DOMAIN_ARTICLES = 'Domain-specific_articles' # READING = 'Further_reading' # REF = 'References' # EXTERNAL_LINKS = 'External_links' # # def heading_text(self): # """ # :return: Get the heading text # """ # return self._driver.find_element_by_id(SearchPage.HEADING).text # # def see_also_text(self): # """ # :return: see also text # """ # return self._driver.find_element_by_xpath(SearchPage.SEE_ALSO).text # # def domain_articles_text(self): # """ # :return: domain article title # """ # return self._driver.find_element_by_xpath(SearchPage.DOMAIN_ARTICLES).text # # def reading_text(self): # """ # :return: reading text # """ # return self._driver.find_element_by_xpath(SearchPage.READING).text # # def ref_text(self): # """ # :return: reference text value # """ # return self._driver.find_element_by_xpath(SearchPage.REF).text # # def external_links_text(self): # """ # :return: external links text value # """ # return self._driver.find_element_by_xpath(SearchPage.EXTERNAL_LINKS).text # # Path: src/page_object_pattern/test_template.py # class TestTemplate(unittest.TestCase): # def setUp(self): # """ # Open the page to be tested # :return: the driver implementation # """ # # self.driver = webdriver.Chrome() # self.driver.get("https://en.wikipedia.org/wiki/Main_Page") # # def tearDown(self): # """ # Quit the browser # """ # self.driver.quit() . Output only the next line.
home_page = HomePage(self.driver)
Predict the next line after this snippet: <|code_start|>""" Description: Test case implementation based on page object pattern and unittest """ class TestSearchPage(TestTemplate): """ Test class for testing a search on Youtube """ def test_result_found(self): """ Perform searches """ home_page = HomePage(self.driver) home_page.set_search_query("Design patterns") home_page.search() <|code_end|> using the current file's imports: from src.page_object_pattern.home_page import HomePage from src.page_object_pattern.search_page import SearchPage from src.page_object_pattern.test_template import TestTemplate and any relevant context from other files: # Path: src/page_object_pattern/home_page.py # class HomePage(BasePage): # """ # Home page # """ # SEARCH_CONTAINER = 'searchInput' # SEARCH_BUTTON = 'searchButton' # CREATE_ACCOUNT = 'pt-createaccount' # LOGIN = 'pt-login' # # def set_search_query(self, query: str): # """ # Search for a string # :param query: string you are looking for # """ # self._driver.find_element_by_id(HomePage.SEARCH_CONTAINER).send_keys(query) # # def check_search(self): # """ # Check search button is visible # """ # return self._driver.find_element_by_id(HomePage.SEARCH_BUTTON).is_displayed() # # def search(self): # """ # Click on search button # """ # self._driver.find_element_by_id(HomePage.SEARCH_BUTTON).click() # # def check_login(self): # """ # Check Login button is visible # """ # return self._driver.find_element_by_id(HomePage.LOGIN).is_displayed() # # def login(self): # """ # Press login button # """ # self._driver.find_element_by_id(HomePage.LOGIN).click() # # def check_create_account(self): # """ # Check create account button available # """ # return self._driver.find_element_by_id(HomePage.CREATE_ACCOUNT).is_displayed() # # def create_account(self): # """ # Press create account button # """ # self._driver.find_element_by_id(HomePage.CREATE_ACCOUNT).click() # # Path: src/page_object_pattern/search_page.py # class SearchPage(BasePage): # """ # Search page # """ # HEADING = 'firstHeading' # SEE_ALSO = 'See_also' # DOMAIN_ARTICLES = 'Domain-specific_articles' # READING = 'Further_reading' # REF = 'References' # EXTERNAL_LINKS = 'External_links' # # def heading_text(self): # """ # :return: Get the heading text # """ # return self._driver.find_element_by_id(SearchPage.HEADING).text # # def see_also_text(self): # """ # :return: see also text # """ # return self._driver.find_element_by_xpath(SearchPage.SEE_ALSO).text # # def domain_articles_text(self): # """ # :return: domain article title # """ # return self._driver.find_element_by_xpath(SearchPage.DOMAIN_ARTICLES).text # # def reading_text(self): # """ # :return: reading text # """ # return self._driver.find_element_by_xpath(SearchPage.READING).text # # def ref_text(self): # """ # :return: reference text value # """ # return self._driver.find_element_by_xpath(SearchPage.REF).text # # def external_links_text(self): # """ # :return: external links text value # """ # return self._driver.find_element_by_xpath(SearchPage.EXTERNAL_LINKS).text # # Path: src/page_object_pattern/test_template.py # class TestTemplate(unittest.TestCase): # def setUp(self): # """ # Open the page to be tested # :return: the driver implementation # """ # # self.driver = webdriver.Chrome() # self.driver.get("https://en.wikipedia.org/wiki/Main_Page") # # def tearDown(self): # """ # Quit the browser # """ # self.driver.quit() . Output only the next line.
result = SearchPage(self.driver)
Given the following code snippet before the placeholder: <|code_start|>""" Description: Test module for module src/singleton/simple_singleton.py @author: Eugen @date: 24/07/2017 """ class TestMyClassBuilder(TestCase): def test_build(self): <|code_end|> , predict the next line using imports from the current file: from unittest import TestCase from src.singleton.simple_singleton import MyClassBuilder and context including class names, function names, and sometimes code from other files: # Path: src/singleton/simple_singleton.py # class MyClassBuilder(object): # """ # Wrapper class for the actual class which implements the singleton design pattern. # """ # # class __PrivateMyClass(object): # """ # Actual implementation of the class. # Together with all the methods and attributes. # """ # # def __init__(self, name): # """ # Constructor with arguments. # :param name: an attribute for the class. # """ # # self.__name = name # # def __str__(self): # """ # ToString method for the class. # :return: returns a string with the state of the class instance. # """ # # return str(self.__name) # # __instance = None # # @staticmethod # def build(**constructor_args): # """ # Builder for the class. # The ONLY EXPOSED way to create an instance of the class __PrivateMyClass. # # Creates a private instance of the actual class and returns it. Else if the class is already # instantiated, it returns the initial instance of the class. # :param constructor_args: the constructor arguments for the class. # :return: returns the instance of the class __PrivateMyClass # """ # # # if the class has not yet been instantiated, create it # if MyClassBuilder.__instance is None: # MyClassBuilder.__instance = MyClassBuilder.__PrivateMyClass(**constructor_args) # # return MyClassBuilder.__instance . Output only the next line.
my_class = MyClassBuilder.build(name='my class')
Based on the snippet: <|code_start|>""" Description: This module provides the menu page related interactions @author: Paul Bodean @date: 10/08/2017 """ class Menu(object): """ A couple of menu actions are implemented in Menu class """ MENU_BUTTON = '#appbar-guide-button > span > span' TREND_BUTTON = '//*[@id="trending-guide-item"]/a/span/span[2]/span' HISTORY_BUTTON = '//*[@id="history-guide-item"]/a/span/span[2]' BROWSE = '//*[@id="guide_builder-guide-item"]/a/span/span[2]/span' def __init__(self, driver: Union[Chrome, Firefox]): """ :param driver: browser driver :type driver: object """ self.__driver = driver def menu_button(self): """ Click on menu """ <|code_end|> , predict the immediate next line with the help of imports: from src.utils import click_retry from typing import Union from selenium.webdriver import Chrome, Firefox and context (classes, functions, sometimes code) from other files: # Path: src/utils.py # def click_retry(driver: Union[Chrome, Firefox], element_identifier: str, id_type: str): # """ # Click on elements based on id type. # Currently supported ids are: # * xpath # * css_selector # # :param driver: browser Driver # :type driver: object # :param element_identifier: id of the element # :type element_identifier: str # :param id_type: selector type e.g. xpath # :type id_type: str # """ # # def retry(action: staticmethod): # """ # Retry an action if raise an error # # :param action: click to be performed # :type action: staticmethod # """ # try: # action # except RuntimeError: # action # # if id_type == 'xpath': # retry(driver.find_element_by_xpath(element_identifier).click()) # else: # retry(driver.find_element_by_css_selector(element_identifier).click()) . Output only the next line.
click_retry(self.__driver, self.MENU_BUTTON, 'css_selector')
Using the snippet: <|code_start|>""" Description: Test module for module src/page_object_patter/base_page.py @author: Paul Bodean @date: 25/07/2017 """ class TestHomePage(TestTemplate): """ Check page page functionality """ def test_buttons_available(self): """ Check Home page buttons are displayed """ <|code_end|> , determine the next line of code. You have imports: from src.page_object_pattern.home_page import HomePage from src.page_object_pattern.test_template import TestTemplate and context (class names, function names, or code) available: # Path: src/page_object_pattern/home_page.py # class HomePage(BasePage): # """ # Home page # """ # SEARCH_CONTAINER = 'searchInput' # SEARCH_BUTTON = 'searchButton' # CREATE_ACCOUNT = 'pt-createaccount' # LOGIN = 'pt-login' # # def set_search_query(self, query: str): # """ # Search for a string # :param query: string you are looking for # """ # self._driver.find_element_by_id(HomePage.SEARCH_CONTAINER).send_keys(query) # # def check_search(self): # """ # Check search button is visible # """ # return self._driver.find_element_by_id(HomePage.SEARCH_BUTTON).is_displayed() # # def search(self): # """ # Click on search button # """ # self._driver.find_element_by_id(HomePage.SEARCH_BUTTON).click() # # def check_login(self): # """ # Check Login button is visible # """ # return self._driver.find_element_by_id(HomePage.LOGIN).is_displayed() # # def login(self): # """ # Press login button # """ # self._driver.find_element_by_id(HomePage.LOGIN).click() # # def check_create_account(self): # """ # Check create account button available # """ # return self._driver.find_element_by_id(HomePage.CREATE_ACCOUNT).is_displayed() # # def create_account(self): # """ # Press create account button # """ # self._driver.find_element_by_id(HomePage.CREATE_ACCOUNT).click() # # Path: src/page_object_pattern/test_template.py # class TestTemplate(unittest.TestCase): # def setUp(self): # """ # Open the page to be tested # :return: the driver implementation # """ # # self.driver = webdriver.Chrome() # self.driver.get("https://en.wikipedia.org/wiki/Main_Page") # # def tearDown(self): # """ # Quit the browser # """ # self.driver.quit() . Output only the next line.
main_page = HomePage(self.driver)
Using the snippet: <|code_start|>""" Description: Test module for module src/page_object_patter/base_page.py @author: Paul Bodean @date: 25/07/2017 """ <|code_end|> , determine the next line of code. You have imports: from src.page_object_pattern.home_page import HomePage from src.page_object_pattern.test_template import TestTemplate and context (class names, function names, or code) available: # Path: src/page_object_pattern/home_page.py # class HomePage(BasePage): # """ # Home page # """ # SEARCH_CONTAINER = 'searchInput' # SEARCH_BUTTON = 'searchButton' # CREATE_ACCOUNT = 'pt-createaccount' # LOGIN = 'pt-login' # # def set_search_query(self, query: str): # """ # Search for a string # :param query: string you are looking for # """ # self._driver.find_element_by_id(HomePage.SEARCH_CONTAINER).send_keys(query) # # def check_search(self): # """ # Check search button is visible # """ # return self._driver.find_element_by_id(HomePage.SEARCH_BUTTON).is_displayed() # # def search(self): # """ # Click on search button # """ # self._driver.find_element_by_id(HomePage.SEARCH_BUTTON).click() # # def check_login(self): # """ # Check Login button is visible # """ # return self._driver.find_element_by_id(HomePage.LOGIN).is_displayed() # # def login(self): # """ # Press login button # """ # self._driver.find_element_by_id(HomePage.LOGIN).click() # # def check_create_account(self): # """ # Check create account button available # """ # return self._driver.find_element_by_id(HomePage.CREATE_ACCOUNT).is_displayed() # # def create_account(self): # """ # Press create account button # """ # self._driver.find_element_by_id(HomePage.CREATE_ACCOUNT).click() # # Path: src/page_object_pattern/test_template.py # class TestTemplate(unittest.TestCase): # def setUp(self): # """ # Open the page to be tested # :return: the driver implementation # """ # # self.driver = webdriver.Chrome() # self.driver.get("https://en.wikipedia.org/wiki/Main_Page") # # def tearDown(self): # """ # Quit the browser # """ # self.driver.quit() . Output only the next line.
class TestHomePage(TestTemplate):
Next line prediction: <|code_start|>""" Description: - Check the object instance memory location @author: Paul Bodean @date: 26/12/2017 """ class TestSingleton(TestCase): def test_singleton(self): <|code_end|> . Use current file imports: (from unittest import TestCase from src.singleton.singleton_classical import ClassicalSingleton) and context including class names, function names, or small code snippets from other files: # Path: src/singleton/singleton_classical.py # class ClassicalSingleton(object): # """ # Singleton class based on overriding the __new__ method # """ # # def __new__(cls): # """ # Override __new__ method to control the obj. creation # :return: Singleton obj. # """ # if not hasattr(cls, 'instance'): # cls.instance = super(ClassicalSingleton, cls).__new__(cls) # # return cls.instance # # @staticmethod # def get_driver(): # """ # # :return: Selenium driver # """ # return webdriver.Chrome() . Output only the next line.
s = ClassicalSingleton()
Next line prediction: <|code_start|> class TestLipoP(PluginTestBase): _plugin_name = "lipop1" def test_lipop1(self): if not self.params['lipop1_bin']: self.params['lipop1_bin'] = 'LipoP' <|code_end|> . Use current file imports: (import os import unittest import sys import inmembrane import inmembrane.tests from inmembrane import helpers from inmembrane.plugins import lipop1 from inmembrane.tests.PluginTestBase import PluginTestBase) and context including class names, function names, or small code snippets from other files: # Path: inmembrane/helpers.py # LOG_SILENT = False # LOG_SILENT = b # def dict_get(this_dict, prop): # def run_with_output(cmd): # def run(cmd, out_file=None): # def silence_log(b): # def log_stderr(s, width=76, comment=True): # def log_stdout(s, width=76): # def parse_fasta_header(header): # def seqid_to_filename(seqid): # def create_proteins_dict(fasta): # def print_proteins(proteins): # def write_proteins_fasta( # fasta_filename, proteins, seqids, width=50): # def proteins_to_fasta(proteins, seqids=[], use_safe_seqid=False, width=50): # def chop_nterminal_peptide(protein, i_cut): # def generate_safe_seqids(proteins): # def clean_directory(top, excluded_files): # def html2text(page, aggressive=False): # # Path: inmembrane/plugins/lipop1.py # def annotate(params, proteins): # def parse_lipop(text, proteins, id_mapping=None): # # Path: inmembrane/tests/PluginTestBase.py # class PluginTestBase(unittest.TestCase): # _plugin_name = "" # # def setUp(self): # """ # Sets up a directory, a parameters dictionary and a proteins dictionary # object in preparation for running a test of a plugin. # # Creates a temporary directory (eg /tmp/.inmembrane_signalp_web_TleeRw ), # copies the test input data (input.fasta) into it and changes the # current working directory. # # Should be subclassed adding a method with the specific test(s) for # the plugin. The subclass should set self._plugin_name to the name of # the plugin. # """ # self.test_data_dir = os.path.join( # os.path.abspath( # os.path.dirname(inmembrane.tests.__file__)), self._plugin_name) # # self.output_dir = tempfile.mkdtemp( # prefix=".inmembrane_%s_" % (self._plugin_name)) # shutil.copyfile(os.path.join(self.test_data_dir, "input.fasta"), # os.path.join(self.output_dir, "input.fasta")) # os.chdir(self.output_dir) # helpers.silence_log(True) # # self.params = inmembrane.get_params() # self.params['fasta'] = "input.fasta" # self.seqids, self.proteins = \ # helpers.create_proteins_dict(self.params['fasta']) . Output only the next line.
lipop1.annotate(self.params, self.proteins)
Continue the code snippet: <|code_start|> class TestTmhmm(PluginTestBase): _plugin_name = "tmhmm" def test_tmhmm(self): if not self.params['tmhmm_bin']: self.params['tmhmm_bin'] = 'tmhmm' <|code_end|> . Use current file imports: import os import unittest import sys import inmembrane import inmembrane.tests import inmembrane import inmembrane.plugins as plugins from inmembrane import helpers from inmembrane.plugins import tmhmm from inmembrane.tests.PluginTestBase import PluginTestBase and context (classes, functions, or code) from other files: # Path: inmembrane/helpers.py # LOG_SILENT = False # LOG_SILENT = b # def dict_get(this_dict, prop): # def run_with_output(cmd): # def run(cmd, out_file=None): # def silence_log(b): # def log_stderr(s, width=76, comment=True): # def log_stdout(s, width=76): # def parse_fasta_header(header): # def seqid_to_filename(seqid): # def create_proteins_dict(fasta): # def print_proteins(proteins): # def write_proteins_fasta( # fasta_filename, proteins, seqids, width=50): # def proteins_to_fasta(proteins, seqids=[], use_safe_seqid=False, width=50): # def chop_nterminal_peptide(protein, i_cut): # def generate_safe_seqids(proteins): # def clean_directory(top, excluded_files): # def html2text(page, aggressive=False): # # Path: inmembrane/plugins/tmhmm.py # def annotate(params, proteins): # def parse_tmhmm(text, proteins, id_mapping=[]): # # Path: inmembrane/tests/PluginTestBase.py # class PluginTestBase(unittest.TestCase): # _plugin_name = "" # # def setUp(self): # """ # Sets up a directory, a parameters dictionary and a proteins dictionary # object in preparation for running a test of a plugin. # # Creates a temporary directory (eg /tmp/.inmembrane_signalp_web_TleeRw ), # copies the test input data (input.fasta) into it and changes the # current working directory. # # Should be subclassed adding a method with the specific test(s) for # the plugin. The subclass should set self._plugin_name to the name of # the plugin. # """ # self.test_data_dir = os.path.join( # os.path.abspath( # os.path.dirname(inmembrane.tests.__file__)), self._plugin_name) # # self.output_dir = tempfile.mkdtemp( # prefix=".inmembrane_%s_" % (self._plugin_name)) # shutil.copyfile(os.path.join(self.test_data_dir, "input.fasta"), # os.path.join(self.output_dir, "input.fasta")) # os.chdir(self.output_dir) # helpers.silence_log(True) # # self.params = inmembrane.get_params() # self.params['fasta'] = "input.fasta" # self.seqids, self.proteins = \ # helpers.create_proteins_dict(self.params['fasta']) . Output only the next line.
tmhmm.annotate(self.params, self.proteins)
Given the code snippet: <|code_start|>citation = {'ref': u"Garrow, A.G., Agnew, A. and Westhead, D.R. TMB-Hunt: An " u"amino acid composition based method to screen proteomes " u"for beta-barrel transmembrane proteins. BMC " u"Bioinformatics, 2005, 6: 56 \n " u"<http://dx.doi.org/10.1186/1471-2105-6-56>", 'name': "TMB-HUNT" } __DEBUG__ = False def annotate(params, proteins, \ force=False): """ DEPRECATED: The TMB-HUNT server appears to be permanently offline. Uses the TMB-HUNT web service (http://bmbpcu36.leeds.ac.uk/~andy/betaBarrel/AACompPred/aaTMB_Hunt.cgi) to predict if proteins are outer membrane beta-barrels. NOTE: In my limited testing, TMB-HUNT tends to perform very poorly in terms of false positives and false negetives. I'd suggest using only BOMP. """ # TODO: automatically split large sets into multiple jobs # TMB-HUNT will only take 10000 seqs at a time if len(proteins) >= 10000: <|code_end|> , generate the next line using the imports in this file: import sys, os, time, StringIO import twill from twill.commands import find, formfile, follow, fv, go, show, \ showforms, showlinks, submit, agent from inmembrane.helpers import log_stderr, parse_fasta_header and context (functions, classes, or occasionally code) from other files: # Path: inmembrane/helpers.py # def log_stderr(s, width=76, comment=True): # """ # Wrapper for all stderr out. Allows future customization. # """ # if LOG_SILENT: # return # if s and s[-1] != "\n": # s += "\n" # if not s.startswith("#"): # s = "# " + s # sys.stderr.write(s) # # def parse_fasta_header(header): # """ # Parses a FASTA format header (with our without the initial '>') and returns a # tuple of sequence id and sequence name/description. # # If NCBI SeqID format (gi|gi-number|gb|accession etc, is detected # the first id in the list is used as the canonical id (see see # http://www.ncbi.nlm.nih.gov/books/NBK21097/#A631 ). # """ # if header[0] == '>': # header = header[1:] # tokens = header.split('|') # # check to see if we have an NCBI-style header # if header.find("|") != -1 and len(tokens[0]) <= 3: # # "gi|ginumber|gb|accession bla bla" becomes "gi|ginumber" # seqid = "%s|%s" % (tokens[0], tokens[1].split()[0]) # name = tokens[-1:][0].strip() # # otherwise just split on spaces & hope for the best # else: # tokens = header.split() # seqid = tokens[0] # name = header[0:-1].strip() # # return seqid, name . Output only the next line.
log_stderr(
Given the code snippet: <|code_start|> except: polltime = polltime * 2 if polltime >= 7200: # 2 hours log_stderr("# TMB-HUNT error: Taking too long.") return txt_out = show() # write raw TMB-HUNT results fh = open(out, 'w') fh.write(txt_out) fh.close() return parse_tmbhunt(proteins, out) def parse_tmbhunt(proteins, out): """ Takes the filename of a TMB-HUNT output file (text format) & parses the outer membrane beta-barrel predictions into the proteins dictionary. """ # parse TMB-HUNT text output tmbhunt_classes = {} for l in open(out, 'r'): # inmembrane.log_stderr("# TMB-HUNT raw: " + l[:-1]) if l[0] == ">": # TMB-HUNT munges FASTA ids by making them all uppercase, # so we find the equivalent any-case id in our proteins list # and use that. ugly but necessary. <|code_end|> , generate the next line using the imports in this file: import sys, os, time, StringIO import twill from twill.commands import find, formfile, follow, fv, go, show, \ showforms, showlinks, submit, agent from inmembrane.helpers import log_stderr, parse_fasta_header and context (functions, classes, or occasionally code) from other files: # Path: inmembrane/helpers.py # def log_stderr(s, width=76, comment=True): # """ # Wrapper for all stderr out. Allows future customization. # """ # if LOG_SILENT: # return # if s and s[-1] != "\n": # s += "\n" # if not s.startswith("#"): # s = "# " + s # sys.stderr.write(s) # # def parse_fasta_header(header): # """ # Parses a FASTA format header (with our without the initial '>') and returns a # tuple of sequence id and sequence name/description. # # If NCBI SeqID format (gi|gi-number|gb|accession etc, is detected # the first id in the list is used as the canonical id (see see # http://www.ncbi.nlm.nih.gov/books/NBK21097/#A631 ). # """ # if header[0] == '>': # header = header[1:] # tokens = header.split('|') # # check to see if we have an NCBI-style header # if header.find("|") != -1 and len(tokens[0]) <= 3: # # "gi|ginumber|gb|accession bla bla" becomes "gi|ginumber" # seqid = "%s|%s" % (tokens[0], tokens[1].split()[0]) # name = tokens[-1:][0].strip() # # otherwise just split on spaces & hope for the best # else: # tokens = header.split() # seqid = tokens[0] # name = header[0:-1].strip() # # return seqid, name . Output only the next line.
seqid, desc = parse_fasta_header(l)
Given the code snippet: <|code_start|># -*- coding: utf-8 -*- citation = {'ref': "http://hmmer.org", 'name': 'HMMER 3.0'} def annotate(params, proteins): """ Returns a reference to the proteins data structure. Uses HMMER to identify sequence motifs in proteins. This function annotates the proteins with: - 'hmmsearch': a list of motifs that are found in the protein. The motifs correspond to the basename of the .hmm files found in the directory indicated by the 'hmm_profiles_dir' field of 'params'. """ <|code_end|> , generate the next line using the imports in this file: import os import glob from inmembrane.helpers import log_stderr, run, parse_fasta_header and context (functions, classes, or occasionally code) from other files: # Path: inmembrane/helpers.py # def log_stderr(s, width=76, comment=True): # """ # Wrapper for all stderr out. Allows future customization. # """ # if LOG_SILENT: # return # if s and s[-1] != "\n": # s += "\n" # if not s.startswith("#"): # s = "# " + s # sys.stderr.write(s) # # def run(cmd, out_file=None): # """ # Wrapper function to run external program so that existence # of binary can be checked and the output directed to a specific # file. # """ # log_stderr("# " + cmd + " > " + out_file) # if os.path.isfile(out_file) and (out_file != None): # log_stderr("# -> skipped: %s already exists" % out_file) # return # binary = cmd.split()[0] # is_binary_there = False # if os.path.isfile(binary): # is_binary_there = True # if run_with_output('which ' + binary): # is_binary_there = True # if not is_binary_there: # raise IOError("Couldn't find executable binary '" + binary + "'") # if out_file: # os.system(cmd + " > " + out_file) # else: # os.system(cmd) # # def parse_fasta_header(header): # """ # Parses a FASTA format header (with our without the initial '>') and returns a # tuple of sequence id and sequence name/description. # # If NCBI SeqID format (gi|gi-number|gb|accession etc, is detected # the first id in the list is used as the canonical id (see see # http://www.ncbi.nlm.nih.gov/books/NBK21097/#A631 ). # """ # if header[0] == '>': # header = header[1:] # tokens = header.split('|') # # check to see if we have an NCBI-style header # if header.find("|") != -1 and len(tokens[0]) <= 3: # # "gi|ginumber|gb|accession bla bla" becomes "gi|ginumber" # seqid = "%s|%s" % (tokens[0], tokens[1].split()[0]) # name = tokens[-1:][0].strip() # # otherwise just split on spaces & hope for the best # else: # tokens = header.split() # seqid = tokens[0] # name = header[0:-1].strip() # # return seqid, name . Output only the next line.
log_stderr(
Using the snippet: <|code_start|># -*- coding: utf-8 -*- citation = {'ref': "http://hmmer.org", 'name': 'HMMER 3.0'} def annotate(params, proteins): """ Returns a reference to the proteins data structure. Uses HMMER to identify sequence motifs in proteins. This function annotates the proteins with: - 'hmmsearch': a list of motifs that are found in the protein. The motifs correspond to the basename of the .hmm files found in the directory indicated by the 'hmm_profiles_dir' field of 'params'. """ log_stderr( "# Searching for HMMER profiles in " + params['hmm_profiles_dir']) file_tag = os.path.join(params['hmm_profiles_dir'], '*.hmm') for hmm_profile in glob.glob(file_tag): params['hmm_profile'] = hmm_profile hmm_profile = os.path.basename(params['hmm_profile']) hmm_name = hmm_profile.replace('.hmm', '') hmmsearch3_out = 'hmm.%s.out' % hmm_name cmd = '%(hmmsearch3_bin)s -Z 2000 -E 10 %(hmm_profile)s %(fasta)s' % params <|code_end|> , determine the next line of code. You have imports: import os import glob from inmembrane.helpers import log_stderr, run, parse_fasta_header and context (class names, function names, or code) available: # Path: inmembrane/helpers.py # def log_stderr(s, width=76, comment=True): # """ # Wrapper for all stderr out. Allows future customization. # """ # if LOG_SILENT: # return # if s and s[-1] != "\n": # s += "\n" # if not s.startswith("#"): # s = "# " + s # sys.stderr.write(s) # # def run(cmd, out_file=None): # """ # Wrapper function to run external program so that existence # of binary can be checked and the output directed to a specific # file. # """ # log_stderr("# " + cmd + " > " + out_file) # if os.path.isfile(out_file) and (out_file != None): # log_stderr("# -> skipped: %s already exists" % out_file) # return # binary = cmd.split()[0] # is_binary_there = False # if os.path.isfile(binary): # is_binary_there = True # if run_with_output('which ' + binary): # is_binary_there = True # if not is_binary_there: # raise IOError("Couldn't find executable binary '" + binary + "'") # if out_file: # os.system(cmd + " > " + out_file) # else: # os.system(cmd) # # def parse_fasta_header(header): # """ # Parses a FASTA format header (with our without the initial '>') and returns a # tuple of sequence id and sequence name/description. # # If NCBI SeqID format (gi|gi-number|gb|accession etc, is detected # the first id in the list is used as the canonical id (see see # http://www.ncbi.nlm.nih.gov/books/NBK21097/#A631 ). # """ # if header[0] == '>': # header = header[1:] # tokens = header.split('|') # # check to see if we have an NCBI-style header # if header.find("|") != -1 and len(tokens[0]) <= 3: # # "gi|ginumber|gb|accession bla bla" becomes "gi|ginumber" # seqid = "%s|%s" % (tokens[0], tokens[1].split()[0]) # name = tokens[-1:][0].strip() # # otherwise just split on spaces & hope for the best # else: # tokens = header.split() # seqid = tokens[0] # name = header[0:-1].strip() # # return seqid, name . Output only the next line.
run(cmd, hmmsearch3_out)
Predict the next line after this snippet: <|code_start|> - 'hmmsearch': a list of motifs that are found in the protein. The motifs correspond to the basename of the .hmm files found in the directory indicated by the 'hmm_profiles_dir' field of 'params'. """ log_stderr( "# Searching for HMMER profiles in " + params['hmm_profiles_dir']) file_tag = os.path.join(params['hmm_profiles_dir'], '*.hmm') for hmm_profile in glob.glob(file_tag): params['hmm_profile'] = hmm_profile hmm_profile = os.path.basename(params['hmm_profile']) hmm_name = hmm_profile.replace('.hmm', '') hmmsearch3_out = 'hmm.%s.out' % hmm_name cmd = '%(hmmsearch3_bin)s -Z 2000 -E 10 %(hmm_profile)s %(fasta)s' % params run(cmd, hmmsearch3_out) # init proteins data structure with blank hmmsearch field first for seqid in proteins: if 'hmmsearch' not in proteins[seqid]: proteins[seqid]['hmmsearch'] = [] # parse the hmmsearch output file seqid = None for l in open(hmmsearch3_out): words = l.split() if l.startswith(">>"): <|code_end|> using the current file's imports: import os import glob from inmembrane.helpers import log_stderr, run, parse_fasta_header and any relevant context from other files: # Path: inmembrane/helpers.py # def log_stderr(s, width=76, comment=True): # """ # Wrapper for all stderr out. Allows future customization. # """ # if LOG_SILENT: # return # if s and s[-1] != "\n": # s += "\n" # if not s.startswith("#"): # s = "# " + s # sys.stderr.write(s) # # def run(cmd, out_file=None): # """ # Wrapper function to run external program so that existence # of binary can be checked and the output directed to a specific # file. # """ # log_stderr("# " + cmd + " > " + out_file) # if os.path.isfile(out_file) and (out_file != None): # log_stderr("# -> skipped: %s already exists" % out_file) # return # binary = cmd.split()[0] # is_binary_there = False # if os.path.isfile(binary): # is_binary_there = True # if run_with_output('which ' + binary): # is_binary_there = True # if not is_binary_there: # raise IOError("Couldn't find executable binary '" + binary + "'") # if out_file: # os.system(cmd + " > " + out_file) # else: # os.system(cmd) # # def parse_fasta_header(header): # """ # Parses a FASTA format header (with our without the initial '>') and returns a # tuple of sequence id and sequence name/description. # # If NCBI SeqID format (gi|gi-number|gb|accession etc, is detected # the first id in the list is used as the canonical id (see see # http://www.ncbi.nlm.nih.gov/books/NBK21097/#A631 ). # """ # if header[0] == '>': # header = header[1:] # tokens = header.split('|') # # check to see if we have an NCBI-style header # if header.find("|") != -1 and len(tokens[0]) <= 3: # # "gi|ginumber|gb|accession bla bla" becomes "gi|ginumber" # seqid = "%s|%s" % (tokens[0], tokens[1].split()[0]) # name = tokens[-1:][0].strip() # # otherwise just split on spaces & hope for the best # else: # tokens = header.split() # seqid = tokens[0] # name = header[0:-1].strip() # # return seqid, name . Output only the next line.
seqid = parse_fasta_header(l[3:])[0]
Predict the next line after this snippet: <|code_start|> __DEBUG__ = False try: except: def annotate(params, proteins, \ batchsize=500, \ force=False): """ This plugin interfaces with the TMHMM web interface (for humans) and scrapes the results. There once was a SOAP service but it was discontinued, so now we use this. """ baseurl = "http://www.cbs.dtu.dk" url = baseurl + '/cgi-bin/webface2.fcgi' # grab the cached results if present outfile = "tmhmm_scrape_web.out" if not force and os.path.isfile(outfile): log_stderr("# -> skipped: %s already exists" % outfile) proteins, id_mapping = generate_safe_seqids(proteins) fh = open(outfile, 'r') resultpage = fh.read() fh.close() # soup = BeautifulSoup(resultpage) <|code_end|> using the current file's imports: import sys, os, time import requests import inmembrane from StringIO import StringIO from BeautifulSoup import BeautifulSoup from collections import OrderedDict from ordereddict import OrderedDict from inmembrane.plugins.tmhmm import parse_tmhmm from inmembrane.helpers import log_stderr from inmembrane.helpers import generate_safe_seqids, proteins_to_fasta and any relevant context from other files: # Path: inmembrane/plugins/tmhmm.py # def parse_tmhmm(text, proteins, id_mapping=[]): # seqid = None # for i_line, l in enumerate(text.split('\n')): # if i_line == 0: # continue # words = l.split() # if not words: # continue # # if l.startswith("#"): # seqid = parse_fasta_header(words[1])[0] # else: # seqid = parse_fasta_header(words[0])[0] # if seqid is None: # continue # # # re-map from a safe_seqid to the original seqid # if id_mapping: # seqid = id_mapping[seqid] # # # initialize fields in proteins[seqid] # if 'tmhmm_helices' not in proteins[seqid]: # proteins[seqid].update({ # 'tmhmm_helices': [], # 'tmhmm_inner_loops': [], # 'tmhmm_outer_loops': [] # }) # # if 'inside' in l: # proteins[seqid]['tmhmm_inner_loops'].append( # (int(words[-2]), int(words[-1]))) # if 'outside' in l: # proteins[seqid]['tmhmm_outer_loops'].append( # (int(words[-2]), int(words[-1]))) # if 'TMhelix' in l: # proteins[seqid]['tmhmm_helices'].append( # (int(words[-2]), int(words[-1]))) # # return proteins # # Path: inmembrane/helpers.py # def log_stderr(s, width=76, comment=True): # """ # Wrapper for all stderr out. Allows future customization. # """ # if LOG_SILENT: # return # if s and s[-1] != "\n": # s += "\n" # if not s.startswith("#"): # s = "# " + s # sys.stderr.write(s) # # Path: inmembrane/helpers.py # def generate_safe_seqids(proteins): # """ # Takes a 'proteins' dictionary, keyed by sequence id, and # adds a 'safe' sequence id ('safe_seqid') that is less likely # to be munged or break various external programs. # # Returns a tuple of the updated proteins dictionary and a dictionary # mapping the 'safe' sequence ids to the original ids. # """ # id_mapping = {} # count = 0 # for seqid in proteins: # safe_id = re.sub(r'[^\w]', "", seqid) + '_' + `count` # id_mapping[safe_id] = seqid # proteins[seqid]['safe_seqid'] = safe_id # count += 1 # # return (proteins, id_mapping) # # def proteins_to_fasta(proteins, seqids=[], use_safe_seqid=False, width=50): # """ # Takes a proteins dictionary and returns a string containing # all the sequences in FASTA format. Option parameters are # a list of seqids to output (seqids) and the line width (width). # """ # if seqids: # idlist = seqids # else: # idlist = proteins # # fasta_out = "" # for seqid in idlist: # seq_wrap = textwrap.fill(proteins[seqid]['seq'], width) # if use_safe_seqid: # header = proteins[seqid]['safe_seqid'] # else: # header = proteins[seqid]['name'] # fasta_out += ">%s\n%s\n" % (header, seq_wrap) # return fasta_out . Output only the next line.
proteins = parse_tmhmm(resultpage, proteins, id_mapping=id_mapping)
Given snippet: <|code_start|> u"L. L. Sonnhammer (2001) Predicting Transmembrane Protein " u"Topology with a Hidden Markov Model: Application to " u"Complete Genomes. J. Mol. Biol. 305:567-580. \n" u"<http://dx.doi.org/10.1006/jmbi.2000.4315>", 'name': "TMHMM 2.0" } __DEBUG__ = False try: except: def annotate(params, proteins, \ batchsize=500, \ force=False): """ This plugin interfaces with the TMHMM web interface (for humans) and scrapes the results. There once was a SOAP service but it was discontinued, so now we use this. """ baseurl = "http://www.cbs.dtu.dk" url = baseurl + '/cgi-bin/webface2.fcgi' # grab the cached results if present outfile = "tmhmm_scrape_web.out" if not force and os.path.isfile(outfile): <|code_end|> , continue by predicting the next line. Consider current file imports: import sys, os, time import requests import inmembrane from StringIO import StringIO from BeautifulSoup import BeautifulSoup from collections import OrderedDict from ordereddict import OrderedDict from inmembrane.plugins.tmhmm import parse_tmhmm from inmembrane.helpers import log_stderr from inmembrane.helpers import generate_safe_seqids, proteins_to_fasta and context: # Path: inmembrane/plugins/tmhmm.py # def parse_tmhmm(text, proteins, id_mapping=[]): # seqid = None # for i_line, l in enumerate(text.split('\n')): # if i_line == 0: # continue # words = l.split() # if not words: # continue # # if l.startswith("#"): # seqid = parse_fasta_header(words[1])[0] # else: # seqid = parse_fasta_header(words[0])[0] # if seqid is None: # continue # # # re-map from a safe_seqid to the original seqid # if id_mapping: # seqid = id_mapping[seqid] # # # initialize fields in proteins[seqid] # if 'tmhmm_helices' not in proteins[seqid]: # proteins[seqid].update({ # 'tmhmm_helices': [], # 'tmhmm_inner_loops': [], # 'tmhmm_outer_loops': [] # }) # # if 'inside' in l: # proteins[seqid]['tmhmm_inner_loops'].append( # (int(words[-2]), int(words[-1]))) # if 'outside' in l: # proteins[seqid]['tmhmm_outer_loops'].append( # (int(words[-2]), int(words[-1]))) # if 'TMhelix' in l: # proteins[seqid]['tmhmm_helices'].append( # (int(words[-2]), int(words[-1]))) # # return proteins # # Path: inmembrane/helpers.py # def log_stderr(s, width=76, comment=True): # """ # Wrapper for all stderr out. Allows future customization. # """ # if LOG_SILENT: # return # if s and s[-1] != "\n": # s += "\n" # if not s.startswith("#"): # s = "# " + s # sys.stderr.write(s) # # Path: inmembrane/helpers.py # def generate_safe_seqids(proteins): # """ # Takes a 'proteins' dictionary, keyed by sequence id, and # adds a 'safe' sequence id ('safe_seqid') that is less likely # to be munged or break various external programs. # # Returns a tuple of the updated proteins dictionary and a dictionary # mapping the 'safe' sequence ids to the original ids. # """ # id_mapping = {} # count = 0 # for seqid in proteins: # safe_id = re.sub(r'[^\w]', "", seqid) + '_' + `count` # id_mapping[safe_id] = seqid # proteins[seqid]['safe_seqid'] = safe_id # count += 1 # # return (proteins, id_mapping) # # def proteins_to_fasta(proteins, seqids=[], use_safe_seqid=False, width=50): # """ # Takes a proteins dictionary and returns a string containing # all the sequences in FASTA format. Option parameters are # a list of seqids to output (seqids) and the line width (width). # """ # if seqids: # idlist = seqids # else: # idlist = proteins # # fasta_out = "" # for seqid in idlist: # seq_wrap = textwrap.fill(proteins[seqid]['seq'], width) # if use_safe_seqid: # header = proteins[seqid]['safe_seqid'] # else: # header = proteins[seqid]['name'] # fasta_out += ">%s\n%s\n" % (header, seq_wrap) # return fasta_out which might include code, classes, or functions. Output only the next line.
log_stderr("# -> skipped: %s already exists" % outfile)
Based on the snippet: <|code_start|> u"Topology with a Hidden Markov Model: Application to " u"Complete Genomes. J. Mol. Biol. 305:567-580. \n" u"<http://dx.doi.org/10.1006/jmbi.2000.4315>", 'name': "TMHMM 2.0" } __DEBUG__ = False try: except: def annotate(params, proteins, \ batchsize=500, \ force=False): """ This plugin interfaces with the TMHMM web interface (for humans) and scrapes the results. There once was a SOAP service but it was discontinued, so now we use this. """ baseurl = "http://www.cbs.dtu.dk" url = baseurl + '/cgi-bin/webface2.fcgi' # grab the cached results if present outfile = "tmhmm_scrape_web.out" if not force and os.path.isfile(outfile): log_stderr("# -> skipped: %s already exists" % outfile) <|code_end|> , predict the immediate next line with the help of imports: import sys, os, time import requests import inmembrane from StringIO import StringIO from BeautifulSoup import BeautifulSoup from collections import OrderedDict from ordereddict import OrderedDict from inmembrane.plugins.tmhmm import parse_tmhmm from inmembrane.helpers import log_stderr from inmembrane.helpers import generate_safe_seqids, proteins_to_fasta and context (classes, functions, sometimes code) from other files: # Path: inmembrane/plugins/tmhmm.py # def parse_tmhmm(text, proteins, id_mapping=[]): # seqid = None # for i_line, l in enumerate(text.split('\n')): # if i_line == 0: # continue # words = l.split() # if not words: # continue # # if l.startswith("#"): # seqid = parse_fasta_header(words[1])[0] # else: # seqid = parse_fasta_header(words[0])[0] # if seqid is None: # continue # # # re-map from a safe_seqid to the original seqid # if id_mapping: # seqid = id_mapping[seqid] # # # initialize fields in proteins[seqid] # if 'tmhmm_helices' not in proteins[seqid]: # proteins[seqid].update({ # 'tmhmm_helices': [], # 'tmhmm_inner_loops': [], # 'tmhmm_outer_loops': [] # }) # # if 'inside' in l: # proteins[seqid]['tmhmm_inner_loops'].append( # (int(words[-2]), int(words[-1]))) # if 'outside' in l: # proteins[seqid]['tmhmm_outer_loops'].append( # (int(words[-2]), int(words[-1]))) # if 'TMhelix' in l: # proteins[seqid]['tmhmm_helices'].append( # (int(words[-2]), int(words[-1]))) # # return proteins # # Path: inmembrane/helpers.py # def log_stderr(s, width=76, comment=True): # """ # Wrapper for all stderr out. Allows future customization. # """ # if LOG_SILENT: # return # if s and s[-1] != "\n": # s += "\n" # if not s.startswith("#"): # s = "# " + s # sys.stderr.write(s) # # Path: inmembrane/helpers.py # def generate_safe_seqids(proteins): # """ # Takes a 'proteins' dictionary, keyed by sequence id, and # adds a 'safe' sequence id ('safe_seqid') that is less likely # to be munged or break various external programs. # # Returns a tuple of the updated proteins dictionary and a dictionary # mapping the 'safe' sequence ids to the original ids. # """ # id_mapping = {} # count = 0 # for seqid in proteins: # safe_id = re.sub(r'[^\w]', "", seqid) + '_' + `count` # id_mapping[safe_id] = seqid # proteins[seqid]['safe_seqid'] = safe_id # count += 1 # # return (proteins, id_mapping) # # def proteins_to_fasta(proteins, seqids=[], use_safe_seqid=False, width=50): # """ # Takes a proteins dictionary and returns a string containing # all the sequences in FASTA format. Option parameters are # a list of seqids to output (seqids) and the line width (width). # """ # if seqids: # idlist = seqids # else: # idlist = proteins # # fasta_out = "" # for seqid in idlist: # seq_wrap = textwrap.fill(proteins[seqid]['seq'], width) # if use_safe_seqid: # header = proteins[seqid]['safe_seqid'] # else: # header = proteins[seqid]['name'] # fasta_out += ">%s\n%s\n" % (header, seq_wrap) # return fasta_out . Output only the next line.
proteins, id_mapping = generate_safe_seqids(proteins)
Given snippet: <|code_start|> This plugin interfaces with the TMHMM web interface (for humans) and scrapes the results. There once was a SOAP service but it was discontinued, so now we use this. """ baseurl = "http://www.cbs.dtu.dk" url = baseurl + '/cgi-bin/webface2.fcgi' # grab the cached results if present outfile = "tmhmm_scrape_web.out" if not force and os.path.isfile(outfile): log_stderr("# -> skipped: %s already exists" % outfile) proteins, id_mapping = generate_safe_seqids(proteins) fh = open(outfile, 'r') resultpage = fh.read() fh.close() # soup = BeautifulSoup(resultpage) proteins = parse_tmhmm(resultpage, proteins, id_mapping=id_mapping) return proteins proteins, id_mapping = generate_safe_seqids(proteins) seqids = proteins.keys() allresultpages = "" while seqids: seqid_batch = seqids[0:batchsize] del seqids[0:batchsize] # get batch of sequences in fasta format with munged ids # (workaround for potential tmhmm sequence id munging) <|code_end|> , continue by predicting the next line. Consider current file imports: import sys, os, time import requests import inmembrane from StringIO import StringIO from BeautifulSoup import BeautifulSoup from collections import OrderedDict from ordereddict import OrderedDict from inmembrane.plugins.tmhmm import parse_tmhmm from inmembrane.helpers import log_stderr from inmembrane.helpers import generate_safe_seqids, proteins_to_fasta and context: # Path: inmembrane/plugins/tmhmm.py # def parse_tmhmm(text, proteins, id_mapping=[]): # seqid = None # for i_line, l in enumerate(text.split('\n')): # if i_line == 0: # continue # words = l.split() # if not words: # continue # # if l.startswith("#"): # seqid = parse_fasta_header(words[1])[0] # else: # seqid = parse_fasta_header(words[0])[0] # if seqid is None: # continue # # # re-map from a safe_seqid to the original seqid # if id_mapping: # seqid = id_mapping[seqid] # # # initialize fields in proteins[seqid] # if 'tmhmm_helices' not in proteins[seqid]: # proteins[seqid].update({ # 'tmhmm_helices': [], # 'tmhmm_inner_loops': [], # 'tmhmm_outer_loops': [] # }) # # if 'inside' in l: # proteins[seqid]['tmhmm_inner_loops'].append( # (int(words[-2]), int(words[-1]))) # if 'outside' in l: # proteins[seqid]['tmhmm_outer_loops'].append( # (int(words[-2]), int(words[-1]))) # if 'TMhelix' in l: # proteins[seqid]['tmhmm_helices'].append( # (int(words[-2]), int(words[-1]))) # # return proteins # # Path: inmembrane/helpers.py # def log_stderr(s, width=76, comment=True): # """ # Wrapper for all stderr out. Allows future customization. # """ # if LOG_SILENT: # return # if s and s[-1] != "\n": # s += "\n" # if not s.startswith("#"): # s = "# " + s # sys.stderr.write(s) # # Path: inmembrane/helpers.py # def generate_safe_seqids(proteins): # """ # Takes a 'proteins' dictionary, keyed by sequence id, and # adds a 'safe' sequence id ('safe_seqid') that is less likely # to be munged or break various external programs. # # Returns a tuple of the updated proteins dictionary and a dictionary # mapping the 'safe' sequence ids to the original ids. # """ # id_mapping = {} # count = 0 # for seqid in proteins: # safe_id = re.sub(r'[^\w]', "", seqid) + '_' + `count` # id_mapping[safe_id] = seqid # proteins[seqid]['safe_seqid'] = safe_id # count += 1 # # return (proteins, id_mapping) # # def proteins_to_fasta(proteins, seqids=[], use_safe_seqid=False, width=50): # """ # Takes a proteins dictionary and returns a string containing # all the sequences in FASTA format. Option parameters are # a list of seqids to output (seqids) and the line width (width). # """ # if seqids: # idlist = seqids # else: # idlist = proteins # # fasta_out = "" # for seqid in idlist: # seq_wrap = textwrap.fill(proteins[seqid]['seq'], width) # if use_safe_seqid: # header = proteins[seqid]['safe_seqid'] # else: # header = proteins[seqid]['name'] # fasta_out += ">%s\n%s\n" % (header, seq_wrap) # return fasta_out which might include code, classes, or functions. Output only the next line.
safe_fasta = proteins_to_fasta(proteins, seqids=seqid_batch,
Based on the snippet: <|code_start|> class TestSignalp(PluginTestBase): _plugin_name = "signalp4" def test_signalp4(self): if not self.params['signalp4_bin']: self.params['signalp4_bin'] = 'signalp' self.params['fasta'] = "input.fasta" self.params['signalp4_organism'] = 'gram+' <|code_end|> , predict the immediate next line with the help of imports: import os import unittest import sys import inmembrane import inmembrane.tests from inmembrane import helpers from inmembrane.plugins import signalp4 from inmembrane.tests.PluginTestBase import PluginTestBase and context (classes, functions, sometimes code) from other files: # Path: inmembrane/helpers.py # LOG_SILENT = False # LOG_SILENT = b # def dict_get(this_dict, prop): # def run_with_output(cmd): # def run(cmd, out_file=None): # def silence_log(b): # def log_stderr(s, width=76, comment=True): # def log_stdout(s, width=76): # def parse_fasta_header(header): # def seqid_to_filename(seqid): # def create_proteins_dict(fasta): # def print_proteins(proteins): # def write_proteins_fasta( # fasta_filename, proteins, seqids, width=50): # def proteins_to_fasta(proteins, seqids=[], use_safe_seqid=False, width=50): # def chop_nterminal_peptide(protein, i_cut): # def generate_safe_seqids(proteins): # def clean_directory(top, excluded_files): # def html2text(page, aggressive=False): # # Path: inmembrane/plugins/signalp4.py # def parse_signalp(signalp4_lines, proteins, id_mapping=None): # def annotate(params, proteins): # # Path: inmembrane/tests/PluginTestBase.py # class PluginTestBase(unittest.TestCase): # _plugin_name = "" # # def setUp(self): # """ # Sets up a directory, a parameters dictionary and a proteins dictionary # object in preparation for running a test of a plugin. # # Creates a temporary directory (eg /tmp/.inmembrane_signalp_web_TleeRw ), # copies the test input data (input.fasta) into it and changes the # current working directory. # # Should be subclassed adding a method with the specific test(s) for # the plugin. The subclass should set self._plugin_name to the name of # the plugin. # """ # self.test_data_dir = os.path.join( # os.path.abspath( # os.path.dirname(inmembrane.tests.__file__)), self._plugin_name) # # self.output_dir = tempfile.mkdtemp( # prefix=".inmembrane_%s_" % (self._plugin_name)) # shutil.copyfile(os.path.join(self.test_data_dir, "input.fasta"), # os.path.join(self.output_dir, "input.fasta")) # os.chdir(self.output_dir) # helpers.silence_log(True) # # self.params = inmembrane.get_params() # self.params['fasta'] = "input.fasta" # self.seqids, self.proteins = \ # helpers.create_proteins_dict(self.params['fasta']) . Output only the next line.
signalp4.annotate(self.params, self.proteins)
Next line prediction: <|code_start|> u"<http://dx.doi.org/10.1006/jmbi.2000.4315>", 'name': "TMHMM 2.0" } def annotate(params, proteins): """ Runs THMHMM and parses the output files. Takes a standard 'inmembrane' params dictionary and a global proteins dictionary which it populates with results. In the current implementation, this function extracts and feeds sequences to tmhmm one by one via a temporary file. These keys are added to the proteins dictionary: - 'tmhmm_helices', a list of tuples describing the first and last residue number of each transmembrane segment; - 'tmhmm_scores', a list of confidence scores (floats) for each predicted tm segment; - 'tmhmm_inner_loops', a list of tuples describing the first and last residue number of each predicted internal loop segment; - 'tmhmm_outer_loops', a list of tuples describing the first and last residue number of each predicted outer loop segment; """ tmhmm_out = 'tmhmm.out' <|code_end|> . Use current file imports: (from inmembrane.helpers import run, parse_fasta_header) and context including class names, function names, or small code snippets from other files: # Path: inmembrane/helpers.py # def run(cmd, out_file=None): # """ # Wrapper function to run external program so that existence # of binary can be checked and the output directed to a specific # file. # """ # log_stderr("# " + cmd + " > " + out_file) # if os.path.isfile(out_file) and (out_file != None): # log_stderr("# -> skipped: %s already exists" % out_file) # return # binary = cmd.split()[0] # is_binary_there = False # if os.path.isfile(binary): # is_binary_there = True # if run_with_output('which ' + binary): # is_binary_there = True # if not is_binary_there: # raise IOError("Couldn't find executable binary '" + binary + "'") # if out_file: # os.system(cmd + " > " + out_file) # else: # os.system(cmd) # # def parse_fasta_header(header): # """ # Parses a FASTA format header (with our without the initial '>') and returns a # tuple of sequence id and sequence name/description. # # If NCBI SeqID format (gi|gi-number|gb|accession etc, is detected # the first id in the list is used as the canonical id (see see # http://www.ncbi.nlm.nih.gov/books/NBK21097/#A631 ). # """ # if header[0] == '>': # header = header[1:] # tokens = header.split('|') # # check to see if we have an NCBI-style header # if header.find("|") != -1 and len(tokens[0]) <= 3: # # "gi|ginumber|gb|accession bla bla" becomes "gi|ginumber" # seqid = "%s|%s" % (tokens[0], tokens[1].split()[0]) # name = tokens[-1:][0].strip() # # otherwise just split on spaces & hope for the best # else: # tokens = header.split() # seqid = tokens[0] # name = header[0:-1].strip() # # return seqid, name . Output only the next line.
run('%(tmhmm_bin)s %(fasta)s' % params, tmhmm_out)
Given the following code snippet before the placeholder: <|code_start|> These keys are added to the proteins dictionary: - 'tmhmm_helices', a list of tuples describing the first and last residue number of each transmembrane segment; - 'tmhmm_scores', a list of confidence scores (floats) for each predicted tm segment; - 'tmhmm_inner_loops', a list of tuples describing the first and last residue number of each predicted internal loop segment; - 'tmhmm_outer_loops', a list of tuples describing the first and last residue number of each predicted outer loop segment; """ tmhmm_out = 'tmhmm.out' run('%(tmhmm_bin)s %(fasta)s' % params, tmhmm_out) return parse_tmhmm(open('tmhmm.out').read(), proteins) def parse_tmhmm(text, proteins, id_mapping=[]): seqid = None for i_line, l in enumerate(text.split('\n')): if i_line == 0: continue words = l.split() if not words: continue if l.startswith("#"): <|code_end|> , predict the next line using imports from the current file: from inmembrane.helpers import run, parse_fasta_header and context including class names, function names, and sometimes code from other files: # Path: inmembrane/helpers.py # def run(cmd, out_file=None): # """ # Wrapper function to run external program so that existence # of binary can be checked and the output directed to a specific # file. # """ # log_stderr("# " + cmd + " > " + out_file) # if os.path.isfile(out_file) and (out_file != None): # log_stderr("# -> skipped: %s already exists" % out_file) # return # binary = cmd.split()[0] # is_binary_there = False # if os.path.isfile(binary): # is_binary_there = True # if run_with_output('which ' + binary): # is_binary_there = True # if not is_binary_there: # raise IOError("Couldn't find executable binary '" + binary + "'") # if out_file: # os.system(cmd + " > " + out_file) # else: # os.system(cmd) # # def parse_fasta_header(header): # """ # Parses a FASTA format header (with our without the initial '>') and returns a # tuple of sequence id and sequence name/description. # # If NCBI SeqID format (gi|gi-number|gb|accession etc, is detected # the first id in the list is used as the canonical id (see see # http://www.ncbi.nlm.nih.gov/books/NBK21097/#A631 ). # """ # if header[0] == '>': # header = header[1:] # tokens = header.split('|') # # check to see if we have an NCBI-style header # if header.find("|") != -1 and len(tokens[0]) <= 3: # # "gi|ginumber|gb|accession bla bla" becomes "gi|ginumber" # seqid = "%s|%s" % (tokens[0], tokens[1].split()[0]) # name = tokens[-1:][0].strip() # # otherwise just split on spaces & hope for the best # else: # tokens = header.split() # seqid = tokens[0] # name = header[0:-1].strip() # # return seqid, name . Output only the next line.
seqid = parse_fasta_header(words[1])[0]
Continue the code snippet: <|code_start|> seqid, result = parse_fasta_header(f) if "Non-Outer Membrane Protein" in result: proteins[seqid]["is_tmbetadisc_rbf"] = False elif "is Outer Membrane Protein" in result: proteins[seqid]["is_tmbetadisc_rbf"] = True fields.pop() except IndexError: # we get here when we run out of table fields to pop pass return proteins def annotate(params, proteins, \ url="http://rbf.bioinfo.tw/" + "~sachen/OMPpredict/" + "TMBETADISC-RBF-Content.html", force=False): """ Interfaces with the TMBETADISC-RBF web service at (http://rbf.bioinfo.tw/~sachen/OMPpredict/TMBETADISC-RBF.php) to predict if protein sequence is likely to be an outer membrane beta-barrel. Note that the default URL we use it different to the regular form used by web browsers, since we need to bypass some AJAX fun. """ # TODO: automatically split large sets into multiple jobs # since TMBETADISC seems to not like more than take # ~5000 seqs at a time if len(proteins) >= 5000: <|code_end|> . Use current file imports: import sys, os, time, StringIO import requests from BeautifulSoup import BeautifulSoup from inmembrane.helpers import log_stderr, parse_fasta_header, dict_get and context (classes, functions, or code) from other files: # Path: inmembrane/helpers.py # def log_stderr(s, width=76, comment=True): # """ # Wrapper for all stderr out. Allows future customization. # """ # if LOG_SILENT: # return # if s and s[-1] != "\n": # s += "\n" # if not s.startswith("#"): # s = "# " + s # sys.stderr.write(s) # # def parse_fasta_header(header): # """ # Parses a FASTA format header (with our without the initial '>') and returns a # tuple of sequence id and sequence name/description. # # If NCBI SeqID format (gi|gi-number|gb|accession etc, is detected # the first id in the list is used as the canonical id (see see # http://www.ncbi.nlm.nih.gov/books/NBK21097/#A631 ). # """ # if header[0] == '>': # header = header[1:] # tokens = header.split('|') # # check to see if we have an NCBI-style header # if header.find("|") != -1 and len(tokens[0]) <= 3: # # "gi|ginumber|gb|accession bla bla" becomes "gi|ginumber" # seqid = "%s|%s" % (tokens[0], tokens[1].split()[0]) # name = tokens[-1:][0].strip() # # otherwise just split on spaces & hope for the best # else: # tokens = header.split() # seqid = tokens[0] # name = header[0:-1].strip() # # return seqid, name # # def dict_get(this_dict, prop): # """ # Useful helper function to get values from dicts. Takes in # the possibility that the key may not exist, and in that # case returns False. Makes it easier to write code to avoid # handling the case of missing keys. # """ # if prop not in this_dict: # return False # return this_dict[prop] . Output only the next line.
log_stderr(
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*- citation = {'ref': "Ou Y-YY, Gromiha MMM, Chen S-AA, Suwa M (2008) " "TMBETADISC-RBF: Discrimination of beta-barrel " "membrane proteins using RBF networks and PSSM profiles. " "Computational biology and chemistry. \n" "<http://dx.doi.org/10.1016/j.compbiolchem.2008.03.002>", 'name': "TMBETADISC-RBF" } __DEBUG__ = False def parse_tmbetadisc_output(output, proteins): """ Parses the TMBETADISC-RBF output (file-like object or a list of strings) an uses it to annotate and return an associated 'proteins' data structure. """ soup = BeautifulSoup(output) # parse the table. we pop of single data cells one at a time fields = soup.findAll("td") fields.reverse() f = fields.pop() # discard first <td>1</td> field try: while len(fields) > 0: f = fields.pop().text <|code_end|> using the current file's imports: import sys, os, time, StringIO import requests from BeautifulSoup import BeautifulSoup from inmembrane.helpers import log_stderr, parse_fasta_header, dict_get and any relevant context from other files: # Path: inmembrane/helpers.py # def log_stderr(s, width=76, comment=True): # """ # Wrapper for all stderr out. Allows future customization. # """ # if LOG_SILENT: # return # if s and s[-1] != "\n": # s += "\n" # if not s.startswith("#"): # s = "# " + s # sys.stderr.write(s) # # def parse_fasta_header(header): # """ # Parses a FASTA format header (with our without the initial '>') and returns a # tuple of sequence id and sequence name/description. # # If NCBI SeqID format (gi|gi-number|gb|accession etc, is detected # the first id in the list is used as the canonical id (see see # http://www.ncbi.nlm.nih.gov/books/NBK21097/#A631 ). # """ # if header[0] == '>': # header = header[1:] # tokens = header.split('|') # # check to see if we have an NCBI-style header # if header.find("|") != -1 and len(tokens[0]) <= 3: # # "gi|ginumber|gb|accession bla bla" becomes "gi|ginumber" # seqid = "%s|%s" % (tokens[0], tokens[1].split()[0]) # name = tokens[-1:][0].strip() # # otherwise just split on spaces & hope for the best # else: # tokens = header.split() # seqid = tokens[0] # name = header[0:-1].strip() # # return seqid, name # # def dict_get(this_dict, prop): # """ # Useful helper function to get values from dicts. Takes in # the possibility that the key may not exist, and in that # case returns False. Makes it easier to write code to avoid # handling the case of missing keys. # """ # if prop not in this_dict: # return False # return this_dict[prop] . Output only the next line.
seqid, result = parse_fasta_header(f)
Given the code snippet: <|code_start|> by web browsers, since we need to bypass some AJAX fun. """ # TODO: automatically split large sets into multiple jobs # since TMBETADISC seems to not like more than take # ~5000 seqs at a time if len(proteins) >= 5000: log_stderr( "# ERROR: TMBETADISC-RBF(web): tends to fail with > ~5000 sequences.") return # set the user-agent so web services can block us if they want ... :/ python_version = sys.version.split()[0] # TODO: Set User-Agent header for requests # agent("Python-urllib/%s (requests; inmembrane)" % python_version) outfn = 'tmbetadisc-rbf.out' log_stderr("# TMBETADISC-RBF(web) %s > %s" % (params['fasta'], outfn)) if not force and os.path.isfile(outfn): log_stderr("# -> skipped: %s already exists" % outfn) fh = open(outfn, 'r') proteins = parse_tmbetadisc_output(fh.read(), proteins) fh.close() return proteins # set the user defined method method_map = {"aa": "Amino Acid Composition", "dp": "Depipetide Composition", "aadp": "Amino Acid & Depipetide Composition", "pssm": "PSSM"} <|code_end|> , generate the next line using the imports in this file: import sys, os, time, StringIO import requests from BeautifulSoup import BeautifulSoup from inmembrane.helpers import log_stderr, parse_fasta_header, dict_get and context (functions, classes, or occasionally code) from other files: # Path: inmembrane/helpers.py # def log_stderr(s, width=76, comment=True): # """ # Wrapper for all stderr out. Allows future customization. # """ # if LOG_SILENT: # return # if s and s[-1] != "\n": # s += "\n" # if not s.startswith("#"): # s = "# " + s # sys.stderr.write(s) # # def parse_fasta_header(header): # """ # Parses a FASTA format header (with our without the initial '>') and returns a # tuple of sequence id and sequence name/description. # # If NCBI SeqID format (gi|gi-number|gb|accession etc, is detected # the first id in the list is used as the canonical id (see see # http://www.ncbi.nlm.nih.gov/books/NBK21097/#A631 ). # """ # if header[0] == '>': # header = header[1:] # tokens = header.split('|') # # check to see if we have an NCBI-style header # if header.find("|") != -1 and len(tokens[0]) <= 3: # # "gi|ginumber|gb|accession bla bla" becomes "gi|ginumber" # seqid = "%s|%s" % (tokens[0], tokens[1].split()[0]) # name = tokens[-1:][0].strip() # # otherwise just split on spaces & hope for the best # else: # tokens = header.split() # seqid = tokens[0] # name = header[0:-1].strip() # # return seqid, name # # def dict_get(this_dict, prop): # """ # Useful helper function to get values from dicts. Takes in # the possibility that the key may not exist, and in that # case returns False. Makes it easier to write code to avoid # handling the case of missing keys. # """ # if prop not in this_dict: # return False # return this_dict[prop] . Output only the next line.
if dict_get(params, 'tmbetadisc_rbf_method'):
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*- citation = {'ref': u"Agnieszka S. Juncker, Hanni Willenbrock, " u"Gunnar Von Heijne, Søren Brunak, Henrik Nielsen, " u"And Anders Krogh. (2003) Prediction of lipoprotein " u"signal peptides in Gram-negative bacteria. Protein " u"Science 12:1652–1662. \n" u"<http://dx.doi.org/10.1110/ps.0303703>", 'name': 'LipoP 1.0' } def annotate(params, proteins): """ Uses LipoP to identify lipo-attachment signals in the protein. The 'proteins' dictionary is annotated by adding two fields: - 'is_lipop' is a boolean indicating whether a signal is found or not - 'lipop_cleave_position' gives the position where the signal is cleaved and the protein is attached to a lipid Returns a reference to the proteins data structure. """ lipop1_out = 'lipop.out' <|code_end|> with the help of current file imports: import re from inmembrane.helpers import run, parse_fasta_header, dict_get and context from other files: # Path: inmembrane/helpers.py # def run(cmd, out_file=None): # """ # Wrapper function to run external program so that existence # of binary can be checked and the output directed to a specific # file. # """ # log_stderr("# " + cmd + " > " + out_file) # if os.path.isfile(out_file) and (out_file != None): # log_stderr("# -> skipped: %s already exists" % out_file) # return # binary = cmd.split()[0] # is_binary_there = False # if os.path.isfile(binary): # is_binary_there = True # if run_with_output('which ' + binary): # is_binary_there = True # if not is_binary_there: # raise IOError("Couldn't find executable binary '" + binary + "'") # if out_file: # os.system(cmd + " > " + out_file) # else: # os.system(cmd) # # def parse_fasta_header(header): # """ # Parses a FASTA format header (with our without the initial '>') and returns a # tuple of sequence id and sequence name/description. # # If NCBI SeqID format (gi|gi-number|gb|accession etc, is detected # the first id in the list is used as the canonical id (see see # http://www.ncbi.nlm.nih.gov/books/NBK21097/#A631 ). # """ # if header[0] == '>': # header = header[1:] # tokens = header.split('|') # # check to see if we have an NCBI-style header # if header.find("|") != -1 and len(tokens[0]) <= 3: # # "gi|ginumber|gb|accession bla bla" becomes "gi|ginumber" # seqid = "%s|%s" % (tokens[0], tokens[1].split()[0]) # name = tokens[-1:][0].strip() # # otherwise just split on spaces & hope for the best # else: # tokens = header.split() # seqid = tokens[0] # name = header[0:-1].strip() # # return seqid, name # # def dict_get(this_dict, prop): # """ # Useful helper function to get values from dicts. Takes in # the possibility that the key may not exist, and in that # case returns False. Makes it easier to write code to avoid # handling the case of missing keys. # """ # if prop not in this_dict: # return False # return this_dict[prop] , which may contain function names, class names, or code. Output only the next line.
run('%(lipop1_bin)s %(fasta)s' % params, lipop1_out)
Given snippet: <|code_start|> lipop1_out = 'lipop.out' run('%(lipop1_bin)s %(fasta)s' % params, lipop1_out) proteins = parse_lipop(open(lipop1_out).read(), proteins) return proteins def parse_lipop(text, proteins, id_mapping=None): """ Parses the text output of the LipoP program and returns a 'proteins' datastructure with annotations. The parser can also that the HTML returned by the LipoP web interface. If a dictionary of {safe_seqid : seqid} mappings is given, the parser will expect the input text to contain safe_seqids. """ if id_mapping is None: id_mapping = [] # initialize fields in each protein for seqid in proteins: proteins[seqid]['is_lipop'] = False proteins[seqid]['lipop_cleave_position'] = None for l in text.split('\n'): words = l.split() if 'SpII score' in l: <|code_end|> , continue by predicting the next line. Consider current file imports: import re from inmembrane.helpers import run, parse_fasta_header, dict_get and context: # Path: inmembrane/helpers.py # def run(cmd, out_file=None): # """ # Wrapper function to run external program so that existence # of binary can be checked and the output directed to a specific # file. # """ # log_stderr("# " + cmd + " > " + out_file) # if os.path.isfile(out_file) and (out_file != None): # log_stderr("# -> skipped: %s already exists" % out_file) # return # binary = cmd.split()[0] # is_binary_there = False # if os.path.isfile(binary): # is_binary_there = True # if run_with_output('which ' + binary): # is_binary_there = True # if not is_binary_there: # raise IOError("Couldn't find executable binary '" + binary + "'") # if out_file: # os.system(cmd + " > " + out_file) # else: # os.system(cmd) # # def parse_fasta_header(header): # """ # Parses a FASTA format header (with our without the initial '>') and returns a # tuple of sequence id and sequence name/description. # # If NCBI SeqID format (gi|gi-number|gb|accession etc, is detected # the first id in the list is used as the canonical id (see see # http://www.ncbi.nlm.nih.gov/books/NBK21097/#A631 ). # """ # if header[0] == '>': # header = header[1:] # tokens = header.split('|') # # check to see if we have an NCBI-style header # if header.find("|") != -1 and len(tokens[0]) <= 3: # # "gi|ginumber|gb|accession bla bla" becomes "gi|ginumber" # seqid = "%s|%s" % (tokens[0], tokens[1].split()[0]) # name = tokens[-1:][0].strip() # # otherwise just split on spaces & hope for the best # else: # tokens = header.split() # seqid = tokens[0] # name = header[0:-1].strip() # # return seqid, name # # def dict_get(this_dict, prop): # """ # Useful helper function to get values from dicts. Takes in # the possibility that the key may not exist, and in that # case returns False. Makes it easier to write code to avoid # handling the case of missing keys. # """ # if prop not in this_dict: # return False # return this_dict[prop] which might include code, classes, or functions. Output only the next line.
seqid = parse_fasta_header(words[1])[0]
Next line prediction: <|code_start|> """ if id_mapping is None: id_mapping = [] # initialize fields in each protein for seqid in proteins: proteins[seqid]['is_lipop'] = False proteins[seqid]['lipop_cleave_position'] = None for l in text.split('\n'): words = l.split() if 'SpII score' in l: seqid = parse_fasta_header(words[1])[0] if id_mapping: seqid = id_mapping[seqid] if 'cleavage' in l: pair = words[5].split("=")[1] i = int(pair.split('-')[0]) else: i = None proteins[seqid]['is_lipop'] = 'Sp' in words[2] proteins[seqid]['lipop_cleave_position'] = i # check for an E.coli style inner membrane retention signal # Asp+2 to cleavage site. There are other apparent retention # signals in E. coli and other gram- bacteria in addition to # the Asp+2 which we don't detect here (yet). # (Yamaguchi et al, 1988; Tokuda and Matsuyama, 2005 [review]) <|code_end|> . Use current file imports: (import re from inmembrane.helpers import run, parse_fasta_header, dict_get) and context including class names, function names, or small code snippets from other files: # Path: inmembrane/helpers.py # def run(cmd, out_file=None): # """ # Wrapper function to run external program so that existence # of binary can be checked and the output directed to a specific # file. # """ # log_stderr("# " + cmd + " > " + out_file) # if os.path.isfile(out_file) and (out_file != None): # log_stderr("# -> skipped: %s already exists" % out_file) # return # binary = cmd.split()[0] # is_binary_there = False # if os.path.isfile(binary): # is_binary_there = True # if run_with_output('which ' + binary): # is_binary_there = True # if not is_binary_there: # raise IOError("Couldn't find executable binary '" + binary + "'") # if out_file: # os.system(cmd + " > " + out_file) # else: # os.system(cmd) # # def parse_fasta_header(header): # """ # Parses a FASTA format header (with our without the initial '>') and returns a # tuple of sequence id and sequence name/description. # # If NCBI SeqID format (gi|gi-number|gb|accession etc, is detected # the first id in the list is used as the canonical id (see see # http://www.ncbi.nlm.nih.gov/books/NBK21097/#A631 ). # """ # if header[0] == '>': # header = header[1:] # tokens = header.split('|') # # check to see if we have an NCBI-style header # if header.find("|") != -1 and len(tokens[0]) <= 3: # # "gi|ginumber|gb|accession bla bla" becomes "gi|ginumber" # seqid = "%s|%s" % (tokens[0], tokens[1].split()[0]) # name = tokens[-1:][0].strip() # # otherwise just split on spaces & hope for the best # else: # tokens = header.split() # seqid = tokens[0] # name = header[0:-1].strip() # # return seqid, name # # def dict_get(this_dict, prop): # """ # Useful helper function to get values from dicts. Takes in # the possibility that the key may not exist, and in that # case returns False. Makes it easier to write code to avoid # handling the case of missing keys. # """ # if prop not in this_dict: # return False # return this_dict[prop] . Output only the next line.
if dict_get(proteins[seqid], 'lipop_cleave_position'):
Next line prediction: <|code_start|> def get_annotations(params): annotations = [] params['signalp4_organism'] = 'gram-' if not params['signalp4_bin'] or params[ 'signalp4_bin'] == 'signalp_scrape_web': annotations += ['signalp_scrape_web'] else: annotations += ['signalp4'] if not params['lipop1_bin'] or params['lipop1_bin'] == 'lipop_scrape_web': annotations += ['lipop_scrape_web'] else: annotations += ['lipop1'] annotations += ['tatfind_web'] <|code_end|> . Use current file imports: (import os from inmembrane.helpers import dict_get, chop_nterminal_peptide, log_stderr) and context including class names, function names, or small code snippets from other files: # Path: inmembrane/helpers.py # def dict_get(this_dict, prop): # """ # Useful helper function to get values from dicts. Takes in # the possibility that the key may not exist, and in that # case returns False. Makes it easier to write code to avoid # handling the case of missing keys. # """ # if prop not in this_dict: # return False # return this_dict[prop] # # def chop_nterminal_peptide(protein, i_cut): # """ # Finds all transmembrane fields in protein ("*_loops" and "*_helices") # and deletes an N-terminal section of the protein indicated by i_cut. # # Assuming the topology of inner and outer loops remain the same, this # may delete a certain number of elements at the N-terminus. Allows a # simple way of removing lipo-protein and secretion-protein signals from # the evaluation of the outer_loops of the protein. # """ # protein['sequence_length'] -= i_cut # for prop in protein: # if '_loops' in prop or '_helices' in prop: # sses = protein[prop] # for i in range(len(sses)): # j, k = sses[i] # sses[i] = (j - i_cut, k - i_cut) # for prop in protein: # if '_loops' in prop or '_helices' in prop: # sses = protein[prop] # for i in reversed(range(len(sses))): # j, k = sses[i] # # tests if this loop or TM-helix has been cut out # if j <= 0 and k <= 0: # del sses[i] # # otherewise, neg value means loop or TM-helix is at the new N-terminal # elif j <= 0 and k > 0: # sses[i] = (1, k) # # if a TM-helix gets cut in half and becomes a new N-terminal, # # convert the remaining residues to a loop and remove the helix # if '_helices' in prop: # program = prop.split('_')[0] # for x in protein: # if x == '%s_loops' % program: # new_N_loop = protein[x][0] # new_N_loop[0] = 1 # del sses[i] # # def log_stderr(s, width=76, comment=True): # """ # Wrapper for all stderr out. Allows future customization. # """ # if LOG_SILENT: # return # if s and s[-1] != "\n": # s += "\n" # if not s.startswith("#"): # s = "# " + s # sys.stderr.write(s) . Output only the next line.
if 'bomp' in dict_get(params, 'barrel_programs'):
Given snippet: <|code_start|> # DEPRECATED: TMB-HUNT server is permanently offline # tmbhunt_prob = dict_get(protein, 'tmbhunt_prob') # if (tmbhunt_prob >= params['tmbhunt_clearly_cutoff']) or \ # (has_signal_pept and tmbhunt_prob >= params['tmbhunt_maybe_cutoff']): # details += ['tmbhunt(%.2f)' % (tmbhunt_prob)] # has_barrel = True if has_signal_pept and dict_get(protein, 'is_tmbetadisc_rbf'): details += ['tmbetadisc-rbf'] has_barrel = True if has_barrel: category = 'OM(barrel)' # we only regard the barrel prediction as a true positive # if a signal peptide is also present # is_barrel = False # if has_signal_pept and has_barrel: # TODO and num_tms <= 1: # category = 'OM(barrel)' # is_barrel = True # set number of predicted OM barrel strands in details if has_barrel and \ dict_get(protein, 'tmbeta_strands'): num_strands = len(protein['tmbeta_strands']) details += ['tmbeta_strands(%i)' % (num_strands)] if has_signal_pept and not is_lipop and \ (dict_get(protein, 'signalp_cleave_position')): # we use the SignalP signal peptidase cleavage site for Tat signals <|code_end|> , continue by predicting the next line. Consider current file imports: import os from inmembrane.helpers import dict_get, chop_nterminal_peptide, log_stderr and context: # Path: inmembrane/helpers.py # def dict_get(this_dict, prop): # """ # Useful helper function to get values from dicts. Takes in # the possibility that the key may not exist, and in that # case returns False. Makes it easier to write code to avoid # handling the case of missing keys. # """ # if prop not in this_dict: # return False # return this_dict[prop] # # def chop_nterminal_peptide(protein, i_cut): # """ # Finds all transmembrane fields in protein ("*_loops" and "*_helices") # and deletes an N-terminal section of the protein indicated by i_cut. # # Assuming the topology of inner and outer loops remain the same, this # may delete a certain number of elements at the N-terminus. Allows a # simple way of removing lipo-protein and secretion-protein signals from # the evaluation of the outer_loops of the protein. # """ # protein['sequence_length'] -= i_cut # for prop in protein: # if '_loops' in prop or '_helices' in prop: # sses = protein[prop] # for i in range(len(sses)): # j, k = sses[i] # sses[i] = (j - i_cut, k - i_cut) # for prop in protein: # if '_loops' in prop or '_helices' in prop: # sses = protein[prop] # for i in reversed(range(len(sses))): # j, k = sses[i] # # tests if this loop or TM-helix has been cut out # if j <= 0 and k <= 0: # del sses[i] # # otherewise, neg value means loop or TM-helix is at the new N-terminal # elif j <= 0 and k > 0: # sses[i] = (1, k) # # if a TM-helix gets cut in half and becomes a new N-terminal, # # convert the remaining residues to a loop and remove the helix # if '_helices' in prop: # program = prop.split('_')[0] # for x in protein: # if x == '%s_loops' % program: # new_N_loop = protein[x][0] # new_N_loop[0] = 1 # del sses[i] # # def log_stderr(s, width=76, comment=True): # """ # Wrapper for all stderr out. Allows future customization. # """ # if LOG_SILENT: # return # if s and s[-1] != "\n": # s += "\n" # if not s.startswith("#"): # s = "# " + s # sys.stderr.write(s) which might include code, classes, or functions. Output only the next line.
chop_nterminal_peptide(protein, protein['signalp_cleave_position'])
Using the snippet: <|code_start|> if line.startswith("#"): past_preamble = True continue if not past_preamble and line.strip() == '': # skip empty lines continue if past_preamble: if line.strip() == '': # in the case of web output of concatenated signalp output # files, an empty line after preamble means we have finished all # 'result' lines for that section past_preamble = False continue words = line.split() seqid = parse_fasta_header(words[0])[0] if id_mapping: seqid = id_mapping[seqid] proteins[seqid]['signalp_cleave_position'] = int(words[4]) proteins[seqid]['is_signalp'] = (words[9] == 'Y') return proteins def annotate(params, proteins): for seqid in proteins: proteins[seqid]['is_signalp'] = False proteins[seqid]['signalp_cleave_position'] = None signalp4_out = 'signalp.out' cmd = '%(signalp4_bin)s -t %(signalp4_organism)s %(fasta)s' % \ params <|code_end|> , determine the next line of code. You have imports: from inmembrane.helpers import run, parse_fasta_header and context (class names, function names, or code) available: # Path: inmembrane/helpers.py # def run(cmd, out_file=None): # """ # Wrapper function to run external program so that existence # of binary can be checked and the output directed to a specific # file. # """ # log_stderr("# " + cmd + " > " + out_file) # if os.path.isfile(out_file) and (out_file != None): # log_stderr("# -> skipped: %s already exists" % out_file) # return # binary = cmd.split()[0] # is_binary_there = False # if os.path.isfile(binary): # is_binary_there = True # if run_with_output('which ' + binary): # is_binary_there = True # if not is_binary_there: # raise IOError("Couldn't find executable binary '" + binary + "'") # if out_file: # os.system(cmd + " > " + out_file) # else: # os.system(cmd) # # def parse_fasta_header(header): # """ # Parses a FASTA format header (with our without the initial '>') and returns a # tuple of sequence id and sequence name/description. # # If NCBI SeqID format (gi|gi-number|gb|accession etc, is detected # the first id in the list is used as the canonical id (see see # http://www.ncbi.nlm.nih.gov/books/NBK21097/#A631 ). # """ # if header[0] == '>': # header = header[1:] # tokens = header.split('|') # # check to see if we have an NCBI-style header # if header.find("|") != -1 and len(tokens[0]) <= 3: # # "gi|ginumber|gb|accession bla bla" becomes "gi|ginumber" # seqid = "%s|%s" % (tokens[0], tokens[1].split()[0]) # name = tokens[-1:][0].strip() # # otherwise just split on spaces & hope for the best # else: # tokens = header.split() # seqid = tokens[0] # name = header[0:-1].strip() # # return seqid, name . Output only the next line.
run(cmd, signalp4_out)
Here is a snippet: <|code_start|># -*- coding: utf-8 -*- citation = {'ref': u"Petersen TN, Brunak S, von Heijne G, Nielsen H. " u"SignalP 4.0: discriminating signal peptides from " u"transmembrane regions. Nature methods 2011 " u"Jan;8(10):785-6. \n" u"<http://dx.doi.org/10.1038/nmeth.1701>", 'name': "SignalP 4.0" } def parse_signalp(signalp4_lines, proteins, id_mapping=None): if id_mapping is None: id_mapping = [] past_preamble = False for line in signalp4_lines: if line.startswith("#"): past_preamble = True continue if not past_preamble and line.strip() == '': # skip empty lines continue if past_preamble: if line.strip() == '': # in the case of web output of concatenated signalp output # files, an empty line after preamble means we have finished all # 'result' lines for that section past_preamble = False continue words = line.split() <|code_end|> . Write the next line using the current file imports: from inmembrane.helpers import run, parse_fasta_header and context from other files: # Path: inmembrane/helpers.py # def run(cmd, out_file=None): # """ # Wrapper function to run external program so that existence # of binary can be checked and the output directed to a specific # file. # """ # log_stderr("# " + cmd + " > " + out_file) # if os.path.isfile(out_file) and (out_file != None): # log_stderr("# -> skipped: %s already exists" % out_file) # return # binary = cmd.split()[0] # is_binary_there = False # if os.path.isfile(binary): # is_binary_there = True # if run_with_output('which ' + binary): # is_binary_there = True # if not is_binary_there: # raise IOError("Couldn't find executable binary '" + binary + "'") # if out_file: # os.system(cmd + " > " + out_file) # else: # os.system(cmd) # # def parse_fasta_header(header): # """ # Parses a FASTA format header (with our without the initial '>') and returns a # tuple of sequence id and sequence name/description. # # If NCBI SeqID format (gi|gi-number|gb|accession etc, is detected # the first id in the list is used as the canonical id (see see # http://www.ncbi.nlm.nih.gov/books/NBK21097/#A631 ). # """ # if header[0] == '>': # header = header[1:] # tokens = header.split('|') # # check to see if we have an NCBI-style header # if header.find("|") != -1 and len(tokens[0]) <= 3: # # "gi|ginumber|gb|accession bla bla" becomes "gi|ginumber" # seqid = "%s|%s" % (tokens[0], tokens[1].split()[0]) # name = tokens[-1:][0].strip() # # otherwise just split on spaces & hope for the best # else: # tokens = header.split() # seqid = tokens[0] # name = header[0:-1].strip() # # return seqid, name , which may include functions, classes, or code. Output only the next line.
seqid = parse_fasta_header(words[0])[0]
Predict the next line after this snippet: <|code_start|> class TestTatfind(PluginTestBase): _plugin_name = "tatfind_web" def test_tatfind_web(self): <|code_end|> using the current file's imports: import os import unittest import sys import inmembrane import inmembrane.tests from inmembrane import helpers from inmembrane.plugins import tatfind_web from inmembrane.tests.PluginTestBase import PluginTestBase and any relevant context from other files: # Path: inmembrane/helpers.py # LOG_SILENT = False # LOG_SILENT = b # def dict_get(this_dict, prop): # def run_with_output(cmd): # def run(cmd, out_file=None): # def silence_log(b): # def log_stderr(s, width=76, comment=True): # def log_stdout(s, width=76): # def parse_fasta_header(header): # def seqid_to_filename(seqid): # def create_proteins_dict(fasta): # def print_proteins(proteins): # def write_proteins_fasta( # fasta_filename, proteins, seqids, width=50): # def proteins_to_fasta(proteins, seqids=[], use_safe_seqid=False, width=50): # def chop_nterminal_peptide(protein, i_cut): # def generate_safe_seqids(proteins): # def clean_directory(top, excluded_files): # def html2text(page, aggressive=False): # # Path: inmembrane/plugins/tatfind_web.py # __DEBUG__ = False # def parse_tatfind_output(output, proteins): # def annotate(params, proteins, \ # url="http://signalfind.org/tatfind.html", force=False): # # Path: inmembrane/tests/PluginTestBase.py # class PluginTestBase(unittest.TestCase): # _plugin_name = "" # # def setUp(self): # """ # Sets up a directory, a parameters dictionary and a proteins dictionary # object in preparation for running a test of a plugin. # # Creates a temporary directory (eg /tmp/.inmembrane_signalp_web_TleeRw ), # copies the test input data (input.fasta) into it and changes the # current working directory. # # Should be subclassed adding a method with the specific test(s) for # the plugin. The subclass should set self._plugin_name to the name of # the plugin. # """ # self.test_data_dir = os.path.join( # os.path.abspath( # os.path.dirname(inmembrane.tests.__file__)), self._plugin_name) # # self.output_dir = tempfile.mkdtemp( # prefix=".inmembrane_%s_" % (self._plugin_name)) # shutil.copyfile(os.path.join(self.test_data_dir, "input.fasta"), # os.path.join(self.output_dir, "input.fasta")) # os.chdir(self.output_dir) # helpers.silence_log(True) # # self.params = inmembrane.get_params() # self.params['fasta'] = "input.fasta" # self.seqids, self.proteins = \ # helpers.create_proteins_dict(self.params['fasta']) . Output only the next line.
tatfind_web.annotate(self.params, self.proteins)
Predict the next line for this snippet: <|code_start|> # NOTE: since memsat3 is dependent on using a particular BLAST sequence # database, if your local version of this database differs to the # one used to generate the expected results below, this test will # fail. There is no straightforward way to solve this, without # packaging a potentially large BLAST database with inmembrane. class TestMemsat3(PluginTestBase): _plugin_name = "memsat3" def test_memsat3(self): <|code_end|> with the help of current file imports: import os import unittest import sys import inmembrane import inmembrane.tests from inmembrane import helpers from inmembrane.plugins import memsat3 from inmembrane.tests.PluginTestBase import PluginTestBase and context from other files: # Path: inmembrane/helpers.py # LOG_SILENT = False # LOG_SILENT = b # def dict_get(this_dict, prop): # def run_with_output(cmd): # def run(cmd, out_file=None): # def silence_log(b): # def log_stderr(s, width=76, comment=True): # def log_stdout(s, width=76): # def parse_fasta_header(header): # def seqid_to_filename(seqid): # def create_proteins_dict(fasta): # def print_proteins(proteins): # def write_proteins_fasta( # fasta_filename, proteins, seqids, width=50): # def proteins_to_fasta(proteins, seqids=[], use_safe_seqid=False, width=50): # def chop_nterminal_peptide(protein, i_cut): # def generate_safe_seqids(proteins): # def clean_directory(top, excluded_files): # def html2text(page, aggressive=False): # # Path: inmembrane/plugins/memsat3.py # def parse_memsat(protein, memsat_out): # def has_transmembrane_in_globmem(globmem_out): # def annotate(params, proteins): # # Path: inmembrane/tests/PluginTestBase.py # class PluginTestBase(unittest.TestCase): # _plugin_name = "" # # def setUp(self): # """ # Sets up a directory, a parameters dictionary and a proteins dictionary # object in preparation for running a test of a plugin. # # Creates a temporary directory (eg /tmp/.inmembrane_signalp_web_TleeRw ), # copies the test input data (input.fasta) into it and changes the # current working directory. # # Should be subclassed adding a method with the specific test(s) for # the plugin. The subclass should set self._plugin_name to the name of # the plugin. # """ # self.test_data_dir = os.path.join( # os.path.abspath( # os.path.dirname(inmembrane.tests.__file__)), self._plugin_name) # # self.output_dir = tempfile.mkdtemp( # prefix=".inmembrane_%s_" % (self._plugin_name)) # shutil.copyfile(os.path.join(self.test_data_dir, "input.fasta"), # os.path.join(self.output_dir, "input.fasta")) # os.chdir(self.output_dir) # helpers.silence_log(True) # # self.params = inmembrane.get_params() # self.params['fasta'] = "input.fasta" # self.seqids, self.proteins = \ # helpers.create_proteins_dict(self.params['fasta']) , which may contain function names, class names, or code. Output only the next line.
memsat3.annotate(self.params, self.proteins)
Given the code snippet: <|code_start|> class TestTmhmmWeb(PluginTestBase): _plugin_name = "tmhmm_scrape_web" def test_tmhmm_scrape_web(self): <|code_end|> , generate the next line using the imports in this file: import os import unittest import sys import inmembrane import inmembrane.tests import inmembrane import inmembrane.plugins as plugins from inmembrane import helpers from inmembrane.plugins import tmhmm_scrape_web from inmembrane.tests.PluginTestBase import PluginTestBase and context (functions, classes, or occasionally code) from other files: # Path: inmembrane/helpers.py # LOG_SILENT = False # LOG_SILENT = b # def dict_get(this_dict, prop): # def run_with_output(cmd): # def run(cmd, out_file=None): # def silence_log(b): # def log_stderr(s, width=76, comment=True): # def log_stdout(s, width=76): # def parse_fasta_header(header): # def seqid_to_filename(seqid): # def create_proteins_dict(fasta): # def print_proteins(proteins): # def write_proteins_fasta( # fasta_filename, proteins, seqids, width=50): # def proteins_to_fasta(proteins, seqids=[], use_safe_seqid=False, width=50): # def chop_nterminal_peptide(protein, i_cut): # def generate_safe_seqids(proteins): # def clean_directory(top, excluded_files): # def html2text(page, aggressive=False): # # Path: inmembrane/plugins/tmhmm_scrape_web.py # __DEBUG__ = False # def annotate(params, proteins, \ # batchsize=500, \ # force=False): # def clean_result_page(resultpage): # # Path: inmembrane/tests/PluginTestBase.py # class PluginTestBase(unittest.TestCase): # _plugin_name = "" # # def setUp(self): # """ # Sets up a directory, a parameters dictionary and a proteins dictionary # object in preparation for running a test of a plugin. # # Creates a temporary directory (eg /tmp/.inmembrane_signalp_web_TleeRw ), # copies the test input data (input.fasta) into it and changes the # current working directory. # # Should be subclassed adding a method with the specific test(s) for # the plugin. The subclass should set self._plugin_name to the name of # the plugin. # """ # self.test_data_dir = os.path.join( # os.path.abspath( # os.path.dirname(inmembrane.tests.__file__)), self._plugin_name) # # self.output_dir = tempfile.mkdtemp( # prefix=".inmembrane_%s_" % (self._plugin_name)) # shutil.copyfile(os.path.join(self.test_data_dir, "input.fasta"), # os.path.join(self.output_dir, "input.fasta")) # os.chdir(self.output_dir) # helpers.silence_log(True) # # self.params = inmembrane.get_params() # self.params['fasta'] = "input.fasta" # self.seqids, self.proteins = \ # helpers.create_proteins_dict(self.params['fasta']) . Output only the next line.
tmhmm_scrape_web.annotate(self.params, self.proteins)
Predict the next line for this snippet: <|code_start|> class PluginTestBase(unittest.TestCase): _plugin_name = "" def setUp(self): """ Sets up a directory, a parameters dictionary and a proteins dictionary object in preparation for running a test of a plugin. Creates a temporary directory (eg /tmp/.inmembrane_signalp_web_TleeRw ), copies the test input data (input.fasta) into it and changes the current working directory. Should be subclassed adding a method with the specific test(s) for the plugin. The subclass should set self._plugin_name to the name of the plugin. """ self.test_data_dir = os.path.join( os.path.abspath( os.path.dirname(inmembrane.tests.__file__)), self._plugin_name) self.output_dir = tempfile.mkdtemp( prefix=".inmembrane_%s_" % (self._plugin_name)) shutil.copyfile(os.path.join(self.test_data_dir, "input.fasta"), os.path.join(self.output_dir, "input.fasta")) os.chdir(self.output_dir) <|code_end|> with the help of current file imports: import os, tempfile, shutil import unittest import sys import inmembrane import inmembrane.tests from inmembrane import helpers and context from other files: # Path: inmembrane/helpers.py # LOG_SILENT = False # LOG_SILENT = b # def dict_get(this_dict, prop): # def run_with_output(cmd): # def run(cmd, out_file=None): # def silence_log(b): # def log_stderr(s, width=76, comment=True): # def log_stdout(s, width=76): # def parse_fasta_header(header): # def seqid_to_filename(seqid): # def create_proteins_dict(fasta): # def print_proteins(proteins): # def write_proteins_fasta( # fasta_filename, proteins, seqids, width=50): # def proteins_to_fasta(proteins, seqids=[], use_safe_seqid=False, width=50): # def chop_nterminal_peptide(protein, i_cut): # def generate_safe_seqids(proteins): # def clean_directory(top, excluded_files): # def html2text(page, aggressive=False): , which may contain function names, class names, or code. Output only the next line.
helpers.silence_log(True)
Given the code snippet: <|code_start|> u"L. L. Sonnhammer (2001) Predicting Transmembrane Protein " u"Topology with a Hidden Markov Model: Application to " u"Complete Genomes. J. Mol. Biol. 305:567-580. \n" u"<http://dx.doi.org/10.1006/jmbi.2000.4315>", 'name': "TMHMM 2.0" } __DEBUG__ = False def annotate(params, proteins, \ # url = 'http://www.cbs.dtu.dk/ws/TMHMM/TMHMM_2_0_ws0.wsdl', \ # url = 'http://www.cbs.dtu.dk/ws/TMHMM/TMHMM_2_0_ws1.wsdl', \ url="http://raw.github.com/boscoh/inmembrane/master/inmembrane/plugins/extra/TMHMM_2_0_ws0.wsdl", \ batchsize=2000, \ force=False): mapping = {'TMhelix': 'tmhmm_helices', \ 'outside': 'tmhmm_outer_loops', \ 'inside': 'tmhmm_inner_loops', \ } if __DEBUG__: logging.basicConfig(level=logging.INFO) # soap messages (in&out) and http headers logging.getLogger('suds.client').setLevel(logging.DEBUG) # grab the cached results if present outfile = "tmhmm_web.out" if not force and os.path.isfile(outfile): <|code_end|> , generate the next line using the imports in this file: import sys, os, time, json, re import logging from suds.client import Client from suds.bindings import binding from inmembrane.helpers import log_stderr, print_proteins and context (functions, classes, or occasionally code) from other files: # Path: inmembrane/helpers.py # def log_stderr(s, width=76, comment=True): # """ # Wrapper for all stderr out. Allows future customization. # """ # if LOG_SILENT: # return # if s and s[-1] != "\n": # s += "\n" # if not s.startswith("#"): # s = "# " + s # sys.stderr.write(s) # # def print_proteins(proteins): # """ # Prints out the proteins dictionary in a formatted # manner that is also Python-eval compatible. # """ # print "{" # for seqid in proteins: # print " '%s': {" % seqid # for key, value in proteins[seqid].items(): # print " '%s': %s, " % (key, repr(value)) # print " }," # print "}" # # Standard Library alternative # # import pprint # # pp = pprint.PrettyPrinter(indent=4) # # print pp.pformat(proteins) . Output only the next line.
log_stderr("# -> skipped: %s already exists" % outfile)
Here is a snippet: <|code_start|> citation["name"] = result[0].method + " " + result[0].version for res in result.ann: # seqid = res.sequence.id seqid = tmhmm_seq_id_mapping[res.sequence.id] if 'tmhmm_helices' not in proteins[seqid]: proteins[seqid].update({ 'tmhmm_helices': [], 'tmhmm_inner_loops': [], 'tmhmm_outer_loops': [] }) if len(res.annrecords) > 0: for segment in res.annrecords.annrecord: if segment.comment in mapping: tmhmmkey = mapping[segment.comment] proteins[seqid][tmhmmkey].append( \ (segment.range.begin, segment.range.end)) # for caching in the outfile if seqid not in tmhmm_dict: tmhmm_dict[seqid] = {} # extract a copy of results from proteins dictionary # ready to we written to cache file for k in mapping.values(): tmhmm_dict[seqid][k] = proteins[seqid][k] tmhmm_dict[seqid]['program_name'] = citation['name'] <|code_end|> . Write the next line using the current file imports: import sys, os, time, json, re import logging from suds.client import Client from suds.bindings import binding from inmembrane.helpers import log_stderr, print_proteins and context from other files: # Path: inmembrane/helpers.py # def log_stderr(s, width=76, comment=True): # """ # Wrapper for all stderr out. Allows future customization. # """ # if LOG_SILENT: # return # if s and s[-1] != "\n": # s += "\n" # if not s.startswith("#"): # s = "# " + s # sys.stderr.write(s) # # def print_proteins(proteins): # """ # Prints out the proteins dictionary in a formatted # manner that is also Python-eval compatible. # """ # print "{" # for seqid in proteins: # print " '%s': {" % seqid # for key, value in proteins[seqid].items(): # print " '%s': %s, " % (key, repr(value)) # print " }," # print "}" # # Standard Library alternative # # import pprint # # pp = pprint.PrettyPrinter(indent=4) # # print pp.pformat(proteins) , which may include functions, classes, or code. Output only the next line.
if __DEBUG__: print_proteins(proteins)
Given the code snippet: <|code_start|># see: http://www.cbs.dtu.dk/ws/ws.php?entry=SignalP4 citation = {'ref': u"Agnieszka S. Juncker, Hanni Willenbrock, " u"Gunnar Von Heijne, Søren Brunak, Henrik Nielsen, " u"And Anders Krogh. (2003) Prediction of lipoprotein " u"signal peptides in Gram-negative bacteria. Protein " u"Science 12:1652–1662. \n" u"<http://dx.doi.org/10.1110/ps.0303703>", 'name': "LipoP 1.0.ws0" } __DEBUG__ = False def annotate(params, proteins, \ # url = 'http://www.cbs.dtu.dk/ws/LipoP/LipoP_1_0_ws0.wsdl', \ # we host our own fixed version of the WSDL for the moment url="http://raw.github.com/boscoh/inmembrane/master/inmembrane/plugins/extra/LipoP_1_0_ws0.wsdl", \ # url = "http://www.cbs.dtu.dk/ws/LipoP/LipoP_1_0_ws0.wsdl", batchsize=2000, \ force=False): if __DEBUG__: logging.basicConfig(level=logging.INFO) # soap messages (in&out) and http headers logging.getLogger('suds.client').setLevel(logging.DEBUG) # grab the cached results if present outfile = "lipop_web.out" if not force and os.path.isfile(outfile): <|code_end|> , generate the next line using the imports in this file: import sys, os, time, json, re, urllib2 import logging from suds.client import Client from suds.bindings import binding from inmembrane.helpers import log_stderr and context (functions, classes, or occasionally code) from other files: # Path: inmembrane/helpers.py # def log_stderr(s, width=76, comment=True): # """ # Wrapper for all stderr out. Allows future customization. # """ # if LOG_SILENT: # return # if s and s[-1] != "\n": # s += "\n" # if not s.startswith("#"): # s = "# " + s # sys.stderr.write(s) . Output only the next line.
log_stderr("# -> skipped: %s already exists" % outfile)
Using the snippet: <|code_start|> def get_annotations(params): """ Creates a list of annotation functions required by this gram_pos protocol. The main program will run the annotation functions of this list, mapping the correct functions to the strings. As well, the function does some bookeeping on params to make sure the 'hmm_profiles_dir' is pointing in the right place. """ annotations = [] params['signalp4_organism'] = 'gram+' if not params['signalp4_bin'] or params[ 'signalp4_bin'] == 'signalp_scrape_web': annotations += ['signalp_scrape_web'] else: annotations += ['signalp4'] if not params['lipop1_bin'] or params['lipop1_bin'] == 'lipop_scrape_web': annotations += ['lipop_scrape_web'] else: annotations += ['lipop1'] annotations += ['hmmsearch3'] <|code_end|> , determine the next line of code. You have imports: import os from inmembrane.helpers import dict_get, chop_nterminal_peptide and context (class names, function names, or code) available: # Path: inmembrane/helpers.py # def dict_get(this_dict, prop): # """ # Useful helper function to get values from dicts. Takes in # the possibility that the key may not exist, and in that # case returns False. Makes it easier to write code to avoid # handling the case of missing keys. # """ # if prop not in this_dict: # return False # return this_dict[prop] # # def chop_nterminal_peptide(protein, i_cut): # """ # Finds all transmembrane fields in protein ("*_loops" and "*_helices") # and deletes an N-terminal section of the protein indicated by i_cut. # # Assuming the topology of inner and outer loops remain the same, this # may delete a certain number of elements at the N-terminus. Allows a # simple way of removing lipo-protein and secretion-protein signals from # the evaluation of the outer_loops of the protein. # """ # protein['sequence_length'] -= i_cut # for prop in protein: # if '_loops' in prop or '_helices' in prop: # sses = protein[prop] # for i in range(len(sses)): # j, k = sses[i] # sses[i] = (j - i_cut, k - i_cut) # for prop in protein: # if '_loops' in prop or '_helices' in prop: # sses = protein[prop] # for i in reversed(range(len(sses))): # j, k = sses[i] # # tests if this loop or TM-helix has been cut out # if j <= 0 and k <= 0: # del sses[i] # # otherewise, neg value means loop or TM-helix is at the new N-terminal # elif j <= 0 and k > 0: # sses[i] = (1, k) # # if a TM-helix gets cut in half and becomes a new N-terminal, # # convert the remaining residues to a loop and remove the helix # if '_helices' in prop: # program = prop.split('_')[0] # for x in protein: # if x == '%s_loops' % program: # new_N_loop = protein[x][0] # new_N_loop[0] = 1 # del sses[i] . Output only the next line.
if dict_get(params, 'helix_programs'):
Here is a snippet: <|code_start|> params['internal_exposed_loop_min'])) if extents: return max(extents) else: return 0 terminal_exposed_loop_min = \ params['terminal_exposed_loop_min'] is_hmm_profile_match = dict_get(protein, 'hmmsearch') is_lipop = dict_get(protein, 'is_lipop') if is_lipop: i_lipop_cut = protein['lipop_cleave_position'] is_signalp = dict_get(protein, 'is_signalp') if is_signalp: i_signalp_cut = protein['signalp_cleave_position'] details = [] if is_hmm_profile_match: details += ["hmm(%s)" % "|".join(protein['hmmsearch'])] if is_lipop: details += ["lipop"] if is_signalp: details += ["signalp"] for program in params['helix_programs']: if has_tm_helix(protein): n = len(protein['%s_helices' % program]) details += [program + "(%d)" % n] if is_lipop: <|code_end|> . Write the next line using the current file imports: import os from inmembrane.helpers import dict_get, chop_nterminal_peptide and context from other files: # Path: inmembrane/helpers.py # def dict_get(this_dict, prop): # """ # Useful helper function to get values from dicts. Takes in # the possibility that the key may not exist, and in that # case returns False. Makes it easier to write code to avoid # handling the case of missing keys. # """ # if prop not in this_dict: # return False # return this_dict[prop] # # def chop_nterminal_peptide(protein, i_cut): # """ # Finds all transmembrane fields in protein ("*_loops" and "*_helices") # and deletes an N-terminal section of the protein indicated by i_cut. # # Assuming the topology of inner and outer loops remain the same, this # may delete a certain number of elements at the N-terminus. Allows a # simple way of removing lipo-protein and secretion-protein signals from # the evaluation of the outer_loops of the protein. # """ # protein['sequence_length'] -= i_cut # for prop in protein: # if '_loops' in prop or '_helices' in prop: # sses = protein[prop] # for i in range(len(sses)): # j, k = sses[i] # sses[i] = (j - i_cut, k - i_cut) # for prop in protein: # if '_loops' in prop or '_helices' in prop: # sses = protein[prop] # for i in reversed(range(len(sses))): # j, k = sses[i] # # tests if this loop or TM-helix has been cut out # if j <= 0 and k <= 0: # del sses[i] # # otherewise, neg value means loop or TM-helix is at the new N-terminal # elif j <= 0 and k > 0: # sses[i] = (1, k) # # if a TM-helix gets cut in half and becomes a new N-terminal, # # convert the remaining residues to a loop and remove the helix # if '_helices' in prop: # program = prop.split('_')[0] # for x in protein: # if x == '%s_loops' % program: # new_N_loop = protein[x][0] # new_N_loop[0] = 1 # del sses[i] , which may include functions, classes, or code. Output only the next line.
chop_nterminal_peptide(protein, i_lipop_cut)
Based on the snippet: <|code_start|># -*- coding: utf-8 -*- __DEBUG__ = False citation = {'ref': u"Berven FS, Flikka K, Jensen HB, Eidhammer I (2004) " u"BOMP: a program to predict integral beta-barrel outer " u"membrane proteins encoded within genomes of Gram-negative " u"bacteria. Nucleic acids research 32: W394-9. \n" u"<http://dx.crossref.org/10.1093/nar/gkh351>", 'name': "BOMP" } def annotate(params, proteins, \ url="http://services.cbu.uib.no/tools/bomp/", force=False): """ Uses the BOMP web service (http://services.cbu.uib.no/tools/bomp/) to predict if proteins are outer membrane beta-barrels. """ # set the user-agent so web services can block us if they want ... :/ python_version = sys.version.split()[0] agent("Python-urllib/%s (twill; inmembrane/%s)" % (python_version, inmembrane.__version__)) bomp_out = 'bomp.out' <|code_end|> , predict the immediate next line with the help of imports: import sys, os, time, StringIO import twill import inmembrane from twill.commands import find, formfile, follow, fv, go, show, \ showforms, showlinks, submit, agent from BeautifulSoup import BeautifulSoup from inmembrane.helpers import log_stderr, parse_fasta_header and context (classes, functions, sometimes code) from other files: # Path: inmembrane/helpers.py # def log_stderr(s, width=76, comment=True): # """ # Wrapper for all stderr out. Allows future customization. # """ # if LOG_SILENT: # return # if s and s[-1] != "\n": # s += "\n" # if not s.startswith("#"): # s = "# " + s # sys.stderr.write(s) # # def parse_fasta_header(header): # """ # Parses a FASTA format header (with our without the initial '>') and returns a # tuple of sequence id and sequence name/description. # # If NCBI SeqID format (gi|gi-number|gb|accession etc, is detected # the first id in the list is used as the canonical id (see see # http://www.ncbi.nlm.nih.gov/books/NBK21097/#A631 ). # """ # if header[0] == '>': # header = header[1:] # tokens = header.split('|') # # check to see if we have an NCBI-style header # if header.find("|") != -1 and len(tokens[0]) <= 3: # # "gi|ginumber|gb|accession bla bla" becomes "gi|ginumber" # seqid = "%s|%s" % (tokens[0], tokens[1].split()[0]) # name = tokens[-1:][0].strip() # # otherwise just split on spaces & hope for the best # else: # tokens = header.split() # seqid = tokens[0] # name = header[0:-1].strip() # # return seqid, name . Output only the next line.
log_stderr("# BOMP(web) %s > %s" % (params['fasta'], bomp_out))
Given snippet: <|code_start|> u"bacteria. Nucleic acids research 32: W394-9. \n" u"<http://dx.crossref.org/10.1093/nar/gkh351>", 'name': "BOMP" } def annotate(params, proteins, \ url="http://services.cbu.uib.no/tools/bomp/", force=False): """ Uses the BOMP web service (http://services.cbu.uib.no/tools/bomp/) to predict if proteins are outer membrane beta-barrels. """ # set the user-agent so web services can block us if they want ... :/ python_version = sys.version.split()[0] agent("Python-urllib/%s (twill; inmembrane/%s)" % (python_version, inmembrane.__version__)) bomp_out = 'bomp.out' log_stderr("# BOMP(web) %s > %s" % (params['fasta'], bomp_out)) if not force and os.path.isfile(bomp_out): log_stderr("# -> skipped: %s already exists" % bomp_out) bomp_categories = {} fh = open(bomp_out, 'r') for l in fh: words = l.split() bomp_category = int(words[-1:][0]) <|code_end|> , continue by predicting the next line. Consider current file imports: import sys, os, time, StringIO import twill import inmembrane from twill.commands import find, formfile, follow, fv, go, show, \ showforms, showlinks, submit, agent from BeautifulSoup import BeautifulSoup from inmembrane.helpers import log_stderr, parse_fasta_header and context: # Path: inmembrane/helpers.py # def log_stderr(s, width=76, comment=True): # """ # Wrapper for all stderr out. Allows future customization. # """ # if LOG_SILENT: # return # if s and s[-1] != "\n": # s += "\n" # if not s.startswith("#"): # s = "# " + s # sys.stderr.write(s) # # def parse_fasta_header(header): # """ # Parses a FASTA format header (with our without the initial '>') and returns a # tuple of sequence id and sequence name/description. # # If NCBI SeqID format (gi|gi-number|gb|accession etc, is detected # the first id in the list is used as the canonical id (see see # http://www.ncbi.nlm.nih.gov/books/NBK21097/#A631 ). # """ # if header[0] == '>': # header = header[1:] # tokens = header.split('|') # # check to see if we have an NCBI-style header # if header.find("|") != -1 and len(tokens[0]) <= 3: # # "gi|ginumber|gb|accession bla bla" becomes "gi|ginumber" # seqid = "%s|%s" % (tokens[0], tokens[1].split()[0]) # name = tokens[-1:][0].strip() # # otherwise just split on spaces & hope for the best # else: # tokens = header.split() # seqid = tokens[0] # name = header[0:-1].strip() # # return seqid, name which might include code, classes, or functions. Output only the next line.
seqid = parse_fasta_header(l)[0]
Continue the code snippet: <|code_start|> class TestBomp(PluginTestBase): _plugin_name = "bomp_web" def test_bomp(self): self.expected_output = { u'gi|107837101': 3, u'gi|107836588': 5, u'gi|107836852': 5 } <|code_end|> . Use current file imports: import os import glob import unittest import sys import inmembrane import inmembrane.tests from inmembrane import helpers from inmembrane.plugins import bomp_web from inmembrane.tests.PluginTestBase import PluginTestBase and context (classes, functions, or code) from other files: # Path: inmembrane/helpers.py # LOG_SILENT = False # LOG_SILENT = b # def dict_get(this_dict, prop): # def run_with_output(cmd): # def run(cmd, out_file=None): # def silence_log(b): # def log_stderr(s, width=76, comment=True): # def log_stdout(s, width=76): # def parse_fasta_header(header): # def seqid_to_filename(seqid): # def create_proteins_dict(fasta): # def print_proteins(proteins): # def write_proteins_fasta( # fasta_filename, proteins, seqids, width=50): # def proteins_to_fasta(proteins, seqids=[], use_safe_seqid=False, width=50): # def chop_nterminal_peptide(protein, i_cut): # def generate_safe_seqids(proteins): # def clean_directory(top, excluded_files): # def html2text(page, aggressive=False): # # Path: inmembrane/plugins/bomp_web.py # __DEBUG__ = False # def annotate(params, proteins, \ # url="http://services.cbu.uib.no/tools/bomp/", force=False): # # Path: inmembrane/tests/PluginTestBase.py # class PluginTestBase(unittest.TestCase): # _plugin_name = "" # # def setUp(self): # """ # Sets up a directory, a parameters dictionary and a proteins dictionary # object in preparation for running a test of a plugin. # # Creates a temporary directory (eg /tmp/.inmembrane_signalp_web_TleeRw ), # copies the test input data (input.fasta) into it and changes the # current working directory. # # Should be subclassed adding a method with the specific test(s) for # the plugin. The subclass should set self._plugin_name to the name of # the plugin. # """ # self.test_data_dir = os.path.join( # os.path.abspath( # os.path.dirname(inmembrane.tests.__file__)), self._plugin_name) # # self.output_dir = tempfile.mkdtemp( # prefix=".inmembrane_%s_" % (self._plugin_name)) # shutil.copyfile(os.path.join(self.test_data_dir, "input.fasta"), # os.path.join(self.output_dir, "input.fasta")) # os.chdir(self.output_dir) # helpers.silence_log(True) # # self.params = inmembrane.get_params() # self.params['fasta'] = "input.fasta" # self.seqids, self.proteins = \ # helpers.create_proteins_dict(self.params['fasta']) . Output only the next line.
self.output = bomp_web.annotate(self.params, self.proteins, force=True)
Predict the next line after this snippet: <|code_start|> Parses the TatFind HTML output (file-like object or a list of strings) an uses it to annotate and return an associated 'proteins' data structure. """ for l in output: if "Results for" in l: seqid = l.split("Results for ")[1].split(":")[:-1][0] # parse id string to bring it to our format seqid, unused = parse_fasta_header(seqid) # "TRUE" or "FALSE" tat_pred = l.split("Results for ")[1].split(":")[-1:][0].strip() if tat_pred == "TRUE": proteins[seqid]["is_tatfind"] = True else: proteins[seqid]["is_tatfind"] = False return proteins def annotate(params, proteins, \ url="http://signalfind.org/tatfind.html", force=False): """ Interfaces with the TatFind web service at (http://signalfind.org/tatfind.html) to predict if protein sequences contain Twin-Arginine Translocation (Tat) signal peptides. """ # set the user-agent so web services can block us if they want ... :/ python_version = sys.version.split()[0] agent("Python-urllib/%s (twill; inmembrane)" % python_version) outfn = 'tatfind.out' <|code_end|> using the current file's imports: import sys, os, time, StringIO import twill from twill.commands import find, formfile, follow, fv, go, show, \ showforms, showlinks, submit, agent from inmembrane.helpers import log_stderr, parse_fasta_header and any relevant context from other files: # Path: inmembrane/helpers.py # def log_stderr(s, width=76, comment=True): # """ # Wrapper for all stderr out. Allows future customization. # """ # if LOG_SILENT: # return # if s and s[-1] != "\n": # s += "\n" # if not s.startswith("#"): # s = "# " + s # sys.stderr.write(s) # # def parse_fasta_header(header): # """ # Parses a FASTA format header (with our without the initial '>') and returns a # tuple of sequence id and sequence name/description. # # If NCBI SeqID format (gi|gi-number|gb|accession etc, is detected # the first id in the list is used as the canonical id (see see # http://www.ncbi.nlm.nih.gov/books/NBK21097/#A631 ). # """ # if header[0] == '>': # header = header[1:] # tokens = header.split('|') # # check to see if we have an NCBI-style header # if header.find("|") != -1 and len(tokens[0]) <= 3: # # "gi|ginumber|gb|accession bla bla" becomes "gi|ginumber" # seqid = "%s|%s" % (tokens[0], tokens[1].split()[0]) # name = tokens[-1:][0].strip() # # otherwise just split on spaces & hope for the best # else: # tokens = header.split() # seqid = tokens[0] # name = header[0:-1].strip() # # return seqid, name . Output only the next line.
log_stderr("# TatFind(web) %s > %s" % (params['fasta'], outfn))
Based on the snippet: <|code_start|># -*- coding: utf-8 -*- citation = {'ref': u"Rose, R.W., T. Brüser,. J. C. Kissinger, and M. " u"Pohlschröder. 2002. Adaptation of protein secretion " u"to extremely high salt concentrations by extensive use " u"of the twin arginine translocation pathway. Mol. Microbiol." u"5: 943-950 \n" u"<http://dx.doi.org/10.1046/j.1365-2958.2002.03090.x>", 'name': "TatFind 1.4" } __DEBUG__ = False def parse_tatfind_output(output, proteins): """ Parses the TatFind HTML output (file-like object or a list of strings) an uses it to annotate and return an associated 'proteins' data structure. """ for l in output: if "Results for" in l: seqid = l.split("Results for ")[1].split(":")[:-1][0] # parse id string to bring it to our format <|code_end|> , predict the immediate next line with the help of imports: import sys, os, time, StringIO import twill from twill.commands import find, formfile, follow, fv, go, show, \ showforms, showlinks, submit, agent from inmembrane.helpers import log_stderr, parse_fasta_header and context (classes, functions, sometimes code) from other files: # Path: inmembrane/helpers.py # def log_stderr(s, width=76, comment=True): # """ # Wrapper for all stderr out. Allows future customization. # """ # if LOG_SILENT: # return # if s and s[-1] != "\n": # s += "\n" # if not s.startswith("#"): # s = "# " + s # sys.stderr.write(s) # # def parse_fasta_header(header): # """ # Parses a FASTA format header (with our without the initial '>') and returns a # tuple of sequence id and sequence name/description. # # If NCBI SeqID format (gi|gi-number|gb|accession etc, is detected # the first id in the list is used as the canonical id (see see # http://www.ncbi.nlm.nih.gov/books/NBK21097/#A631 ). # """ # if header[0] == '>': # header = header[1:] # tokens = header.split('|') # # check to see if we have an NCBI-style header # if header.find("|") != -1 and len(tokens[0]) <= 3: # # "gi|ginumber|gb|accession bla bla" becomes "gi|ginumber" # seqid = "%s|%s" % (tokens[0], tokens[1].split()[0]) # name = tokens[-1:][0].strip() # # otherwise just split on spaces & hope for the best # else: # tokens = header.split() # seqid = tokens[0] # name = header[0:-1].strip() # # return seqid, name . Output only the next line.
seqid, unused = parse_fasta_header(seqid)
Given the code snippet: <|code_start|> 'name': "LipoP 1.0 (web interface)" } __DEBUG__ = False try: except: def annotate(params, proteins, batchsize=2000, force=False): """ This plugin interfaces with the LipoP web interface (for humans) and scrapes the results. There once was a SOAP service but it was discontinued, so now we use this. """ baseurl = "http://www.cbs.dtu.dk" url = baseurl + "/cgi-bin/webface2.fcgi" # grab the cached results if present outfile = "lipop_scrape_web.out" if not force and os.path.isfile(outfile): log_stderr("# -> skipped: %s already exists" % outfile) proteins, id_mapping = generate_safe_seqids(proteins) fh = open(outfile, 'r') resultpage = fh.read() fh.close() # soup = BeautifulSoup(resultpage) <|code_end|> , generate the next line using the imports in this file: import sys, os, time import requests import inmembrane from StringIO import StringIO from BeautifulSoup import BeautifulSoup from collections import OrderedDict from ordereddict import OrderedDict from inmembrane.plugins.lipop1 import parse_lipop from inmembrane.helpers import log_stderr from inmembrane.helpers import generate_safe_seqids, proteins_to_fasta and context (functions, classes, or occasionally code) from other files: # Path: inmembrane/plugins/lipop1.py # def parse_lipop(text, proteins, id_mapping=None): # """ # Parses the text output of the LipoP program and returns a 'proteins' # datastructure with annotations. # # The parser can also that the HTML returned by the LipoP web interface. # If a dictionary of {safe_seqid : seqid} mappings is given, the parser # will expect the input text to contain safe_seqids. # """ # # if id_mapping is None: # id_mapping = [] # # # initialize fields in each protein # for seqid in proteins: # proteins[seqid]['is_lipop'] = False # proteins[seqid]['lipop_cleave_position'] = None # # for l in text.split('\n'): # words = l.split() # # if 'SpII score' in l: # seqid = parse_fasta_header(words[1])[0] # if id_mapping: # seqid = id_mapping[seqid] # if 'cleavage' in l: # pair = words[5].split("=")[1] # i = int(pair.split('-')[0]) # else: # i = None # proteins[seqid]['is_lipop'] = 'Sp' in words[2] # proteins[seqid]['lipop_cleave_position'] = i # # # check for an E.coli style inner membrane retention signal # # Asp+2 to cleavage site. There are other apparent retention # # signals in E. coli and other gram- bacteria in addition to # # the Asp+2 which we don't detect here (yet). # # (Yamaguchi et al, 1988; Tokuda and Matsuyama, 2005 [review]) # if dict_get(proteins[seqid], 'lipop_cleave_position'): # plus_two = proteins[seqid]['lipop_cleave_position'] + 1 # if proteins[seqid]['seq'][plus_two] == 'D': # proteins[seqid]['lipop_im_retention_signal'] = True # # return proteins # # Path: inmembrane/helpers.py # def log_stderr(s, width=76, comment=True): # """ # Wrapper for all stderr out. Allows future customization. # """ # if LOG_SILENT: # return # if s and s[-1] != "\n": # s += "\n" # if not s.startswith("#"): # s = "# " + s # sys.stderr.write(s) # # Path: inmembrane/helpers.py # def generate_safe_seqids(proteins): # """ # Takes a 'proteins' dictionary, keyed by sequence id, and # adds a 'safe' sequence id ('safe_seqid') that is less likely # to be munged or break various external programs. # # Returns a tuple of the updated proteins dictionary and a dictionary # mapping the 'safe' sequence ids to the original ids. # """ # id_mapping = {} # count = 0 # for seqid in proteins: # safe_id = re.sub(r'[^\w]', "", seqid) + '_' + `count` # id_mapping[safe_id] = seqid # proteins[seqid]['safe_seqid'] = safe_id # count += 1 # # return (proteins, id_mapping) # # def proteins_to_fasta(proteins, seqids=[], use_safe_seqid=False, width=50): # """ # Takes a proteins dictionary and returns a string containing # all the sequences in FASTA format. Option parameters are # a list of seqids to output (seqids) and the line width (width). # """ # if seqids: # idlist = seqids # else: # idlist = proteins # # fasta_out = "" # for seqid in idlist: # seq_wrap = textwrap.fill(proteins[seqid]['seq'], width) # if use_safe_seqid: # header = proteins[seqid]['safe_seqid'] # else: # header = proteins[seqid]['name'] # fasta_out += ">%s\n%s\n" % (header, seq_wrap) # return fasta_out . Output only the next line.
proteins = parse_lipop(resultpage, proteins, id_mapping=id_mapping)
Here is a snippet: <|code_start|>citation = {'ref': u"Agnieszka S. Juncker, Hanni Willenbrock, " u"Gunnar Von Heijne, Søren Brunak, Henrik Nielsen, " u"And Anders Krogh. (2003) Prediction of lipoprotein " u"signal peptides in Gram-negative bacteria. Protein " u"Science 12:1652–1662. \n" u"<http://dx.doi.org/10.1110/ps.0303703>", 'name': "LipoP 1.0 (web interface)" } __DEBUG__ = False try: except: def annotate(params, proteins, batchsize=2000, force=False): """ This plugin interfaces with the LipoP web interface (for humans) and scrapes the results. There once was a SOAP service but it was discontinued, so now we use this. """ baseurl = "http://www.cbs.dtu.dk" url = baseurl + "/cgi-bin/webface2.fcgi" # grab the cached results if present outfile = "lipop_scrape_web.out" if not force and os.path.isfile(outfile): <|code_end|> . Write the next line using the current file imports: import sys, os, time import requests import inmembrane from StringIO import StringIO from BeautifulSoup import BeautifulSoup from collections import OrderedDict from ordereddict import OrderedDict from inmembrane.plugins.lipop1 import parse_lipop from inmembrane.helpers import log_stderr from inmembrane.helpers import generate_safe_seqids, proteins_to_fasta and context from other files: # Path: inmembrane/plugins/lipop1.py # def parse_lipop(text, proteins, id_mapping=None): # """ # Parses the text output of the LipoP program and returns a 'proteins' # datastructure with annotations. # # The parser can also that the HTML returned by the LipoP web interface. # If a dictionary of {safe_seqid : seqid} mappings is given, the parser # will expect the input text to contain safe_seqids. # """ # # if id_mapping is None: # id_mapping = [] # # # initialize fields in each protein # for seqid in proteins: # proteins[seqid]['is_lipop'] = False # proteins[seqid]['lipop_cleave_position'] = None # # for l in text.split('\n'): # words = l.split() # # if 'SpII score' in l: # seqid = parse_fasta_header(words[1])[0] # if id_mapping: # seqid = id_mapping[seqid] # if 'cleavage' in l: # pair = words[5].split("=")[1] # i = int(pair.split('-')[0]) # else: # i = None # proteins[seqid]['is_lipop'] = 'Sp' in words[2] # proteins[seqid]['lipop_cleave_position'] = i # # # check for an E.coli style inner membrane retention signal # # Asp+2 to cleavage site. There are other apparent retention # # signals in E. coli and other gram- bacteria in addition to # # the Asp+2 which we don't detect here (yet). # # (Yamaguchi et al, 1988; Tokuda and Matsuyama, 2005 [review]) # if dict_get(proteins[seqid], 'lipop_cleave_position'): # plus_two = proteins[seqid]['lipop_cleave_position'] + 1 # if proteins[seqid]['seq'][plus_two] == 'D': # proteins[seqid]['lipop_im_retention_signal'] = True # # return proteins # # Path: inmembrane/helpers.py # def log_stderr(s, width=76, comment=True): # """ # Wrapper for all stderr out. Allows future customization. # """ # if LOG_SILENT: # return # if s and s[-1] != "\n": # s += "\n" # if not s.startswith("#"): # s = "# " + s # sys.stderr.write(s) # # Path: inmembrane/helpers.py # def generate_safe_seqids(proteins): # """ # Takes a 'proteins' dictionary, keyed by sequence id, and # adds a 'safe' sequence id ('safe_seqid') that is less likely # to be munged or break various external programs. # # Returns a tuple of the updated proteins dictionary and a dictionary # mapping the 'safe' sequence ids to the original ids. # """ # id_mapping = {} # count = 0 # for seqid in proteins: # safe_id = re.sub(r'[^\w]', "", seqid) + '_' + `count` # id_mapping[safe_id] = seqid # proteins[seqid]['safe_seqid'] = safe_id # count += 1 # # return (proteins, id_mapping) # # def proteins_to_fasta(proteins, seqids=[], use_safe_seqid=False, width=50): # """ # Takes a proteins dictionary and returns a string containing # all the sequences in FASTA format. Option parameters are # a list of seqids to output (seqids) and the line width (width). # """ # if seqids: # idlist = seqids # else: # idlist = proteins # # fasta_out = "" # for seqid in idlist: # seq_wrap = textwrap.fill(proteins[seqid]['seq'], width) # if use_safe_seqid: # header = proteins[seqid]['safe_seqid'] # else: # header = proteins[seqid]['name'] # fasta_out += ">%s\n%s\n" % (header, seq_wrap) # return fasta_out , which may include functions, classes, or code. Output only the next line.
log_stderr("# -> skipped: %s already exists" % outfile)
Predict the next line after this snippet: <|code_start|> u"Gunnar Von Heijne, Søren Brunak, Henrik Nielsen, " u"And Anders Krogh. (2003) Prediction of lipoprotein " u"signal peptides in Gram-negative bacteria. Protein " u"Science 12:1652–1662. \n" u"<http://dx.doi.org/10.1110/ps.0303703>", 'name': "LipoP 1.0 (web interface)" } __DEBUG__ = False try: except: def annotate(params, proteins, batchsize=2000, force=False): """ This plugin interfaces with the LipoP web interface (for humans) and scrapes the results. There once was a SOAP service but it was discontinued, so now we use this. """ baseurl = "http://www.cbs.dtu.dk" url = baseurl + "/cgi-bin/webface2.fcgi" # grab the cached results if present outfile = "lipop_scrape_web.out" if not force and os.path.isfile(outfile): log_stderr("# -> skipped: %s already exists" % outfile) <|code_end|> using the current file's imports: import sys, os, time import requests import inmembrane from StringIO import StringIO from BeautifulSoup import BeautifulSoup from collections import OrderedDict from ordereddict import OrderedDict from inmembrane.plugins.lipop1 import parse_lipop from inmembrane.helpers import log_stderr from inmembrane.helpers import generate_safe_seqids, proteins_to_fasta and any relevant context from other files: # Path: inmembrane/plugins/lipop1.py # def parse_lipop(text, proteins, id_mapping=None): # """ # Parses the text output of the LipoP program and returns a 'proteins' # datastructure with annotations. # # The parser can also that the HTML returned by the LipoP web interface. # If a dictionary of {safe_seqid : seqid} mappings is given, the parser # will expect the input text to contain safe_seqids. # """ # # if id_mapping is None: # id_mapping = [] # # # initialize fields in each protein # for seqid in proteins: # proteins[seqid]['is_lipop'] = False # proteins[seqid]['lipop_cleave_position'] = None # # for l in text.split('\n'): # words = l.split() # # if 'SpII score' in l: # seqid = parse_fasta_header(words[1])[0] # if id_mapping: # seqid = id_mapping[seqid] # if 'cleavage' in l: # pair = words[5].split("=")[1] # i = int(pair.split('-')[0]) # else: # i = None # proteins[seqid]['is_lipop'] = 'Sp' in words[2] # proteins[seqid]['lipop_cleave_position'] = i # # # check for an E.coli style inner membrane retention signal # # Asp+2 to cleavage site. There are other apparent retention # # signals in E. coli and other gram- bacteria in addition to # # the Asp+2 which we don't detect here (yet). # # (Yamaguchi et al, 1988; Tokuda and Matsuyama, 2005 [review]) # if dict_get(proteins[seqid], 'lipop_cleave_position'): # plus_two = proteins[seqid]['lipop_cleave_position'] + 1 # if proteins[seqid]['seq'][plus_two] == 'D': # proteins[seqid]['lipop_im_retention_signal'] = True # # return proteins # # Path: inmembrane/helpers.py # def log_stderr(s, width=76, comment=True): # """ # Wrapper for all stderr out. Allows future customization. # """ # if LOG_SILENT: # return # if s and s[-1] != "\n": # s += "\n" # if not s.startswith("#"): # s = "# " + s # sys.stderr.write(s) # # Path: inmembrane/helpers.py # def generate_safe_seqids(proteins): # """ # Takes a 'proteins' dictionary, keyed by sequence id, and # adds a 'safe' sequence id ('safe_seqid') that is less likely # to be munged or break various external programs. # # Returns a tuple of the updated proteins dictionary and a dictionary # mapping the 'safe' sequence ids to the original ids. # """ # id_mapping = {} # count = 0 # for seqid in proteins: # safe_id = re.sub(r'[^\w]', "", seqid) + '_' + `count` # id_mapping[safe_id] = seqid # proteins[seqid]['safe_seqid'] = safe_id # count += 1 # # return (proteins, id_mapping) # # def proteins_to_fasta(proteins, seqids=[], use_safe_seqid=False, width=50): # """ # Takes a proteins dictionary and returns a string containing # all the sequences in FASTA format. Option parameters are # a list of seqids to output (seqids) and the line width (width). # """ # if seqids: # idlist = seqids # else: # idlist = proteins # # fasta_out = "" # for seqid in idlist: # seq_wrap = textwrap.fill(proteins[seqid]['seq'], width) # if use_safe_seqid: # header = proteins[seqid]['safe_seqid'] # else: # header = proteins[seqid]['name'] # fasta_out += ">%s\n%s\n" % (header, seq_wrap) # return fasta_out . Output only the next line.
proteins, id_mapping = generate_safe_seqids(proteins)
Using the snippet: <|code_start|> This plugin interfaces with the LipoP web interface (for humans) and scrapes the results. There once was a SOAP service but it was discontinued, so now we use this. """ baseurl = "http://www.cbs.dtu.dk" url = baseurl + "/cgi-bin/webface2.fcgi" # grab the cached results if present outfile = "lipop_scrape_web.out" if not force and os.path.isfile(outfile): log_stderr("# -> skipped: %s already exists" % outfile) proteins, id_mapping = generate_safe_seqids(proteins) fh = open(outfile, 'r') resultpage = fh.read() fh.close() # soup = BeautifulSoup(resultpage) proteins = parse_lipop(resultpage, proteins, id_mapping=id_mapping) return proteins proteins, id_mapping = generate_safe_seqids(proteins) seqids = proteins.keys() allresultpages = "" while seqids: seqid_batch = seqids[0:batchsize] del seqids[0:batchsize] # get batch of sequences in fasta format with munged ids # (workaround for lipop sequence id munging) <|code_end|> , determine the next line of code. You have imports: import sys, os, time import requests import inmembrane from StringIO import StringIO from BeautifulSoup import BeautifulSoup from collections import OrderedDict from ordereddict import OrderedDict from inmembrane.plugins.lipop1 import parse_lipop from inmembrane.helpers import log_stderr from inmembrane.helpers import generate_safe_seqids, proteins_to_fasta and context (class names, function names, or code) available: # Path: inmembrane/plugins/lipop1.py # def parse_lipop(text, proteins, id_mapping=None): # """ # Parses the text output of the LipoP program and returns a 'proteins' # datastructure with annotations. # # The parser can also that the HTML returned by the LipoP web interface. # If a dictionary of {safe_seqid : seqid} mappings is given, the parser # will expect the input text to contain safe_seqids. # """ # # if id_mapping is None: # id_mapping = [] # # # initialize fields in each protein # for seqid in proteins: # proteins[seqid]['is_lipop'] = False # proteins[seqid]['lipop_cleave_position'] = None # # for l in text.split('\n'): # words = l.split() # # if 'SpII score' in l: # seqid = parse_fasta_header(words[1])[0] # if id_mapping: # seqid = id_mapping[seqid] # if 'cleavage' in l: # pair = words[5].split("=")[1] # i = int(pair.split('-')[0]) # else: # i = None # proteins[seqid]['is_lipop'] = 'Sp' in words[2] # proteins[seqid]['lipop_cleave_position'] = i # # # check for an E.coli style inner membrane retention signal # # Asp+2 to cleavage site. There are other apparent retention # # signals in E. coli and other gram- bacteria in addition to # # the Asp+2 which we don't detect here (yet). # # (Yamaguchi et al, 1988; Tokuda and Matsuyama, 2005 [review]) # if dict_get(proteins[seqid], 'lipop_cleave_position'): # plus_two = proteins[seqid]['lipop_cleave_position'] + 1 # if proteins[seqid]['seq'][plus_two] == 'D': # proteins[seqid]['lipop_im_retention_signal'] = True # # return proteins # # Path: inmembrane/helpers.py # def log_stderr(s, width=76, comment=True): # """ # Wrapper for all stderr out. Allows future customization. # """ # if LOG_SILENT: # return # if s and s[-1] != "\n": # s += "\n" # if not s.startswith("#"): # s = "# " + s # sys.stderr.write(s) # # Path: inmembrane/helpers.py # def generate_safe_seqids(proteins): # """ # Takes a 'proteins' dictionary, keyed by sequence id, and # adds a 'safe' sequence id ('safe_seqid') that is less likely # to be munged or break various external programs. # # Returns a tuple of the updated proteins dictionary and a dictionary # mapping the 'safe' sequence ids to the original ids. # """ # id_mapping = {} # count = 0 # for seqid in proteins: # safe_id = re.sub(r'[^\w]', "", seqid) + '_' + `count` # id_mapping[safe_id] = seqid # proteins[seqid]['safe_seqid'] = safe_id # count += 1 # # return (proteins, id_mapping) # # def proteins_to_fasta(proteins, seqids=[], use_safe_seqid=False, width=50): # """ # Takes a proteins dictionary and returns a string containing # all the sequences in FASTA format. Option parameters are # a list of seqids to output (seqids) and the line width (width). # """ # if seqids: # idlist = seqids # else: # idlist = proteins # # fasta_out = "" # for seqid in idlist: # seq_wrap = textwrap.fill(proteins[seqid]['seq'], width) # if use_safe_seqid: # header = proteins[seqid]['safe_seqid'] # else: # header = proteins[seqid]['name'] # fasta_out += ">%s\n%s\n" % (header, seq_wrap) # return fasta_out . Output only the next line.
safe_fasta = proteins_to_fasta(proteins,
Next line prediction: <|code_start|> class TestSignalpScrapeWeb(PluginTestBase): _plugin_name = "signalp_scrape_web" def test_signalp4(self): if not self.params['signalp4_bin']: self.params['signalp4_bin'] = 'signalp_scrape_web' self.params['fasta'] = "input.fasta" self.params['signalp4_organism'] = 'gram+' <|code_end|> . Use current file imports: (import os import unittest import sys import inmembrane import inmembrane.tests from inmembrane import helpers from inmembrane.plugins import signalp_scrape_web from inmembrane.tests.PluginTestBase import PluginTestBase) and context including class names, function names, or small code snippets from other files: # Path: inmembrane/helpers.py # LOG_SILENT = False # LOG_SILENT = b # def dict_get(this_dict, prop): # def run_with_output(cmd): # def run(cmd, out_file=None): # def silence_log(b): # def log_stderr(s, width=76, comment=True): # def log_stdout(s, width=76): # def parse_fasta_header(header): # def seqid_to_filename(seqid): # def create_proteins_dict(fasta): # def print_proteins(proteins): # def write_proteins_fasta( # fasta_filename, proteins, seqids, width=50): # def proteins_to_fasta(proteins, seqids=[], use_safe_seqid=False, width=50): # def chop_nterminal_peptide(protein, i_cut): # def generate_safe_seqids(proteins): # def clean_directory(top, excluded_files): # def html2text(page, aggressive=False): # # Path: inmembrane/plugins/signalp_scrape_web.py # __DEBUG__ = False # def annotate(params, proteins, batchsize=2000, force=False): # # Path: inmembrane/tests/PluginTestBase.py # class PluginTestBase(unittest.TestCase): # _plugin_name = "" # # def setUp(self): # """ # Sets up a directory, a parameters dictionary and a proteins dictionary # object in preparation for running a test of a plugin. # # Creates a temporary directory (eg /tmp/.inmembrane_signalp_web_TleeRw ), # copies the test input data (input.fasta) into it and changes the # current working directory. # # Should be subclassed adding a method with the specific test(s) for # the plugin. The subclass should set self._plugin_name to the name of # the plugin. # """ # self.test_data_dir = os.path.join( # os.path.abspath( # os.path.dirname(inmembrane.tests.__file__)), self._plugin_name) # # self.output_dir = tempfile.mkdtemp( # prefix=".inmembrane_%s_" % (self._plugin_name)) # shutil.copyfile(os.path.join(self.test_data_dir, "input.fasta"), # os.path.join(self.output_dir, "input.fasta")) # os.chdir(self.output_dir) # helpers.silence_log(True) # # self.params = inmembrane.get_params() # self.params['fasta'] = "input.fasta" # self.seqids, self.proteins = \ # helpers.create_proteins_dict(self.params['fasta']) . Output only the next line.
signalp_scrape_web.annotate(self.params, self.proteins)
Continue the code snippet: <|code_start|> class TestHmmsearch3(PluginTestBase): _plugin_name = "hmmsearch3" def test_hmmsearch3(self): self.params['hmm_profiles_dir'] = os.path.join(inmembrane.module_dir, "protocols/gram_pos_profiles") <|code_end|> . Use current file imports: import os import unittest import sys import inmembrane import inmembrane.tests from inmembrane import helpers from inmembrane.plugins import hmmsearch3 from inmembrane.tests.PluginTestBase import PluginTestBase and context (classes, functions, or code) from other files: # Path: inmembrane/helpers.py # LOG_SILENT = False # LOG_SILENT = b # def dict_get(this_dict, prop): # def run_with_output(cmd): # def run(cmd, out_file=None): # def silence_log(b): # def log_stderr(s, width=76, comment=True): # def log_stdout(s, width=76): # def parse_fasta_header(header): # def seqid_to_filename(seqid): # def create_proteins_dict(fasta): # def print_proteins(proteins): # def write_proteins_fasta( # fasta_filename, proteins, seqids, width=50): # def proteins_to_fasta(proteins, seqids=[], use_safe_seqid=False, width=50): # def chop_nterminal_peptide(protein, i_cut): # def generate_safe_seqids(proteins): # def clean_directory(top, excluded_files): # def html2text(page, aggressive=False): # # Path: inmembrane/plugins/hmmsearch3.py # def annotate(params, proteins): # # Path: inmembrane/tests/PluginTestBase.py # class PluginTestBase(unittest.TestCase): # _plugin_name = "" # # def setUp(self): # """ # Sets up a directory, a parameters dictionary and a proteins dictionary # object in preparation for running a test of a plugin. # # Creates a temporary directory (eg /tmp/.inmembrane_signalp_web_TleeRw ), # copies the test input data (input.fasta) into it and changes the # current working directory. # # Should be subclassed adding a method with the specific test(s) for # the plugin. The subclass should set self._plugin_name to the name of # the plugin. # """ # self.test_data_dir = os.path.join( # os.path.abspath( # os.path.dirname(inmembrane.tests.__file__)), self._plugin_name) # # self.output_dir = tempfile.mkdtemp( # prefix=".inmembrane_%s_" % (self._plugin_name)) # shutil.copyfile(os.path.join(self.test_data_dir, "input.fasta"), # os.path.join(self.output_dir, "input.fasta")) # os.chdir(self.output_dir) # helpers.silence_log(True) # # self.params = inmembrane.get_params() # self.params['fasta'] = "input.fasta" # self.seqids, self.proteins = \ # helpers.create_proteins_dict(self.params['fasta']) . Output only the next line.
hmmsearch3.annotate(self.params, self.proteins)
Predict the next line after this snippet: <|code_start|> In the current implementation, this function extracts and feeds sequences to MEMSAT3 one by one via a temporary file. These keys are added to the proteins dictionary: - 'memsat3_helices', a list of tuples describing the first and last residue number of each transmembrane segment; - 'memsat3_scores', a list of confidence scores (floats) for each predicted tm segment; - 'memsat3_inner_loops', a list of tuples describing the first and last residue number of each predicted internal loop segment; - 'memsat3_outer_loops', a list of tuples describing the first and last residue number of each predicted outer loop segment; """ for seqid in proteins: protein = proteins[seqid] # initialize the protein data structure protein.update({ 'memsat3_scores': [], 'memsat3_helices': [], 'memsat3_inner_loops': [], 'memsat3_outer_loops': [] }) # write seq to single fasta file <|code_end|> using the current file's imports: import os import re from inmembrane.helpers import seqid_to_filename, run, write_proteins_fasta and any relevant context from other files: # Path: inmembrane/helpers.py # def seqid_to_filename(seqid): # """ # Makes a sequence id filename friendly. # (eg, replaces '|' with '_') # """ # return seqid.replace("|", "_") # # def run(cmd, out_file=None): # """ # Wrapper function to run external program so that existence # of binary can be checked and the output directed to a specific # file. # """ # log_stderr("# " + cmd + " > " + out_file) # if os.path.isfile(out_file) and (out_file != None): # log_stderr("# -> skipped: %s already exists" % out_file) # return # binary = cmd.split()[0] # is_binary_there = False # if os.path.isfile(binary): # is_binary_there = True # if run_with_output('which ' + binary): # is_binary_there = True # if not is_binary_there: # raise IOError("Couldn't find executable binary '" + binary + "'") # if out_file: # os.system(cmd + " > " + out_file) # else: # os.system(cmd) # # def write_proteins_fasta( # fasta_filename, proteins, seqids, width=50): # """ # Creates a fasta file of the sequences of a subset of the proteins. # """ # f = open(fasta_filename, "w") # out = proteins_to_fasta(proteins, seqids=seqids, width=width) # f.write(out) # f.close() . Output only the next line.
single_fasta = seqid_to_filename(seqid) + '.fasta'
Continue the code snippet: <|code_start|> - 'memsat3_helices', a list of tuples describing the first and last residue number of each transmembrane segment; - 'memsat3_scores', a list of confidence scores (floats) for each predicted tm segment; - 'memsat3_inner_loops', a list of tuples describing the first and last residue number of each predicted internal loop segment; - 'memsat3_outer_loops', a list of tuples describing the first and last residue number of each predicted outer loop segment; """ for seqid in proteins: protein = proteins[seqid] # initialize the protein data structure protein.update({ 'memsat3_scores': [], 'memsat3_helices': [], 'memsat3_inner_loops': [], 'memsat3_outer_loops': [] }) # write seq to single fasta file single_fasta = seqid_to_filename(seqid) + '.fasta' if not os.path.isfile(single_fasta): write_proteins_fasta(single_fasta, proteins, [seqid]) memsat_out = single_fasta.replace('fasta', 'memsat') <|code_end|> . Use current file imports: import os import re from inmembrane.helpers import seqid_to_filename, run, write_proteins_fasta and context (classes, functions, or code) from other files: # Path: inmembrane/helpers.py # def seqid_to_filename(seqid): # """ # Makes a sequence id filename friendly. # (eg, replaces '|' with '_') # """ # return seqid.replace("|", "_") # # def run(cmd, out_file=None): # """ # Wrapper function to run external program so that existence # of binary can be checked and the output directed to a specific # file. # """ # log_stderr("# " + cmd + " > " + out_file) # if os.path.isfile(out_file) and (out_file != None): # log_stderr("# -> skipped: %s already exists" % out_file) # return # binary = cmd.split()[0] # is_binary_there = False # if os.path.isfile(binary): # is_binary_there = True # if run_with_output('which ' + binary): # is_binary_there = True # if not is_binary_there: # raise IOError("Couldn't find executable binary '" + binary + "'") # if out_file: # os.system(cmd + " > " + out_file) # else: # os.system(cmd) # # def write_proteins_fasta( # fasta_filename, proteins, seqids, width=50): # """ # Creates a fasta file of the sequences of a subset of the proteins. # """ # f = open(fasta_filename, "w") # out = proteins_to_fasta(proteins, seqids=seqids, width=width) # f.write(out) # f.close() . Output only the next line.
run('%s %s' % (params['memsat3_bin'], single_fasta), memsat_out)
Given snippet: <|code_start|> one by one via a temporary file. These keys are added to the proteins dictionary: - 'memsat3_helices', a list of tuples describing the first and last residue number of each transmembrane segment; - 'memsat3_scores', a list of confidence scores (floats) for each predicted tm segment; - 'memsat3_inner_loops', a list of tuples describing the first and last residue number of each predicted internal loop segment; - 'memsat3_outer_loops', a list of tuples describing the first and last residue number of each predicted outer loop segment; """ for seqid in proteins: protein = proteins[seqid] # initialize the protein data structure protein.update({ 'memsat3_scores': [], 'memsat3_helices': [], 'memsat3_inner_loops': [], 'memsat3_outer_loops': [] }) # write seq to single fasta file single_fasta = seqid_to_filename(seqid) + '.fasta' if not os.path.isfile(single_fasta): <|code_end|> , continue by predicting the next line. Consider current file imports: import os import re from inmembrane.helpers import seqid_to_filename, run, write_proteins_fasta and context: # Path: inmembrane/helpers.py # def seqid_to_filename(seqid): # """ # Makes a sequence id filename friendly. # (eg, replaces '|' with '_') # """ # return seqid.replace("|", "_") # # def run(cmd, out_file=None): # """ # Wrapper function to run external program so that existence # of binary can be checked and the output directed to a specific # file. # """ # log_stderr("# " + cmd + " > " + out_file) # if os.path.isfile(out_file) and (out_file != None): # log_stderr("# -> skipped: %s already exists" % out_file) # return # binary = cmd.split()[0] # is_binary_there = False # if os.path.isfile(binary): # is_binary_there = True # if run_with_output('which ' + binary): # is_binary_there = True # if not is_binary_there: # raise IOError("Couldn't find executable binary '" + binary + "'") # if out_file: # os.system(cmd + " > " + out_file) # else: # os.system(cmd) # # def write_proteins_fasta( # fasta_filename, proteins, seqids, width=50): # """ # Creates a fasta file of the sequences of a subset of the proteins. # """ # f = open(fasta_filename, "w") # out = proteins_to_fasta(proteins, seqids=seqids, width=width) # f.write(out) # f.close() which might include code, classes, or functions. Output only the next line.
write_proteins_fasta(single_fasta, proteins, [seqid])
Here is a snippet: <|code_start|> 'name': "SignalP 4.1" } __DEBUG__ = False try: except: def annotate(params, proteins, batchsize=2000, force=False): """ This plugin interfaces with the SignalP web interface (for humans) and scrapes the results. There once was a SOAP service but it was discontinued, so now we use this. """ baseurl = "http://www.cbs.dtu.dk" url = baseurl + "/cgi-bin/webface2.fcgi" # grab the cached results if present outfile = "signalp_scrape_web.out" if not force and os.path.isfile(outfile): log_stderr("# -> skipped: %s already exists" % outfile) proteins, id_mapping = generate_safe_seqids(proteins) fh = open(outfile, 'r') resultpage = fh.read() fh.close() # soup = BeautifulSoup(resultpage) <|code_end|> . Write the next line using the current file imports: import sys, os, time import requests import inmembrane from StringIO import StringIO from BeautifulSoup import BeautifulSoup from collections import OrderedDict from ordereddict import OrderedDict from inmembrane.plugins.signalp4 import parse_signalp from inmembrane.helpers import log_stderr from inmembrane.helpers import (generate_safe_seqids, proteins_to_fasta, html2text) and context from other files: # Path: inmembrane/plugins/signalp4.py # def parse_signalp(signalp4_lines, proteins, id_mapping=None): # if id_mapping is None: # id_mapping = [] # # past_preamble = False # for line in signalp4_lines: # if line.startswith("#"): # past_preamble = True # continue # if not past_preamble and line.strip() == '': # skip empty lines # continue # if past_preamble: # if line.strip() == '': # # in the case of web output of concatenated signalp output # # files, an empty line after preamble means we have finished all # # 'result' lines for that section # past_preamble = False # continue # words = line.split() # seqid = parse_fasta_header(words[0])[0] # if id_mapping: # seqid = id_mapping[seqid] # proteins[seqid]['signalp_cleave_position'] = int(words[4]) # proteins[seqid]['is_signalp'] = (words[9] == 'Y') # # return proteins # # Path: inmembrane/helpers.py # def log_stderr(s, width=76, comment=True): # """ # Wrapper for all stderr out. Allows future customization. # """ # if LOG_SILENT: # return # if s and s[-1] != "\n": # s += "\n" # if not s.startswith("#"): # s = "# " + s # sys.stderr.write(s) # # Path: inmembrane/helpers.py # def generate_safe_seqids(proteins): # """ # Takes a 'proteins' dictionary, keyed by sequence id, and # adds a 'safe' sequence id ('safe_seqid') that is less likely # to be munged or break various external programs. # # Returns a tuple of the updated proteins dictionary and a dictionary # mapping the 'safe' sequence ids to the original ids. # """ # id_mapping = {} # count = 0 # for seqid in proteins: # safe_id = re.sub(r'[^\w]', "", seqid) + '_' + `count` # id_mapping[safe_id] = seqid # proteins[seqid]['safe_seqid'] = safe_id # count += 1 # # return (proteins, id_mapping) # # def proteins_to_fasta(proteins, seqids=[], use_safe_seqid=False, width=50): # """ # Takes a proteins dictionary and returns a string containing # all the sequences in FASTA format. Option parameters are # a list of seqids to output (seqids) and the line width (width). # """ # if seqids: # idlist = seqids # else: # idlist = proteins # # fasta_out = "" # for seqid in idlist: # seq_wrap = textwrap.fill(proteins[seqid]['seq'], width) # if use_safe_seqid: # header = proteins[seqid]['safe_seqid'] # else: # header = proteins[seqid]['name'] # fasta_out += ">%s\n%s\n" % (header, seq_wrap) # return fasta_out # # def html2text(page, aggressive=False): # soup = BeautifulSoup(page, 'html.parser') # # # kill all script and style elements # for script in soup(["script", "style"]): # script.extract() # # # get text # text = soup.get_text() # # # break into lines and remove leading and trailing space on each # lines = (line.strip() for line in text.splitlines()) # if aggressive: # # break multi-headlines into a line each # chunks = (phrase.strip() for line in lines for phrase in # line.split(" ")) # # drop blank lines # text = '\n'.join(chunk for chunk in chunks if chunk) # else: # text = '\n'.join(lines) # # return text , which may include functions, classes, or code. Output only the next line.
proteins = parse_signalp(resultpage.splitlines(),
Here is a snippet: <|code_start|># -*- coding: utf-8 -*- citation = {'ref': u"Petersen TN, Brunak S, von Heijne G, Nielsen H. " u"SignalP 4.0: discriminating signal peptides from " u"transmembrane regions. Nature methods 2011 " u"Jan;8(10):785-6. \n" u"<http://dx.doi.org/10.1038/nmeth.1701>", 'name': "SignalP 4.1" } __DEBUG__ = False try: except: def annotate(params, proteins, batchsize=2000, force=False): """ This plugin interfaces with the SignalP web interface (for humans) and scrapes the results. There once was a SOAP service but it was discontinued, so now we use this. """ baseurl = "http://www.cbs.dtu.dk" url = baseurl + "/cgi-bin/webface2.fcgi" # grab the cached results if present outfile = "signalp_scrape_web.out" if not force and os.path.isfile(outfile): <|code_end|> . Write the next line using the current file imports: import sys, os, time import requests import inmembrane from StringIO import StringIO from BeautifulSoup import BeautifulSoup from collections import OrderedDict from ordereddict import OrderedDict from inmembrane.plugins.signalp4 import parse_signalp from inmembrane.helpers import log_stderr from inmembrane.helpers import (generate_safe_seqids, proteins_to_fasta, html2text) and context from other files: # Path: inmembrane/plugins/signalp4.py # def parse_signalp(signalp4_lines, proteins, id_mapping=None): # if id_mapping is None: # id_mapping = [] # # past_preamble = False # for line in signalp4_lines: # if line.startswith("#"): # past_preamble = True # continue # if not past_preamble and line.strip() == '': # skip empty lines # continue # if past_preamble: # if line.strip() == '': # # in the case of web output of concatenated signalp output # # files, an empty line after preamble means we have finished all # # 'result' lines for that section # past_preamble = False # continue # words = line.split() # seqid = parse_fasta_header(words[0])[0] # if id_mapping: # seqid = id_mapping[seqid] # proteins[seqid]['signalp_cleave_position'] = int(words[4]) # proteins[seqid]['is_signalp'] = (words[9] == 'Y') # # return proteins # # Path: inmembrane/helpers.py # def log_stderr(s, width=76, comment=True): # """ # Wrapper for all stderr out. Allows future customization. # """ # if LOG_SILENT: # return # if s and s[-1] != "\n": # s += "\n" # if not s.startswith("#"): # s = "# " + s # sys.stderr.write(s) # # Path: inmembrane/helpers.py # def generate_safe_seqids(proteins): # """ # Takes a 'proteins' dictionary, keyed by sequence id, and # adds a 'safe' sequence id ('safe_seqid') that is less likely # to be munged or break various external programs. # # Returns a tuple of the updated proteins dictionary and a dictionary # mapping the 'safe' sequence ids to the original ids. # """ # id_mapping = {} # count = 0 # for seqid in proteins: # safe_id = re.sub(r'[^\w]', "", seqid) + '_' + `count` # id_mapping[safe_id] = seqid # proteins[seqid]['safe_seqid'] = safe_id # count += 1 # # return (proteins, id_mapping) # # def proteins_to_fasta(proteins, seqids=[], use_safe_seqid=False, width=50): # """ # Takes a proteins dictionary and returns a string containing # all the sequences in FASTA format. Option parameters are # a list of seqids to output (seqids) and the line width (width). # """ # if seqids: # idlist = seqids # else: # idlist = proteins # # fasta_out = "" # for seqid in idlist: # seq_wrap = textwrap.fill(proteins[seqid]['seq'], width) # if use_safe_seqid: # header = proteins[seqid]['safe_seqid'] # else: # header = proteins[seqid]['name'] # fasta_out += ">%s\n%s\n" % (header, seq_wrap) # return fasta_out # # def html2text(page, aggressive=False): # soup = BeautifulSoup(page, 'html.parser') # # # kill all script and style elements # for script in soup(["script", "style"]): # script.extract() # # # get text # text = soup.get_text() # # # break into lines and remove leading and trailing space on each # lines = (line.strip() for line in text.splitlines()) # if aggressive: # # break multi-headlines into a line each # chunks = (phrase.strip() for line in lines for phrase in # line.split(" ")) # # drop blank lines # text = '\n'.join(chunk for chunk in chunks if chunk) # else: # text = '\n'.join(lines) # # return text , which may include functions, classes, or code. Output only the next line.
log_stderr("# -> skipped: %s already exists" % outfile)
Continue the code snippet: <|code_start|>citation = {'ref': u"Petersen TN, Brunak S, von Heijne G, Nielsen H. " u"SignalP 4.0: discriminating signal peptides from " u"transmembrane regions. Nature methods 2011 " u"Jan;8(10):785-6. \n" u"<http://dx.doi.org/10.1038/nmeth.1701>", 'name': "SignalP 4.1" } __DEBUG__ = False try: except: def annotate(params, proteins, batchsize=2000, force=False): """ This plugin interfaces with the SignalP web interface (for humans) and scrapes the results. There once was a SOAP service but it was discontinued, so now we use this. """ baseurl = "http://www.cbs.dtu.dk" url = baseurl + "/cgi-bin/webface2.fcgi" # grab the cached results if present outfile = "signalp_scrape_web.out" if not force and os.path.isfile(outfile): log_stderr("# -> skipped: %s already exists" % outfile) <|code_end|> . Use current file imports: import sys, os, time import requests import inmembrane from StringIO import StringIO from BeautifulSoup import BeautifulSoup from collections import OrderedDict from ordereddict import OrderedDict from inmembrane.plugins.signalp4 import parse_signalp from inmembrane.helpers import log_stderr from inmembrane.helpers import (generate_safe_seqids, proteins_to_fasta, html2text) and context (classes, functions, or code) from other files: # Path: inmembrane/plugins/signalp4.py # def parse_signalp(signalp4_lines, proteins, id_mapping=None): # if id_mapping is None: # id_mapping = [] # # past_preamble = False # for line in signalp4_lines: # if line.startswith("#"): # past_preamble = True # continue # if not past_preamble and line.strip() == '': # skip empty lines # continue # if past_preamble: # if line.strip() == '': # # in the case of web output of concatenated signalp output # # files, an empty line after preamble means we have finished all # # 'result' lines for that section # past_preamble = False # continue # words = line.split() # seqid = parse_fasta_header(words[0])[0] # if id_mapping: # seqid = id_mapping[seqid] # proteins[seqid]['signalp_cleave_position'] = int(words[4]) # proteins[seqid]['is_signalp'] = (words[9] == 'Y') # # return proteins # # Path: inmembrane/helpers.py # def log_stderr(s, width=76, comment=True): # """ # Wrapper for all stderr out. Allows future customization. # """ # if LOG_SILENT: # return # if s and s[-1] != "\n": # s += "\n" # if not s.startswith("#"): # s = "# " + s # sys.stderr.write(s) # # Path: inmembrane/helpers.py # def generate_safe_seqids(proteins): # """ # Takes a 'proteins' dictionary, keyed by sequence id, and # adds a 'safe' sequence id ('safe_seqid') that is less likely # to be munged or break various external programs. # # Returns a tuple of the updated proteins dictionary and a dictionary # mapping the 'safe' sequence ids to the original ids. # """ # id_mapping = {} # count = 0 # for seqid in proteins: # safe_id = re.sub(r'[^\w]', "", seqid) + '_' + `count` # id_mapping[safe_id] = seqid # proteins[seqid]['safe_seqid'] = safe_id # count += 1 # # return (proteins, id_mapping) # # def proteins_to_fasta(proteins, seqids=[], use_safe_seqid=False, width=50): # """ # Takes a proteins dictionary and returns a string containing # all the sequences in FASTA format. Option parameters are # a list of seqids to output (seqids) and the line width (width). # """ # if seqids: # idlist = seqids # else: # idlist = proteins # # fasta_out = "" # for seqid in idlist: # seq_wrap = textwrap.fill(proteins[seqid]['seq'], width) # if use_safe_seqid: # header = proteins[seqid]['safe_seqid'] # else: # header = proteins[seqid]['name'] # fasta_out += ">%s\n%s\n" % (header, seq_wrap) # return fasta_out # # def html2text(page, aggressive=False): # soup = BeautifulSoup(page, 'html.parser') # # # kill all script and style elements # for script in soup(["script", "style"]): # script.extract() # # # get text # text = soup.get_text() # # # break into lines and remove leading and trailing space on each # lines = (line.strip() for line in text.splitlines()) # if aggressive: # # break multi-headlines into a line each # chunks = (phrase.strip() for line in lines for phrase in # line.split(" ")) # # drop blank lines # text = '\n'.join(chunk for chunk in chunks if chunk) # else: # text = '\n'.join(lines) # # return text . Output only the next line.
proteins, id_mapping = generate_safe_seqids(proteins)
Using the snippet: <|code_start|> """ This plugin interfaces with the SignalP web interface (for humans) and scrapes the results. There once was a SOAP service but it was discontinued, so now we use this. """ baseurl = "http://www.cbs.dtu.dk" url = baseurl + "/cgi-bin/webface2.fcgi" # grab the cached results if present outfile = "signalp_scrape_web.out" if not force and os.path.isfile(outfile): log_stderr("# -> skipped: %s already exists" % outfile) proteins, id_mapping = generate_safe_seqids(proteins) fh = open(outfile, 'r') resultpage = fh.read() fh.close() # soup = BeautifulSoup(resultpage) proteins = parse_signalp(resultpage.splitlines(), proteins, id_mapping=id_mapping) return proteins proteins, id_mapping = generate_safe_seqids(proteins) seqids = proteins.keys() allresultpages = "" while seqids: seqid_batch = seqids[0:batchsize] del seqids[0:batchsize] <|code_end|> , determine the next line of code. You have imports: import sys, os, time import requests import inmembrane from StringIO import StringIO from BeautifulSoup import BeautifulSoup from collections import OrderedDict from ordereddict import OrderedDict from inmembrane.plugins.signalp4 import parse_signalp from inmembrane.helpers import log_stderr from inmembrane.helpers import (generate_safe_seqids, proteins_to_fasta, html2text) and context (class names, function names, or code) available: # Path: inmembrane/plugins/signalp4.py # def parse_signalp(signalp4_lines, proteins, id_mapping=None): # if id_mapping is None: # id_mapping = [] # # past_preamble = False # for line in signalp4_lines: # if line.startswith("#"): # past_preamble = True # continue # if not past_preamble and line.strip() == '': # skip empty lines # continue # if past_preamble: # if line.strip() == '': # # in the case of web output of concatenated signalp output # # files, an empty line after preamble means we have finished all # # 'result' lines for that section # past_preamble = False # continue # words = line.split() # seqid = parse_fasta_header(words[0])[0] # if id_mapping: # seqid = id_mapping[seqid] # proteins[seqid]['signalp_cleave_position'] = int(words[4]) # proteins[seqid]['is_signalp'] = (words[9] == 'Y') # # return proteins # # Path: inmembrane/helpers.py # def log_stderr(s, width=76, comment=True): # """ # Wrapper for all stderr out. Allows future customization. # """ # if LOG_SILENT: # return # if s and s[-1] != "\n": # s += "\n" # if not s.startswith("#"): # s = "# " + s # sys.stderr.write(s) # # Path: inmembrane/helpers.py # def generate_safe_seqids(proteins): # """ # Takes a 'proteins' dictionary, keyed by sequence id, and # adds a 'safe' sequence id ('safe_seqid') that is less likely # to be munged or break various external programs. # # Returns a tuple of the updated proteins dictionary and a dictionary # mapping the 'safe' sequence ids to the original ids. # """ # id_mapping = {} # count = 0 # for seqid in proteins: # safe_id = re.sub(r'[^\w]', "", seqid) + '_' + `count` # id_mapping[safe_id] = seqid # proteins[seqid]['safe_seqid'] = safe_id # count += 1 # # return (proteins, id_mapping) # # def proteins_to_fasta(proteins, seqids=[], use_safe_seqid=False, width=50): # """ # Takes a proteins dictionary and returns a string containing # all the sequences in FASTA format. Option parameters are # a list of seqids to output (seqids) and the line width (width). # """ # if seqids: # idlist = seqids # else: # idlist = proteins # # fasta_out = "" # for seqid in idlist: # seq_wrap = textwrap.fill(proteins[seqid]['seq'], width) # if use_safe_seqid: # header = proteins[seqid]['safe_seqid'] # else: # header = proteins[seqid]['name'] # fasta_out += ">%s\n%s\n" % (header, seq_wrap) # return fasta_out # # def html2text(page, aggressive=False): # soup = BeautifulSoup(page, 'html.parser') # # # kill all script and style elements # for script in soup(["script", "style"]): # script.extract() # # # get text # text = soup.get_text() # # # break into lines and remove leading and trailing space on each # lines = (line.strip() for line in text.splitlines()) # if aggressive: # # break multi-headlines into a line each # chunks = (phrase.strip() for line in lines for phrase in # line.split(" ")) # # drop blank lines # text = '\n'.join(chunk for chunk in chunks if chunk) # else: # text = '\n'.join(lines) # # return text . Output only the next line.
safe_fasta = proteins_to_fasta(proteins,
Continue the code snippet: <|code_start|> waittime = 1.0 time.sleep(waittime) # (len(proteins)/500) resultpage = requests.get(pollingurl).text retries = 0 while (("<title>Job status of" in resultpage) and (retries < 15)): sys.stderr.write(".") time.sleep(waittime) # (len(proteins)/500) resultpage = requests.get(pollingurl).text waittime += 1; retries += 1 waittime = min(waittime, 20) sys.stderr.write(" .. done !\n") if __DEBUG__: log_stderr(resultpage) # Example: # # <pre> # # lcl_AE004092.1_cdsid_AAK33146.1 CYT score=-0.200913 # # Cut-off=-3 # lcl_AE004092.1_cdsid_AAK33146.1 LipoP1.0:Best CYT 1 1 -0.200913 # <P> # <hr> # # lcl_AE004092.1_cdsid_AAK33147.1 CYT score=-0.200913 # # Cut-off=-3 # lcl_AE004092.1_cdsid_AAK33147.1 LipoP1.0:Best CYT 1 1 -0.200913 # <P> # <hr> <|code_end|> . Use current file imports: import sys, os, time import requests import inmembrane from StringIO import StringIO from BeautifulSoup import BeautifulSoup from collections import OrderedDict from ordereddict import OrderedDict from inmembrane.plugins.signalp4 import parse_signalp from inmembrane.helpers import log_stderr from inmembrane.helpers import (generate_safe_seqids, proteins_to_fasta, html2text) and context (classes, functions, or code) from other files: # Path: inmembrane/plugins/signalp4.py # def parse_signalp(signalp4_lines, proteins, id_mapping=None): # if id_mapping is None: # id_mapping = [] # # past_preamble = False # for line in signalp4_lines: # if line.startswith("#"): # past_preamble = True # continue # if not past_preamble and line.strip() == '': # skip empty lines # continue # if past_preamble: # if line.strip() == '': # # in the case of web output of concatenated signalp output # # files, an empty line after preamble means we have finished all # # 'result' lines for that section # past_preamble = False # continue # words = line.split() # seqid = parse_fasta_header(words[0])[0] # if id_mapping: # seqid = id_mapping[seqid] # proteins[seqid]['signalp_cleave_position'] = int(words[4]) # proteins[seqid]['is_signalp'] = (words[9] == 'Y') # # return proteins # # Path: inmembrane/helpers.py # def log_stderr(s, width=76, comment=True): # """ # Wrapper for all stderr out. Allows future customization. # """ # if LOG_SILENT: # return # if s and s[-1] != "\n": # s += "\n" # if not s.startswith("#"): # s = "# " + s # sys.stderr.write(s) # # Path: inmembrane/helpers.py # def generate_safe_seqids(proteins): # """ # Takes a 'proteins' dictionary, keyed by sequence id, and # adds a 'safe' sequence id ('safe_seqid') that is less likely # to be munged or break various external programs. # # Returns a tuple of the updated proteins dictionary and a dictionary # mapping the 'safe' sequence ids to the original ids. # """ # id_mapping = {} # count = 0 # for seqid in proteins: # safe_id = re.sub(r'[^\w]', "", seqid) + '_' + `count` # id_mapping[safe_id] = seqid # proteins[seqid]['safe_seqid'] = safe_id # count += 1 # # return (proteins, id_mapping) # # def proteins_to_fasta(proteins, seqids=[], use_safe_seqid=False, width=50): # """ # Takes a proteins dictionary and returns a string containing # all the sequences in FASTA format. Option parameters are # a list of seqids to output (seqids) and the line width (width). # """ # if seqids: # idlist = seqids # else: # idlist = proteins # # fasta_out = "" # for seqid in idlist: # seq_wrap = textwrap.fill(proteins[seqid]['seq'], width) # if use_safe_seqid: # header = proteins[seqid]['safe_seqid'] # else: # header = proteins[seqid]['name'] # fasta_out += ">%s\n%s\n" % (header, seq_wrap) # return fasta_out # # def html2text(page, aggressive=False): # soup = BeautifulSoup(page, 'html.parser') # # # kill all script and style elements # for script in soup(["script", "style"]): # script.extract() # # # get text # text = soup.get_text() # # # break into lines and remove leading and trailing space on each # lines = (line.strip() for line in text.splitlines()) # if aggressive: # # break multi-headlines into a line each # chunks = (phrase.strip() for line in lines for phrase in # line.split(" ")) # # drop blank lines # text = '\n'.join(chunk for chunk in chunks if chunk) # else: # text = '\n'.join(lines) # # return text . Output only the next line.
allresultpages += html2text(
Predict the next line after this snippet: <|code_start|> class TestLipoP(PluginTestBase): _plugin_name = "lipop_scrape_web" def test_lipop_scrape_web(self): <|code_end|> using the current file's imports: import os import unittest import sys import inmembrane import inmembrane.tests from inmembrane import helpers from inmembrane.plugins import lipop_scrape_web from inmembrane.tests.PluginTestBase import PluginTestBase and any relevant context from other files: # Path: inmembrane/helpers.py # LOG_SILENT = False # LOG_SILENT = b # def dict_get(this_dict, prop): # def run_with_output(cmd): # def run(cmd, out_file=None): # def silence_log(b): # def log_stderr(s, width=76, comment=True): # def log_stdout(s, width=76): # def parse_fasta_header(header): # def seqid_to_filename(seqid): # def create_proteins_dict(fasta): # def print_proteins(proteins): # def write_proteins_fasta( # fasta_filename, proteins, seqids, width=50): # def proteins_to_fasta(proteins, seqids=[], use_safe_seqid=False, width=50): # def chop_nterminal_peptide(protein, i_cut): # def generate_safe_seqids(proteins): # def clean_directory(top, excluded_files): # def html2text(page, aggressive=False): # # Path: inmembrane/plugins/lipop_scrape_web.py # __DEBUG__ = False # def annotate(params, proteins, batchsize=2000, force=False): # def clean_result_page(resultpage): # # Path: inmembrane/tests/PluginTestBase.py # class PluginTestBase(unittest.TestCase): # _plugin_name = "" # # def setUp(self): # """ # Sets up a directory, a parameters dictionary and a proteins dictionary # object in preparation for running a test of a plugin. # # Creates a temporary directory (eg /tmp/.inmembrane_signalp_web_TleeRw ), # copies the test input data (input.fasta) into it and changes the # current working directory. # # Should be subclassed adding a method with the specific test(s) for # the plugin. The subclass should set self._plugin_name to the name of # the plugin. # """ # self.test_data_dir = os.path.join( # os.path.abspath( # os.path.dirname(inmembrane.tests.__file__)), self._plugin_name) # # self.output_dir = tempfile.mkdtemp( # prefix=".inmembrane_%s_" % (self._plugin_name)) # shutil.copyfile(os.path.join(self.test_data_dir, "input.fasta"), # os.path.join(self.output_dir, "input.fasta")) # os.chdir(self.output_dir) # helpers.silence_log(True) # # self.params = inmembrane.get_params() # self.params['fasta'] = "input.fasta" # self.seqids, self.proteins = \ # helpers.create_proteins_dict(self.params['fasta']) . Output only the next line.
lipop_scrape_web.annotate(self.params, self.proteins)
Continue the code snippet: <|code_start|># Copyright (c) 2015 Intel Corporation # # Author: Julio Montes <julio.montes@intel.com> # Author: Victor Morales <victor.morales@intel.com> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # class SequenceTest(testtools.TestCase): def setUp(self): super(SequenceTest, self).setUp() def test_run(self): mock_function = mock.Mock(return_value=False) mock_function.__name__ = 'Bar' <|code_end|> . Use current file imports: import mock import testtools from clearstack.sequence import Sequence and context (classes, functions, or code) from other files: # Path: clearstack/sequence.py # class Sequence: # def __init__(self, desc, function, args=None): # self.description = desc # self.function = function # self.function_args = args # # def run(self): # LOG.info(self.description) # if self.function_args: # if not self.function(*self.function_args): # raise Exception("error running {0}({1})" # .format(self.function.__name__, # self.function_args)) # else: # if not self.function(): # raise Exception("error running {0}" # .format(self.function.__name__)) . Output only the next line.
seq = Sequence('test', mock_function)
Predict the next line for this snippet: <|code_start|># # Copyright (c) 2015 Intel Corporation # # Author: Alberto Murillo <alberto.murillo.silva@intel.com> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # def init_config(): conf = { "CEILOMETER": [ Argument("ceilometer-db-pw", "Password for ceilometer to access DB", "CONFIG_CEILOMETER_DB_PW", <|code_end|> with the help of current file imports: from clearstack import utils from clearstack import validators from clearstack.controller import Controller from clearstack.argument import Argument from clearstack.common import util and context from other files: # Path: clearstack/utils.py # def arg(*args, **kwargs): # def _decorator(func): # def run_recipe(recipe_file, recipe_src, hosts): # def _run_recipe_local(recipe_file): # def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts): # def get_all_hosts(): # def generate_conf_file(conf_file): # def copy_resources(): # def _copy_resources_local(): # def _copy_resources_to_hosts(_hosts): # def get_logs(): # def get_template(template): # def generate_random_pw(): # def generate_ssh_keys(output): # def setup_debugging(debug): # # Path: clearstack/validators.py # def y_or_n(value): # def ip_or_hostname(value): # def cidr(value): # def file(value): # def not_empty(value): # def digit(value): # # Path: clearstack/controller.py # class Controller: # CONF = {} # _plugins = [] # _groups = [] # _sequences = [] # # def add_sequence(self, desc, function, args=None): # self._sequences.append(Sequence(desc, function, args)) # # def run_all_sequences(self): # for seq in self._sequences: # try: # seq.run() # except Exception as e: # raise e # # def add_plugin(self, plugin): # self._plugins.append(plugin) # # def get_all_plugins(self): # return self._plugins # # def add_group(self, name, args): # self._groups.append(Group(name, args)) # # def get_all_groups(self): # return self._groups # # def get_all_arguments(self): # """Get a list of the configuration argument loaded""" # arguments = [] # for group in self._groups: # arguments.extend([argument.conf_name # for argument in group.get_all_arguments()]) # return arguments # # def validate_groups(self, conf_values): # """ Load validation functions, in order to check # the values in the answer file """ # arguments = {} # for group in self._groups: # for arg in group.get_all_arguments(): # try: # arg.validate(conf_values[arg.conf_name]) # except Exception as e: # raise Exception("{0}: {1}".format(arg.conf_name, str(e))) # return arguments # # Path: clearstack/argument.py # class Argument(object): # def __init__(self, cmd_option, description, # conf_name, default_value, validators=[], # options=None): # self.cmd_option = cmd_option # self.description = description # self.conf_name = conf_name # self.default_value = default_value # self.validators = validators # self.option_list = options # # def validate(self, option): # for validator in self.validators: # try: # validator(option) # except ValueError as e: # raise ValueError("{0}: {1}".format(self.conf_name, str(e))) # # Path: clearstack/common/util.py # HOST_LOG_DIR = '/var/log/clearstack' # HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR) # LOG_DIR = '/var/log/clearstack' # LOG_DIR = '/tmp/log/clearstack' # LOG_FILE = "{0}/clearstack.log".format(LOG_DIR) # LOG = logging.getLogger("Clearstack") # def _print_error_message(self, e, file_name): # def port_open(port): # def service_status(service): # def service_enabled(service): # def setup_debugging(debug, is_remote_host=True): # def run_command(command, stdin=None, environ=None, debug=True): # def str2bool(value): # def write_config(file, data): # def write_properties(file, data): # def get_option(file, section, option): # def delete_option(file, section, option=None): # def write_in_file_ine(file, data): # def get_dns(): # def get_netmask(): # def get_gateway(): # def get_net_interface(): # def get_ips(): # def get_nic(ip): # def get_ip(): # def find_my_ip_from_config(config_ips): # def is_localhost(host): # def has_localhost(hosts): # def remove_localhost(hosts): # def ensure_directory(dir): # def link_file(source, target): , which may contain function names, class names, or code. Output only the next line.
utils.generate_random_pw(),
Using the snippet: <|code_start|># # Copyright (c) 2015 Intel Corporation # # Author: Alberto Murillo <alberto.murillo.silva@intel.com> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # def init_config(): conf = { "CEILOMETER": [ Argument("ceilometer-db-pw", "Password for ceilometer to access DB", "CONFIG_CEILOMETER_DB_PW", utils.generate_random_pw(), <|code_end|> , determine the next line of code. You have imports: from clearstack import utils from clearstack import validators from clearstack.controller import Controller from clearstack.argument import Argument from clearstack.common import util and context (class names, function names, or code) available: # Path: clearstack/utils.py # def arg(*args, **kwargs): # def _decorator(func): # def run_recipe(recipe_file, recipe_src, hosts): # def _run_recipe_local(recipe_file): # def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts): # def get_all_hosts(): # def generate_conf_file(conf_file): # def copy_resources(): # def _copy_resources_local(): # def _copy_resources_to_hosts(_hosts): # def get_logs(): # def get_template(template): # def generate_random_pw(): # def generate_ssh_keys(output): # def setup_debugging(debug): # # Path: clearstack/validators.py # def y_or_n(value): # def ip_or_hostname(value): # def cidr(value): # def file(value): # def not_empty(value): # def digit(value): # # Path: clearstack/controller.py # class Controller: # CONF = {} # _plugins = [] # _groups = [] # _sequences = [] # # def add_sequence(self, desc, function, args=None): # self._sequences.append(Sequence(desc, function, args)) # # def run_all_sequences(self): # for seq in self._sequences: # try: # seq.run() # except Exception as e: # raise e # # def add_plugin(self, plugin): # self._plugins.append(plugin) # # def get_all_plugins(self): # return self._plugins # # def add_group(self, name, args): # self._groups.append(Group(name, args)) # # def get_all_groups(self): # return self._groups # # def get_all_arguments(self): # """Get a list of the configuration argument loaded""" # arguments = [] # for group in self._groups: # arguments.extend([argument.conf_name # for argument in group.get_all_arguments()]) # return arguments # # def validate_groups(self, conf_values): # """ Load validation functions, in order to check # the values in the answer file """ # arguments = {} # for group in self._groups: # for arg in group.get_all_arguments(): # try: # arg.validate(conf_values[arg.conf_name]) # except Exception as e: # raise Exception("{0}: {1}".format(arg.conf_name, str(e))) # return arguments # # Path: clearstack/argument.py # class Argument(object): # def __init__(self, cmd_option, description, # conf_name, default_value, validators=[], # options=None): # self.cmd_option = cmd_option # self.description = description # self.conf_name = conf_name # self.default_value = default_value # self.validators = validators # self.option_list = options # # def validate(self, option): # for validator in self.validators: # try: # validator(option) # except ValueError as e: # raise ValueError("{0}: {1}".format(self.conf_name, str(e))) # # Path: clearstack/common/util.py # HOST_LOG_DIR = '/var/log/clearstack' # HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR) # LOG_DIR = '/var/log/clearstack' # LOG_DIR = '/tmp/log/clearstack' # LOG_FILE = "{0}/clearstack.log".format(LOG_DIR) # LOG = logging.getLogger("Clearstack") # def _print_error_message(self, e, file_name): # def port_open(port): # def service_status(service): # def service_enabled(service): # def setup_debugging(debug, is_remote_host=True): # def run_command(command, stdin=None, environ=None, debug=True): # def str2bool(value): # def write_config(file, data): # def write_properties(file, data): # def get_option(file, section, option): # def delete_option(file, section, option=None): # def write_in_file_ine(file, data): # def get_dns(): # def get_netmask(): # def get_gateway(): # def get_net_interface(): # def get_ips(): # def get_nic(ip): # def get_ip(): # def find_my_ip_from_config(config_ips): # def is_localhost(host): # def has_localhost(hosts): # def remove_localhost(hosts): # def ensure_directory(dir): # def link_file(source, target): . Output only the next line.
validators=[validators.not_empty]),
Here is a snippet: <|code_start|># # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # def init_config(): conf = { "CEILOMETER": [ Argument("ceilometer-db-pw", "Password for ceilometer to access DB", "CONFIG_CEILOMETER_DB_PW", utils.generate_random_pw(), validators=[validators.not_empty]), Argument("ceilometer-ks-pw", "Password to use for Ceilometer to" " authenticate with Keystone", "CONFIG_CEILOMETER_KS_PW", utils.generate_random_pw(), validators=[validators.not_empty]) ] } for group in conf: <|code_end|> . Write the next line using the current file imports: from clearstack import utils from clearstack import validators from clearstack.controller import Controller from clearstack.argument import Argument from clearstack.common import util and context from other files: # Path: clearstack/utils.py # def arg(*args, **kwargs): # def _decorator(func): # def run_recipe(recipe_file, recipe_src, hosts): # def _run_recipe_local(recipe_file): # def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts): # def get_all_hosts(): # def generate_conf_file(conf_file): # def copy_resources(): # def _copy_resources_local(): # def _copy_resources_to_hosts(_hosts): # def get_logs(): # def get_template(template): # def generate_random_pw(): # def generate_ssh_keys(output): # def setup_debugging(debug): # # Path: clearstack/validators.py # def y_or_n(value): # def ip_or_hostname(value): # def cidr(value): # def file(value): # def not_empty(value): # def digit(value): # # Path: clearstack/controller.py # class Controller: # CONF = {} # _plugins = [] # _groups = [] # _sequences = [] # # def add_sequence(self, desc, function, args=None): # self._sequences.append(Sequence(desc, function, args)) # # def run_all_sequences(self): # for seq in self._sequences: # try: # seq.run() # except Exception as e: # raise e # # def add_plugin(self, plugin): # self._plugins.append(plugin) # # def get_all_plugins(self): # return self._plugins # # def add_group(self, name, args): # self._groups.append(Group(name, args)) # # def get_all_groups(self): # return self._groups # # def get_all_arguments(self): # """Get a list of the configuration argument loaded""" # arguments = [] # for group in self._groups: # arguments.extend([argument.conf_name # for argument in group.get_all_arguments()]) # return arguments # # def validate_groups(self, conf_values): # """ Load validation functions, in order to check # the values in the answer file """ # arguments = {} # for group in self._groups: # for arg in group.get_all_arguments(): # try: # arg.validate(conf_values[arg.conf_name]) # except Exception as e: # raise Exception("{0}: {1}".format(arg.conf_name, str(e))) # return arguments # # Path: clearstack/argument.py # class Argument(object): # def __init__(self, cmd_option, description, # conf_name, default_value, validators=[], # options=None): # self.cmd_option = cmd_option # self.description = description # self.conf_name = conf_name # self.default_value = default_value # self.validators = validators # self.option_list = options # # def validate(self, option): # for validator in self.validators: # try: # validator(option) # except ValueError as e: # raise ValueError("{0}: {1}".format(self.conf_name, str(e))) # # Path: clearstack/common/util.py # HOST_LOG_DIR = '/var/log/clearstack' # HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR) # LOG_DIR = '/var/log/clearstack' # LOG_DIR = '/tmp/log/clearstack' # LOG_FILE = "{0}/clearstack.log".format(LOG_DIR) # LOG = logging.getLogger("Clearstack") # def _print_error_message(self, e, file_name): # def port_open(port): # def service_status(service): # def service_enabled(service): # def setup_debugging(debug, is_remote_host=True): # def run_command(command, stdin=None, environ=None, debug=True): # def str2bool(value): # def write_config(file, data): # def write_properties(file, data): # def get_option(file, section, option): # def delete_option(file, section, option=None): # def write_in_file_ine(file, data): # def get_dns(): # def get_netmask(): # def get_gateway(): # def get_net_interface(): # def get_ips(): # def get_nic(ip): # def get_ip(): # def find_my_ip_from_config(config_ips): # def is_localhost(host): # def has_localhost(hosts): # def remove_localhost(hosts): # def ensure_directory(dir): # def link_file(source, target): , which may include functions, classes, or code. Output only the next line.
Controller.get().add_group(group, conf[group])
Given the code snippet: <|code_start|># # Copyright (c) 2015 Intel Corporation # # Author: Alberto Murillo <alberto.murillo.silva@intel.com> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # def init_config(): conf = { "CEILOMETER": [ <|code_end|> , generate the next line using the imports in this file: from clearstack import utils from clearstack import validators from clearstack.controller import Controller from clearstack.argument import Argument from clearstack.common import util and context (functions, classes, or occasionally code) from other files: # Path: clearstack/utils.py # def arg(*args, **kwargs): # def _decorator(func): # def run_recipe(recipe_file, recipe_src, hosts): # def _run_recipe_local(recipe_file): # def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts): # def get_all_hosts(): # def generate_conf_file(conf_file): # def copy_resources(): # def _copy_resources_local(): # def _copy_resources_to_hosts(_hosts): # def get_logs(): # def get_template(template): # def generate_random_pw(): # def generate_ssh_keys(output): # def setup_debugging(debug): # # Path: clearstack/validators.py # def y_or_n(value): # def ip_or_hostname(value): # def cidr(value): # def file(value): # def not_empty(value): # def digit(value): # # Path: clearstack/controller.py # class Controller: # CONF = {} # _plugins = [] # _groups = [] # _sequences = [] # # def add_sequence(self, desc, function, args=None): # self._sequences.append(Sequence(desc, function, args)) # # def run_all_sequences(self): # for seq in self._sequences: # try: # seq.run() # except Exception as e: # raise e # # def add_plugin(self, plugin): # self._plugins.append(plugin) # # def get_all_plugins(self): # return self._plugins # # def add_group(self, name, args): # self._groups.append(Group(name, args)) # # def get_all_groups(self): # return self._groups # # def get_all_arguments(self): # """Get a list of the configuration argument loaded""" # arguments = [] # for group in self._groups: # arguments.extend([argument.conf_name # for argument in group.get_all_arguments()]) # return arguments # # def validate_groups(self, conf_values): # """ Load validation functions, in order to check # the values in the answer file """ # arguments = {} # for group in self._groups: # for arg in group.get_all_arguments(): # try: # arg.validate(conf_values[arg.conf_name]) # except Exception as e: # raise Exception("{0}: {1}".format(arg.conf_name, str(e))) # return arguments # # Path: clearstack/argument.py # class Argument(object): # def __init__(self, cmd_option, description, # conf_name, default_value, validators=[], # options=None): # self.cmd_option = cmd_option # self.description = description # self.conf_name = conf_name # self.default_value = default_value # self.validators = validators # self.option_list = options # # def validate(self, option): # for validator in self.validators: # try: # validator(option) # except ValueError as e: # raise ValueError("{0}: {1}".format(self.conf_name, str(e))) # # Path: clearstack/common/util.py # HOST_LOG_DIR = '/var/log/clearstack' # HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR) # LOG_DIR = '/var/log/clearstack' # LOG_DIR = '/tmp/log/clearstack' # LOG_FILE = "{0}/clearstack.log".format(LOG_DIR) # LOG = logging.getLogger("Clearstack") # def _print_error_message(self, e, file_name): # def port_open(port): # def service_status(service): # def service_enabled(service): # def setup_debugging(debug, is_remote_host=True): # def run_command(command, stdin=None, environ=None, debug=True): # def str2bool(value): # def write_config(file, data): # def write_properties(file, data): # def get_option(file, section, option): # def delete_option(file, section, option=None): # def write_in_file_ine(file, data): # def get_dns(): # def get_netmask(): # def get_gateway(): # def get_net_interface(): # def get_ips(): # def get_nic(ip): # def get_ip(): # def find_my_ip_from_config(config_ips): # def is_localhost(host): # def has_localhost(hosts): # def remove_localhost(hosts): # def ensure_directory(dir): # def link_file(source, target): . Output only the next line.
Argument("ceilometer-db-pw",
Based on the snippet: <|code_start|># See the License for the specific language governing permissions and # limitations under the License. # def init_config(): conf = { "CEILOMETER": [ Argument("ceilometer-db-pw", "Password for ceilometer to access DB", "CONFIG_CEILOMETER_DB_PW", utils.generate_random_pw(), validators=[validators.not_empty]), Argument("ceilometer-ks-pw", "Password to use for Ceilometer to" " authenticate with Keystone", "CONFIG_CEILOMETER_KS_PW", utils.generate_random_pw(), validators=[validators.not_empty]) ] } for group in conf: Controller.get().add_group(group, conf[group]) def init_sequences(): controller = Controller.get() conf = controller.CONF <|code_end|> , predict the immediate next line with the help of imports: from clearstack import utils from clearstack import validators from clearstack.controller import Controller from clearstack.argument import Argument from clearstack.common import util and context (classes, functions, sometimes code) from other files: # Path: clearstack/utils.py # def arg(*args, **kwargs): # def _decorator(func): # def run_recipe(recipe_file, recipe_src, hosts): # def _run_recipe_local(recipe_file): # def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts): # def get_all_hosts(): # def generate_conf_file(conf_file): # def copy_resources(): # def _copy_resources_local(): # def _copy_resources_to_hosts(_hosts): # def get_logs(): # def get_template(template): # def generate_random_pw(): # def generate_ssh_keys(output): # def setup_debugging(debug): # # Path: clearstack/validators.py # def y_or_n(value): # def ip_or_hostname(value): # def cidr(value): # def file(value): # def not_empty(value): # def digit(value): # # Path: clearstack/controller.py # class Controller: # CONF = {} # _plugins = [] # _groups = [] # _sequences = [] # # def add_sequence(self, desc, function, args=None): # self._sequences.append(Sequence(desc, function, args)) # # def run_all_sequences(self): # for seq in self._sequences: # try: # seq.run() # except Exception as e: # raise e # # def add_plugin(self, plugin): # self._plugins.append(plugin) # # def get_all_plugins(self): # return self._plugins # # def add_group(self, name, args): # self._groups.append(Group(name, args)) # # def get_all_groups(self): # return self._groups # # def get_all_arguments(self): # """Get a list of the configuration argument loaded""" # arguments = [] # for group in self._groups: # arguments.extend([argument.conf_name # for argument in group.get_all_arguments()]) # return arguments # # def validate_groups(self, conf_values): # """ Load validation functions, in order to check # the values in the answer file """ # arguments = {} # for group in self._groups: # for arg in group.get_all_arguments(): # try: # arg.validate(conf_values[arg.conf_name]) # except Exception as e: # raise Exception("{0}: {1}".format(arg.conf_name, str(e))) # return arguments # # Path: clearstack/argument.py # class Argument(object): # def __init__(self, cmd_option, description, # conf_name, default_value, validators=[], # options=None): # self.cmd_option = cmd_option # self.description = description # self.conf_name = conf_name # self.default_value = default_value # self.validators = validators # self.option_list = options # # def validate(self, option): # for validator in self.validators: # try: # validator(option) # except ValueError as e: # raise ValueError("{0}: {1}".format(self.conf_name, str(e))) # # Path: clearstack/common/util.py # HOST_LOG_DIR = '/var/log/clearstack' # HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR) # LOG_DIR = '/var/log/clearstack' # LOG_DIR = '/tmp/log/clearstack' # LOG_FILE = "{0}/clearstack.log".format(LOG_DIR) # LOG = logging.getLogger("Clearstack") # def _print_error_message(self, e, file_name): # def port_open(port): # def service_status(service): # def service_enabled(service): # def setup_debugging(debug, is_remote_host=True): # def run_command(command, stdin=None, environ=None, debug=True): # def str2bool(value): # def write_config(file, data): # def write_properties(file, data): # def get_option(file, section, option): # def delete_option(file, section, option=None): # def write_in_file_ine(file, data): # def get_dns(): # def get_netmask(): # def get_gateway(): # def get_net_interface(): # def get_ips(): # def get_nic(ip): # def get_ip(): # def find_my_ip_from_config(config_ips): # def is_localhost(host): # def has_localhost(hosts): # def remove_localhost(hosts): # def ensure_directory(dir): # def link_file(source, target): . Output only the next line.
if util.str2bool(conf['CONFIG_CEILOMETER_INSTALL']):
Given the code snippet: <|code_start|># # Copyright (c) 2015 Intel Corporation # # Author: Julio Montes <julio.montes@intel.com> # Author: Obed Munoz <obed.n.munoz@intel.com> # Author: Victor Morales <victor.morales@intel.com> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # @Singleton class SshHandler(object): def __init__(self): <|code_end|> , generate the next line using the imports in this file: import os import paramiko from clearstack.controller import Controller from clearstack.common import util from clearstack.common.util import LOG from clearstack.common.singleton import Singleton and context (functions, classes, or occasionally code) from other files: # Path: clearstack/controller.py # class Controller: # CONF = {} # _plugins = [] # _groups = [] # _sequences = [] # # def add_sequence(self, desc, function, args=None): # self._sequences.append(Sequence(desc, function, args)) # # def run_all_sequences(self): # for seq in self._sequences: # try: # seq.run() # except Exception as e: # raise e # # def add_plugin(self, plugin): # self._plugins.append(plugin) # # def get_all_plugins(self): # return self._plugins # # def add_group(self, name, args): # self._groups.append(Group(name, args)) # # def get_all_groups(self): # return self._groups # # def get_all_arguments(self): # """Get a list of the configuration argument loaded""" # arguments = [] # for group in self._groups: # arguments.extend([argument.conf_name # for argument in group.get_all_arguments()]) # return arguments # # def validate_groups(self, conf_values): # """ Load validation functions, in order to check # the values in the answer file """ # arguments = {} # for group in self._groups: # for arg in group.get_all_arguments(): # try: # arg.validate(conf_values[arg.conf_name]) # except Exception as e: # raise Exception("{0}: {1}".format(arg.conf_name, str(e))) # return arguments # # Path: clearstack/common/util.py # HOST_LOG_DIR = '/var/log/clearstack' # HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR) # LOG_DIR = '/var/log/clearstack' # LOG_DIR = '/tmp/log/clearstack' # LOG_FILE = "{0}/clearstack.log".format(LOG_DIR) # LOG = logging.getLogger("Clearstack") # def _print_error_message(self, e, file_name): # def port_open(port): # def service_status(service): # def service_enabled(service): # def setup_debugging(debug, is_remote_host=True): # def run_command(command, stdin=None, environ=None, debug=True): # def str2bool(value): # def write_config(file, data): # def write_properties(file, data): # def get_option(file, section, option): # def delete_option(file, section, option=None): # def write_in_file_ine(file, data): # def get_dns(): # def get_netmask(): # def get_gateway(): # def get_net_interface(): # def get_ips(): # def get_nic(ip): # def get_ip(): # def find_my_ip_from_config(config_ips): # def is_localhost(host): # def has_localhost(hosts): # def remove_localhost(hosts): # def ensure_directory(dir): # def link_file(source, target): # # Path: clearstack/common/util.py # LOG = logging.getLogger("Clearstack") # # Path: clearstack/common/singleton.py # class Singleton: # def __init__(self, decorated): # self._decorated = decorated # # def get(self): # try: # return self._instance # except AttributeError: # self._instance = self._decorated() # return self._instance # # def __call__(self): # raise TypeError('Singletons must be accessed through `Get()`.') # # def __instancecheck__(self, inst): # return isinstance(inst, self._decorated) . Output only the next line.
conf = Controller.get().CONF
Given snippet: <|code_start|> for dirpath, dirnames, filenames in os.walk(file): remote_path = dest_path + dirpath.split(parent_dir)[1] try: sftp.mkdir(remote_path) except: LOG.info("clearstack: Directory {0} is already created" "in remote host".format(remote_path)) for filename in filenames: local_path = os.path.join(dirpath, filename) remote_filepath = os.path.join(remote_path, filename) sftp.put(local_path, remote_filepath) else: filename = file.split('/')[-1] sftp.put(file, "{0}/{1}".format(dest_path, filename)) connection.close() def test_python_in_host(self, host, connection): try: stdin, stdout, stderr = self.run_command(connection, 'python3 --version') except: raise Exception("cannot run python3 in {0}," " please install python3".format(host)) def test_hosts(self, _hosts): hosts = set(_hosts) connection = None conf = Controller.get().CONF <|code_end|> , continue by predicting the next line. Consider current file imports: import os import paramiko from clearstack.controller import Controller from clearstack.common import util from clearstack.common.util import LOG from clearstack.common.singleton import Singleton and context: # Path: clearstack/controller.py # class Controller: # CONF = {} # _plugins = [] # _groups = [] # _sequences = [] # # def add_sequence(self, desc, function, args=None): # self._sequences.append(Sequence(desc, function, args)) # # def run_all_sequences(self): # for seq in self._sequences: # try: # seq.run() # except Exception as e: # raise e # # def add_plugin(self, plugin): # self._plugins.append(plugin) # # def get_all_plugins(self): # return self._plugins # # def add_group(self, name, args): # self._groups.append(Group(name, args)) # # def get_all_groups(self): # return self._groups # # def get_all_arguments(self): # """Get a list of the configuration argument loaded""" # arguments = [] # for group in self._groups: # arguments.extend([argument.conf_name # for argument in group.get_all_arguments()]) # return arguments # # def validate_groups(self, conf_values): # """ Load validation functions, in order to check # the values in the answer file """ # arguments = {} # for group in self._groups: # for arg in group.get_all_arguments(): # try: # arg.validate(conf_values[arg.conf_name]) # except Exception as e: # raise Exception("{0}: {1}".format(arg.conf_name, str(e))) # return arguments # # Path: clearstack/common/util.py # HOST_LOG_DIR = '/var/log/clearstack' # HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR) # LOG_DIR = '/var/log/clearstack' # LOG_DIR = '/tmp/log/clearstack' # LOG_FILE = "{0}/clearstack.log".format(LOG_DIR) # LOG = logging.getLogger("Clearstack") # def _print_error_message(self, e, file_name): # def port_open(port): # def service_status(service): # def service_enabled(service): # def setup_debugging(debug, is_remote_host=True): # def run_command(command, stdin=None, environ=None, debug=True): # def str2bool(value): # def write_config(file, data): # def write_properties(file, data): # def get_option(file, section, option): # def delete_option(file, section, option=None): # def write_in_file_ine(file, data): # def get_dns(): # def get_netmask(): # def get_gateway(): # def get_net_interface(): # def get_ips(): # def get_nic(ip): # def get_ip(): # def find_my_ip_from_config(config_ips): # def is_localhost(host): # def has_localhost(hosts): # def remove_localhost(hosts): # def ensure_directory(dir): # def link_file(source, target): # # Path: clearstack/common/util.py # LOG = logging.getLogger("Clearstack") # # Path: clearstack/common/singleton.py # class Singleton: # def __init__(self, decorated): # self._decorated = decorated # # def get(self): # try: # return self._instance # except AttributeError: # self._instance = self._decorated() # return self._instance # # def __call__(self): # raise TypeError('Singletons must be accessed through `Get()`.') # # def __instancecheck__(self, inst): # return isinstance(inst, self._decorated) which might include code, classes, or functions. Output only the next line.
util.remove_localhost(hosts)
Using the snippet: <|code_start|> pass except Exception as e: raise e ''' if stderr is not empty then something fail ''' error = stderr.read() if error: raise Exception(error.decode('utf-8')) return stdin, stdout, stderr def transfer_file(self, file, dest_path, ip): try: connection = self.connect(self.ssh_user, self.ssh_private_key, ip) sftp = connection.open_sftp() except paramiko.ssh_exception.SSHException: raise Exception("cannot send {0} to {1}, please check" " your ssh connection".format(file, ip)) if os.path.isdir(file): parent_dir = "/".join(file.split('/')[:-1]) try: sftp.mkdir(dest_path) except IOError: pass for dirpath, dirnames, filenames in os.walk(file): remote_path = dest_path + dirpath.split(parent_dir)[1] try: sftp.mkdir(remote_path) except: <|code_end|> , determine the next line of code. You have imports: import os import paramiko from clearstack.controller import Controller from clearstack.common import util from clearstack.common.util import LOG from clearstack.common.singleton import Singleton and context (class names, function names, or code) available: # Path: clearstack/controller.py # class Controller: # CONF = {} # _plugins = [] # _groups = [] # _sequences = [] # # def add_sequence(self, desc, function, args=None): # self._sequences.append(Sequence(desc, function, args)) # # def run_all_sequences(self): # for seq in self._sequences: # try: # seq.run() # except Exception as e: # raise e # # def add_plugin(self, plugin): # self._plugins.append(plugin) # # def get_all_plugins(self): # return self._plugins # # def add_group(self, name, args): # self._groups.append(Group(name, args)) # # def get_all_groups(self): # return self._groups # # def get_all_arguments(self): # """Get a list of the configuration argument loaded""" # arguments = [] # for group in self._groups: # arguments.extend([argument.conf_name # for argument in group.get_all_arguments()]) # return arguments # # def validate_groups(self, conf_values): # """ Load validation functions, in order to check # the values in the answer file """ # arguments = {} # for group in self._groups: # for arg in group.get_all_arguments(): # try: # arg.validate(conf_values[arg.conf_name]) # except Exception as e: # raise Exception("{0}: {1}".format(arg.conf_name, str(e))) # return arguments # # Path: clearstack/common/util.py # HOST_LOG_DIR = '/var/log/clearstack' # HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR) # LOG_DIR = '/var/log/clearstack' # LOG_DIR = '/tmp/log/clearstack' # LOG_FILE = "{0}/clearstack.log".format(LOG_DIR) # LOG = logging.getLogger("Clearstack") # def _print_error_message(self, e, file_name): # def port_open(port): # def service_status(service): # def service_enabled(service): # def setup_debugging(debug, is_remote_host=True): # def run_command(command, stdin=None, environ=None, debug=True): # def str2bool(value): # def write_config(file, data): # def write_properties(file, data): # def get_option(file, section, option): # def delete_option(file, section, option=None): # def write_in_file_ine(file, data): # def get_dns(): # def get_netmask(): # def get_gateway(): # def get_net_interface(): # def get_ips(): # def get_nic(ip): # def get_ip(): # def find_my_ip_from_config(config_ips): # def is_localhost(host): # def has_localhost(hosts): # def remove_localhost(hosts): # def ensure_directory(dir): # def link_file(source, target): # # Path: clearstack/common/util.py # LOG = logging.getLogger("Clearstack") # # Path: clearstack/common/singleton.py # class Singleton: # def __init__(self, decorated): # self._decorated = decorated # # def get(self): # try: # return self._instance # except AttributeError: # self._instance = self._decorated() # return self._instance # # def __call__(self): # raise TypeError('Singletons must be accessed through `Get()`.') # # def __instancecheck__(self, inst): # return isinstance(inst, self._decorated) . Output only the next line.
LOG.info("clearstack: Directory {0} is already created"
Predict the next line after this snippet: <|code_start|># You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # def init_config(): conf = {} for group in conf: Controller.get().add_group(group, conf[group]) def init_sequences(): controller = Controller.get() conf = controller.CONF if util.str2bool(conf['CONFIG_HORIZON_INSTALL']): controller.add_sequence("Setting up horizon", setup_horizon) def setup_horizon(): template = "horizon" conf = Controller.get().CONF <|code_end|> using the current file's imports: from clearstack import utils from clearstack.controller import Controller from clearstack.common import util and any relevant context from other files: # Path: clearstack/utils.py # def arg(*args, **kwargs): # def _decorator(func): # def run_recipe(recipe_file, recipe_src, hosts): # def _run_recipe_local(recipe_file): # def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts): # def get_all_hosts(): # def generate_conf_file(conf_file): # def copy_resources(): # def _copy_resources_local(): # def _copy_resources_to_hosts(_hosts): # def get_logs(): # def get_template(template): # def generate_random_pw(): # def generate_ssh_keys(output): # def setup_debugging(debug): # # Path: clearstack/controller.py # class Controller: # CONF = {} # _plugins = [] # _groups = [] # _sequences = [] # # def add_sequence(self, desc, function, args=None): # self._sequences.append(Sequence(desc, function, args)) # # def run_all_sequences(self): # for seq in self._sequences: # try: # seq.run() # except Exception as e: # raise e # # def add_plugin(self, plugin): # self._plugins.append(plugin) # # def get_all_plugins(self): # return self._plugins # # def add_group(self, name, args): # self._groups.append(Group(name, args)) # # def get_all_groups(self): # return self._groups # # def get_all_arguments(self): # """Get a list of the configuration argument loaded""" # arguments = [] # for group in self._groups: # arguments.extend([argument.conf_name # for argument in group.get_all_arguments()]) # return arguments # # def validate_groups(self, conf_values): # """ Load validation functions, in order to check # the values in the answer file """ # arguments = {} # for group in self._groups: # for arg in group.get_all_arguments(): # try: # arg.validate(conf_values[arg.conf_name]) # except Exception as e: # raise Exception("{0}: {1}".format(arg.conf_name, str(e))) # return arguments # # Path: clearstack/common/util.py # HOST_LOG_DIR = '/var/log/clearstack' # HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR) # LOG_DIR = '/var/log/clearstack' # LOG_DIR = '/tmp/log/clearstack' # LOG_FILE = "{0}/clearstack.log".format(LOG_DIR) # LOG = logging.getLogger("Clearstack") # def _print_error_message(self, e, file_name): # def port_open(port): # def service_status(service): # def service_enabled(service): # def setup_debugging(debug, is_remote_host=True): # def run_command(command, stdin=None, environ=None, debug=True): # def str2bool(value): # def write_config(file, data): # def write_properties(file, data): # def get_option(file, section, option): # def delete_option(file, section, option=None): # def write_in_file_ine(file, data): # def get_dns(): # def get_netmask(): # def get_gateway(): # def get_net_interface(): # def get_ips(): # def get_nic(ip): # def get_ip(): # def find_my_ip_from_config(config_ips): # def is_localhost(host): # def has_localhost(hosts): # def remove_localhost(hosts): # def ensure_directory(dir): # def link_file(source, target): . Output only the next line.
recipe = utils.get_template(template)
Predict the next line for this snippet: <|code_start|># # Copyright (c) 2015 Intel Corporation # # Author: Alberto Murillo <alberto.murillo.silva@intel.com> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # def init_config(): conf = {} for group in conf: <|code_end|> with the help of current file imports: from clearstack import utils from clearstack.controller import Controller from clearstack.common import util and context from other files: # Path: clearstack/utils.py # def arg(*args, **kwargs): # def _decorator(func): # def run_recipe(recipe_file, recipe_src, hosts): # def _run_recipe_local(recipe_file): # def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts): # def get_all_hosts(): # def generate_conf_file(conf_file): # def copy_resources(): # def _copy_resources_local(): # def _copy_resources_to_hosts(_hosts): # def get_logs(): # def get_template(template): # def generate_random_pw(): # def generate_ssh_keys(output): # def setup_debugging(debug): # # Path: clearstack/controller.py # class Controller: # CONF = {} # _plugins = [] # _groups = [] # _sequences = [] # # def add_sequence(self, desc, function, args=None): # self._sequences.append(Sequence(desc, function, args)) # # def run_all_sequences(self): # for seq in self._sequences: # try: # seq.run() # except Exception as e: # raise e # # def add_plugin(self, plugin): # self._plugins.append(plugin) # # def get_all_plugins(self): # return self._plugins # # def add_group(self, name, args): # self._groups.append(Group(name, args)) # # def get_all_groups(self): # return self._groups # # def get_all_arguments(self): # """Get a list of the configuration argument loaded""" # arguments = [] # for group in self._groups: # arguments.extend([argument.conf_name # for argument in group.get_all_arguments()]) # return arguments # # def validate_groups(self, conf_values): # """ Load validation functions, in order to check # the values in the answer file """ # arguments = {} # for group in self._groups: # for arg in group.get_all_arguments(): # try: # arg.validate(conf_values[arg.conf_name]) # except Exception as e: # raise Exception("{0}: {1}".format(arg.conf_name, str(e))) # return arguments # # Path: clearstack/common/util.py # HOST_LOG_DIR = '/var/log/clearstack' # HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR) # LOG_DIR = '/var/log/clearstack' # LOG_DIR = '/tmp/log/clearstack' # LOG_FILE = "{0}/clearstack.log".format(LOG_DIR) # LOG = logging.getLogger("Clearstack") # def _print_error_message(self, e, file_name): # def port_open(port): # def service_status(service): # def service_enabled(service): # def setup_debugging(debug, is_remote_host=True): # def run_command(command, stdin=None, environ=None, debug=True): # def str2bool(value): # def write_config(file, data): # def write_properties(file, data): # def get_option(file, section, option): # def delete_option(file, section, option=None): # def write_in_file_ine(file, data): # def get_dns(): # def get_netmask(): # def get_gateway(): # def get_net_interface(): # def get_ips(): # def get_nic(ip): # def get_ip(): # def find_my_ip_from_config(config_ips): # def is_localhost(host): # def has_localhost(hosts): # def remove_localhost(hosts): # def ensure_directory(dir): # def link_file(source, target): , which may contain function names, class names, or code. Output only the next line.
Controller.get().add_group(group, conf[group])
Predict the next line for this snippet: <|code_start|># # Copyright (c) 2015 Intel Corporation # # Author: Alberto Murillo <alberto.murillo.silva@intel.com> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # def init_config(): conf = {} for group in conf: Controller.get().add_group(group, conf[group]) def init_sequences(): controller = Controller.get() conf = controller.CONF <|code_end|> with the help of current file imports: from clearstack import utils from clearstack.controller import Controller from clearstack.common import util and context from other files: # Path: clearstack/utils.py # def arg(*args, **kwargs): # def _decorator(func): # def run_recipe(recipe_file, recipe_src, hosts): # def _run_recipe_local(recipe_file): # def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts): # def get_all_hosts(): # def generate_conf_file(conf_file): # def copy_resources(): # def _copy_resources_local(): # def _copy_resources_to_hosts(_hosts): # def get_logs(): # def get_template(template): # def generate_random_pw(): # def generate_ssh_keys(output): # def setup_debugging(debug): # # Path: clearstack/controller.py # class Controller: # CONF = {} # _plugins = [] # _groups = [] # _sequences = [] # # def add_sequence(self, desc, function, args=None): # self._sequences.append(Sequence(desc, function, args)) # # def run_all_sequences(self): # for seq in self._sequences: # try: # seq.run() # except Exception as e: # raise e # # def add_plugin(self, plugin): # self._plugins.append(plugin) # # def get_all_plugins(self): # return self._plugins # # def add_group(self, name, args): # self._groups.append(Group(name, args)) # # def get_all_groups(self): # return self._groups # # def get_all_arguments(self): # """Get a list of the configuration argument loaded""" # arguments = [] # for group in self._groups: # arguments.extend([argument.conf_name # for argument in group.get_all_arguments()]) # return arguments # # def validate_groups(self, conf_values): # """ Load validation functions, in order to check # the values in the answer file """ # arguments = {} # for group in self._groups: # for arg in group.get_all_arguments(): # try: # arg.validate(conf_values[arg.conf_name]) # except Exception as e: # raise Exception("{0}: {1}".format(arg.conf_name, str(e))) # return arguments # # Path: clearstack/common/util.py # HOST_LOG_DIR = '/var/log/clearstack' # HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR) # LOG_DIR = '/var/log/clearstack' # LOG_DIR = '/tmp/log/clearstack' # LOG_FILE = "{0}/clearstack.log".format(LOG_DIR) # LOG = logging.getLogger("Clearstack") # def _print_error_message(self, e, file_name): # def port_open(port): # def service_status(service): # def service_enabled(service): # def setup_debugging(debug, is_remote_host=True): # def run_command(command, stdin=None, environ=None, debug=True): # def str2bool(value): # def write_config(file, data): # def write_properties(file, data): # def get_option(file, section, option): # def delete_option(file, section, option=None): # def write_in_file_ine(file, data): # def get_dns(): # def get_netmask(): # def get_gateway(): # def get_net_interface(): # def get_ips(): # def get_nic(ip): # def get_ip(): # def find_my_ip_from_config(config_ips): # def is_localhost(host): # def has_localhost(hosts): # def remove_localhost(hosts): # def ensure_directory(dir): # def link_file(source, target): , which may contain function names, class names, or code. Output only the next line.
if util.str2bool(conf['CONFIG_HORIZON_INSTALL']):
Using the snippet: <|code_start|># # Copyright (c) 2015 Intel Corporation # # Author: Alberto Murillo <alberto.murillo.silva@intel.com> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # def init_config(): conf = { "NEUTRON": [ Argument("neutron-ks-pw", "Password to use for OpenStack Networking (neutron) to" " authenticate with the Identity service.", "CONFIG_NEUTRON_KS_PW", <|code_end|> , determine the next line of code. You have imports: from clearstack import utils from clearstack import validators from clearstack.controller import Controller from clearstack.argument import Argument from clearstack.common import util and context (class names, function names, or code) available: # Path: clearstack/utils.py # def arg(*args, **kwargs): # def _decorator(func): # def run_recipe(recipe_file, recipe_src, hosts): # def _run_recipe_local(recipe_file): # def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts): # def get_all_hosts(): # def generate_conf_file(conf_file): # def copy_resources(): # def _copy_resources_local(): # def _copy_resources_to_hosts(_hosts): # def get_logs(): # def get_template(template): # def generate_random_pw(): # def generate_ssh_keys(output): # def setup_debugging(debug): # # Path: clearstack/validators.py # def y_or_n(value): # def ip_or_hostname(value): # def cidr(value): # def file(value): # def not_empty(value): # def digit(value): # # Path: clearstack/controller.py # class Controller: # CONF = {} # _plugins = [] # _groups = [] # _sequences = [] # # def add_sequence(self, desc, function, args=None): # self._sequences.append(Sequence(desc, function, args)) # # def run_all_sequences(self): # for seq in self._sequences: # try: # seq.run() # except Exception as e: # raise e # # def add_plugin(self, plugin): # self._plugins.append(plugin) # # def get_all_plugins(self): # return self._plugins # # def add_group(self, name, args): # self._groups.append(Group(name, args)) # # def get_all_groups(self): # return self._groups # # def get_all_arguments(self): # """Get a list of the configuration argument loaded""" # arguments = [] # for group in self._groups: # arguments.extend([argument.conf_name # for argument in group.get_all_arguments()]) # return arguments # # def validate_groups(self, conf_values): # """ Load validation functions, in order to check # the values in the answer file """ # arguments = {} # for group in self._groups: # for arg in group.get_all_arguments(): # try: # arg.validate(conf_values[arg.conf_name]) # except Exception as e: # raise Exception("{0}: {1}".format(arg.conf_name, str(e))) # return arguments # # Path: clearstack/argument.py # class Argument(object): # def __init__(self, cmd_option, description, # conf_name, default_value, validators=[], # options=None): # self.cmd_option = cmd_option # self.description = description # self.conf_name = conf_name # self.default_value = default_value # self.validators = validators # self.option_list = options # # def validate(self, option): # for validator in self.validators: # try: # validator(option) # except ValueError as e: # raise ValueError("{0}: {1}".format(self.conf_name, str(e))) # # Path: clearstack/common/util.py # HOST_LOG_DIR = '/var/log/clearstack' # HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR) # LOG_DIR = '/var/log/clearstack' # LOG_DIR = '/tmp/log/clearstack' # LOG_FILE = "{0}/clearstack.log".format(LOG_DIR) # LOG = logging.getLogger("Clearstack") # def _print_error_message(self, e, file_name): # def port_open(port): # def service_status(service): # def service_enabled(service): # def setup_debugging(debug, is_remote_host=True): # def run_command(command, stdin=None, environ=None, debug=True): # def str2bool(value): # def write_config(file, data): # def write_properties(file, data): # def get_option(file, section, option): # def delete_option(file, section, option=None): # def write_in_file_ine(file, data): # def get_dns(): # def get_netmask(): # def get_gateway(): # def get_net_interface(): # def get_ips(): # def get_nic(ip): # def get_ip(): # def find_my_ip_from_config(config_ips): # def is_localhost(host): # def has_localhost(hosts): # def remove_localhost(hosts): # def ensure_directory(dir): # def link_file(source, target): . Output only the next line.
utils.generate_random_pw(),
Next line prediction: <|code_start|># # Copyright (c) 2015 Intel Corporation # # Author: Alberto Murillo <alberto.murillo.silva@intel.com> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # def init_config(): conf = { "NEUTRON": [ Argument("neutron-ks-pw", "Password to use for OpenStack Networking (neutron) to" " authenticate with the Identity service.", "CONFIG_NEUTRON_KS_PW", utils.generate_random_pw(), <|code_end|> . Use current file imports: (from clearstack import utils from clearstack import validators from clearstack.controller import Controller from clearstack.argument import Argument from clearstack.common import util) and context including class names, function names, or small code snippets from other files: # Path: clearstack/utils.py # def arg(*args, **kwargs): # def _decorator(func): # def run_recipe(recipe_file, recipe_src, hosts): # def _run_recipe_local(recipe_file): # def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts): # def get_all_hosts(): # def generate_conf_file(conf_file): # def copy_resources(): # def _copy_resources_local(): # def _copy_resources_to_hosts(_hosts): # def get_logs(): # def get_template(template): # def generate_random_pw(): # def generate_ssh_keys(output): # def setup_debugging(debug): # # Path: clearstack/validators.py # def y_or_n(value): # def ip_or_hostname(value): # def cidr(value): # def file(value): # def not_empty(value): # def digit(value): # # Path: clearstack/controller.py # class Controller: # CONF = {} # _plugins = [] # _groups = [] # _sequences = [] # # def add_sequence(self, desc, function, args=None): # self._sequences.append(Sequence(desc, function, args)) # # def run_all_sequences(self): # for seq in self._sequences: # try: # seq.run() # except Exception as e: # raise e # # def add_plugin(self, plugin): # self._plugins.append(plugin) # # def get_all_plugins(self): # return self._plugins # # def add_group(self, name, args): # self._groups.append(Group(name, args)) # # def get_all_groups(self): # return self._groups # # def get_all_arguments(self): # """Get a list of the configuration argument loaded""" # arguments = [] # for group in self._groups: # arguments.extend([argument.conf_name # for argument in group.get_all_arguments()]) # return arguments # # def validate_groups(self, conf_values): # """ Load validation functions, in order to check # the values in the answer file """ # arguments = {} # for group in self._groups: # for arg in group.get_all_arguments(): # try: # arg.validate(conf_values[arg.conf_name]) # except Exception as e: # raise Exception("{0}: {1}".format(arg.conf_name, str(e))) # return arguments # # Path: clearstack/argument.py # class Argument(object): # def __init__(self, cmd_option, description, # conf_name, default_value, validators=[], # options=None): # self.cmd_option = cmd_option # self.description = description # self.conf_name = conf_name # self.default_value = default_value # self.validators = validators # self.option_list = options # # def validate(self, option): # for validator in self.validators: # try: # validator(option) # except ValueError as e: # raise ValueError("{0}: {1}".format(self.conf_name, str(e))) # # Path: clearstack/common/util.py # HOST_LOG_DIR = '/var/log/clearstack' # HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR) # LOG_DIR = '/var/log/clearstack' # LOG_DIR = '/tmp/log/clearstack' # LOG_FILE = "{0}/clearstack.log".format(LOG_DIR) # LOG = logging.getLogger("Clearstack") # def _print_error_message(self, e, file_name): # def port_open(port): # def service_status(service): # def service_enabled(service): # def setup_debugging(debug, is_remote_host=True): # def run_command(command, stdin=None, environ=None, debug=True): # def str2bool(value): # def write_config(file, data): # def write_properties(file, data): # def get_option(file, section, option): # def delete_option(file, section, option=None): # def write_in_file_ine(file, data): # def get_dns(): # def get_netmask(): # def get_gateway(): # def get_net_interface(): # def get_ips(): # def get_nic(ip): # def get_ip(): # def find_my_ip_from_config(config_ips): # def is_localhost(host): # def has_localhost(hosts): # def remove_localhost(hosts): # def ensure_directory(dir): # def link_file(source, target): . Output only the next line.
validators=[validators.not_empty]),
Here is a snippet: <|code_start|> "Comma-separated, ordered list of network types to " "allocate as tenant networks", "CONFIG_NEUTRON_ML2_MECHANISM_DRIVERS", "linuxbridge,l2population", options=['openvswitch', 'linuxbridge'], validators=[validators.not_empty]), Argument("neutron-ml2-flat-networks", "Comma-separated list of physical_network names with " "wich flat networks can be created.", "CONFIG_NEUTRON_ML2_FLAT_NETWORKS", "public", validators=[validators.not_empty]), Argument("neutron-ml2-tunnel-id-ranges", "Comma-separated list of <tun_min>:<tun_max> tuples " "enumerating ranges of GRE tunnel IDs that are available " "for tenant-network allocation.", "CONFIG_NEUTRON_ML2_TUNNEL_ID_RANGES", "1:1000", validators=[validators.not_empty]), Argument("neutron-l2-agent", "Name of the L2 agent to be used with OpenStack " "Networking", "CONFIG_NEUTRON_L2_AGENT", "linuxbridge", options=['openvswitch', 'linuxbridge'], validators=[validators.not_empty]) ] } for group in conf: <|code_end|> . Write the next line using the current file imports: from clearstack import utils from clearstack import validators from clearstack.controller import Controller from clearstack.argument import Argument from clearstack.common import util and context from other files: # Path: clearstack/utils.py # def arg(*args, **kwargs): # def _decorator(func): # def run_recipe(recipe_file, recipe_src, hosts): # def _run_recipe_local(recipe_file): # def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts): # def get_all_hosts(): # def generate_conf_file(conf_file): # def copy_resources(): # def _copy_resources_local(): # def _copy_resources_to_hosts(_hosts): # def get_logs(): # def get_template(template): # def generate_random_pw(): # def generate_ssh_keys(output): # def setup_debugging(debug): # # Path: clearstack/validators.py # def y_or_n(value): # def ip_or_hostname(value): # def cidr(value): # def file(value): # def not_empty(value): # def digit(value): # # Path: clearstack/controller.py # class Controller: # CONF = {} # _plugins = [] # _groups = [] # _sequences = [] # # def add_sequence(self, desc, function, args=None): # self._sequences.append(Sequence(desc, function, args)) # # def run_all_sequences(self): # for seq in self._sequences: # try: # seq.run() # except Exception as e: # raise e # # def add_plugin(self, plugin): # self._plugins.append(plugin) # # def get_all_plugins(self): # return self._plugins # # def add_group(self, name, args): # self._groups.append(Group(name, args)) # # def get_all_groups(self): # return self._groups # # def get_all_arguments(self): # """Get a list of the configuration argument loaded""" # arguments = [] # for group in self._groups: # arguments.extend([argument.conf_name # for argument in group.get_all_arguments()]) # return arguments # # def validate_groups(self, conf_values): # """ Load validation functions, in order to check # the values in the answer file """ # arguments = {} # for group in self._groups: # for arg in group.get_all_arguments(): # try: # arg.validate(conf_values[arg.conf_name]) # except Exception as e: # raise Exception("{0}: {1}".format(arg.conf_name, str(e))) # return arguments # # Path: clearstack/argument.py # class Argument(object): # def __init__(self, cmd_option, description, # conf_name, default_value, validators=[], # options=None): # self.cmd_option = cmd_option # self.description = description # self.conf_name = conf_name # self.default_value = default_value # self.validators = validators # self.option_list = options # # def validate(self, option): # for validator in self.validators: # try: # validator(option) # except ValueError as e: # raise ValueError("{0}: {1}".format(self.conf_name, str(e))) # # Path: clearstack/common/util.py # HOST_LOG_DIR = '/var/log/clearstack' # HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR) # LOG_DIR = '/var/log/clearstack' # LOG_DIR = '/tmp/log/clearstack' # LOG_FILE = "{0}/clearstack.log".format(LOG_DIR) # LOG = logging.getLogger("Clearstack") # def _print_error_message(self, e, file_name): # def port_open(port): # def service_status(service): # def service_enabled(service): # def setup_debugging(debug, is_remote_host=True): # def run_command(command, stdin=None, environ=None, debug=True): # def str2bool(value): # def write_config(file, data): # def write_properties(file, data): # def get_option(file, section, option): # def delete_option(file, section, option=None): # def write_in_file_ine(file, data): # def get_dns(): # def get_netmask(): # def get_gateway(): # def get_net_interface(): # def get_ips(): # def get_nic(ip): # def get_ip(): # def find_my_ip_from_config(config_ips): # def is_localhost(host): # def has_localhost(hosts): # def remove_localhost(hosts): # def ensure_directory(dir): # def link_file(source, target): , which may include functions, classes, or code. Output only the next line.
Controller.get().add_group(group, conf[group])
Continue the code snippet: <|code_start|># # Copyright (c) 2015 Intel Corporation # # Author: Alberto Murillo <alberto.murillo.silva@intel.com> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # def init_config(): conf = { "NEUTRON": [ <|code_end|> . Use current file imports: from clearstack import utils from clearstack import validators from clearstack.controller import Controller from clearstack.argument import Argument from clearstack.common import util and context (classes, functions, or code) from other files: # Path: clearstack/utils.py # def arg(*args, **kwargs): # def _decorator(func): # def run_recipe(recipe_file, recipe_src, hosts): # def _run_recipe_local(recipe_file): # def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts): # def get_all_hosts(): # def generate_conf_file(conf_file): # def copy_resources(): # def _copy_resources_local(): # def _copy_resources_to_hosts(_hosts): # def get_logs(): # def get_template(template): # def generate_random_pw(): # def generate_ssh_keys(output): # def setup_debugging(debug): # # Path: clearstack/validators.py # def y_or_n(value): # def ip_or_hostname(value): # def cidr(value): # def file(value): # def not_empty(value): # def digit(value): # # Path: clearstack/controller.py # class Controller: # CONF = {} # _plugins = [] # _groups = [] # _sequences = [] # # def add_sequence(self, desc, function, args=None): # self._sequences.append(Sequence(desc, function, args)) # # def run_all_sequences(self): # for seq in self._sequences: # try: # seq.run() # except Exception as e: # raise e # # def add_plugin(self, plugin): # self._plugins.append(plugin) # # def get_all_plugins(self): # return self._plugins # # def add_group(self, name, args): # self._groups.append(Group(name, args)) # # def get_all_groups(self): # return self._groups # # def get_all_arguments(self): # """Get a list of the configuration argument loaded""" # arguments = [] # for group in self._groups: # arguments.extend([argument.conf_name # for argument in group.get_all_arguments()]) # return arguments # # def validate_groups(self, conf_values): # """ Load validation functions, in order to check # the values in the answer file """ # arguments = {} # for group in self._groups: # for arg in group.get_all_arguments(): # try: # arg.validate(conf_values[arg.conf_name]) # except Exception as e: # raise Exception("{0}: {1}".format(arg.conf_name, str(e))) # return arguments # # Path: clearstack/argument.py # class Argument(object): # def __init__(self, cmd_option, description, # conf_name, default_value, validators=[], # options=None): # self.cmd_option = cmd_option # self.description = description # self.conf_name = conf_name # self.default_value = default_value # self.validators = validators # self.option_list = options # # def validate(self, option): # for validator in self.validators: # try: # validator(option) # except ValueError as e: # raise ValueError("{0}: {1}".format(self.conf_name, str(e))) # # Path: clearstack/common/util.py # HOST_LOG_DIR = '/var/log/clearstack' # HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR) # LOG_DIR = '/var/log/clearstack' # LOG_DIR = '/tmp/log/clearstack' # LOG_FILE = "{0}/clearstack.log".format(LOG_DIR) # LOG = logging.getLogger("Clearstack") # def _print_error_message(self, e, file_name): # def port_open(port): # def service_status(service): # def service_enabled(service): # def setup_debugging(debug, is_remote_host=True): # def run_command(command, stdin=None, environ=None, debug=True): # def str2bool(value): # def write_config(file, data): # def write_properties(file, data): # def get_option(file, section, option): # def delete_option(file, section, option=None): # def write_in_file_ine(file, data): # def get_dns(): # def get_netmask(): # def get_gateway(): # def get_net_interface(): # def get_ips(): # def get_nic(ip): # def get_ip(): # def find_my_ip_from_config(config_ips): # def is_localhost(host): # def has_localhost(hosts): # def remove_localhost(hosts): # def ensure_directory(dir): # def link_file(source, target): . Output only the next line.
Argument("neutron-ks-pw",
Here is a snippet: <|code_start|> Argument("neutron-ml2-flat-networks", "Comma-separated list of physical_network names with " "wich flat networks can be created.", "CONFIG_NEUTRON_ML2_FLAT_NETWORKS", "public", validators=[validators.not_empty]), Argument("neutron-ml2-tunnel-id-ranges", "Comma-separated list of <tun_min>:<tun_max> tuples " "enumerating ranges of GRE tunnel IDs that are available " "for tenant-network allocation.", "CONFIG_NEUTRON_ML2_TUNNEL_ID_RANGES", "1:1000", validators=[validators.not_empty]), Argument("neutron-l2-agent", "Name of the L2 agent to be used with OpenStack " "Networking", "CONFIG_NEUTRON_L2_AGENT", "linuxbridge", options=['openvswitch', 'linuxbridge'], validators=[validators.not_empty]) ] } for group in conf: Controller.get().add_group(group, conf[group]) def init_sequences(): controller = Controller.get() conf = controller.CONF <|code_end|> . Write the next line using the current file imports: from clearstack import utils from clearstack import validators from clearstack.controller import Controller from clearstack.argument import Argument from clearstack.common import util and context from other files: # Path: clearstack/utils.py # def arg(*args, **kwargs): # def _decorator(func): # def run_recipe(recipe_file, recipe_src, hosts): # def _run_recipe_local(recipe_file): # def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts): # def get_all_hosts(): # def generate_conf_file(conf_file): # def copy_resources(): # def _copy_resources_local(): # def _copy_resources_to_hosts(_hosts): # def get_logs(): # def get_template(template): # def generate_random_pw(): # def generate_ssh_keys(output): # def setup_debugging(debug): # # Path: clearstack/validators.py # def y_or_n(value): # def ip_or_hostname(value): # def cidr(value): # def file(value): # def not_empty(value): # def digit(value): # # Path: clearstack/controller.py # class Controller: # CONF = {} # _plugins = [] # _groups = [] # _sequences = [] # # def add_sequence(self, desc, function, args=None): # self._sequences.append(Sequence(desc, function, args)) # # def run_all_sequences(self): # for seq in self._sequences: # try: # seq.run() # except Exception as e: # raise e # # def add_plugin(self, plugin): # self._plugins.append(plugin) # # def get_all_plugins(self): # return self._plugins # # def add_group(self, name, args): # self._groups.append(Group(name, args)) # # def get_all_groups(self): # return self._groups # # def get_all_arguments(self): # """Get a list of the configuration argument loaded""" # arguments = [] # for group in self._groups: # arguments.extend([argument.conf_name # for argument in group.get_all_arguments()]) # return arguments # # def validate_groups(self, conf_values): # """ Load validation functions, in order to check # the values in the answer file """ # arguments = {} # for group in self._groups: # for arg in group.get_all_arguments(): # try: # arg.validate(conf_values[arg.conf_name]) # except Exception as e: # raise Exception("{0}: {1}".format(arg.conf_name, str(e))) # return arguments # # Path: clearstack/argument.py # class Argument(object): # def __init__(self, cmd_option, description, # conf_name, default_value, validators=[], # options=None): # self.cmd_option = cmd_option # self.description = description # self.conf_name = conf_name # self.default_value = default_value # self.validators = validators # self.option_list = options # # def validate(self, option): # for validator in self.validators: # try: # validator(option) # except ValueError as e: # raise ValueError("{0}: {1}".format(self.conf_name, str(e))) # # Path: clearstack/common/util.py # HOST_LOG_DIR = '/var/log/clearstack' # HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR) # LOG_DIR = '/var/log/clearstack' # LOG_DIR = '/tmp/log/clearstack' # LOG_FILE = "{0}/clearstack.log".format(LOG_DIR) # LOG = logging.getLogger("Clearstack") # def _print_error_message(self, e, file_name): # def port_open(port): # def service_status(service): # def service_enabled(service): # def setup_debugging(debug, is_remote_host=True): # def run_command(command, stdin=None, environ=None, debug=True): # def str2bool(value): # def write_config(file, data): # def write_properties(file, data): # def get_option(file, section, option): # def delete_option(file, section, option=None): # def write_in_file_ine(file, data): # def get_dns(): # def get_netmask(): # def get_gateway(): # def get_net_interface(): # def get_ips(): # def get_nic(ip): # def get_ip(): # def find_my_ip_from_config(config_ips): # def is_localhost(host): # def has_localhost(hosts): # def remove_localhost(hosts): # def ensure_directory(dir): # def link_file(source, target): , which may include functions, classes, or code. Output only the next line.
if util.str2bool(conf['CONFIG_NEUTRON_INSTALL']):
Given the following code snippet before the placeholder: <|code_start|># # Copyright (c) 2015 Intel Corporation # # Author: Alberto Murillo <alberto.murillo.silva@intel.com> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # def init_config(): conf = { "SWIFT": [ Argument("swift-ks-pw", "Password to use for the Object Storage service to " " authenticate with with the Identity service", "CONFIG_SWIFT_KS_PW", <|code_end|> , predict the next line using imports from the current file: import os import stat from clearstack import utils from clearstack import validators from clearstack.controller import Controller from clearstack.argument import Argument from clearstack.common import util and context including class names, function names, and sometimes code from other files: # Path: clearstack/utils.py # def arg(*args, **kwargs): # def _decorator(func): # def run_recipe(recipe_file, recipe_src, hosts): # def _run_recipe_local(recipe_file): # def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts): # def get_all_hosts(): # def generate_conf_file(conf_file): # def copy_resources(): # def _copy_resources_local(): # def _copy_resources_to_hosts(_hosts): # def get_logs(): # def get_template(template): # def generate_random_pw(): # def generate_ssh_keys(output): # def setup_debugging(debug): # # Path: clearstack/validators.py # def y_or_n(value): # def ip_or_hostname(value): # def cidr(value): # def file(value): # def not_empty(value): # def digit(value): # # Path: clearstack/controller.py # class Controller: # CONF = {} # _plugins = [] # _groups = [] # _sequences = [] # # def add_sequence(self, desc, function, args=None): # self._sequences.append(Sequence(desc, function, args)) # # def run_all_sequences(self): # for seq in self._sequences: # try: # seq.run() # except Exception as e: # raise e # # def add_plugin(self, plugin): # self._plugins.append(plugin) # # def get_all_plugins(self): # return self._plugins # # def add_group(self, name, args): # self._groups.append(Group(name, args)) # # def get_all_groups(self): # return self._groups # # def get_all_arguments(self): # """Get a list of the configuration argument loaded""" # arguments = [] # for group in self._groups: # arguments.extend([argument.conf_name # for argument in group.get_all_arguments()]) # return arguments # # def validate_groups(self, conf_values): # """ Load validation functions, in order to check # the values in the answer file """ # arguments = {} # for group in self._groups: # for arg in group.get_all_arguments(): # try: # arg.validate(conf_values[arg.conf_name]) # except Exception as e: # raise Exception("{0}: {1}".format(arg.conf_name, str(e))) # return arguments # # Path: clearstack/argument.py # class Argument(object): # def __init__(self, cmd_option, description, # conf_name, default_value, validators=[], # options=None): # self.cmd_option = cmd_option # self.description = description # self.conf_name = conf_name # self.default_value = default_value # self.validators = validators # self.option_list = options # # def validate(self, option): # for validator in self.validators: # try: # validator(option) # except ValueError as e: # raise ValueError("{0}: {1}".format(self.conf_name, str(e))) # # Path: clearstack/common/util.py # HOST_LOG_DIR = '/var/log/clearstack' # HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR) # LOG_DIR = '/var/log/clearstack' # LOG_DIR = '/tmp/log/clearstack' # LOG_FILE = "{0}/clearstack.log".format(LOG_DIR) # LOG = logging.getLogger("Clearstack") # def _print_error_message(self, e, file_name): # def port_open(port): # def service_status(service): # def service_enabled(service): # def setup_debugging(debug, is_remote_host=True): # def run_command(command, stdin=None, environ=None, debug=True): # def str2bool(value): # def write_config(file, data): # def write_properties(file, data): # def get_option(file, section, option): # def delete_option(file, section, option=None): # def write_in_file_ine(file, data): # def get_dns(): # def get_netmask(): # def get_gateway(): # def get_net_interface(): # def get_ips(): # def get_nic(ip): # def get_ip(): # def find_my_ip_from_config(config_ips): # def is_localhost(host): # def has_localhost(hosts): # def remove_localhost(hosts): # def ensure_directory(dir): # def link_file(source, target): . Output only the next line.
utils.generate_random_pw(),
Using the snippet: <|code_start|># # Copyright (c) 2015 Intel Corporation # # Author: Alberto Murillo <alberto.murillo.silva@intel.com> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # def init_config(): conf = { "SWIFT": [ Argument("swift-ks-pw", "Password to use for the Object Storage service to " " authenticate with with the Identity service", "CONFIG_SWIFT_KS_PW", utils.generate_random_pw(), <|code_end|> , determine the next line of code. You have imports: import os import stat from clearstack import utils from clearstack import validators from clearstack.controller import Controller from clearstack.argument import Argument from clearstack.common import util and context (class names, function names, or code) available: # Path: clearstack/utils.py # def arg(*args, **kwargs): # def _decorator(func): # def run_recipe(recipe_file, recipe_src, hosts): # def _run_recipe_local(recipe_file): # def _run_recipe_in_hosts(recipe_file, recipes_dir, _hosts): # def get_all_hosts(): # def generate_conf_file(conf_file): # def copy_resources(): # def _copy_resources_local(): # def _copy_resources_to_hosts(_hosts): # def get_logs(): # def get_template(template): # def generate_random_pw(): # def generate_ssh_keys(output): # def setup_debugging(debug): # # Path: clearstack/validators.py # def y_or_n(value): # def ip_or_hostname(value): # def cidr(value): # def file(value): # def not_empty(value): # def digit(value): # # Path: clearstack/controller.py # class Controller: # CONF = {} # _plugins = [] # _groups = [] # _sequences = [] # # def add_sequence(self, desc, function, args=None): # self._sequences.append(Sequence(desc, function, args)) # # def run_all_sequences(self): # for seq in self._sequences: # try: # seq.run() # except Exception as e: # raise e # # def add_plugin(self, plugin): # self._plugins.append(plugin) # # def get_all_plugins(self): # return self._plugins # # def add_group(self, name, args): # self._groups.append(Group(name, args)) # # def get_all_groups(self): # return self._groups # # def get_all_arguments(self): # """Get a list of the configuration argument loaded""" # arguments = [] # for group in self._groups: # arguments.extend([argument.conf_name # for argument in group.get_all_arguments()]) # return arguments # # def validate_groups(self, conf_values): # """ Load validation functions, in order to check # the values in the answer file """ # arguments = {} # for group in self._groups: # for arg in group.get_all_arguments(): # try: # arg.validate(conf_values[arg.conf_name]) # except Exception as e: # raise Exception("{0}: {1}".format(arg.conf_name, str(e))) # return arguments # # Path: clearstack/argument.py # class Argument(object): # def __init__(self, cmd_option, description, # conf_name, default_value, validators=[], # options=None): # self.cmd_option = cmd_option # self.description = description # self.conf_name = conf_name # self.default_value = default_value # self.validators = validators # self.option_list = options # # def validate(self, option): # for validator in self.validators: # try: # validator(option) # except ValueError as e: # raise ValueError("{0}: {1}".format(self.conf_name, str(e))) # # Path: clearstack/common/util.py # HOST_LOG_DIR = '/var/log/clearstack' # HOST_LOG_FILE = "{0}/clearstack.log".format(HOST_LOG_DIR) # LOG_DIR = '/var/log/clearstack' # LOG_DIR = '/tmp/log/clearstack' # LOG_FILE = "{0}/clearstack.log".format(LOG_DIR) # LOG = logging.getLogger("Clearstack") # def _print_error_message(self, e, file_name): # def port_open(port): # def service_status(service): # def service_enabled(service): # def setup_debugging(debug, is_remote_host=True): # def run_command(command, stdin=None, environ=None, debug=True): # def str2bool(value): # def write_config(file, data): # def write_properties(file, data): # def get_option(file, section, option): # def delete_option(file, section, option=None): # def write_in_file_ine(file, data): # def get_dns(): # def get_netmask(): # def get_gateway(): # def get_net_interface(): # def get_ips(): # def get_nic(ip): # def get_ip(): # def find_my_ip_from_config(config_ips): # def is_localhost(host): # def has_localhost(hosts): # def remove_localhost(hosts): # def ensure_directory(dir): # def link_file(source, target): . Output only the next line.
validators=[validators.not_empty]),