Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Based on the snippet: <|code_start|>
class TestAnalysis(unittest.TestCase):
@patch.object(requests.Session, "request")
def test_get(self, mock_request: unittest.mock):
mock_request.return_value = unittest.mock.MagicMock(status_code=200)
<|code_end|>
, predict the immediate next line with the help of imports:
import requests
import unittest
from unittest.mock import patch, PropertyMock
from memsource import constants, models
from memsource.api_rest.analysis import Analysis
and context (classes, functions, sometimes code) from other files:
# Path: memsource/constants.py
# class Base(enum.Enum):
# class JobStatus(enum.Enum):
# class ProjectStatus(enum.Enum):
# class AnalysisFormat(enum.Enum):
# class TermBaseFormat(enum.Enum):
# class ApiVersion(enum.Enum):
# class HttpMethod(enum.Enum):
# class BaseRest(enum.Enum):
# class JobStatusRest(enum.Enum):
# NEW = "New"
# EMAILED = "Emailed"
# ASSIGNED = "Assigned"
# DECLINED_BY_LINGUIST = "Declined_By_Linguist"
# COMPLETED_BY_LINGUIST = "Completed_By_Linguist"
# COMPLETED = "Completed"
# CANCELLED = "Cancelled"
# NEW = "New"
# ASSIGNED = "Assigned"
# COMPLETED = "Completed"
# CANCELLED = "Cancelled"
# ACCEPTED_BY_VENDOR = "Accepted_By_Vendor"
# DECLINED_BY_VENDOR = "Declined_By_Vendor"
# COMPLETED_BY_VENDOR = "Completed_By_Vendor"
# CSV = "CSV"
# LOG = "LOG"
# CSV_EXTENDED = "CSV_EXTENDED"
# XLSX = "XLSX"
# TBX = "TBX"
# NEW = "NEW"
# ACCEPTED = "ACCEPTED"
# DECLINED = "DECLINED"
# REJECTED = "REJECTED"
# DELIVERED = "DELIVERED"
# EMAILED = "EMAILED"
# COMPLETED = "COMPLETED"
# CANCELLED = "CANCELLED"
# CHUNK_SIZE = 1024
# CHAR_SET = "UTF-8"
# TM_THRESHOLD = 0.7
#
# Path: memsource/models.py
# class BaseModel(dict):
# class User(BaseModel):
# class Authentication(BaseModel):
# class Client(BaseModel):
# class Domain(BaseModel):
# class Language(BaseModel):
# class Project(BaseModel):
# class Job(BaseModel):
# class JobPart(BaseModel):
# class TranslationMemory(BaseModel):
# class AsynchronousRequest(BaseModel):
# class AsynchronousResponse(BaseModel):
# class Segment(BaseModel):
# class SegmentSearchResult(BaseModel):
# class Analysis(BaseModel):
# class MxliffUnit(BaseModel):
# class TermBase(BaseModel):
# def __getattr__(self, key):
# def _iso8601_to_datetime(self, source):
# def date_created(self):
# def __init__(self, source):
# def is_complete(self):
# def has_error(self):
#
# Path: memsource/api_rest/analysis.py
# class Analysis(api_rest.BaseApi):
# # Document: https://cloud.memsource.com/web/docs/api#tag/Analysis
#
# def get(self, analysis_id: int) -> models.Analysis:
# """Call get API.
#
# :param analysis_id: Get analysis of this id.
# :return: Result of analysis.
# """
# return models.Analysis(self._get("v3/analyses/{}".format(analysis_id)))
#
# def create(self, jobs: List[int]) -> models.AsynchronousRequest:
# """Create new analysis.
#
# :param jobs: Target of analysis.
# :return: Result of analysis.
# """
# return models.AsynchronousRequest(self._post("v2/analyses", {
# "jobs": [{"uid": job} for job in jobs],
# }))
#
# def delete(self, analysis_id: int, purge: bool=False) -> None:
# """Delete an analysis.
#
# :param analysis_id: Analysis ID you want to delete.
# :param purge:
# """
# self._delete("v1/analyses/{}".format(analysis_id), {"purge": purge})
#
# def get_by_project(self, project_id: str) -> List[models.Analysis]:
# """List Analyses By Project.
#
# :param project_id: Project ID for which you want to get the analyses.
# :return: List of Analyses.
# """
# project_analyses = self._get("v2/projects/{}/analyses".format(project_id))
# return [models.Analysis(analysis) for analysis in project_analyses["content"]]
#
# def download(
# self,
# analysis_id: int,
# dest_file_path: str,
# file_format: constants.AnalysisFormat=constants.AnalysisFormat.CSV,
# ) -> None:
# """Download analysis into specified file format.
#
# :param analysis_id: Anaylsis ID for which you download.
# :param dest_file_path: Destination path where you want to download the file.
# :param file_format: File format of file.
# :return: Downloaded file with content of the analysis
# """
# with open(dest_file_path, "wb") as f:
# for chunk in self._get_analysis_stream(analysis_id, file_format):
# f.write(chunk)
#
# def _get_analysis_stream(
# self,
# analysis_id: int,
# file_format: constants.AnalysisFormat
# ) -> Iterator[bytes]:
# """Process bytes return by API
#
# :param analysis_id: Anaylsis ID for which you download.
# :param file_format: File format of file.
# :return: Downloaded analysis file with iterator.
# """
# return self._get_stream("v1/analyses/{}/download".format(analysis_id), {
# "format": file_format.value,
# }).iter_content(constants.CHUNK_SIZE)
. Output only the next line. | Analysis(token="mock-token").get(1) |
Given the following code snippet before the placeholder: <|code_start|>
class TestLanguage(unittest.TestCase):
@patch.object(requests.Session, "request")
def test_list(self, mock_request: unittest.mock):
ms_response = unittest.mock.MagicMock(status_code=200)
ms_response.json.return_value = {
"languages": [
{"name": "Abkhaz", "code": "ab"},
{"name": "Afar", "code": "aa"},
]
}
mock_request.return_value = ms_response
expected = [
models.Language(name="Abkhaz", code="ab"),
models.Language(name="Afar", code="aa"),
]
for lang, expected_lang in zip(
Language(token="mock-token").listSupportedLangs(), expected
):
self.assertEqual(lang, expected_lang)
self.assertIsInstance(lang, models.Language)
mock_request.assert_called_with(
<|code_end|>
, predict the next line using imports from the current file:
import requests
import unittest
from unittest.mock import patch
from memsource import constants, models
from memsource.api_rest.language import Language
and context including class names, function names, and sometimes code from other files:
# Path: memsource/constants.py
# class Base(enum.Enum):
# class JobStatus(enum.Enum):
# class ProjectStatus(enum.Enum):
# class AnalysisFormat(enum.Enum):
# class TermBaseFormat(enum.Enum):
# class ApiVersion(enum.Enum):
# class HttpMethod(enum.Enum):
# class BaseRest(enum.Enum):
# class JobStatusRest(enum.Enum):
# NEW = "New"
# EMAILED = "Emailed"
# ASSIGNED = "Assigned"
# DECLINED_BY_LINGUIST = "Declined_By_Linguist"
# COMPLETED_BY_LINGUIST = "Completed_By_Linguist"
# COMPLETED = "Completed"
# CANCELLED = "Cancelled"
# NEW = "New"
# ASSIGNED = "Assigned"
# COMPLETED = "Completed"
# CANCELLED = "Cancelled"
# ACCEPTED_BY_VENDOR = "Accepted_By_Vendor"
# DECLINED_BY_VENDOR = "Declined_By_Vendor"
# COMPLETED_BY_VENDOR = "Completed_By_Vendor"
# CSV = "CSV"
# LOG = "LOG"
# CSV_EXTENDED = "CSV_EXTENDED"
# XLSX = "XLSX"
# TBX = "TBX"
# NEW = "NEW"
# ACCEPTED = "ACCEPTED"
# DECLINED = "DECLINED"
# REJECTED = "REJECTED"
# DELIVERED = "DELIVERED"
# EMAILED = "EMAILED"
# COMPLETED = "COMPLETED"
# CANCELLED = "CANCELLED"
# CHUNK_SIZE = 1024
# CHAR_SET = "UTF-8"
# TM_THRESHOLD = 0.7
#
# Path: memsource/models.py
# class BaseModel(dict):
# class User(BaseModel):
# class Authentication(BaseModel):
# class Client(BaseModel):
# class Domain(BaseModel):
# class Language(BaseModel):
# class Project(BaseModel):
# class Job(BaseModel):
# class JobPart(BaseModel):
# class TranslationMemory(BaseModel):
# class AsynchronousRequest(BaseModel):
# class AsynchronousResponse(BaseModel):
# class Segment(BaseModel):
# class SegmentSearchResult(BaseModel):
# class Analysis(BaseModel):
# class MxliffUnit(BaseModel):
# class TermBase(BaseModel):
# def __getattr__(self, key):
# def _iso8601_to_datetime(self, source):
# def date_created(self):
# def __init__(self, source):
# def is_complete(self):
# def has_error(self):
#
# Path: memsource/api_rest/language.py
# class Language(api_rest.BaseApi):
# # Document: https://cloud.memsource.com/web/docs/api#tag/Supported-Languages
#
# def listSupportedLangs(self) -> List[models.Language]:
# languages = self._get("v1/languages")
# return [models.Language(language) for language in languages.get("languages", [])]
. Output only the next line. | constants.HttpMethod.get.value, |
Predict the next line for this snippet: <|code_start|>
class TestLanguage(unittest.TestCase):
@patch.object(requests.Session, "request")
def test_list(self, mock_request: unittest.mock):
ms_response = unittest.mock.MagicMock(status_code=200)
ms_response.json.return_value = {
"languages": [
{"name": "Abkhaz", "code": "ab"},
{"name": "Afar", "code": "aa"},
]
}
mock_request.return_value = ms_response
expected = [
<|code_end|>
with the help of current file imports:
import requests
import unittest
from unittest.mock import patch
from memsource import constants, models
from memsource.api_rest.language import Language
and context from other files:
# Path: memsource/constants.py
# class Base(enum.Enum):
# class JobStatus(enum.Enum):
# class ProjectStatus(enum.Enum):
# class AnalysisFormat(enum.Enum):
# class TermBaseFormat(enum.Enum):
# class ApiVersion(enum.Enum):
# class HttpMethod(enum.Enum):
# class BaseRest(enum.Enum):
# class JobStatusRest(enum.Enum):
# NEW = "New"
# EMAILED = "Emailed"
# ASSIGNED = "Assigned"
# DECLINED_BY_LINGUIST = "Declined_By_Linguist"
# COMPLETED_BY_LINGUIST = "Completed_By_Linguist"
# COMPLETED = "Completed"
# CANCELLED = "Cancelled"
# NEW = "New"
# ASSIGNED = "Assigned"
# COMPLETED = "Completed"
# CANCELLED = "Cancelled"
# ACCEPTED_BY_VENDOR = "Accepted_By_Vendor"
# DECLINED_BY_VENDOR = "Declined_By_Vendor"
# COMPLETED_BY_VENDOR = "Completed_By_Vendor"
# CSV = "CSV"
# LOG = "LOG"
# CSV_EXTENDED = "CSV_EXTENDED"
# XLSX = "XLSX"
# TBX = "TBX"
# NEW = "NEW"
# ACCEPTED = "ACCEPTED"
# DECLINED = "DECLINED"
# REJECTED = "REJECTED"
# DELIVERED = "DELIVERED"
# EMAILED = "EMAILED"
# COMPLETED = "COMPLETED"
# CANCELLED = "CANCELLED"
# CHUNK_SIZE = 1024
# CHAR_SET = "UTF-8"
# TM_THRESHOLD = 0.7
#
# Path: memsource/models.py
# class BaseModel(dict):
# class User(BaseModel):
# class Authentication(BaseModel):
# class Client(BaseModel):
# class Domain(BaseModel):
# class Language(BaseModel):
# class Project(BaseModel):
# class Job(BaseModel):
# class JobPart(BaseModel):
# class TranslationMemory(BaseModel):
# class AsynchronousRequest(BaseModel):
# class AsynchronousResponse(BaseModel):
# class Segment(BaseModel):
# class SegmentSearchResult(BaseModel):
# class Analysis(BaseModel):
# class MxliffUnit(BaseModel):
# class TermBase(BaseModel):
# def __getattr__(self, key):
# def _iso8601_to_datetime(self, source):
# def date_created(self):
# def __init__(self, source):
# def is_complete(self):
# def has_error(self):
#
# Path: memsource/api_rest/language.py
# class Language(api_rest.BaseApi):
# # Document: https://cloud.memsource.com/web/docs/api#tag/Supported-Languages
#
# def listSupportedLangs(self) -> List[models.Language]:
# languages = self._get("v1/languages")
# return [models.Language(language) for language in languages.get("languages", [])]
, which may contain function names, class names, or code. Output only the next line. | models.Language(name="Abkhaz", code="ab"), |
Continue the code snippet: <|code_start|>
class TestLanguage(unittest.TestCase):
@patch.object(requests.Session, "request")
def test_list(self, mock_request: unittest.mock):
ms_response = unittest.mock.MagicMock(status_code=200)
ms_response.json.return_value = {
"languages": [
{"name": "Abkhaz", "code": "ab"},
{"name": "Afar", "code": "aa"},
]
}
mock_request.return_value = ms_response
expected = [
<|code_end|>
. Use current file imports:
import requests
import unittest
from unittest.mock import patch
from memsource import constants, models
from memsource.api_rest.language import Language
and context (classes, functions, or code) from other files:
# Path: memsource/constants.py
# class Base(enum.Enum):
# class JobStatus(enum.Enum):
# class ProjectStatus(enum.Enum):
# class AnalysisFormat(enum.Enum):
# class TermBaseFormat(enum.Enum):
# class ApiVersion(enum.Enum):
# class HttpMethod(enum.Enum):
# class BaseRest(enum.Enum):
# class JobStatusRest(enum.Enum):
# NEW = "New"
# EMAILED = "Emailed"
# ASSIGNED = "Assigned"
# DECLINED_BY_LINGUIST = "Declined_By_Linguist"
# COMPLETED_BY_LINGUIST = "Completed_By_Linguist"
# COMPLETED = "Completed"
# CANCELLED = "Cancelled"
# NEW = "New"
# ASSIGNED = "Assigned"
# COMPLETED = "Completed"
# CANCELLED = "Cancelled"
# ACCEPTED_BY_VENDOR = "Accepted_By_Vendor"
# DECLINED_BY_VENDOR = "Declined_By_Vendor"
# COMPLETED_BY_VENDOR = "Completed_By_Vendor"
# CSV = "CSV"
# LOG = "LOG"
# CSV_EXTENDED = "CSV_EXTENDED"
# XLSX = "XLSX"
# TBX = "TBX"
# NEW = "NEW"
# ACCEPTED = "ACCEPTED"
# DECLINED = "DECLINED"
# REJECTED = "REJECTED"
# DELIVERED = "DELIVERED"
# EMAILED = "EMAILED"
# COMPLETED = "COMPLETED"
# CANCELLED = "CANCELLED"
# CHUNK_SIZE = 1024
# CHAR_SET = "UTF-8"
# TM_THRESHOLD = 0.7
#
# Path: memsource/models.py
# class BaseModel(dict):
# class User(BaseModel):
# class Authentication(BaseModel):
# class Client(BaseModel):
# class Domain(BaseModel):
# class Language(BaseModel):
# class Project(BaseModel):
# class Job(BaseModel):
# class JobPart(BaseModel):
# class TranslationMemory(BaseModel):
# class AsynchronousRequest(BaseModel):
# class AsynchronousResponse(BaseModel):
# class Segment(BaseModel):
# class SegmentSearchResult(BaseModel):
# class Analysis(BaseModel):
# class MxliffUnit(BaseModel):
# class TermBase(BaseModel):
# def __getattr__(self, key):
# def _iso8601_to_datetime(self, source):
# def date_created(self):
# def __init__(self, source):
# def is_complete(self):
# def has_error(self):
#
# Path: memsource/api_rest/language.py
# class Language(api_rest.BaseApi):
# # Document: https://cloud.memsource.com/web/docs/api#tag/Supported-Languages
#
# def listSupportedLangs(self) -> List[models.Language]:
# languages = self._get("v1/languages")
# return [models.Language(language) for language in languages.get("languages", [])]
. Output only the next line. | models.Language(name="Abkhaz", code="ab"), |
Next line prediction: <|code_start|>
class MxliffParser(object):
"""
Parse xliff file of Memsource.
"""
def parse(self, resource: {'XML file content as bytes': bytes}):
root = objectify.fromstring(resource)
memsource_namespace = root.nsmap['m']
def to_memsouce_key(s: str) -> str:
return '{{{}}}{}'.format(memsource_namespace, s)
self.score_key = to_memsouce_key('score')
self.gloss_score_key = to_memsouce_key('gross-score')
self.tunit_metadata_key = to_memsouce_key('tunit-metadata')
self.mark_key = to_memsouce_key('mark')
self.type_key = to_memsouce_key('type')
self.content_key = to_memsouce_key('content')
return [
self.parse_group(group) for group in root.file.body.getchildren()
]
<|code_end|>
. Use current file imports:
(from memsource import models
from lxml import objectify)
and context including class names, function names, or small code snippets from other files:
# Path: memsource/models.py
# class BaseModel(dict):
# class User(BaseModel):
# class Authentication(BaseModel):
# class Client(BaseModel):
# class Domain(BaseModel):
# class Language(BaseModel):
# class Project(BaseModel):
# class Job(BaseModel):
# class JobPart(BaseModel):
# class TranslationMemory(BaseModel):
# class AsynchronousRequest(BaseModel):
# class AsynchronousResponse(BaseModel):
# class Segment(BaseModel):
# class SegmentSearchResult(BaseModel):
# class Analysis(BaseModel):
# class MxliffUnit(BaseModel):
# class TermBase(BaseModel):
# def __getattr__(self, key):
# def _iso8601_to_datetime(self, source):
# def date_created(self):
# def __init__(self, source):
# def is_complete(self):
# def has_error(self):
. Output only the next line. | def parse_group(self, group: objectify.ObjectifiedElement) -> models.MxliffUnit: |
Here is a snippet: <|code_start|>
class TestAuth(unittest.TestCase):
@patch.object(requests.Session, "request")
def test_login(self, mock_request: unittest.mock):
ms_response = unittest.mock.Mock(status_code=200)
ms_response.json.return_value = {
"user": {
"lastName": "mock-last-name",
"email": "mock-tm@gengo.com",
"firstName": "mock-first-name",
"id": "1234",
"userName": "mock-tm",
"role": "ADMIN",
"uid": "QWERTY"
},
"token": "mock-token",
"expires": "2020-06-19T07:31:23+0000"
}
mock_request.return_value = ms_response
response = auth.Auth().login(user_name="mock-user", password="mock-password")
<|code_end|>
. Write the next line using the current file imports:
import requests
import unittest
from unittest.mock import patch
from memsource import models
from memsource.api_rest import auth
and context from other files:
# Path: memsource/models.py
# class BaseModel(dict):
# class User(BaseModel):
# class Authentication(BaseModel):
# class Client(BaseModel):
# class Domain(BaseModel):
# class Language(BaseModel):
# class Project(BaseModel):
# class Job(BaseModel):
# class JobPart(BaseModel):
# class TranslationMemory(BaseModel):
# class AsynchronousRequest(BaseModel):
# class AsynchronousResponse(BaseModel):
# class Segment(BaseModel):
# class SegmentSearchResult(BaseModel):
# class Analysis(BaseModel):
# class MxliffUnit(BaseModel):
# class TermBase(BaseModel):
# def __getattr__(self, key):
# def _iso8601_to_datetime(self, source):
# def date_created(self):
# def __init__(self, source):
# def is_complete(self):
# def has_error(self):
#
# Path: memsource/api_rest/auth.py
# class Auth(api_rest.BaseApi):
# def login(self, user_name: str, password: str) -> models.Authentication:
, which may include functions, classes, or code. Output only the next line. | self.assertIsInstance(response, models.Authentication) |
Based on the snippet: <|code_start|>
class TestAuth(unittest.TestCase):
@patch.object(requests.Session, "request")
def test_login(self, mock_request: unittest.mock):
ms_response = unittest.mock.Mock(status_code=200)
ms_response.json.return_value = {
"user": {
"lastName": "mock-last-name",
"email": "mock-tm@gengo.com",
"firstName": "mock-first-name",
"id": "1234",
"userName": "mock-tm",
"role": "ADMIN",
"uid": "QWERTY"
},
"token": "mock-token",
"expires": "2020-06-19T07:31:23+0000"
}
mock_request.return_value = ms_response
<|code_end|>
, predict the immediate next line with the help of imports:
import requests
import unittest
from unittest.mock import patch
from memsource import models
from memsource.api_rest import auth
and context (classes, functions, sometimes code) from other files:
# Path: memsource/models.py
# class BaseModel(dict):
# class User(BaseModel):
# class Authentication(BaseModel):
# class Client(BaseModel):
# class Domain(BaseModel):
# class Language(BaseModel):
# class Project(BaseModel):
# class Job(BaseModel):
# class JobPart(BaseModel):
# class TranslationMemory(BaseModel):
# class AsynchronousRequest(BaseModel):
# class AsynchronousResponse(BaseModel):
# class Segment(BaseModel):
# class SegmentSearchResult(BaseModel):
# class Analysis(BaseModel):
# class MxliffUnit(BaseModel):
# class TermBase(BaseModel):
# def __getattr__(self, key):
# def _iso8601_to_datetime(self, source):
# def date_created(self):
# def __init__(self, source):
# def is_complete(self):
# def has_error(self):
#
# Path: memsource/api_rest/auth.py
# class Auth(api_rest.BaseApi):
# def login(self, user_name: str, password: str) -> models.Authentication:
. Output only the next line. | response = auth.Auth().login(user_name="mock-user", password="mock-password") |
Given snippet: <|code_start|>
class TestDomain(unittest.TestCase):
@patch.object(requests.Session, "request")
def test_create(self, mock_request: unittest.mock):
ms_response = unittest.mock.MagicMock(status_code=200)
ms_response.json.return_value = {
"id": "mock-id",
"name": "mock-test",
}
mock_request.return_value = ms_response
response = Domain(token="mock-token").create("mock-test")
self.assertEqual(response, {
"id": "mock-id",
"name": "mock-test",
})
mock_request.assert_called_with(
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import requests
import unittest
from unittest.mock import patch
from memsource import constants, models
from memsource.api_rest.domain import Domain
and context:
# Path: memsource/constants.py
# class Base(enum.Enum):
# class JobStatus(enum.Enum):
# class ProjectStatus(enum.Enum):
# class AnalysisFormat(enum.Enum):
# class TermBaseFormat(enum.Enum):
# class ApiVersion(enum.Enum):
# class HttpMethod(enum.Enum):
# class BaseRest(enum.Enum):
# class JobStatusRest(enum.Enum):
# NEW = "New"
# EMAILED = "Emailed"
# ASSIGNED = "Assigned"
# DECLINED_BY_LINGUIST = "Declined_By_Linguist"
# COMPLETED_BY_LINGUIST = "Completed_By_Linguist"
# COMPLETED = "Completed"
# CANCELLED = "Cancelled"
# NEW = "New"
# ASSIGNED = "Assigned"
# COMPLETED = "Completed"
# CANCELLED = "Cancelled"
# ACCEPTED_BY_VENDOR = "Accepted_By_Vendor"
# DECLINED_BY_VENDOR = "Declined_By_Vendor"
# COMPLETED_BY_VENDOR = "Completed_By_Vendor"
# CSV = "CSV"
# LOG = "LOG"
# CSV_EXTENDED = "CSV_EXTENDED"
# XLSX = "XLSX"
# TBX = "TBX"
# NEW = "NEW"
# ACCEPTED = "ACCEPTED"
# DECLINED = "DECLINED"
# REJECTED = "REJECTED"
# DELIVERED = "DELIVERED"
# EMAILED = "EMAILED"
# COMPLETED = "COMPLETED"
# CANCELLED = "CANCELLED"
# CHUNK_SIZE = 1024
# CHAR_SET = "UTF-8"
# TM_THRESHOLD = 0.7
#
# Path: memsource/models.py
# class BaseModel(dict):
# class User(BaseModel):
# class Authentication(BaseModel):
# class Client(BaseModel):
# class Domain(BaseModel):
# class Language(BaseModel):
# class Project(BaseModel):
# class Job(BaseModel):
# class JobPart(BaseModel):
# class TranslationMemory(BaseModel):
# class AsynchronousRequest(BaseModel):
# class AsynchronousResponse(BaseModel):
# class Segment(BaseModel):
# class SegmentSearchResult(BaseModel):
# class Analysis(BaseModel):
# class MxliffUnit(BaseModel):
# class TermBase(BaseModel):
# def __getattr__(self, key):
# def _iso8601_to_datetime(self, source):
# def date_created(self):
# def __init__(self, source):
# def is_complete(self):
# def has_error(self):
#
# Path: memsource/api_rest/domain.py
# class Domain(api_rest.BaseApi):
# # Document: https://cloud.memsource.com/web/docs/api#tag/Domain
#
# def create(self, name: str) -> Dict[str, Any]:
# return self._post("v1/domains", {"name": name})
#
# def get(self, domainID: int) -> models.Domain:
# return models.Domain(self._get("v1/domains/{}".format(domainID)))
#
# def list(self, page: int=0) -> List[models.Domain]:
# domains = self._get("v1/domains", {"page": page})
# return [models.Domain(domain) for domain in domains.get("content", [])]
which might include code, classes, or functions. Output only the next line. | constants.HttpMethod.post.value, |
Continue the code snippet: <|code_start|> mock_request.return_value = ms_response
response = Domain(token="mock-token").create("mock-test")
self.assertEqual(response, {
"id": "mock-id",
"name": "mock-test",
})
mock_request.assert_called_with(
constants.HttpMethod.post.value,
"https://cloud.memsource.com/web/api2/v1/domains",
json={"name": "mock-test"},
params={"token": "mock-token"},
timeout=60
)
@patch.object(requests.Session, "request")
def test_get(self, mock_request: unittest.mock):
ms_response = unittest.mock.MagicMock(status_code=200)
ms_response.json.return_value = {
"id": "1",
"name": "1",
}
mock_request.return_value = ms_response
response = Domain(token="mock-token").get(1)
expected = {
"name": "1",
"id": "1",
}
self.assertEqual(response, expected)
<|code_end|>
. Use current file imports:
import requests
import unittest
from unittest.mock import patch
from memsource import constants, models
from memsource.api_rest.domain import Domain
and context (classes, functions, or code) from other files:
# Path: memsource/constants.py
# class Base(enum.Enum):
# class JobStatus(enum.Enum):
# class ProjectStatus(enum.Enum):
# class AnalysisFormat(enum.Enum):
# class TermBaseFormat(enum.Enum):
# class ApiVersion(enum.Enum):
# class HttpMethod(enum.Enum):
# class BaseRest(enum.Enum):
# class JobStatusRest(enum.Enum):
# NEW = "New"
# EMAILED = "Emailed"
# ASSIGNED = "Assigned"
# DECLINED_BY_LINGUIST = "Declined_By_Linguist"
# COMPLETED_BY_LINGUIST = "Completed_By_Linguist"
# COMPLETED = "Completed"
# CANCELLED = "Cancelled"
# NEW = "New"
# ASSIGNED = "Assigned"
# COMPLETED = "Completed"
# CANCELLED = "Cancelled"
# ACCEPTED_BY_VENDOR = "Accepted_By_Vendor"
# DECLINED_BY_VENDOR = "Declined_By_Vendor"
# COMPLETED_BY_VENDOR = "Completed_By_Vendor"
# CSV = "CSV"
# LOG = "LOG"
# CSV_EXTENDED = "CSV_EXTENDED"
# XLSX = "XLSX"
# TBX = "TBX"
# NEW = "NEW"
# ACCEPTED = "ACCEPTED"
# DECLINED = "DECLINED"
# REJECTED = "REJECTED"
# DELIVERED = "DELIVERED"
# EMAILED = "EMAILED"
# COMPLETED = "COMPLETED"
# CANCELLED = "CANCELLED"
# CHUNK_SIZE = 1024
# CHAR_SET = "UTF-8"
# TM_THRESHOLD = 0.7
#
# Path: memsource/models.py
# class BaseModel(dict):
# class User(BaseModel):
# class Authentication(BaseModel):
# class Client(BaseModel):
# class Domain(BaseModel):
# class Language(BaseModel):
# class Project(BaseModel):
# class Job(BaseModel):
# class JobPart(BaseModel):
# class TranslationMemory(BaseModel):
# class AsynchronousRequest(BaseModel):
# class AsynchronousResponse(BaseModel):
# class Segment(BaseModel):
# class SegmentSearchResult(BaseModel):
# class Analysis(BaseModel):
# class MxliffUnit(BaseModel):
# class TermBase(BaseModel):
# def __getattr__(self, key):
# def _iso8601_to_datetime(self, source):
# def date_created(self):
# def __init__(self, source):
# def is_complete(self):
# def has_error(self):
#
# Path: memsource/api_rest/domain.py
# class Domain(api_rest.BaseApi):
# # Document: https://cloud.memsource.com/web/docs/api#tag/Domain
#
# def create(self, name: str) -> Dict[str, Any]:
# return self._post("v1/domains", {"name": name})
#
# def get(self, domainID: int) -> models.Domain:
# return models.Domain(self._get("v1/domains/{}".format(domainID)))
#
# def list(self, page: int=0) -> List[models.Domain]:
# domains = self._get("v1/domains", {"page": page})
# return [models.Domain(domain) for domain in domains.get("content", [])]
. Output only the next line. | self.assertIsInstance(response, models.Domain) |
Using the snippet: <|code_start|>
class TestDomain(unittest.TestCase):
@patch.object(requests.Session, "request")
def test_create(self, mock_request: unittest.mock):
ms_response = unittest.mock.MagicMock(status_code=200)
ms_response.json.return_value = {
"id": "mock-id",
"name": "mock-test",
}
mock_request.return_value = ms_response
<|code_end|>
, determine the next line of code. You have imports:
import requests
import unittest
from unittest.mock import patch
from memsource import constants, models
from memsource.api_rest.domain import Domain
and context (class names, function names, or code) available:
# Path: memsource/constants.py
# class Base(enum.Enum):
# class JobStatus(enum.Enum):
# class ProjectStatus(enum.Enum):
# class AnalysisFormat(enum.Enum):
# class TermBaseFormat(enum.Enum):
# class ApiVersion(enum.Enum):
# class HttpMethod(enum.Enum):
# class BaseRest(enum.Enum):
# class JobStatusRest(enum.Enum):
# NEW = "New"
# EMAILED = "Emailed"
# ASSIGNED = "Assigned"
# DECLINED_BY_LINGUIST = "Declined_By_Linguist"
# COMPLETED_BY_LINGUIST = "Completed_By_Linguist"
# COMPLETED = "Completed"
# CANCELLED = "Cancelled"
# NEW = "New"
# ASSIGNED = "Assigned"
# COMPLETED = "Completed"
# CANCELLED = "Cancelled"
# ACCEPTED_BY_VENDOR = "Accepted_By_Vendor"
# DECLINED_BY_VENDOR = "Declined_By_Vendor"
# COMPLETED_BY_VENDOR = "Completed_By_Vendor"
# CSV = "CSV"
# LOG = "LOG"
# CSV_EXTENDED = "CSV_EXTENDED"
# XLSX = "XLSX"
# TBX = "TBX"
# NEW = "NEW"
# ACCEPTED = "ACCEPTED"
# DECLINED = "DECLINED"
# REJECTED = "REJECTED"
# DELIVERED = "DELIVERED"
# EMAILED = "EMAILED"
# COMPLETED = "COMPLETED"
# CANCELLED = "CANCELLED"
# CHUNK_SIZE = 1024
# CHAR_SET = "UTF-8"
# TM_THRESHOLD = 0.7
#
# Path: memsource/models.py
# class BaseModel(dict):
# class User(BaseModel):
# class Authentication(BaseModel):
# class Client(BaseModel):
# class Domain(BaseModel):
# class Language(BaseModel):
# class Project(BaseModel):
# class Job(BaseModel):
# class JobPart(BaseModel):
# class TranslationMemory(BaseModel):
# class AsynchronousRequest(BaseModel):
# class AsynchronousResponse(BaseModel):
# class Segment(BaseModel):
# class SegmentSearchResult(BaseModel):
# class Analysis(BaseModel):
# class MxliffUnit(BaseModel):
# class TermBase(BaseModel):
# def __getattr__(self, key):
# def _iso8601_to_datetime(self, source):
# def date_created(self):
# def __init__(self, source):
# def is_complete(self):
# def has_error(self):
#
# Path: memsource/api_rest/domain.py
# class Domain(api_rest.BaseApi):
# # Document: https://cloud.memsource.com/web/docs/api#tag/Domain
#
# def create(self, name: str) -> Dict[str, Any]:
# return self._post("v1/domains", {"name": name})
#
# def get(self, domainID: int) -> models.Domain:
# return models.Domain(self._get("v1/domains/{}".format(domainID)))
#
# def list(self, page: int=0) -> List[models.Domain]:
# domains = self._get("v1/domains", {"page": page})
# return [models.Domain(domain) for domain in domains.get("content", [])]
. Output only the next line. | response = Domain(token="mock-token").create("mock-test") |
Given the code snippet: <|code_start|>
class TestMxliffParser(unittest.TestCase):
def setUp(self):
# Read test.mxliff file from same directory with this file.
file_dir = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(file_dir, 'test.mxliff')) as f:
self.mxliff_text = f.read().encode()
with open(os.path.join(file_dir, 'test_meta.mxliff')) as f:
self.mxliff_text_meta = f.read().encode()
def test_parse_no_meta(self):
<|code_end|>
, generate the next line using the imports in this file:
import unittest
import os.path
from memsource.lib.mxliff import MxliffParser
from memsource import models
and context (functions, classes, or occasionally code) from other files:
# Path: memsource/lib/mxliff.py
# class MxliffParser(object):
# """
# Parse xliff file of Memsource.
# """
#
# def parse(self, resource: {'XML file content as bytes': bytes}):
# root = objectify.fromstring(resource)
# memsource_namespace = root.nsmap['m']
#
# def to_memsouce_key(s: str) -> str:
# return '{{{}}}{}'.format(memsource_namespace, s)
#
# self.score_key = to_memsouce_key('score')
# self.gloss_score_key = to_memsouce_key('gross-score')
# self.tunit_metadata_key = to_memsouce_key('tunit-metadata')
# self.mark_key = to_memsouce_key('mark')
# self.type_key = to_memsouce_key('type')
# self.content_key = to_memsouce_key('content')
#
# return [
# self.parse_group(group) for group in root.file.body.getchildren()
# ]
#
# def parse_group(self, group: objectify.ObjectifiedElement) -> models.MxliffUnit:
# # Because we cannot write 'group.trans-unit'.
# trans_unit = getattr(group, 'trans-unit')
# source = {
# 'id': trans_unit.attrib['id'],
# 'score': float(trans_unit.attrib[self.score_key]),
# 'gross_score': float(trans_unit.attrib[self.gloss_score_key]),
# 'source': trans_unit.source.text,
# 'target': trans_unit.target.text,
# 'tunit_metadata': self.parse_tunit_metadata(trans_unit),
# }
#
# for alt_trans in getattr(trans_unit, 'alt-trans'):
# # machine-trans, memsource-tm -> machine_trans, memsource_tm
# source[alt_trans.attrib['origin'].replace('-', '_')] = alt_trans.target.text
#
# return models.MxliffUnit(source)
#
# def parse_tunit_metadata(self, trans_unit: objectify.ObjectifiedElement) -> list:
# tunit_metadata = getattr(trans_unit, self.tunit_metadata_key, None)
#
# # There is no meta data.
# if tunit_metadata is None:
# return []
#
# return [{
# 'id': mark.attrib['id'],
# 'type': getattr(mark, self.type_key).text,
# 'content': getattr(mark, self.content_key).text,
# } for mark in getattr(tunit_metadata, self.mark_key)]
#
# Path: memsource/models.py
# class BaseModel(dict):
# class User(BaseModel):
# class Authentication(BaseModel):
# class Client(BaseModel):
# class Domain(BaseModel):
# class Language(BaseModel):
# class Project(BaseModel):
# class Job(BaseModel):
# class JobPart(BaseModel):
# class TranslationMemory(BaseModel):
# class AsynchronousRequest(BaseModel):
# class AsynchronousResponse(BaseModel):
# class Segment(BaseModel):
# class SegmentSearchResult(BaseModel):
# class Analysis(BaseModel):
# class MxliffUnit(BaseModel):
# class TermBase(BaseModel):
# def __getattr__(self, key):
# def _iso8601_to_datetime(self, source):
# def date_created(self):
# def __init__(self, source):
# def is_complete(self):
# def has_error(self):
. Output only the next line. | mxliff_units = MxliffParser().parse(self.mxliff_text) |
Given snippet: <|code_start|>
class TestMxliffParser(unittest.TestCase):
def setUp(self):
# Read test.mxliff file from same directory with this file.
file_dir = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(file_dir, 'test.mxliff')) as f:
self.mxliff_text = f.read().encode()
with open(os.path.join(file_dir, 'test_meta.mxliff')) as f:
self.mxliff_text_meta = f.read().encode()
def test_parse_no_meta(self):
mxliff_units = MxliffParser().parse(self.mxliff_text)
self.assertEqual(len(mxliff_units), 2)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import unittest
import os.path
from memsource.lib.mxliff import MxliffParser
from memsource import models
and context:
# Path: memsource/lib/mxliff.py
# class MxliffParser(object):
# """
# Parse xliff file of Memsource.
# """
#
# def parse(self, resource: {'XML file content as bytes': bytes}):
# root = objectify.fromstring(resource)
# memsource_namespace = root.nsmap['m']
#
# def to_memsouce_key(s: str) -> str:
# return '{{{}}}{}'.format(memsource_namespace, s)
#
# self.score_key = to_memsouce_key('score')
# self.gloss_score_key = to_memsouce_key('gross-score')
# self.tunit_metadata_key = to_memsouce_key('tunit-metadata')
# self.mark_key = to_memsouce_key('mark')
# self.type_key = to_memsouce_key('type')
# self.content_key = to_memsouce_key('content')
#
# return [
# self.parse_group(group) for group in root.file.body.getchildren()
# ]
#
# def parse_group(self, group: objectify.ObjectifiedElement) -> models.MxliffUnit:
# # Because we cannot write 'group.trans-unit'.
# trans_unit = getattr(group, 'trans-unit')
# source = {
# 'id': trans_unit.attrib['id'],
# 'score': float(trans_unit.attrib[self.score_key]),
# 'gross_score': float(trans_unit.attrib[self.gloss_score_key]),
# 'source': trans_unit.source.text,
# 'target': trans_unit.target.text,
# 'tunit_metadata': self.parse_tunit_metadata(trans_unit),
# }
#
# for alt_trans in getattr(trans_unit, 'alt-trans'):
# # machine-trans, memsource-tm -> machine_trans, memsource_tm
# source[alt_trans.attrib['origin'].replace('-', '_')] = alt_trans.target.text
#
# return models.MxliffUnit(source)
#
# def parse_tunit_metadata(self, trans_unit: objectify.ObjectifiedElement) -> list:
# tunit_metadata = getattr(trans_unit, self.tunit_metadata_key, None)
#
# # There is no meta data.
# if tunit_metadata is None:
# return []
#
# return [{
# 'id': mark.attrib['id'],
# 'type': getattr(mark, self.type_key).text,
# 'content': getattr(mark, self.content_key).text,
# } for mark in getattr(tunit_metadata, self.mark_key)]
#
# Path: memsource/models.py
# class BaseModel(dict):
# class User(BaseModel):
# class Authentication(BaseModel):
# class Client(BaseModel):
# class Domain(BaseModel):
# class Language(BaseModel):
# class Project(BaseModel):
# class Job(BaseModel):
# class JobPart(BaseModel):
# class TranslationMemory(BaseModel):
# class AsynchronousRequest(BaseModel):
# class AsynchronousResponse(BaseModel):
# class Segment(BaseModel):
# class SegmentSearchResult(BaseModel):
# class Analysis(BaseModel):
# class MxliffUnit(BaseModel):
# class TermBase(BaseModel):
# def __getattr__(self, key):
# def _iso8601_to_datetime(self, source):
# def date_created(self):
# def __init__(self, source):
# def is_complete(self):
# def has_error(self):
which might include code, classes, or functions. Output only the next line. | self.assertIsInstance(mxliff_units[0], models.MxliffUnit) |
Predict the next line after this snippet: <|code_start|>
class TestProject(unittest.TestCase):
@patch.object(requests.Session, "request")
def test_create(self, mock_request: unittest.mock):
ms_response = unittest.mock.MagicMock(status_code=200)
ms_response.json.return_value = {
"uid": "1234",
"internalId": 0,
"id": "1234",
"name": "mock-project",
"dateCreated": "2020-06-22T01:44:04Z",
"domain": {"name": "mock-domain", "id": "1"},
"sourceLang": "en",
"targetLangs": ["ja", "de"],
}
mock_request.return_value = ms_response
<|code_end|>
using the current file's imports:
import requests
import unittest
from unittest.mock import patch
from memsource import constants, models
from memsource.api_rest.project import Project
and any relevant context from other files:
# Path: memsource/constants.py
# class Base(enum.Enum):
# class JobStatus(enum.Enum):
# class ProjectStatus(enum.Enum):
# class AnalysisFormat(enum.Enum):
# class TermBaseFormat(enum.Enum):
# class ApiVersion(enum.Enum):
# class HttpMethod(enum.Enum):
# class BaseRest(enum.Enum):
# class JobStatusRest(enum.Enum):
# NEW = "New"
# EMAILED = "Emailed"
# ASSIGNED = "Assigned"
# DECLINED_BY_LINGUIST = "Declined_By_Linguist"
# COMPLETED_BY_LINGUIST = "Completed_By_Linguist"
# COMPLETED = "Completed"
# CANCELLED = "Cancelled"
# NEW = "New"
# ASSIGNED = "Assigned"
# COMPLETED = "Completed"
# CANCELLED = "Cancelled"
# ACCEPTED_BY_VENDOR = "Accepted_By_Vendor"
# DECLINED_BY_VENDOR = "Declined_By_Vendor"
# COMPLETED_BY_VENDOR = "Completed_By_Vendor"
# CSV = "CSV"
# LOG = "LOG"
# CSV_EXTENDED = "CSV_EXTENDED"
# XLSX = "XLSX"
# TBX = "TBX"
# NEW = "NEW"
# ACCEPTED = "ACCEPTED"
# DECLINED = "DECLINED"
# REJECTED = "REJECTED"
# DELIVERED = "DELIVERED"
# EMAILED = "EMAILED"
# COMPLETED = "COMPLETED"
# CANCELLED = "CANCELLED"
# CHUNK_SIZE = 1024
# CHAR_SET = "UTF-8"
# TM_THRESHOLD = 0.7
#
# Path: memsource/models.py
# class BaseModel(dict):
# class User(BaseModel):
# class Authentication(BaseModel):
# class Client(BaseModel):
# class Domain(BaseModel):
# class Language(BaseModel):
# class Project(BaseModel):
# class Job(BaseModel):
# class JobPart(BaseModel):
# class TranslationMemory(BaseModel):
# class AsynchronousRequest(BaseModel):
# class AsynchronousResponse(BaseModel):
# class Segment(BaseModel):
# class SegmentSearchResult(BaseModel):
# class Analysis(BaseModel):
# class MxliffUnit(BaseModel):
# class TermBase(BaseModel):
# def __getattr__(self, key):
# def _iso8601_to_datetime(self, source):
# def date_created(self):
# def __init__(self, source):
# def is_complete(self):
# def has_error(self):
#
# Path: memsource/api_rest/project.py
# class Project(api_rest.BaseApi):
# # Document: https://cloud.memsource.com/web/docs/api#tag/Project
#
# def create(
# self,
# name: str,
# source_lang: str,
# target_langs: List[str],
# client: int=None,
# domain: int=None,
# ) -> int:
# return self._post("v1/projects", {
# "name": name,
# "sourceLang": source_lang,
# "targetLangs": target_langs,
# "client": client,
# "domain": domain,
# })["id"]
#
# def list(self, **query) -> List[models.Project]:
# projects = self._get("v1/projects", query)
# return [models.Project(project) for project in projects.get("content", [])]
#
# def get_trans_memories(self, project_id: int) -> List[models.TranslationMemory]:
# translation_memories = self._get("v1/projects/{}/transMemories".format(project_id))
# return [
# models.TranslationMemory(tm)
# for tm in translation_memories.get("transMemories", [])
# ]
#
# def set_trans_memories(
# self,
# project_id: int,
# translation_memories: List[Dict[str, Any]],
# target_lang: str=None,
# workflow_step: Optional[Dict[str, str]]=None,
# ) -> None:
# """You can set translation memory to a project.
#
# :param project_id: set translation memory to this id of project
# :param translation_memories: Read/Write to these translation memories
# :param target_lang: set translation memories only for the specific project target language
# """
# params = {"transMemories": translation_memories}
#
# if target_lang is not None:
# params["targetLang"] = target_lang
#
# if workflow_step is not None:
# params["workflowStep"] = workflow_step
#
# # This end-point return nothing.
# self._put("v2/projects/{}/transMemories".format(project_id), params)
#
# def set_status(self, project_id: int, status: constants.ProjectStatus) -> None:
# """Update project status
#
# ProjectStatus: New, Emailed, Assigned, Declined_By_Linguist,
# Completed_By_Linguist, Completed, Cancelled
#
# :param project_id: id of project you want to update.
# :param status: status of project to update. Acceptable type is ProjectStatus constant.
# """
#
# self._post("v1/projects/{}/setStatus".format(project_id), {
# "status": status.value.upper()
# })
#
# def get_term_bases(self, project_id: int) -> List[models.TermBase]:
# """Returns the list of term bases belonging to a project.
# :param project_id: ID of the project containing the term bases
# """
# term_bases = self._get("v1/projects/{}/termBases".format(project_id))
# return [models.TermBase(term_base) for term_base in term_bases.get("termBases", [])]
. Output only the next line. | response = Project(token="mock-token").create( |
Next line prediction: <|code_start|> "email": "mock-tm@gengo.com",
"userName": "mock-tm",
"uid": "1234",
"lastName": "mock-last-name",
"id": "1",
"firstName": "mock-first-name",
"role": "ADMIN"
},
}
mock_request.return_value = ms_response
response = Client().get(1)
expected = {
"id": "1",
"note": None,
"priceList": None,
"displayNoteInProject": False,
"name": "1",
"createdBy": {
"id": "1",
"email": "mock-tm@gengo.com",
"uid": "1234",
"firstName": "mock-first-name",
"lastName": "mock-last-name",
"userName": "mock-tm", "role": "ADMIN"
},
"netRateScheme": None,
"externalId": None
}
self.assertEqual(response, expected)
<|code_end|>
. Use current file imports:
(import requests
import unittest
from unittest.mock import patch
from memsource import models
from memsource.api_rest.client import Client)
and context including class names, function names, or small code snippets from other files:
# Path: memsource/models.py
# class BaseModel(dict):
# class User(BaseModel):
# class Authentication(BaseModel):
# class Client(BaseModel):
# class Domain(BaseModel):
# class Language(BaseModel):
# class Project(BaseModel):
# class Job(BaseModel):
# class JobPart(BaseModel):
# class TranslationMemory(BaseModel):
# class AsynchronousRequest(BaseModel):
# class AsynchronousResponse(BaseModel):
# class Segment(BaseModel):
# class SegmentSearchResult(BaseModel):
# class Analysis(BaseModel):
# class MxliffUnit(BaseModel):
# class TermBase(BaseModel):
# def __getattr__(self, key):
# def _iso8601_to_datetime(self, source):
# def date_created(self):
# def __init__(self, source):
# def is_complete(self):
# def has_error(self):
#
# Path: memsource/api_rest/client.py
# class Client(api_rest.BaseApi):
# # Document: https://cloud.memsource.com/web/docs/api#tag/Client
#
# def create(self, name: str) -> str:
# return self._post("v1/client", {"name": name})["id"]
#
# def get(self, clientID: int) -> models.Client:
# return models.Client(self._get("v1/clients/{}".format(clientID)))
#
# def list(self, page: int=0) -> List[models.Client]:
# clients = self._get("v1/clients", {"page": page})
# return [models.Client(client) for client in clients.get("content", [])]
. Output only the next line. | self.assertIsInstance(response, models.Client) |
Based on the snippet: <|code_start|>
class TestClient(unittest.TestCase):
@patch.object(requests.Session, "request")
def test_create(self, mock_request: unittest.mock):
ms_response = unittest.mock.MagicMock(status_code=200)
ms_response.json.return_value = {
"id": "mock-id"
}
mock_request.return_value = ms_response
<|code_end|>
, predict the immediate next line with the help of imports:
import requests
import unittest
from unittest.mock import patch
from memsource import models
from memsource.api_rest.client import Client
and context (classes, functions, sometimes code) from other files:
# Path: memsource/models.py
# class BaseModel(dict):
# class User(BaseModel):
# class Authentication(BaseModel):
# class Client(BaseModel):
# class Domain(BaseModel):
# class Language(BaseModel):
# class Project(BaseModel):
# class Job(BaseModel):
# class JobPart(BaseModel):
# class TranslationMemory(BaseModel):
# class AsynchronousRequest(BaseModel):
# class AsynchronousResponse(BaseModel):
# class Segment(BaseModel):
# class SegmentSearchResult(BaseModel):
# class Analysis(BaseModel):
# class MxliffUnit(BaseModel):
# class TermBase(BaseModel):
# def __getattr__(self, key):
# def _iso8601_to_datetime(self, source):
# def date_created(self):
# def __init__(self, source):
# def is_complete(self):
# def has_error(self):
#
# Path: memsource/api_rest/client.py
# class Client(api_rest.BaseApi):
# # Document: https://cloud.memsource.com/web/docs/api#tag/Client
#
# def create(self, name: str) -> str:
# return self._post("v1/client", {"name": name})["id"]
#
# def get(self, clientID: int) -> models.Client:
# return models.Client(self._get("v1/clients/{}".format(clientID)))
#
# def list(self, page: int=0) -> List[models.Client]:
# clients = self._get("v1/clients", {"page": page})
# return [models.Client(client) for client in clients.get("content", [])]
. Output only the next line. | response = Client().create("mock-test") |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
log = logging.getLogger(__name__)
def test_dals():
test_string = """
This little piggy went to the market.
This little piggy stayed home.
This little piggy had roast beef.
"""
assert test_string.count('\n') == 4
<|code_end|>
, determine the next line of code. You have imports:
import logging
from auxlib.ish import dals
and context (class names, function names, or code) available:
# Path: auxlib/ish.py
# def dals(string):
# """dedent and left-strip"""
# return dedent(string).lstrip()
. Output only the next line. | assert dals(test_string).count('\n') == 3 |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
class TestBase64Encoding(TestCase):
def test_encode(self):
test_str = "Mickey Mouse"
result_str = "TWlja2V5IE1vdXNl".encode('UTF-8')
<|code_end|>
using the current file's imports:
from unittest import TestCase
from auxlib import crypt
from auxlib.crypt import AuthenticationError, encrypt, decrypt
import os
and any relevant context from other files:
# Path: auxlib/crypt.py
# AES_BLOCK_SIZE = AES.block_size
# AES_KEY_SIZE = 32 # 32 byte key size ==> AES-256
# HMAC_SIG_SIZE = hashlib.sha256().digest_size
# def encrypt(secret_key, data):
# def decrypt(secret_key, encryption_key_encrypted, encrypted_data):
# def as_base64(content):
# def from_base64(content):
# def generate_encryption_key():
# def generate_hash_from_secret(secret):
# def aes_encrypt(base64_encryption_key, data):
# def aes_decrypt(base64_encryption_key, base64_data):
# def _pad(s):
# def _unpad(s):
# def _extract_keys(key_str):
#
# Path: auxlib/crypt.py
# AES_BLOCK_SIZE = AES.block_size
# AES_KEY_SIZE = 32 # 32 byte key size ==> AES-256
# HMAC_SIG_SIZE = hashlib.sha256().digest_size
# def encrypt(secret_key, data):
# def decrypt(secret_key, encryption_key_encrypted, encrypted_data):
# def as_base64(content):
# def from_base64(content):
# def generate_encryption_key():
# def generate_hash_from_secret(secret):
# def aes_encrypt(base64_encryption_key, data):
# def aes_decrypt(base64_encryption_key, base64_data):
# def _pad(s):
# def _unpad(s):
# def _extract_keys(key_str):
. Output only the next line. | self.assertEqual(crypt.as_base64(test_str), |
Continue the code snippet: <|code_start|> # generate new key, and make sure it's different than the last
self.assertNotEqual(crypt.generate_encryption_key(), key)
def test_hashing_secret(self):
secret = 'test secret'
key_hash = crypt.generate_hash_from_secret(secret)
self.assertEquals(len(crypt.from_base64(key_hash)),
crypt.AES_KEY_SIZE + crypt.HMAC_SIG_SIZE)
# hash should always be the same
self.assertEqual(key_hash, crypt.generate_hash_from_secret(secret))
class TestAESEncryption(TestCase):
def test_encrypt_and_decrypt_end_to_end(self):
test_data = u"Mickey & Miννie Μouse"
encryption_key = crypt.generate_encryption_key()
encrypted_data = crypt.aes_encrypt(encryption_key, test_data)
decrypted_data = crypt.aes_decrypt(encryption_key, encrypted_data)
self.assertEquals(decrypted_data, test_data.encode('UTF-8'))
def test_invalid_hmac_throws_error(self):
test_data = u"Mickey & Miννie Μouse"
encryption_key = crypt.generate_encryption_key()
encrypted_data = crypt.from_base64(crypt.aes_encrypt(encryption_key, test_data))
enc_data_only = encrypted_data[:-crypt.HMAC_SIG_SIZE]
real_hmac_signature = encrypted_data[-crypt.HMAC_SIG_SIZE:]
fake_hmac_signature = os.urandom(crypt.HMAC_SIG_SIZE)
self.assertEqual(encrypted_data, enc_data_only + real_hmac_signature)
<|code_end|>
. Use current file imports:
from unittest import TestCase
from auxlib import crypt
from auxlib.crypt import AuthenticationError, encrypt, decrypt
import os
and context (classes, functions, or code) from other files:
# Path: auxlib/crypt.py
# AES_BLOCK_SIZE = AES.block_size
# AES_KEY_SIZE = 32 # 32 byte key size ==> AES-256
# HMAC_SIG_SIZE = hashlib.sha256().digest_size
# def encrypt(secret_key, data):
# def decrypt(secret_key, encryption_key_encrypted, encrypted_data):
# def as_base64(content):
# def from_base64(content):
# def generate_encryption_key():
# def generate_hash_from_secret(secret):
# def aes_encrypt(base64_encryption_key, data):
# def aes_decrypt(base64_encryption_key, base64_data):
# def _pad(s):
# def _unpad(s):
# def _extract_keys(key_str):
#
# Path: auxlib/crypt.py
# AES_BLOCK_SIZE = AES.block_size
# AES_KEY_SIZE = 32 # 32 byte key size ==> AES-256
# HMAC_SIG_SIZE = hashlib.sha256().digest_size
# def encrypt(secret_key, data):
# def decrypt(secret_key, encryption_key_encrypted, encrypted_data):
# def as_base64(content):
# def from_base64(content):
# def generate_encryption_key():
# def generate_hash_from_secret(secret):
# def aes_encrypt(base64_encryption_key, data):
# def aes_decrypt(base64_encryption_key, base64_data):
# def _pad(s):
# def _unpad(s):
# def _extract_keys(key_str):
. Output only the next line. | self.assertRaises(AuthenticationError, crypt.aes_decrypt, encryption_key, |
Continue the code snippet: <|code_start|> # hash should always be the same
self.assertEqual(key_hash, crypt.generate_hash_from_secret(secret))
class TestAESEncryption(TestCase):
def test_encrypt_and_decrypt_end_to_end(self):
test_data = u"Mickey & Miννie Μouse"
encryption_key = crypt.generate_encryption_key()
encrypted_data = crypt.aes_encrypt(encryption_key, test_data)
decrypted_data = crypt.aes_decrypt(encryption_key, encrypted_data)
self.assertEquals(decrypted_data, test_data.encode('UTF-8'))
def test_invalid_hmac_throws_error(self):
test_data = u"Mickey & Miννie Μouse"
encryption_key = crypt.generate_encryption_key()
encrypted_data = crypt.from_base64(crypt.aes_encrypt(encryption_key, test_data))
enc_data_only = encrypted_data[:-crypt.HMAC_SIG_SIZE]
real_hmac_signature = encrypted_data[-crypt.HMAC_SIG_SIZE:]
fake_hmac_signature = os.urandom(crypt.HMAC_SIG_SIZE)
self.assertEqual(encrypted_data, enc_data_only + real_hmac_signature)
self.assertRaises(AuthenticationError, crypt.aes_decrypt, encryption_key,
crypt.as_base64(enc_data_only + fake_hmac_signature))
decrypted_data = crypt.aes_decrypt(encryption_key,
crypt.as_base64(enc_data_only + real_hmac_signature))
self.assertEquals(decrypted_data, test_data.encode('UTF-8'))
def test_encrypt_decrypt(self):
data = ('abcdefg\n' * 5000).encode('UTF-8')
secret_key = "test_scoobydoobydoo".encode('UTF-8')
<|code_end|>
. Use current file imports:
from unittest import TestCase
from auxlib import crypt
from auxlib.crypt import AuthenticationError, encrypt, decrypt
import os
and context (classes, functions, or code) from other files:
# Path: auxlib/crypt.py
# AES_BLOCK_SIZE = AES.block_size
# AES_KEY_SIZE = 32 # 32 byte key size ==> AES-256
# HMAC_SIG_SIZE = hashlib.sha256().digest_size
# def encrypt(secret_key, data):
# def decrypt(secret_key, encryption_key_encrypted, encrypted_data):
# def as_base64(content):
# def from_base64(content):
# def generate_encryption_key():
# def generate_hash_from_secret(secret):
# def aes_encrypt(base64_encryption_key, data):
# def aes_decrypt(base64_encryption_key, base64_data):
# def _pad(s):
# def _unpad(s):
# def _extract_keys(key_str):
#
# Path: auxlib/crypt.py
# AES_BLOCK_SIZE = AES.block_size
# AES_KEY_SIZE = 32 # 32 byte key size ==> AES-256
# HMAC_SIG_SIZE = hashlib.sha256().digest_size
# def encrypt(secret_key, data):
# def decrypt(secret_key, encryption_key_encrypted, encrypted_data):
# def as_base64(content):
# def from_base64(content):
# def generate_encryption_key():
# def generate_hash_from_secret(secret):
# def aes_encrypt(base64_encryption_key, data):
# def aes_decrypt(base64_encryption_key, base64_data):
# def _pad(s):
# def _unpad(s):
# def _extract_keys(key_str):
. Output only the next line. | encryption_key_encrypted, encrypted_data = encrypt(secret_key, data) |
Given snippet: <|code_start|> self.assertEqual(key_hash, crypt.generate_hash_from_secret(secret))
class TestAESEncryption(TestCase):
def test_encrypt_and_decrypt_end_to_end(self):
test_data = u"Mickey & Miννie Μouse"
encryption_key = crypt.generate_encryption_key()
encrypted_data = crypt.aes_encrypt(encryption_key, test_data)
decrypted_data = crypt.aes_decrypt(encryption_key, encrypted_data)
self.assertEquals(decrypted_data, test_data.encode('UTF-8'))
def test_invalid_hmac_throws_error(self):
test_data = u"Mickey & Miννie Μouse"
encryption_key = crypt.generate_encryption_key()
encrypted_data = crypt.from_base64(crypt.aes_encrypt(encryption_key, test_data))
enc_data_only = encrypted_data[:-crypt.HMAC_SIG_SIZE]
real_hmac_signature = encrypted_data[-crypt.HMAC_SIG_SIZE:]
fake_hmac_signature = os.urandom(crypt.HMAC_SIG_SIZE)
self.assertEqual(encrypted_data, enc_data_only + real_hmac_signature)
self.assertRaises(AuthenticationError, crypt.aes_decrypt, encryption_key,
crypt.as_base64(enc_data_only + fake_hmac_signature))
decrypted_data = crypt.aes_decrypt(encryption_key,
crypt.as_base64(enc_data_only + real_hmac_signature))
self.assertEquals(decrypted_data, test_data.encode('UTF-8'))
def test_encrypt_decrypt(self):
data = ('abcdefg\n' * 5000).encode('UTF-8')
secret_key = "test_scoobydoobydoo".encode('UTF-8')
encryption_key_encrypted, encrypted_data = encrypt(secret_key, data)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from unittest import TestCase
from auxlib import crypt
from auxlib.crypt import AuthenticationError, encrypt, decrypt
import os
and context:
# Path: auxlib/crypt.py
# AES_BLOCK_SIZE = AES.block_size
# AES_KEY_SIZE = 32 # 32 byte key size ==> AES-256
# HMAC_SIG_SIZE = hashlib.sha256().digest_size
# def encrypt(secret_key, data):
# def decrypt(secret_key, encryption_key_encrypted, encrypted_data):
# def as_base64(content):
# def from_base64(content):
# def generate_encryption_key():
# def generate_hash_from_secret(secret):
# def aes_encrypt(base64_encryption_key, data):
# def aes_decrypt(base64_encryption_key, base64_data):
# def _pad(s):
# def _unpad(s):
# def _extract_keys(key_str):
#
# Path: auxlib/crypt.py
# AES_BLOCK_SIZE = AES.block_size
# AES_KEY_SIZE = 32 # 32 byte key size ==> AES-256
# HMAC_SIG_SIZE = hashlib.sha256().digest_size
# def encrypt(secret_key, data):
# def decrypt(secret_key, encryption_key_encrypted, encrypted_data):
# def as_base64(content):
# def from_base64(content):
# def generate_encryption_key():
# def generate_hash_from_secret(secret):
# def aes_encrypt(base64_encryption_key, data):
# def aes_decrypt(base64_encryption_key, base64_data):
# def _pad(s):
# def _unpad(s):
# def _extract_keys(key_str):
which might include code, classes, or functions. Output only the next line. | round_trip = decrypt(secret_key, encryption_key_encrypted, encrypted_data) |
Predict the next line for this snippet: <|code_start|># assert _get_version_from_pkg_info('tests') == test_version
# finally:
# if os.path.exists('.version'):
# os.remove('.version')
#
# def test_is_git_dirty(self):
# result = _is_git_dirty(os.getcwd())
# assert result is True or result is False
#
#
# def test_get_git_hash(self):
# hash = _get_git_hash(os.getcwd())
# assert len(hash) == 7
#
# def test_not_git_repo(self):
# assert not is_git_repo(ROOT_PATH)
class TestPackagingNotGitRepo(TestCase):
def setUp(self):
super(TestPackagingNotGitRepo, self).setUp()
self.cwd = os.getcwd()
os.chdir('/')
def tearDown(self):
super(TestPackagingNotGitRepo, self).tearDown()
os.chdir(self.cwd)
def test_get_most_recent_git_tag_no_repo(self):
<|code_end|>
with the help of current file imports:
from unittest import TestCase
from auxlib.packaging import get_version
import os
and context from other files:
# Path: auxlib/packaging.py
# def get_version(dunder_file):
# """Returns a version string for the current package, derived
# either from git or from a .version file.
#
# This function is expected to run in two contexts. In a development
# context, where .git/ exists, the version is pulled from git tags.
# Using the BuildPyCommand and SDistCommand classes for cmdclass in
# setup.py will write a .version file into any dist.
#
# In an installed context, the .version file written at dist build
# time is the source of version information.
#
# """
# path = abspath(expanduser(dirname(dunder_file)))
# try:
# return _get_version_from_version_file(path) or _get_version_from_git_tag(path)
# except CalledProcessError as e:
# log.warn(repr(e))
# return None
# except Exception as e:
# log.exception(e)
# return None
, which may contain function names, class names, or code. Output only the next line. | tag = get_version(os.getcwd()) |
Predict the next line for this snippet: <|code_start|> >>> typify('32.0.0')
'32.0.0'
>>> [typify(x) for x in ('true', 'yes', 'on')]
[True, True, True]
>>> [typify(x) for x in ('no', 'FALSe', 'off')]
[False, False, False]
>>> [typify(x) for x in ('none', 'None', None)]
[None, None, None]
"""
# value must be a string, or there at least needs to be a type hint
if isinstance(value, string_types):
value = value.strip()
elif type_hint is None:
# can't do anything because value isn't a string and there's no type hint
return value
# now we either have a stripped string, a type hint, or both
# use the hint if it exists
if isiterable(type_hint):
if isinstance(type_hint, type) and issubclass(type_hint, Enum):
try:
return type_hint(value)
except ValueError:
return type_hint[value]
type_hint = set(type_hint)
if not (type_hint - NUMBER_TYPES_SET):
return numberify(value)
elif not (type_hint - STRING_TYPES_SET):
return text_type(value)
<|code_end|>
with the help of current file imports:
from collections import Mapping
from itertools import chain
from re import IGNORECASE, compile
from enum import Enum
from .compat import NoneType, integer_types, isiterable, iteritems, string_types, text_type
from .decorators import memoizedproperty
from .exceptions import AuxlibError
and context from other files:
# Path: auxlib/compat.py
# def isiterable(obj):
#
# Path: auxlib/decorators.py
# def memoizedproperty(func):
# """
# Decorator to cause a method to cache it's results in self for each
# combination of inputs and return the cached result on subsequent calls.
# Does not support named arguments or arg values that are not hashable.
#
# >>> class Foo (object):
# ... _x = 1
# ... @memoizedproperty
# ... def foo(self):
# ... self._x += 1
# ... print('updating and returning {0}'.format(self._x))
# ... return self._x
# ...
# >>> foo1 = Foo()
# >>> foo2 = Foo()
# >>> foo1.foo
# updating and returning 2
# 2
# >>> foo1.foo
# 2
# >>> foo2.foo
# updating and returning 2
# 2
# >>> foo1.foo
# 2
# """
# inner_attname = '__%s' % func.__name__
#
# def new_fget(self):
# if not hasattr(self, '_cache_'):
# self._cache_ = dict()
# cache = self._cache_
# if inner_attname not in cache:
# cache[inner_attname] = func(self)
# return cache[inner_attname]
#
# return property(new_fget)
#
# Path: auxlib/exceptions.py
# class AuxlibError(object):
# """Mixin to identify exceptions associated with the auxlib package."""
, which may contain function names, class names, or code. Output only the next line. | elif not (type_hint - {bool, NoneType}): |
Predict the next line for this snippet: <|code_start|>"""Collection of functions to coerce conversion of types with an intelligent guess."""
__all__ = ["boolify", "typify", "maybecall", "listify", "numberify"]
BOOLISH_TRUE = ("true", "yes", "on", "y")
BOOLISH_FALSE = ("false", "off", "n", "no", "non", "none", "")
NULL_STRINGS = ("none", "~", "null", "\0")
<|code_end|>
with the help of current file imports:
from collections import Mapping
from itertools import chain
from re import IGNORECASE, compile
from enum import Enum
from .compat import NoneType, integer_types, isiterable, iteritems, string_types, text_type
from .decorators import memoizedproperty
from .exceptions import AuxlibError
and context from other files:
# Path: auxlib/compat.py
# def isiterable(obj):
#
# Path: auxlib/decorators.py
# def memoizedproperty(func):
# """
# Decorator to cause a method to cache it's results in self for each
# combination of inputs and return the cached result on subsequent calls.
# Does not support named arguments or arg values that are not hashable.
#
# >>> class Foo (object):
# ... _x = 1
# ... @memoizedproperty
# ... def foo(self):
# ... self._x += 1
# ... print('updating and returning {0}'.format(self._x))
# ... return self._x
# ...
# >>> foo1 = Foo()
# >>> foo2 = Foo()
# >>> foo1.foo
# updating and returning 2
# 2
# >>> foo1.foo
# 2
# >>> foo2.foo
# updating and returning 2
# 2
# >>> foo1.foo
# 2
# """
# inner_attname = '__%s' % func.__name__
#
# def new_fget(self):
# if not hasattr(self, '_cache_'):
# self._cache_ = dict()
# cache = self._cache_
# if inner_attname not in cache:
# cache[inner_attname] = func(self)
# return cache[inner_attname]
#
# return property(new_fget)
#
# Path: auxlib/exceptions.py
# class AuxlibError(object):
# """Mixin to identify exceptions associated with the auxlib package."""
, which may contain function names, class names, or code. Output only the next line. | BOOL_COERCEABLE_TYPES = integer_types + (bool, float, complex, list, set, dict, tuple) |
Next line prediction: <|code_start|> Args:
value (Any): Usually a string, not a sequence
type_hint (type or Tuple[type]):
Examples:
>>> typify('32')
32
>>> typify('32', float)
32.0
>>> typify('32.0')
32.0
>>> typify('32.0.0')
'32.0.0'
>>> [typify(x) for x in ('true', 'yes', 'on')]
[True, True, True]
>>> [typify(x) for x in ('no', 'FALSe', 'off')]
[False, False, False]
>>> [typify(x) for x in ('none', 'None', None)]
[None, None, None]
"""
# value must be a string, or there at least needs to be a type hint
if isinstance(value, string_types):
value = value.strip()
elif type_hint is None:
# can't do anything because value isn't a string and there's no type hint
return value
# now we either have a stripped string, a type hint, or both
# use the hint if it exists
<|code_end|>
. Use current file imports:
(from collections import Mapping
from itertools import chain
from re import IGNORECASE, compile
from enum import Enum
from .compat import NoneType, integer_types, isiterable, iteritems, string_types, text_type
from .decorators import memoizedproperty
from .exceptions import AuxlibError)
and context including class names, function names, or small code snippets from other files:
# Path: auxlib/compat.py
# def isiterable(obj):
#
# Path: auxlib/decorators.py
# def memoizedproperty(func):
# """
# Decorator to cause a method to cache it's results in self for each
# combination of inputs and return the cached result on subsequent calls.
# Does not support named arguments or arg values that are not hashable.
#
# >>> class Foo (object):
# ... _x = 1
# ... @memoizedproperty
# ... def foo(self):
# ... self._x += 1
# ... print('updating and returning {0}'.format(self._x))
# ... return self._x
# ...
# >>> foo1 = Foo()
# >>> foo2 = Foo()
# >>> foo1.foo
# updating and returning 2
# 2
# >>> foo1.foo
# 2
# >>> foo2.foo
# updating and returning 2
# 2
# >>> foo1.foo
# 2
# """
# inner_attname = '__%s' % func.__name__
#
# def new_fget(self):
# if not hasattr(self, '_cache_'):
# self._cache_ = dict()
# cache = self._cache_
# if inner_attname not in cache:
# cache[inner_attname] = func(self)
# return cache[inner_attname]
#
# return property(new_fget)
#
# Path: auxlib/exceptions.py
# class AuxlibError(object):
# """Mixin to identify exceptions associated with the auxlib package."""
. Output only the next line. | if isiterable(type_hint): |
Next line prediction: <|code_start|> if not (type_hint - NUMBER_TYPES_SET):
return numberify(value)
elif not (type_hint - STRING_TYPES_SET):
return text_type(value)
elif not (type_hint - {bool, NoneType}):
return boolify(value, nullable=True)
elif not (type_hint - (STRING_TYPES_SET | {bool})):
return boolify(value, return_string=True)
elif not (type_hint - (STRING_TYPES_SET | {NoneType})):
value = text_type(value)
return None if value.lower() == 'none' else value
elif not (type_hint - {bool, int}):
return typify_str_no_hint(text_type(value))
else:
raise NotImplementedError()
elif type_hint is not None:
# coerce using the type hint, or use boolify for bool
try:
return boolify(value) if type_hint == bool else type_hint(value)
except ValueError as e:
# ValueError: invalid literal for int() with base 10: 'nope'
raise TypeCoercionError(value, text_type(e))
else:
# no type hint, but we know value is a string, so try to match with the regex patterns
# if there's still no match, `typify_str_no_hint` will return `value`
return typify_str_no_hint(value)
def typify_data_structure(value, type_hint=None):
if isinstance(value, Mapping):
<|code_end|>
. Use current file imports:
(from collections import Mapping
from itertools import chain
from re import IGNORECASE, compile
from enum import Enum
from .compat import NoneType, integer_types, isiterable, iteritems, string_types, text_type
from .decorators import memoizedproperty
from .exceptions import AuxlibError)
and context including class names, function names, or small code snippets from other files:
# Path: auxlib/compat.py
# def isiterable(obj):
#
# Path: auxlib/decorators.py
# def memoizedproperty(func):
# """
# Decorator to cause a method to cache it's results in self for each
# combination of inputs and return the cached result on subsequent calls.
# Does not support named arguments or arg values that are not hashable.
#
# >>> class Foo (object):
# ... _x = 1
# ... @memoizedproperty
# ... def foo(self):
# ... self._x += 1
# ... print('updating and returning {0}'.format(self._x))
# ... return self._x
# ...
# >>> foo1 = Foo()
# >>> foo2 = Foo()
# >>> foo1.foo
# updating and returning 2
# 2
# >>> foo1.foo
# 2
# >>> foo2.foo
# updating and returning 2
# 2
# >>> foo1.foo
# 2
# """
# inner_attname = '__%s' % func.__name__
#
# def new_fget(self):
# if not hasattr(self, '_cache_'):
# self._cache_ = dict()
# cache = self._cache_
# if inner_attname not in cache:
# cache[inner_attname] = func(self)
# return cache[inner_attname]
#
# return property(new_fget)
#
# Path: auxlib/exceptions.py
# class AuxlibError(object):
# """Mixin to identify exceptions associated with the auxlib package."""
. Output only the next line. | return type(value)((k, typify(v, type_hint)) for k, v in iteritems(value)) |
Next line prediction: <|code_start|>"""Collection of functions to coerce conversion of types with an intelligent guess."""
__all__ = ["boolify", "typify", "maybecall", "listify", "numberify"]
BOOLISH_TRUE = ("true", "yes", "on", "y")
BOOLISH_FALSE = ("false", "off", "n", "no", "non", "none", "")
NULL_STRINGS = ("none", "~", "null", "\0")
BOOL_COERCEABLE_TYPES = integer_types + (bool, float, complex, list, set, dict, tuple)
NUMBER_TYPES = integer_types + (float, complex)
NUMBER_TYPES_SET = set(NUMBER_TYPES)
<|code_end|>
. Use current file imports:
(from collections import Mapping
from itertools import chain
from re import IGNORECASE, compile
from enum import Enum
from .compat import NoneType, integer_types, isiterable, iteritems, string_types, text_type
from .decorators import memoizedproperty
from .exceptions import AuxlibError)
and context including class names, function names, or small code snippets from other files:
# Path: auxlib/compat.py
# def isiterable(obj):
#
# Path: auxlib/decorators.py
# def memoizedproperty(func):
# """
# Decorator to cause a method to cache it's results in self for each
# combination of inputs and return the cached result on subsequent calls.
# Does not support named arguments or arg values that are not hashable.
#
# >>> class Foo (object):
# ... _x = 1
# ... @memoizedproperty
# ... def foo(self):
# ... self._x += 1
# ... print('updating and returning {0}'.format(self._x))
# ... return self._x
# ...
# >>> foo1 = Foo()
# >>> foo2 = Foo()
# >>> foo1.foo
# updating and returning 2
# 2
# >>> foo1.foo
# 2
# >>> foo2.foo
# updating and returning 2
# 2
# >>> foo1.foo
# 2
# """
# inner_attname = '__%s' % func.__name__
#
# def new_fget(self):
# if not hasattr(self, '_cache_'):
# self._cache_ = dict()
# cache = self._cache_
# if inner_attname not in cache:
# cache[inner_attname] = func(self)
# return cache[inner_attname]
#
# return property(new_fget)
#
# Path: auxlib/exceptions.py
# class AuxlibError(object):
# """Mixin to identify exceptions associated with the auxlib package."""
. Output only the next line. | STRING_TYPES_SET = set(string_types) |
Given snippet: <|code_start|>
def boolify(value, nullable=False, return_string=False):
"""Convert a number, string, or sequence type into a pure boolean.
Args:
value (number, string, sequence): pretty much anything
Returns:
bool: boolean representation of the given value
Examples:
>>> [boolify(x) for x in ('yes', 'no')]
[True, False]
>>> [boolify(x) for x in (0.1, 0+0j, True, '0', '0.0', '0.1', '2')]
[True, False, True, False, False, True, True]
>>> [boolify(x) for x in ("true", "yes", "on", "y")]
[True, True, True, True]
>>> [boolify(x) for x in ("no", "non", "none", "off", "")]
[False, False, False, False, False]
>>> [boolify(x) for x in ([], set(), dict(), tuple())]
[False, False, False, False]
>>> [boolify(x) for x in ([1], set([False]), dict({'a': 1}), tuple([2]))]
[True, True, True, True]
"""
# cast number types naturally
if isinstance(value, BOOL_COERCEABLE_TYPES):
return bool(value)
# try to coerce string into number
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from collections import Mapping
from itertools import chain
from re import IGNORECASE, compile
from enum import Enum
from .compat import NoneType, integer_types, isiterable, iteritems, string_types, text_type
from .decorators import memoizedproperty
from .exceptions import AuxlibError
and context:
# Path: auxlib/compat.py
# def isiterable(obj):
#
# Path: auxlib/decorators.py
# def memoizedproperty(func):
# """
# Decorator to cause a method to cache it's results in self for each
# combination of inputs and return the cached result on subsequent calls.
# Does not support named arguments or arg values that are not hashable.
#
# >>> class Foo (object):
# ... _x = 1
# ... @memoizedproperty
# ... def foo(self):
# ... self._x += 1
# ... print('updating and returning {0}'.format(self._x))
# ... return self._x
# ...
# >>> foo1 = Foo()
# >>> foo2 = Foo()
# >>> foo1.foo
# updating and returning 2
# 2
# >>> foo1.foo
# 2
# >>> foo2.foo
# updating and returning 2
# 2
# >>> foo1.foo
# 2
# """
# inner_attname = '__%s' % func.__name__
#
# def new_fget(self):
# if not hasattr(self, '_cache_'):
# self._cache_ = dict()
# cache = self._cache_
# if inner_attname not in cache:
# cache[inner_attname] = func(self)
# return cache[inner_attname]
#
# return property(new_fget)
#
# Path: auxlib/exceptions.py
# class AuxlibError(object):
# """Mixin to identify exceptions associated with the auxlib package."""
which might include code, classes, or functions. Output only the next line. | val = text_type(value).strip().lower().replace('.', '', 1) |
Continue the code snippet: <|code_start|>"""Collection of functions to coerce conversion of types with an intelligent guess."""
__all__ = ["boolify", "typify", "maybecall", "listify", "numberify"]
BOOLISH_TRUE = ("true", "yes", "on", "y")
BOOLISH_FALSE = ("false", "off", "n", "no", "non", "none", "")
NULL_STRINGS = ("none", "~", "null", "\0")
BOOL_COERCEABLE_TYPES = integer_types + (bool, float, complex, list, set, dict, tuple)
NUMBER_TYPES = integer_types + (float, complex)
NUMBER_TYPES_SET = set(NUMBER_TYPES)
STRING_TYPES_SET = set(string_types)
NO_MATCH = object()
class TypeCoercionError(AuxlibError, ValueError):
def __init__(self, value, msg, *args, **kwargs):
self.value = value
super(TypeCoercionError, self).__init__(msg, *args, **kwargs)
class _Regex(object):
<|code_end|>
. Use current file imports:
from collections import Mapping
from itertools import chain
from re import IGNORECASE, compile
from enum import Enum
from .compat import NoneType, integer_types, isiterable, iteritems, string_types, text_type
from .decorators import memoizedproperty
from .exceptions import AuxlibError
and context (classes, functions, or code) from other files:
# Path: auxlib/compat.py
# def isiterable(obj):
#
# Path: auxlib/decorators.py
# def memoizedproperty(func):
# """
# Decorator to cause a method to cache it's results in self for each
# combination of inputs and return the cached result on subsequent calls.
# Does not support named arguments or arg values that are not hashable.
#
# >>> class Foo (object):
# ... _x = 1
# ... @memoizedproperty
# ... def foo(self):
# ... self._x += 1
# ... print('updating and returning {0}'.format(self._x))
# ... return self._x
# ...
# >>> foo1 = Foo()
# >>> foo2 = Foo()
# >>> foo1.foo
# updating and returning 2
# 2
# >>> foo1.foo
# 2
# >>> foo2.foo
# updating and returning 2
# 2
# >>> foo1.foo
# 2
# """
# inner_attname = '__%s' % func.__name__
#
# def new_fget(self):
# if not hasattr(self, '_cache_'):
# self._cache_ = dict()
# cache = self._cache_
# if inner_attname not in cache:
# cache[inner_attname] = func(self)
# return cache[inner_attname]
#
# return property(new_fget)
#
# Path: auxlib/exceptions.py
# class AuxlibError(object):
# """Mixin to identify exceptions associated with the auxlib package."""
. Output only the next line. | @memoizedproperty |
Here is a snippet: <|code_start|>"""Collection of functions to coerce conversion of types with an intelligent guess."""
__all__ = ["boolify", "typify", "maybecall", "listify", "numberify"]
BOOLISH_TRUE = ("true", "yes", "on", "y")
BOOLISH_FALSE = ("false", "off", "n", "no", "non", "none", "")
NULL_STRINGS = ("none", "~", "null", "\0")
BOOL_COERCEABLE_TYPES = integer_types + (bool, float, complex, list, set, dict, tuple)
NUMBER_TYPES = integer_types + (float, complex)
NUMBER_TYPES_SET = set(NUMBER_TYPES)
STRING_TYPES_SET = set(string_types)
NO_MATCH = object()
<|code_end|>
. Write the next line using the current file imports:
from collections import Mapping
from itertools import chain
from re import IGNORECASE, compile
from enum import Enum
from .compat import NoneType, integer_types, isiterable, iteritems, string_types, text_type
from .decorators import memoizedproperty
from .exceptions import AuxlibError
and context from other files:
# Path: auxlib/compat.py
# def isiterable(obj):
#
# Path: auxlib/decorators.py
# def memoizedproperty(func):
# """
# Decorator to cause a method to cache it's results in self for each
# combination of inputs and return the cached result on subsequent calls.
# Does not support named arguments or arg values that are not hashable.
#
# >>> class Foo (object):
# ... _x = 1
# ... @memoizedproperty
# ... def foo(self):
# ... self._x += 1
# ... print('updating and returning {0}'.format(self._x))
# ... return self._x
# ...
# >>> foo1 = Foo()
# >>> foo2 = Foo()
# >>> foo1.foo
# updating and returning 2
# 2
# >>> foo1.foo
# 2
# >>> foo2.foo
# updating and returning 2
# 2
# >>> foo1.foo
# 2
# """
# inner_attname = '__%s' % func.__name__
#
# def new_fget(self):
# if not hasattr(self, '_cache_'):
# self._cache_ = dict()
# cache = self._cache_
# if inner_attname not in cache:
# cache[inner_attname] = func(self)
# return cache[inner_attname]
#
# return property(new_fget)
#
# Path: auxlib/exceptions.py
# class AuxlibError(object):
# """Mixin to identify exceptions associated with the auxlib package."""
, which may include functions, classes, or code. Output only the next line. | class TypeCoercionError(AuxlibError, ValueError): |
Given snippet: <|code_start|> if 'skip_registration' in cls.__dict__ and cls.skip_registration:
pass # we don't even care # pragma: no cover
elif cls.factory is None:
# this must be the base implementation; add a factory object
cls.factory = type(cls.__name__ + 'Factory', (FactoryBase, ),
{'providers': dict(), 'cache': dict()})
if hasattr(cls, 'gateways'):
cls.gateways.add(cls)
else:
# must be a derived object, register it as a provider in cls.factory
cls.factory.providers[cls.__name__] = cls
def __call__(cls, *args):
if 'factory' in cls.__dict__:
if args and args[0]:
return cls.factory.get_instance(args[0])
else:
return cls.factory.get_instance()
else:
if not getattr(cls, 'do_cache', False):
return super(FactoryType, cls).__call__(*args)
cache_id = "{0}".format(cls.__name__)
try:
return cls.factory.cache[cache_id]
except KeyError:
instance = super(FactoryType, cls).__call__(*args)
cls.factory.cache[cache_id] = instance
return instance
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from .compat import with_metaclass
from .exceptions import InitializationError
and context:
# Path: auxlib/compat.py
# def isiterable(obj):
#
# Path: auxlib/exceptions.py
# class InitializationError(AuxlibError, EnvironmentError):
# pass
which might include code, classes, or functions. Output only the next line. | @with_metaclass(FactoryType) |
Given the code snippet: <|code_start|>"""A python implementation of the factory design pattern. It's designed for use as a base class
for various types of data gateways.
"""
from __future__ import absolute_import, division, print_function
__all__ = ['Factory']
class FactoryBase(object):
@classmethod
def initialize(cls, context, default_provider):
cls.context = context
cls._default_provider = (default_provider.__name__ if isinstance(default_provider, type)
else str(default_provider))
if not cls.is_registered_provider(cls._default_provider):
raise RuntimeError("{0} is not a registered provider for "
"{1}".format(cls._default_provider, cls.__name__))
@classmethod
def get_instance(cls, provider=None):
if not hasattr(cls, 'context'):
<|code_end|>
, generate the next line using the imports in this file:
from .compat import with_metaclass
from .exceptions import InitializationError
and context (functions, classes, or occasionally code) from other files:
# Path: auxlib/compat.py
# def isiterable(obj):
#
# Path: auxlib/exceptions.py
# class InitializationError(AuxlibError, EnvironmentError):
# pass
. Output only the next line. | raise InitializationError("RecordRepoFactory has not been initialized.") |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
log = getLogger(__name__)
class TestLoggingSetup(TestCase):
def test_basic_stderr(self):
detach_stderr()
<|code_end|>
using the current file's imports:
from logging import getLogger
from unittest import TestCase
from requests import Request
from auxlib.logz import attach_stderr, detach_stderr, initialize_logging, stringify
and any relevant context from other files:
# Path: auxlib/logz.py
# def attach_stderr(level=INFO):
# has_stderr_handler = any(handler.name == 'stderr' for handler in root_log.handlers)
# if not has_stderr_handler:
# handler = StreamHandler(stderr)
# handler.name = 'stderr'
# if level is not None:
# handler.setLevel(level)
# handler.setFormatter(DEBUG_FORMATTER if level == DEBUG else INFO_FORMATTER)
# root_log.addHandler(handler)
# return True
# else:
# return False
#
# def detach_stderr():
# for handler in root_log.handlers:
# if handler.name == 'stderr':
# root_log.removeHandler(handler)
# return True
# return False
#
# def initialize_logging(level=INFO):
# attach_stderr(level)
#
# def stringify(obj, content_max_len=0):
# def bottle_builder(builder, bottle_object):
# builder.append("{0} {1}{2} {3}".format(bottle_object.method,
# bottle_object.path,
# bottle_object.environ.get('QUERY_STRING', ''),
# bottle_object.get('SERVER_PROTOCOL')))
# builder += ["{0}: {1}".format(key, value) for key, value in bottle_object.headers.items()]
# builder.append('')
# body = bottle_object.body.read().strip()
# if body:
# builder.append(body)
#
# def requests_models_PreparedRequest_builder(builder, request_object):
# builder.append(">>{0} {1} {2}".format(request_object.method, request_object.path_url,
# request_object.url.split(':', 1)[0].upper()))
# builder.extend("> {0}: {1}".format(key, value)
# for key, value in sorted(request_object.headers.items(),
# key=request_header_sort_key))
# builder.append('')
# if request_object.body:
# builder.append(request_object.body)
#
# def requests_models_Response_builder(builder, response_object):
# builder.append("<<{0} {1} {2}".format(response_object.url.split(':', 1)[0].upper(),
# response_object.status_code, response_object.reason))
# builder.extend("< {0}: {1}".format(key, value)
# for key, value in sorted(response_object.headers.items(),
# key=response_header_sort_key))
# elapsed = text_type(response_object.elapsed).split(':', 1)[-1]
# builder.append('< Elapsed: {0}'.format(elapsed))
# if content_max_len:
# builder.append('')
# content_type = response_object.headers.get('Content-Type')
# if content_type == 'application/json':
# content = pformat(response_object.json(), indent=2)
# content = content[:content_max_len] if len(content) > content_max_len else content
# builder.append(content)
# builder.append('')
# elif content_type is not None and (content_type.startswith('text/')
# or content_type == 'application/xml'):
# text = response_object.text
# content = text[:content_max_len] if len(text) > content_max_len else text
# builder.append(content)
#
# try:
# name = fullname(obj)
# builder = [''] # start with new line
# if name.startswith('bottle.'):
# bottle_builder(builder, obj)
# elif name.endswith('requests.models.PreparedRequest'):
# requests_models_PreparedRequest_builder(builder, obj)
# elif name.endswith('requests.models.Response'):
# if getattr(obj, 'request'):
# requests_models_PreparedRequest_builder(builder, obj.request)
# else:
# log.info("request is 'None' for Response object with url %s", obj.url)
# requests_models_Response_builder(builder, obj)
# else:
# return None
# builder.append('') # end with new line
# return "\n".join(builder)
# except Exception as e:
# log.exception(e)
. Output only the next line. | assert attach_stderr() |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
log = getLogger(__name__)
class TestLoggingSetup(TestCase):
def test_basic_stderr(self):
<|code_end|>
, predict the immediate next line with the help of imports:
from logging import getLogger
from unittest import TestCase
from requests import Request
from auxlib.logz import attach_stderr, detach_stderr, initialize_logging, stringify
and context (classes, functions, sometimes code) from other files:
# Path: auxlib/logz.py
# def attach_stderr(level=INFO):
# has_stderr_handler = any(handler.name == 'stderr' for handler in root_log.handlers)
# if not has_stderr_handler:
# handler = StreamHandler(stderr)
# handler.name = 'stderr'
# if level is not None:
# handler.setLevel(level)
# handler.setFormatter(DEBUG_FORMATTER if level == DEBUG else INFO_FORMATTER)
# root_log.addHandler(handler)
# return True
# else:
# return False
#
# def detach_stderr():
# for handler in root_log.handlers:
# if handler.name == 'stderr':
# root_log.removeHandler(handler)
# return True
# return False
#
# def initialize_logging(level=INFO):
# attach_stderr(level)
#
# def stringify(obj, content_max_len=0):
# def bottle_builder(builder, bottle_object):
# builder.append("{0} {1}{2} {3}".format(bottle_object.method,
# bottle_object.path,
# bottle_object.environ.get('QUERY_STRING', ''),
# bottle_object.get('SERVER_PROTOCOL')))
# builder += ["{0}: {1}".format(key, value) for key, value in bottle_object.headers.items()]
# builder.append('')
# body = bottle_object.body.read().strip()
# if body:
# builder.append(body)
#
# def requests_models_PreparedRequest_builder(builder, request_object):
# builder.append(">>{0} {1} {2}".format(request_object.method, request_object.path_url,
# request_object.url.split(':', 1)[0].upper()))
# builder.extend("> {0}: {1}".format(key, value)
# for key, value in sorted(request_object.headers.items(),
# key=request_header_sort_key))
# builder.append('')
# if request_object.body:
# builder.append(request_object.body)
#
# def requests_models_Response_builder(builder, response_object):
# builder.append("<<{0} {1} {2}".format(response_object.url.split(':', 1)[0].upper(),
# response_object.status_code, response_object.reason))
# builder.extend("< {0}: {1}".format(key, value)
# for key, value in sorted(response_object.headers.items(),
# key=response_header_sort_key))
# elapsed = text_type(response_object.elapsed).split(':', 1)[-1]
# builder.append('< Elapsed: {0}'.format(elapsed))
# if content_max_len:
# builder.append('')
# content_type = response_object.headers.get('Content-Type')
# if content_type == 'application/json':
# content = pformat(response_object.json(), indent=2)
# content = content[:content_max_len] if len(content) > content_max_len else content
# builder.append(content)
# builder.append('')
# elif content_type is not None and (content_type.startswith('text/')
# or content_type == 'application/xml'):
# text = response_object.text
# content = text[:content_max_len] if len(text) > content_max_len else text
# builder.append(content)
#
# try:
# name = fullname(obj)
# builder = [''] # start with new line
# if name.startswith('bottle.'):
# bottle_builder(builder, obj)
# elif name.endswith('requests.models.PreparedRequest'):
# requests_models_PreparedRequest_builder(builder, obj)
# elif name.endswith('requests.models.Response'):
# if getattr(obj, 'request'):
# requests_models_PreparedRequest_builder(builder, obj.request)
# else:
# log.info("request is 'None' for Response object with url %s", obj.url)
# requests_models_Response_builder(builder, obj)
# else:
# return None
# builder.append('') # end with new line
# return "\n".join(builder)
# except Exception as e:
# log.exception(e)
. Output only the next line. | detach_stderr() |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
log = getLogger(__name__)
class TestLoggingSetup(TestCase):
def test_basic_stderr(self):
detach_stderr()
assert attach_stderr()
assert not attach_stderr()
assert detach_stderr()
assert not detach_stderr()
assert attach_stderr()
def test_initialize_logging(self):
attach_stderr()
<|code_end|>
. Write the next line using the current file imports:
from logging import getLogger
from unittest import TestCase
from requests import Request
from auxlib.logz import attach_stderr, detach_stderr, initialize_logging, stringify
and context from other files:
# Path: auxlib/logz.py
# def attach_stderr(level=INFO):
# has_stderr_handler = any(handler.name == 'stderr' for handler in root_log.handlers)
# if not has_stderr_handler:
# handler = StreamHandler(stderr)
# handler.name = 'stderr'
# if level is not None:
# handler.setLevel(level)
# handler.setFormatter(DEBUG_FORMATTER if level == DEBUG else INFO_FORMATTER)
# root_log.addHandler(handler)
# return True
# else:
# return False
#
# def detach_stderr():
# for handler in root_log.handlers:
# if handler.name == 'stderr':
# root_log.removeHandler(handler)
# return True
# return False
#
# def initialize_logging(level=INFO):
# attach_stderr(level)
#
# def stringify(obj, content_max_len=0):
# def bottle_builder(builder, bottle_object):
# builder.append("{0} {1}{2} {3}".format(bottle_object.method,
# bottle_object.path,
# bottle_object.environ.get('QUERY_STRING', ''),
# bottle_object.get('SERVER_PROTOCOL')))
# builder += ["{0}: {1}".format(key, value) for key, value in bottle_object.headers.items()]
# builder.append('')
# body = bottle_object.body.read().strip()
# if body:
# builder.append(body)
#
# def requests_models_PreparedRequest_builder(builder, request_object):
# builder.append(">>{0} {1} {2}".format(request_object.method, request_object.path_url,
# request_object.url.split(':', 1)[0].upper()))
# builder.extend("> {0}: {1}".format(key, value)
# for key, value in sorted(request_object.headers.items(),
# key=request_header_sort_key))
# builder.append('')
# if request_object.body:
# builder.append(request_object.body)
#
# def requests_models_Response_builder(builder, response_object):
# builder.append("<<{0} {1} {2}".format(response_object.url.split(':', 1)[0].upper(),
# response_object.status_code, response_object.reason))
# builder.extend("< {0}: {1}".format(key, value)
# for key, value in sorted(response_object.headers.items(),
# key=response_header_sort_key))
# elapsed = text_type(response_object.elapsed).split(':', 1)[-1]
# builder.append('< Elapsed: {0}'.format(elapsed))
# if content_max_len:
# builder.append('')
# content_type = response_object.headers.get('Content-Type')
# if content_type == 'application/json':
# content = pformat(response_object.json(), indent=2)
# content = content[:content_max_len] if len(content) > content_max_len else content
# builder.append(content)
# builder.append('')
# elif content_type is not None and (content_type.startswith('text/')
# or content_type == 'application/xml'):
# text = response_object.text
# content = text[:content_max_len] if len(text) > content_max_len else text
# builder.append(content)
#
# try:
# name = fullname(obj)
# builder = [''] # start with new line
# if name.startswith('bottle.'):
# bottle_builder(builder, obj)
# elif name.endswith('requests.models.PreparedRequest'):
# requests_models_PreparedRequest_builder(builder, obj)
# elif name.endswith('requests.models.Response'):
# if getattr(obj, 'request'):
# requests_models_PreparedRequest_builder(builder, obj.request)
# else:
# log.info("request is 'None' for Response object with url %s", obj.url)
# requests_models_Response_builder(builder, obj)
# else:
# return None
# builder.append('') # end with new line
# return "\n".join(builder)
# except Exception as e:
# log.exception(e)
, which may include functions, classes, or code. Output only the next line. | initialize_logging() |
Predict the next line after this snippet: <|code_start|>
log = getLogger(__name__)
class TestLoggingSetup(TestCase):
def test_basic_stderr(self):
detach_stderr()
assert attach_stderr()
assert not attach_stderr()
assert detach_stderr()
assert not detach_stderr()
assert attach_stderr()
def test_initialize_logging(self):
attach_stderr()
initialize_logging()
log.error("Very important message.")
class TestStringify(TestCase):
def test_requests_stringify(self):
url = "http://jenkins.ci/job/awesome_build/buildWithParameters"
headers = {"Accpet": "application/json",
"Content-Type": "application/json"}
data = {"GIT_BRANCH": "feature/awesome-feature",
"GIT_HASH": "abbacadaba1234567890"}
req = Request('POST', url, headers=headers, json=data).prepare()
<|code_end|>
using the current file's imports:
from logging import getLogger
from unittest import TestCase
from requests import Request
from auxlib.logz import attach_stderr, detach_stderr, initialize_logging, stringify
and any relevant context from other files:
# Path: auxlib/logz.py
# def attach_stderr(level=INFO):
# has_stderr_handler = any(handler.name == 'stderr' for handler in root_log.handlers)
# if not has_stderr_handler:
# handler = StreamHandler(stderr)
# handler.name = 'stderr'
# if level is not None:
# handler.setLevel(level)
# handler.setFormatter(DEBUG_FORMATTER if level == DEBUG else INFO_FORMATTER)
# root_log.addHandler(handler)
# return True
# else:
# return False
#
# def detach_stderr():
# for handler in root_log.handlers:
# if handler.name == 'stderr':
# root_log.removeHandler(handler)
# return True
# return False
#
# def initialize_logging(level=INFO):
# attach_stderr(level)
#
# def stringify(obj, content_max_len=0):
# def bottle_builder(builder, bottle_object):
# builder.append("{0} {1}{2} {3}".format(bottle_object.method,
# bottle_object.path,
# bottle_object.environ.get('QUERY_STRING', ''),
# bottle_object.get('SERVER_PROTOCOL')))
# builder += ["{0}: {1}".format(key, value) for key, value in bottle_object.headers.items()]
# builder.append('')
# body = bottle_object.body.read().strip()
# if body:
# builder.append(body)
#
# def requests_models_PreparedRequest_builder(builder, request_object):
# builder.append(">>{0} {1} {2}".format(request_object.method, request_object.path_url,
# request_object.url.split(':', 1)[0].upper()))
# builder.extend("> {0}: {1}".format(key, value)
# for key, value in sorted(request_object.headers.items(),
# key=request_header_sort_key))
# builder.append('')
# if request_object.body:
# builder.append(request_object.body)
#
# def requests_models_Response_builder(builder, response_object):
# builder.append("<<{0} {1} {2}".format(response_object.url.split(':', 1)[0].upper(),
# response_object.status_code, response_object.reason))
# builder.extend("< {0}: {1}".format(key, value)
# for key, value in sorted(response_object.headers.items(),
# key=response_header_sort_key))
# elapsed = text_type(response_object.elapsed).split(':', 1)[-1]
# builder.append('< Elapsed: {0}'.format(elapsed))
# if content_max_len:
# builder.append('')
# content_type = response_object.headers.get('Content-Type')
# if content_type == 'application/json':
# content = pformat(response_object.json(), indent=2)
# content = content[:content_max_len] if len(content) > content_max_len else content
# builder.append(content)
# builder.append('')
# elif content_type is not None and (content_type.startswith('text/')
# or content_type == 'application/xml'):
# text = response_object.text
# content = text[:content_max_len] if len(text) > content_max_len else text
# builder.append(content)
#
# try:
# name = fullname(obj)
# builder = [''] # start with new line
# if name.startswith('bottle.'):
# bottle_builder(builder, obj)
# elif name.endswith('requests.models.PreparedRequest'):
# requests_models_PreparedRequest_builder(builder, obj)
# elif name.endswith('requests.models.Response'):
# if getattr(obj, 'request'):
# requests_models_PreparedRequest_builder(builder, obj.request)
# else:
# log.info("request is 'None' for Response object with url %s", obj.url)
# requests_models_Response_builder(builder, obj)
# else:
# return None
# builder.append('') # end with new line
# return "\n".join(builder)
# except Exception as e:
# log.exception(e)
. Output only the next line. | strng = stringify(req) |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
log = getLogger(__name__)
class AllTheAnswers(object):
_x = 42
_y = 43
def __init__(self, x, y):
self._x = x
self._y = y
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from logging import getLogger
from unittest import TestCase
from auxlib.decorators import classproperty
and context:
# Path: auxlib/decorators.py
# class classproperty(object): # pylint: disable=C0103
# # from celery.five
#
# def __init__(self, getter=None, setter=None):
# if getter is not None and not isinstance(getter, classmethod):
# getter = classmethod(getter)
# if setter is not None and not isinstance(setter, classmethod):
# setter = classmethod(setter)
# self.__get = getter
# self.__set = setter
#
# info = getter.__get__(object) # just need the info attrs.
# self.__doc__ = info.__doc__
# self.__name__ = info.__name__
# self.__module__ = info.__module__
#
# def __get__(self, obj, type_=None):
# if obj and type_ is None:
# type_ = obj.__class__
# return self.__get.__get__(obj, type_)()
#
# def __set__(self, obj, value):
# if obj is None:
# return self
# return self.__set.__get__(obj)(value)
#
# def setter(self, setter):
# return self.__class__(self.__get, setter)
which might include code, classes, or functions. Output only the next line. | @classproperty |
Continue the code snippet: <|code_start|>except ImportError: # pragma: no cover
logging.getLogger(__name__).error('auxlib.crypt is a pycrypto wrapper, '
'which is not installed in the current '
'environment.') # pragma: no cover
log = logging.getLogger(__name__)
__all__ = ["as_base64", "from_base64", "encrypt", "decrypt", "aes_encrypt", "aes_decrypt"]
AES_KEY_SIZE = 32 # 32 byte key size ==> AES-256
HMAC_SIG_SIZE = hashlib.sha256().digest_size
def encrypt(secret_key, data):
message_encryption_key = generate_encryption_key()
encrypted_data = aes_encrypt(message_encryption_key, data)
hashed_secret = generate_hash_from_secret(secret_key)
encryption_key_encrypted = aes_encrypt(hashed_secret, message_encryption_key)
return encryption_key_encrypted, encrypted_data
def decrypt(secret_key, encryption_key_encrypted, encrypted_data):
hashed_secret = generate_hash_from_secret(secret_key)
message_encryption_key = aes_decrypt(hashed_secret, encryption_key_encrypted)
data = aes_decrypt(message_encryption_key, encrypted_data)
return data
def as_base64(content):
<|code_end|>
. Use current file imports:
import base64
import hashlib
import hmac
import logging
import os
from Crypto.Cipher import AES
from .compat import text_type
from .exceptions import AuthenticationError
and context (classes, functions, or code) from other files:
# Path: auxlib/compat.py
# def isiterable(obj):
#
# Path: auxlib/exceptions.py
# class AuthenticationError(AuxlibError, ValueError):
# pass
. Output only the next line. | if isinstance(content, text_type): |
Given the code snippet: <|code_start|> data = data.encode("UTF-8")
aes_key_bytes, hmac_key_bytes = _extract_keys(base64_encryption_key)
data = _pad(data)
iv_bytes = os.urandom(AES_BLOCK_SIZE)
cipher = AES.new(aes_key_bytes, mode=AES.MODE_CBC, IV=iv_bytes)
data = iv_bytes + cipher.encrypt(data) # prepend init vector
hmac_signature = hmac.new(hmac_key_bytes, data, hashlib.sha256).digest()
return as_base64(data + hmac_signature)
def aes_decrypt(base64_encryption_key, base64_data):
"""Verify HMAC-SHA256 signature and decrypt data with AES-CBC
Arguments:
encryption_key (str): a base64-encoded string containing an AES encryption key and HMAC
signing key as generated by generate_encryption_key()
data (str): a byte string containing the data decrypted with an HMAC signing key
appended to the end
Returns:
str: a byte string containing the data that was originally encrypted
Raises:
AuthenticationError: when the HMAC-SHA256 signature authentication fails
"""
data = from_base64(base64_data)
aes_key_bytes, hmac_key_bytes = _extract_keys(base64_encryption_key)
data, hmac_signature = data[:-HMAC_SIG_SIZE], data[-HMAC_SIG_SIZE:]
if hmac.new(hmac_key_bytes, data, hashlib.sha256).digest() != hmac_signature:
<|code_end|>
, generate the next line using the imports in this file:
import base64
import hashlib
import hmac
import logging
import os
from Crypto.Cipher import AES
from .compat import text_type
from .exceptions import AuthenticationError
and context (functions, classes, or occasionally code) from other files:
# Path: auxlib/compat.py
# def isiterable(obj):
#
# Path: auxlib/exceptions.py
# class AuthenticationError(AuxlibError, ValueError):
# pass
. Output only the next line. | raise AuthenticationError("HMAC authentication failed") |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
"""Common collection classes."""
from __future__ import print_function, division, absolute_import
def make_immutable(value):
# this function is recursive, and if nested data structures fold back on themselves,
# there will likely be recursion errors
if isinstance(value, Mapping):
if isinstance(value, frozenodict):
return value
return frozenodict((k, make_immutable(v)) for k, v in iteritems(value))
elif isinstance(value, Set):
if isinstance(value, frozenset):
return value
return frozenset(make_immutable(v) for v in value)
<|code_end|>
using the current file's imports:
from functools import reduce
from collections import Mapping, Set
from .compat import isiterable, iteritems, odict, text_type
and any relevant context from other files:
# Path: auxlib/compat.py
# def isiterable(obj):
. Output only the next line. | elif isiterable(value): |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
"""Common collection classes."""
from __future__ import print_function, division, absolute_import
def make_immutable(value):
# this function is recursive, and if nested data structures fold back on themselves,
# there will likely be recursion errors
if isinstance(value, Mapping):
if isinstance(value, frozenodict):
return value
<|code_end|>
. Use current file imports:
(from functools import reduce
from collections import Mapping, Set
from .compat import isiterable, iteritems, odict, text_type)
and context including class names, function names, or small code snippets from other files:
# Path: auxlib/compat.py
# def isiterable(obj):
. Output only the next line. | return frozenodict((k, make_immutable(v)) for k, v in iteritems(value)) |
Predict the next line for this snippet: <|code_start|> return self._dict[key]
def __contains__(self, key):
return key in self._dict
def copy(self, **add_or_replace):
return self.__class__(self, **add_or_replace)
def __iter__(self):
return iter(self._dict)
def __len__(self):
return len(self._dict)
def __repr__(self):
return '<%s %r>' % (self.__class__.__name__, self._dict)
def __hash__(self):
if self._hash is None:
h = 0
for key, value in iteritems(self._dict):
h ^= hash((key, value))
self._hash = h
return self._hash
def __json__(self):
return self._dict
class frozenodict(frozendict):
<|code_end|>
with the help of current file imports:
from functools import reduce
from collections import Mapping, Set
from .compat import isiterable, iteritems, odict, text_type
and context from other files:
# Path: auxlib/compat.py
# def isiterable(obj):
, which may contain function names, class names, or code. Output only the next line. | dict_cls = odict |
Based on the snippet: <|code_start|> The optional `key` argument specifies a one-argument predicate function
like that used for `filter()`. The `key` argument, if supplied, must be
in keyword form. For example:
>>> first([1, 1, 3, 4, 5], key=lambda x: x % 2 == 0)
4
"""
return next((apply(x) for x in seq if key(x)), default() if callable(default) else default)
def firstitem(map, key=lambda k, v: bool(k), default=None, apply=lambda k, v: (k, v)):
return next((apply(k, v) for k, v in map if key(k, v)), default)
def last(seq, key=lambda x: bool(x), default=None, apply=lambda x: x):
return next((apply(x) for x in reversed(seq) if key(x)), default)
def call_each(seq):
"""Calls each element of sequence to invoke the side effect.
Args:
seq:
Returns: None
"""
try:
reduce(lambda _, y: y(), seq)
except TypeError as e:
<|code_end|>
, predict the immediate next line with the help of imports:
from functools import reduce
from collections import Mapping, Set
from .compat import isiterable, iteritems, odict, text_type
and context (classes, functions, sometimes code) from other files:
# Path: auxlib/compat.py
# def isiterable(obj):
. Output only the next line. | if text_type(e) != "reduce() of empty sequence with no initial value": |
Given snippet: <|code_start|># file: netdevice/forms.py
class RouterForm(forms.ModelForm):
class Meta:
model = router
fields = ('__all__')
class VrfForm(forms.ModelForm):
class Meta:
model = vrf
fields = ('__all__')
class InterfaceForm(forms.ModelForm):
class Meta:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django import forms
from netdevice.models import router, interface, logical_interface, vrf
and context:
# Path: netdevice/models.py
# class router(models.Model):
# """
# Router - A network device that moves packets around.
# routing_id: An IP address the router will use as identification and routing decisions. [203.0.113.1]
# hostname: The (DNS) hostname of the router, domain included. [Router1.isp]
# ibgp: Boolean value to build an iBGP mesh with every router in the database. [True]
# network_os: The network operating system and subsequent template this router is tied too.
# service_ssh: Boolean value to enable SSHv2 on the router. [True]
# service_netconf: Boolean value to enable NETCONF on the router. [True]
# local_aut_num: Local autonomous system number for the router.
# Example string: Router1
# """
#
# routing_id = models.GenericIPAddressField(unpack_ipv4=True)
# hostname = models.CharField(max_length=255)
# ibgp = models.BooleanField()
# network_os = models.ForeignKey('network_os', on_delete=models.CASCADE)
# service_ssh = models.BooleanField(default=True)
# service_netconf = models.BooleanField(default=True)
# local_aut_num = models.ForeignKey('bgp.aut_num', on_delete=models.CASCADE)
#
# def ldp_exists(self):
# return self.interface_set.filter(logical_interface__ldp=True).exists()
#
# def __str__(self):
# return self.hostname
#
# class interface(models.Model):
# """
# Interface - Physical network interface, may contain multiple logical interfaces.
# router: Router that the interface is tied to.
# name: Name of the actual interface, on the target platform. [et-1/0/0]
# description: A quick sentence or details on what this interface holds. (optional) [An ethernet interface]
# mtu: Maximum Transmission Unit, used when needed. [1514]
# dot1q: Enable 802.1Q VLAN Tags on the interface [True]
# Example string: Router1 et-1/0/0
# """
#
# router = models.ForeignKey('router', on_delete=models.CASCADE)
# name = models.CharField(max_length=255)
# description = models.CharField(max_length=1024, blank=True)
# mtu = models.BigIntegerField(default=1514)
# dot1q = models.BooleanField(default=False)
# disabled = models.BooleanField(default=False)
#
# def __str__(self):
# return self.router.hostname + " " + self.name + " (" + self.description + ")"
#
# class logical_interface(models.Model):
# """
# Logical Interface - An abstract instance of a physical interface, usually seperated layer2 protocols (VLANs, DLCIs, etc.)
# interface: The physical interface that this logical interface is tied to.
# name: Actual name of the interface, usually an integer. [1]
# description: A quick sentence or details on what this interface holds. (optional) [An ethernet interface]
# mtu: Maximum Transmission Unit, used when needed. [1500]
# vlan: A VLAN tag ID, used when needed. (optional) [1]
# physical_interface: A boolean value if this logical interface takes up the entire physical interface. [False]
# ldp: A boolean value to set LDP transmit and recieve on the interface. [False]
# inet_dhcp_client: A boolean value for using the interface as a dhcp-client. [False]
# inet6_dhcp_client: A boolean value for using the interface as a dhcpv6-client. [False]
# Example string: Router1 FastEthernet1/0
# Router2 et-1/0/0.100
# """
#
# interface = models.ForeignKey('interface', on_delete=models.CASCADE)
# vrf = models.ForeignKey(
# 'netdevice.vrf',
# on_delete=models.CASCADE,
# null=True,
# blank=True
# )
# name = models.CharField(max_length=255)
# description = models.CharField(max_length=1024, blank=True)
# mtu = models.BigIntegerField(default=1500)
# vlan = models.IntegerField(null=True, blank=True, validators=[MinValueValidator(1),MaxValueValidator(4096)])
# physical_interface = models.BooleanField(default=False)
# ldp = models.BooleanField(default=False)
# inet_dhcp_client = models.BooleanField(default=False)
# inet6_dhcp_client = models.BooleanField(default=False)
# disabled = models.BooleanField(default=False)
#
# def __str__(self):
# if self.physical_interface:
# return self.interface.router.hostname + " " + self.interface.name + " (" + self.description + ")"
# else:
# return self.interface.router.hostname + " " + self.interface.name + "." + self.name + " (" + self.description + ")"
#
# class vrf(models.Model):
# """
# Virtual Routing and Forwarding - multiple co-existing routing instances in
# a single physical router.
#
# vrf_name: The name of this VRF instance.
# vrf_target: String of what the target identifier for the VRF is.
# [target:65000:65000]
#
# Example string: VRF_Name (target:65000:65000)
# """
#
# name = models.CharField(max_length=255)
# target = models.CharField(max_length=255)
#
# def __str__(self):
# return self.name + " (" + self.target + ")"
which might include code, classes, or functions. Output only the next line. | model = interface |
Given snippet: <|code_start|># file: netdevice/forms.py
class RouterForm(forms.ModelForm):
class Meta:
model = router
fields = ('__all__')
class VrfForm(forms.ModelForm):
class Meta:
model = vrf
fields = ('__all__')
class InterfaceForm(forms.ModelForm):
class Meta:
model = interface
fields = ('__all__')
class LogicalInterfaceForm(forms.ModelForm):
class Meta:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django import forms
from netdevice.models import router, interface, logical_interface, vrf
and context:
# Path: netdevice/models.py
# class router(models.Model):
# """
# Router - A network device that moves packets around.
# routing_id: An IP address the router will use as identification and routing decisions. [203.0.113.1]
# hostname: The (DNS) hostname of the router, domain included. [Router1.isp]
# ibgp: Boolean value to build an iBGP mesh with every router in the database. [True]
# network_os: The network operating system and subsequent template this router is tied too.
# service_ssh: Boolean value to enable SSHv2 on the router. [True]
# service_netconf: Boolean value to enable NETCONF on the router. [True]
# local_aut_num: Local autonomous system number for the router.
# Example string: Router1
# """
#
# routing_id = models.GenericIPAddressField(unpack_ipv4=True)
# hostname = models.CharField(max_length=255)
# ibgp = models.BooleanField()
# network_os = models.ForeignKey('network_os', on_delete=models.CASCADE)
# service_ssh = models.BooleanField(default=True)
# service_netconf = models.BooleanField(default=True)
# local_aut_num = models.ForeignKey('bgp.aut_num', on_delete=models.CASCADE)
#
# def ldp_exists(self):
# return self.interface_set.filter(logical_interface__ldp=True).exists()
#
# def __str__(self):
# return self.hostname
#
# class interface(models.Model):
# """
# Interface - Physical network interface, may contain multiple logical interfaces.
# router: Router that the interface is tied to.
# name: Name of the actual interface, on the target platform. [et-1/0/0]
# description: A quick sentence or details on what this interface holds. (optional) [An ethernet interface]
# mtu: Maximum Transmission Unit, used when needed. [1514]
# dot1q: Enable 802.1Q VLAN Tags on the interface [True]
# Example string: Router1 et-1/0/0
# """
#
# router = models.ForeignKey('router', on_delete=models.CASCADE)
# name = models.CharField(max_length=255)
# description = models.CharField(max_length=1024, blank=True)
# mtu = models.BigIntegerField(default=1514)
# dot1q = models.BooleanField(default=False)
# disabled = models.BooleanField(default=False)
#
# def __str__(self):
# return self.router.hostname + " " + self.name + " (" + self.description + ")"
#
# class logical_interface(models.Model):
# """
# Logical Interface - An abstract instance of a physical interface, usually seperated layer2 protocols (VLANs, DLCIs, etc.)
# interface: The physical interface that this logical interface is tied to.
# name: Actual name of the interface, usually an integer. [1]
# description: A quick sentence or details on what this interface holds. (optional) [An ethernet interface]
# mtu: Maximum Transmission Unit, used when needed. [1500]
# vlan: A VLAN tag ID, used when needed. (optional) [1]
# physical_interface: A boolean value if this logical interface takes up the entire physical interface. [False]
# ldp: A boolean value to set LDP transmit and recieve on the interface. [False]
# inet_dhcp_client: A boolean value for using the interface as a dhcp-client. [False]
# inet6_dhcp_client: A boolean value for using the interface as a dhcpv6-client. [False]
# Example string: Router1 FastEthernet1/0
# Router2 et-1/0/0.100
# """
#
# interface = models.ForeignKey('interface', on_delete=models.CASCADE)
# vrf = models.ForeignKey(
# 'netdevice.vrf',
# on_delete=models.CASCADE,
# null=True,
# blank=True
# )
# name = models.CharField(max_length=255)
# description = models.CharField(max_length=1024, blank=True)
# mtu = models.BigIntegerField(default=1500)
# vlan = models.IntegerField(null=True, blank=True, validators=[MinValueValidator(1),MaxValueValidator(4096)])
# physical_interface = models.BooleanField(default=False)
# ldp = models.BooleanField(default=False)
# inet_dhcp_client = models.BooleanField(default=False)
# inet6_dhcp_client = models.BooleanField(default=False)
# disabled = models.BooleanField(default=False)
#
# def __str__(self):
# if self.physical_interface:
# return self.interface.router.hostname + " " + self.interface.name + " (" + self.description + ")"
# else:
# return self.interface.router.hostname + " " + self.interface.name + "." + self.name + " (" + self.description + ")"
#
# class vrf(models.Model):
# """
# Virtual Routing and Forwarding - multiple co-existing routing instances in
# a single physical router.
#
# vrf_name: The name of this VRF instance.
# vrf_target: String of what the target identifier for the VRF is.
# [target:65000:65000]
#
# Example string: VRF_Name (target:65000:65000)
# """
#
# name = models.CharField(max_length=255)
# target = models.CharField(max_length=255)
#
# def __str__(self):
# return self.name + " (" + self.target + ")"
which might include code, classes, or functions. Output only the next line. | model = logical_interface |
Given the following code snippet before the placeholder: <|code_start|># file: netdevice/forms.py
class RouterForm(forms.ModelForm):
class Meta:
model = router
fields = ('__all__')
class VrfForm(forms.ModelForm):
class Meta:
<|code_end|>
, predict the next line using imports from the current file:
from django import forms
from netdevice.models import router, interface, logical_interface, vrf
and context including class names, function names, and sometimes code from other files:
# Path: netdevice/models.py
# class router(models.Model):
# """
# Router - A network device that moves packets around.
# routing_id: An IP address the router will use as identification and routing decisions. [203.0.113.1]
# hostname: The (DNS) hostname of the router, domain included. [Router1.isp]
# ibgp: Boolean value to build an iBGP mesh with every router in the database. [True]
# network_os: The network operating system and subsequent template this router is tied too.
# service_ssh: Boolean value to enable SSHv2 on the router. [True]
# service_netconf: Boolean value to enable NETCONF on the router. [True]
# local_aut_num: Local autonomous system number for the router.
# Example string: Router1
# """
#
# routing_id = models.GenericIPAddressField(unpack_ipv4=True)
# hostname = models.CharField(max_length=255)
# ibgp = models.BooleanField()
# network_os = models.ForeignKey('network_os', on_delete=models.CASCADE)
# service_ssh = models.BooleanField(default=True)
# service_netconf = models.BooleanField(default=True)
# local_aut_num = models.ForeignKey('bgp.aut_num', on_delete=models.CASCADE)
#
# def ldp_exists(self):
# return self.interface_set.filter(logical_interface__ldp=True).exists()
#
# def __str__(self):
# return self.hostname
#
# class interface(models.Model):
# """
# Interface - Physical network interface, may contain multiple logical interfaces.
# router: Router that the interface is tied to.
# name: Name of the actual interface, on the target platform. [et-1/0/0]
# description: A quick sentence or details on what this interface holds. (optional) [An ethernet interface]
# mtu: Maximum Transmission Unit, used when needed. [1514]
# dot1q: Enable 802.1Q VLAN Tags on the interface [True]
# Example string: Router1 et-1/0/0
# """
#
# router = models.ForeignKey('router', on_delete=models.CASCADE)
# name = models.CharField(max_length=255)
# description = models.CharField(max_length=1024, blank=True)
# mtu = models.BigIntegerField(default=1514)
# dot1q = models.BooleanField(default=False)
# disabled = models.BooleanField(default=False)
#
# def __str__(self):
# return self.router.hostname + " " + self.name + " (" + self.description + ")"
#
# class logical_interface(models.Model):
# """
# Logical Interface - An abstract instance of a physical interface, usually seperated layer2 protocols (VLANs, DLCIs, etc.)
# interface: The physical interface that this logical interface is tied to.
# name: Actual name of the interface, usually an integer. [1]
# description: A quick sentence or details on what this interface holds. (optional) [An ethernet interface]
# mtu: Maximum Transmission Unit, used when needed. [1500]
# vlan: A VLAN tag ID, used when needed. (optional) [1]
# physical_interface: A boolean value if this logical interface takes up the entire physical interface. [False]
# ldp: A boolean value to set LDP transmit and recieve on the interface. [False]
# inet_dhcp_client: A boolean value for using the interface as a dhcp-client. [False]
# inet6_dhcp_client: A boolean value for using the interface as a dhcpv6-client. [False]
# Example string: Router1 FastEthernet1/0
# Router2 et-1/0/0.100
# """
#
# interface = models.ForeignKey('interface', on_delete=models.CASCADE)
# vrf = models.ForeignKey(
# 'netdevice.vrf',
# on_delete=models.CASCADE,
# null=True,
# blank=True
# )
# name = models.CharField(max_length=255)
# description = models.CharField(max_length=1024, blank=True)
# mtu = models.BigIntegerField(default=1500)
# vlan = models.IntegerField(null=True, blank=True, validators=[MinValueValidator(1),MaxValueValidator(4096)])
# physical_interface = models.BooleanField(default=False)
# ldp = models.BooleanField(default=False)
# inet_dhcp_client = models.BooleanField(default=False)
# inet6_dhcp_client = models.BooleanField(default=False)
# disabled = models.BooleanField(default=False)
#
# def __str__(self):
# if self.physical_interface:
# return self.interface.router.hostname + " " + self.interface.name + " (" + self.description + ")"
# else:
# return self.interface.router.hostname + " " + self.interface.name + "." + self.name + " (" + self.description + ")"
#
# class vrf(models.Model):
# """
# Virtual Routing and Forwarding - multiple co-existing routing instances in
# a single physical router.
#
# vrf_name: The name of this VRF instance.
# vrf_target: String of what the target identifier for the VRF is.
# [target:65000:65000]
#
# Example string: VRF_Name (target:65000:65000)
# """
#
# name = models.CharField(max_length=255)
# target = models.CharField(max_length=255)
#
# def __str__(self):
# return self.name + " (" + self.target + ")"
. Output only the next line. | model = vrf |
Using the snippet: <|code_start|># file: netdevice/serializers.py
class LogicalInterfaceSerializer(serializers.ModelSerializer):
class Meta:
model = logical_interface
fields = ('__all__')
class InterfaceSerializer(serializers.ModelSerializer):
class Meta:
<|code_end|>
, determine the next line of code. You have imports:
from rest_framework import serializers
from .models import logical_interface, interface, router, network_os, vrf
and context (class names, function names, or code) available:
# Path: netdevice/models.py
# class logical_interface(models.Model):
# """
# Logical Interface - An abstract instance of a physical interface, usually seperated layer2 protocols (VLANs, DLCIs, etc.)
# interface: The physical interface that this logical interface is tied to.
# name: Actual name of the interface, usually an integer. [1]
# description: A quick sentence or details on what this interface holds. (optional) [An ethernet interface]
# mtu: Maximum Transmission Unit, used when needed. [1500]
# vlan: A VLAN tag ID, used when needed. (optional) [1]
# physical_interface: A boolean value if this logical interface takes up the entire physical interface. [False]
# ldp: A boolean value to set LDP transmit and recieve on the interface. [False]
# inet_dhcp_client: A boolean value for using the interface as a dhcp-client. [False]
# inet6_dhcp_client: A boolean value for using the interface as a dhcpv6-client. [False]
# Example string: Router1 FastEthernet1/0
# Router2 et-1/0/0.100
# """
#
# interface = models.ForeignKey('interface', on_delete=models.CASCADE)
# vrf = models.ForeignKey(
# 'netdevice.vrf',
# on_delete=models.CASCADE,
# null=True,
# blank=True
# )
# name = models.CharField(max_length=255)
# description = models.CharField(max_length=1024, blank=True)
# mtu = models.BigIntegerField(default=1500)
# vlan = models.IntegerField(null=True, blank=True, validators=[MinValueValidator(1),MaxValueValidator(4096)])
# physical_interface = models.BooleanField(default=False)
# ldp = models.BooleanField(default=False)
# inet_dhcp_client = models.BooleanField(default=False)
# inet6_dhcp_client = models.BooleanField(default=False)
# disabled = models.BooleanField(default=False)
#
# def __str__(self):
# if self.physical_interface:
# return self.interface.router.hostname + " " + self.interface.name + " (" + self.description + ")"
# else:
# return self.interface.router.hostname + " " + self.interface.name + "." + self.name + " (" + self.description + ")"
#
# class interface(models.Model):
# """
# Interface - Physical network interface, may contain multiple logical interfaces.
# router: Router that the interface is tied to.
# name: Name of the actual interface, on the target platform. [et-1/0/0]
# description: A quick sentence or details on what this interface holds. (optional) [An ethernet interface]
# mtu: Maximum Transmission Unit, used when needed. [1514]
# dot1q: Enable 802.1Q VLAN Tags on the interface [True]
# Example string: Router1 et-1/0/0
# """
#
# router = models.ForeignKey('router', on_delete=models.CASCADE)
# name = models.CharField(max_length=255)
# description = models.CharField(max_length=1024, blank=True)
# mtu = models.BigIntegerField(default=1514)
# dot1q = models.BooleanField(default=False)
# disabled = models.BooleanField(default=False)
#
# def __str__(self):
# return self.router.hostname + " " + self.name + " (" + self.description + ")"
#
# class router(models.Model):
# """
# Router - A network device that moves packets around.
# routing_id: An IP address the router will use as identification and routing decisions. [203.0.113.1]
# hostname: The (DNS) hostname of the router, domain included. [Router1.isp]
# ibgp: Boolean value to build an iBGP mesh with every router in the database. [True]
# network_os: The network operating system and subsequent template this router is tied too.
# service_ssh: Boolean value to enable SSHv2 on the router. [True]
# service_netconf: Boolean value to enable NETCONF on the router. [True]
# local_aut_num: Local autonomous system number for the router.
# Example string: Router1
# """
#
# routing_id = models.GenericIPAddressField(unpack_ipv4=True)
# hostname = models.CharField(max_length=255)
# ibgp = models.BooleanField()
# network_os = models.ForeignKey('network_os', on_delete=models.CASCADE)
# service_ssh = models.BooleanField(default=True)
# service_netconf = models.BooleanField(default=True)
# local_aut_num = models.ForeignKey('bgp.aut_num', on_delete=models.CASCADE)
#
# def ldp_exists(self):
# return self.interface_set.filter(logical_interface__ldp=True).exists()
#
# def __str__(self):
# return self.hostname
#
# class network_os(models.Model):
# """
# Network Operating Systems - The software platform which runs networking focused hardware.
# name: The name of the NOS, and the template file to build the configuration with. [junos]
# mgmt_interface_name: Name prefix for platform management interfaces. [fxp]
# Example string: junos
# ios-12
# ios-xe
# """
#
# name = models.CharField(max_length=255)
# mgmt_interface_name = models.CharField(max_length=255, null=True, blank=True)
#
# def __str__(self):
# return self.name
#
# class vrf(models.Model):
# """
# Virtual Routing and Forwarding - multiple co-existing routing instances in
# a single physical router.
#
# vrf_name: The name of this VRF instance.
# vrf_target: String of what the target identifier for the VRF is.
# [target:65000:65000]
#
# Example string: VRF_Name (target:65000:65000)
# """
#
# name = models.CharField(max_length=255)
# target = models.CharField(max_length=255)
#
# def __str__(self):
# return self.name + " (" + self.target + ")"
. Output only the next line. | model = interface |
Predict the next line after this snippet: <|code_start|># file: op_webgui/urls.py
app_name = 'op_webgui'
urlpatterns = [
url(
r'^$',
<|code_end|>
using the current file's imports:
from django.conf.urls import url
from django.contrib.auth import views as auth_views
from op_webgui import views
and any relevant context from other files:
# Path: op_webgui/views.py
# def index(request):
# def router_list(request):
. Output only the next line. | views.index, |
Based on the snippet: <|code_start|># file: static/forms.py
class IPv6StaticForm(forms.ModelForm):
class Meta:
model = ipv6_static
fields = ('__all__')
class IPv4StaticForm(forms.ModelForm):
class Meta:
<|code_end|>
, predict the immediate next line with the help of imports:
from django import forms
from static.models import ipv6_static, ipv4_static
and context (classes, functions, sometimes code) from other files:
# Path: static/models.py
# class ipv6_static(models.Model):
# """
# IPv6 Static Routes - Routes set by the user in a given router.
#
# router: The router to place this static route.
# network: The network address of the route. [2001:db8::]
# cidr: The CIDR length of this static route. [64]
# next-hop: Next-hop device of this static route. [2001:db8:1:1::1]
#
# Example string: Router1 2001:db8:: next-hop 2001:db8:1:1::1
# """
#
# router = models.ForeignKey('netdevice.router', on_delete=models.CASCADE, null=True, blank=True)
# vrf = models.ForeignKey(
# 'netdevice.vrf',
# on_delete=models.CASCADE,
# null=True,
# blank=True
# )
# network = models.GenericIPAddressField(unpack_ipv4=False)
# cidr = models.PositiveSmallIntegerField(default=64)
# next_hop = models.GenericIPAddressField(unpack_ipv4=True)
#
# def __str__(self):
# return self.router.hostname + " " + str(self.network) + "/" + str(self.cidr) + " next-hop " + str(self.next_hop)
#
# class ipv4_static(models.Model):
# """
# IPv4 Static Routes - Routes set by the user in a given router
#
# router: The router to place this static route.
# network: The network address of the route. [198.51.100.0]
# cidr: The CIDR length of this static route. [24]
# next-hop: Next-hop device of this static route. [198.51.100.1]
#
# Example string: Router1 198.51.100.0/24 next-hop 198.51.100.1
# """
#
# router = models.ForeignKey('netdevice.router', on_delete=models.CASCADE, null=True, blank=True)
# vrf = models.ForeignKey(
# 'netdevice.vrf',
# on_delete=models.CASCADE,
# null=True,
# blank=True
# )
# network = models.GenericIPAddressField(unpack_ipv4=True)
# cidr = models.PositiveSmallIntegerField(default=24)
# next_hop = models.GenericIPAddressField(unpack_ipv4=True)
#
# def subnet_mask(self):
# host_bits = 32 - int(self.cidr)
# netmask = socket.inet_ntoa(struct.pack('!I', (1 << 32) - (1 << host_bits)))
# return netmask
#
# def __str__(self):
# return self.router.hostname + " " + str(self.network) + "/" + str(self.cidr) + " next-hop " + str(self.next_hop)
. Output only the next line. | model = ipv4_static |
Given the code snippet: <|code_start|> def test_index_view_with_no_routers(self):
"""
We want to see an error if there are no routers.
"""
self.client.login(username='test', password='test')
response = self.client.get(reverse('op_webgui:router_list'), follow=True)
self.assertEqual(response.status_code, 200)
self.assertContains(response, "No routers")
self.assertQuerysetEqual(response.context['router_list'], [])
def test_index_view_with_routers(self):
"""
Create a router, then check that the view reflects this.
"""
test_router = create_router('ios')
response = self.client.get(reverse('op_webgui:router_list'))
self.assertQuerysetEqual(
response.context['router_list'], ['<router: test-router>']
)
def test_index_view_with_many_routers(self):
"""
Create a bunch of routers, then verify the view.
"""
nos = network_os.objects.create(name='many-test-os')
local_aut_num = aut_num.objects.create(asn=65000, name='test asn')
new_router_list = []
for i in range(0, 5):
<|code_end|>
, generate the next line using the imports in this file:
from django.test import TestCase
from django.urls import reverse
from django.contrib.auth.models import User
from netdevice.models import router, network_os
from netdevice.tests import create_router
from bgp.models import aut_num
and context (functions, classes, or occasionally code) from other files:
# Path: netdevice/models.py
# class router(models.Model):
# """
# Router - A network device that moves packets around.
# routing_id: An IP address the router will use as identification and routing decisions. [203.0.113.1]
# hostname: The (DNS) hostname of the router, domain included. [Router1.isp]
# ibgp: Boolean value to build an iBGP mesh with every router in the database. [True]
# network_os: The network operating system and subsequent template this router is tied too.
# service_ssh: Boolean value to enable SSHv2 on the router. [True]
# service_netconf: Boolean value to enable NETCONF on the router. [True]
# local_aut_num: Local autonomous system number for the router.
# Example string: Router1
# """
#
# routing_id = models.GenericIPAddressField(unpack_ipv4=True)
# hostname = models.CharField(max_length=255)
# ibgp = models.BooleanField()
# network_os = models.ForeignKey('network_os', on_delete=models.CASCADE)
# service_ssh = models.BooleanField(default=True)
# service_netconf = models.BooleanField(default=True)
# local_aut_num = models.ForeignKey('bgp.aut_num', on_delete=models.CASCADE)
#
# def ldp_exists(self):
# return self.interface_set.filter(logical_interface__ldp=True).exists()
#
# def __str__(self):
# return self.hostname
#
# class network_os(models.Model):
# """
# Network Operating Systems - The software platform which runs networking focused hardware.
# name: The name of the NOS, and the template file to build the configuration with. [junos]
# mgmt_interface_name: Name prefix for platform management interfaces. [fxp]
# Example string: junos
# ios-12
# ios-xe
# """
#
# name = models.CharField(max_length=255)
# mgmt_interface_name = models.CharField(max_length=255, null=True, blank=True)
#
# def __str__(self):
# return self.name
#
# Path: netdevice/tests.py
# def create_router(network_os_name):
# nos = network_os.objects.get(name=network_os_name)
# local_aut_num = aut_num.objects.create(asn=65000, name='Test ASN')
# test_router = router.objects.create(routing_id='1.1.1.1',
# hostname='test-router',
# ibgp=True,
# network_os=nos,
# local_aut_num=local_aut_num,
# )
#
# return test_router
#
# Path: bgp/models.py
# class aut_num(models.Model):
# """
# Autonomous System Number - Used in BGPv4 to represent an
# administrative domain where internet prefixes
# are exchanged.
#
# asn: The actual autonomous system number of someone we neighbor.
# [65000]
# name: A specific company or personal name for the peer.
# [123 ISP Inc.]
# contact: An email address to go along with the name.
# [john.smith@example.com]
#
# Example string: 65000: 123 ISP Inc. (john.smith@example.com)
# """
#
# asn = models.BigIntegerField(unique=False)
# name = models.CharField(max_length=255)
# contact = models.EmailField(blank=True)
# vrf = models.ForeignKey(
# 'netdevice.vrf',
# on_delete=models.CASCADE,
# null=True,
# blank=True
# )
# class Meta:
# unique_together = ("asn", "vrf")
#
# def __str__(self):
# return str(self.asn) + ": " + self.name + " (" + self.contact + ")"
. Output only the next line. | router.objects.create( |
Given the following code snippet before the placeholder: <|code_start|>
class WebGUIViewTests(TestCase):
def setUp(self):
self.client.force_login(User.objects.get_or_create(username='testuser')[0])
def test_index_view_with_no_routers(self):
"""
We want to see an error if there are no routers.
"""
self.client.login(username='test', password='test')
response = self.client.get(reverse('op_webgui:router_list'), follow=True)
self.assertEqual(response.status_code, 200)
self.assertContains(response, "No routers")
self.assertQuerysetEqual(response.context['router_list'], [])
def test_index_view_with_routers(self):
"""
Create a router, then check that the view reflects this.
"""
test_router = create_router('ios')
response = self.client.get(reverse('op_webgui:router_list'))
self.assertQuerysetEqual(
response.context['router_list'], ['<router: test-router>']
)
def test_index_view_with_many_routers(self):
"""
Create a bunch of routers, then verify the view.
"""
<|code_end|>
, predict the next line using imports from the current file:
from django.test import TestCase
from django.urls import reverse
from django.contrib.auth.models import User
from netdevice.models import router, network_os
from netdevice.tests import create_router
from bgp.models import aut_num
and context including class names, function names, and sometimes code from other files:
# Path: netdevice/models.py
# class router(models.Model):
# """
# Router - A network device that moves packets around.
# routing_id: An IP address the router will use as identification and routing decisions. [203.0.113.1]
# hostname: The (DNS) hostname of the router, domain included. [Router1.isp]
# ibgp: Boolean value to build an iBGP mesh with every router in the database. [True]
# network_os: The network operating system and subsequent template this router is tied too.
# service_ssh: Boolean value to enable SSHv2 on the router. [True]
# service_netconf: Boolean value to enable NETCONF on the router. [True]
# local_aut_num: Local autonomous system number for the router.
# Example string: Router1
# """
#
# routing_id = models.GenericIPAddressField(unpack_ipv4=True)
# hostname = models.CharField(max_length=255)
# ibgp = models.BooleanField()
# network_os = models.ForeignKey('network_os', on_delete=models.CASCADE)
# service_ssh = models.BooleanField(default=True)
# service_netconf = models.BooleanField(default=True)
# local_aut_num = models.ForeignKey('bgp.aut_num', on_delete=models.CASCADE)
#
# def ldp_exists(self):
# return self.interface_set.filter(logical_interface__ldp=True).exists()
#
# def __str__(self):
# return self.hostname
#
# class network_os(models.Model):
# """
# Network Operating Systems - The software platform which runs networking focused hardware.
# name: The name of the NOS, and the template file to build the configuration with. [junos]
# mgmt_interface_name: Name prefix for platform management interfaces. [fxp]
# Example string: junos
# ios-12
# ios-xe
# """
#
# name = models.CharField(max_length=255)
# mgmt_interface_name = models.CharField(max_length=255, null=True, blank=True)
#
# def __str__(self):
# return self.name
#
# Path: netdevice/tests.py
# def create_router(network_os_name):
# nos = network_os.objects.get(name=network_os_name)
# local_aut_num = aut_num.objects.create(asn=65000, name='Test ASN')
# test_router = router.objects.create(routing_id='1.1.1.1',
# hostname='test-router',
# ibgp=True,
# network_os=nos,
# local_aut_num=local_aut_num,
# )
#
# return test_router
#
# Path: bgp/models.py
# class aut_num(models.Model):
# """
# Autonomous System Number - Used in BGPv4 to represent an
# administrative domain where internet prefixes
# are exchanged.
#
# asn: The actual autonomous system number of someone we neighbor.
# [65000]
# name: A specific company or personal name for the peer.
# [123 ISP Inc.]
# contact: An email address to go along with the name.
# [john.smith@example.com]
#
# Example string: 65000: 123 ISP Inc. (john.smith@example.com)
# """
#
# asn = models.BigIntegerField(unique=False)
# name = models.CharField(max_length=255)
# contact = models.EmailField(blank=True)
# vrf = models.ForeignKey(
# 'netdevice.vrf',
# on_delete=models.CASCADE,
# null=True,
# blank=True
# )
# class Meta:
# unique_together = ("asn", "vrf")
#
# def __str__(self):
# return str(self.asn) + ": " + self.name + " (" + self.contact + ")"
. Output only the next line. | nos = network_os.objects.create(name='many-test-os') |
Given the code snippet: <|code_start|># file: op_webgui/tests.py
class WebGUIViewTests(TestCase):
def setUp(self):
self.client.force_login(User.objects.get_or_create(username='testuser')[0])
def test_index_view_with_no_routers(self):
"""
We want to see an error if there are no routers.
"""
self.client.login(username='test', password='test')
response = self.client.get(reverse('op_webgui:router_list'), follow=True)
self.assertEqual(response.status_code, 200)
self.assertContains(response, "No routers")
self.assertQuerysetEqual(response.context['router_list'], [])
def test_index_view_with_routers(self):
"""
Create a router, then check that the view reflects this.
"""
<|code_end|>
, generate the next line using the imports in this file:
from django.test import TestCase
from django.urls import reverse
from django.contrib.auth.models import User
from netdevice.models import router, network_os
from netdevice.tests import create_router
from bgp.models import aut_num
and context (functions, classes, or occasionally code) from other files:
# Path: netdevice/models.py
# class router(models.Model):
# """
# Router - A network device that moves packets around.
# routing_id: An IP address the router will use as identification and routing decisions. [203.0.113.1]
# hostname: The (DNS) hostname of the router, domain included. [Router1.isp]
# ibgp: Boolean value to build an iBGP mesh with every router in the database. [True]
# network_os: The network operating system and subsequent template this router is tied too.
# service_ssh: Boolean value to enable SSHv2 on the router. [True]
# service_netconf: Boolean value to enable NETCONF on the router. [True]
# local_aut_num: Local autonomous system number for the router.
# Example string: Router1
# """
#
# routing_id = models.GenericIPAddressField(unpack_ipv4=True)
# hostname = models.CharField(max_length=255)
# ibgp = models.BooleanField()
# network_os = models.ForeignKey('network_os', on_delete=models.CASCADE)
# service_ssh = models.BooleanField(default=True)
# service_netconf = models.BooleanField(default=True)
# local_aut_num = models.ForeignKey('bgp.aut_num', on_delete=models.CASCADE)
#
# def ldp_exists(self):
# return self.interface_set.filter(logical_interface__ldp=True).exists()
#
# def __str__(self):
# return self.hostname
#
# class network_os(models.Model):
# """
# Network Operating Systems - The software platform which runs networking focused hardware.
# name: The name of the NOS, and the template file to build the configuration with. [junos]
# mgmt_interface_name: Name prefix for platform management interfaces. [fxp]
# Example string: junos
# ios-12
# ios-xe
# """
#
# name = models.CharField(max_length=255)
# mgmt_interface_name = models.CharField(max_length=255, null=True, blank=True)
#
# def __str__(self):
# return self.name
#
# Path: netdevice/tests.py
# def create_router(network_os_name):
# nos = network_os.objects.get(name=network_os_name)
# local_aut_num = aut_num.objects.create(asn=65000, name='Test ASN')
# test_router = router.objects.create(routing_id='1.1.1.1',
# hostname='test-router',
# ibgp=True,
# network_os=nos,
# local_aut_num=local_aut_num,
# )
#
# return test_router
#
# Path: bgp/models.py
# class aut_num(models.Model):
# """
# Autonomous System Number - Used in BGPv4 to represent an
# administrative domain where internet prefixes
# are exchanged.
#
# asn: The actual autonomous system number of someone we neighbor.
# [65000]
# name: A specific company or personal name for the peer.
# [123 ISP Inc.]
# contact: An email address to go along with the name.
# [john.smith@example.com]
#
# Example string: 65000: 123 ISP Inc. (john.smith@example.com)
# """
#
# asn = models.BigIntegerField(unique=False)
# name = models.CharField(max_length=255)
# contact = models.EmailField(blank=True)
# vrf = models.ForeignKey(
# 'netdevice.vrf',
# on_delete=models.CASCADE,
# null=True,
# blank=True
# )
# class Meta:
# unique_together = ("asn", "vrf")
#
# def __str__(self):
# return str(self.asn) + ": " + self.name + " (" + self.contact + ")"
. Output only the next line. | test_router = create_router('ios') |
Continue the code snippet: <|code_start|>class WebGUIViewTests(TestCase):
def setUp(self):
self.client.force_login(User.objects.get_or_create(username='testuser')[0])
def test_index_view_with_no_routers(self):
"""
We want to see an error if there are no routers.
"""
self.client.login(username='test', password='test')
response = self.client.get(reverse('op_webgui:router_list'), follow=True)
self.assertEqual(response.status_code, 200)
self.assertContains(response, "No routers")
self.assertQuerysetEqual(response.context['router_list'], [])
def test_index_view_with_routers(self):
"""
Create a router, then check that the view reflects this.
"""
test_router = create_router('ios')
response = self.client.get(reverse('op_webgui:router_list'))
self.assertQuerysetEqual(
response.context['router_list'], ['<router: test-router>']
)
def test_index_view_with_many_routers(self):
"""
Create a bunch of routers, then verify the view.
"""
nos = network_os.objects.create(name='many-test-os')
<|code_end|>
. Use current file imports:
from django.test import TestCase
from django.urls import reverse
from django.contrib.auth.models import User
from netdevice.models import router, network_os
from netdevice.tests import create_router
from bgp.models import aut_num
and context (classes, functions, or code) from other files:
# Path: netdevice/models.py
# class router(models.Model):
# """
# Router - A network device that moves packets around.
# routing_id: An IP address the router will use as identification and routing decisions. [203.0.113.1]
# hostname: The (DNS) hostname of the router, domain included. [Router1.isp]
# ibgp: Boolean value to build an iBGP mesh with every router in the database. [True]
# network_os: The network operating system and subsequent template this router is tied too.
# service_ssh: Boolean value to enable SSHv2 on the router. [True]
# service_netconf: Boolean value to enable NETCONF on the router. [True]
# local_aut_num: Local autonomous system number for the router.
# Example string: Router1
# """
#
# routing_id = models.GenericIPAddressField(unpack_ipv4=True)
# hostname = models.CharField(max_length=255)
# ibgp = models.BooleanField()
# network_os = models.ForeignKey('network_os', on_delete=models.CASCADE)
# service_ssh = models.BooleanField(default=True)
# service_netconf = models.BooleanField(default=True)
# local_aut_num = models.ForeignKey('bgp.aut_num', on_delete=models.CASCADE)
#
# def ldp_exists(self):
# return self.interface_set.filter(logical_interface__ldp=True).exists()
#
# def __str__(self):
# return self.hostname
#
# class network_os(models.Model):
# """
# Network Operating Systems - The software platform which runs networking focused hardware.
# name: The name of the NOS, and the template file to build the configuration with. [junos]
# mgmt_interface_name: Name prefix for platform management interfaces. [fxp]
# Example string: junos
# ios-12
# ios-xe
# """
#
# name = models.CharField(max_length=255)
# mgmt_interface_name = models.CharField(max_length=255, null=True, blank=True)
#
# def __str__(self):
# return self.name
#
# Path: netdevice/tests.py
# def create_router(network_os_name):
# nos = network_os.objects.get(name=network_os_name)
# local_aut_num = aut_num.objects.create(asn=65000, name='Test ASN')
# test_router = router.objects.create(routing_id='1.1.1.1',
# hostname='test-router',
# ibgp=True,
# network_os=nos,
# local_aut_num=local_aut_num,
# )
#
# return test_router
#
# Path: bgp/models.py
# class aut_num(models.Model):
# """
# Autonomous System Number - Used in BGPv4 to represent an
# administrative domain where internet prefixes
# are exchanged.
#
# asn: The actual autonomous system number of someone we neighbor.
# [65000]
# name: A specific company or personal name for the peer.
# [123 ISP Inc.]
# contact: An email address to go along with the name.
# [john.smith@example.com]
#
# Example string: 65000: 123 ISP Inc. (john.smith@example.com)
# """
#
# asn = models.BigIntegerField(unique=False)
# name = models.CharField(max_length=255)
# contact = models.EmailField(blank=True)
# vrf = models.ForeignKey(
# 'netdevice.vrf',
# on_delete=models.CASCADE,
# null=True,
# blank=True
# )
# class Meta:
# unique_together = ("asn", "vrf")
#
# def __str__(self):
# return str(self.asn) + ": " + self.name + " (" + self.contact + ")"
. Output only the next line. | local_aut_num = aut_num.objects.create(asn=65000, name='test asn') |
Here is a snippet: <|code_start|># file: api/urls.py
app_name = 'api'
urlpatterns = [
url(
r'^routers/$',
<|code_end|>
. Write the next line using the current file imports:
from django.conf.urls import url
from rest_framework.urlpatterns import format_suffix_patterns
from api import views
and context from other files:
# Path: api/views.py
# class RouterList(generics.ListCreateAPIView):
# class RouterDetail(generics.RetrieveUpdateDestroyAPIView):
# class NetworkOsList(generics.ListCreateAPIView):
# class NetworkOsDetail(generics.RetrieveUpdateDestroyAPIView):
# class InterfaceList(generics.ListCreateAPIView):
# class InterfaceDetail(generics.RetrieveUpdateDestroyAPIView):
# class LogicalInterfaceList(generics.ListCreateAPIView):
# class LogicalInterfaceDetail(generics.RetrieveUpdateDestroyAPIView):
# class Ipv6AddressList(generics.ListCreateAPIView):
# class Ipv6AddressDetail(generics.RetrieveUpdateDestroyAPIView):
# class Ipv4AddressList(generics.ListCreateAPIView):
# class Ipv4AddressDetail(generics.RetrieveUpdateDestroyAPIView):
# class Ipv6StaticList(generics.ListCreateAPIView):
# class Ipv6StaticDetail(generics.RetrieveUpdateDestroyAPIView):
# class Ipv4StaticList(generics.ListCreateAPIView):
# class Ipv4StaticDetail(generics.RetrieveUpdateDestroyAPIView):
# class AutNumList(generics.ListCreateAPIView):
# class AutNumDetail(generics.RetrieveUpdateDestroyAPIView):
# class NeighborList(generics.ListCreateAPIView):
# class NeighborDetail(generics.RetrieveUpdateDestroyAPIView):
, which may include functions, classes, or code. Output only the next line. | views.RouterList.as_view(), |
Based on the snippet: <|code_start|># file: op_webgui/views.py
def index(request):
info = {}
info['router_count'] = router.objects.count()
<|code_end|>
, predict the immediate next line with the help of imports:
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.shortcuts import get_object_or_404, render, redirect
from bgp.models import aut_num
from netdevice.models import router
and context (classes, functions, sometimes code) from other files:
# Path: bgp/models.py
# class aut_num(models.Model):
# """
# Autonomous System Number - Used in BGPv4 to represent an
# administrative domain where internet prefixes
# are exchanged.
#
# asn: The actual autonomous system number of someone we neighbor.
# [65000]
# name: A specific company or personal name for the peer.
# [123 ISP Inc.]
# contact: An email address to go along with the name.
# [john.smith@example.com]
#
# Example string: 65000: 123 ISP Inc. (john.smith@example.com)
# """
#
# asn = models.BigIntegerField(unique=False)
# name = models.CharField(max_length=255)
# contact = models.EmailField(blank=True)
# vrf = models.ForeignKey(
# 'netdevice.vrf',
# on_delete=models.CASCADE,
# null=True,
# blank=True
# )
# class Meta:
# unique_together = ("asn", "vrf")
#
# def __str__(self):
# return str(self.asn) + ": " + self.name + " (" + self.contact + ")"
#
# Path: netdevice/models.py
# class router(models.Model):
# """
# Router - A network device that moves packets around.
# routing_id: An IP address the router will use as identification and routing decisions. [203.0.113.1]
# hostname: The (DNS) hostname of the router, domain included. [Router1.isp]
# ibgp: Boolean value to build an iBGP mesh with every router in the database. [True]
# network_os: The network operating system and subsequent template this router is tied too.
# service_ssh: Boolean value to enable SSHv2 on the router. [True]
# service_netconf: Boolean value to enable NETCONF on the router. [True]
# local_aut_num: Local autonomous system number for the router.
# Example string: Router1
# """
#
# routing_id = models.GenericIPAddressField(unpack_ipv4=True)
# hostname = models.CharField(max_length=255)
# ibgp = models.BooleanField()
# network_os = models.ForeignKey('network_os', on_delete=models.CASCADE)
# service_ssh = models.BooleanField(default=True)
# service_netconf = models.BooleanField(default=True)
# local_aut_num = models.ForeignKey('bgp.aut_num', on_delete=models.CASCADE)
#
# def ldp_exists(self):
# return self.interface_set.filter(logical_interface__ldp=True).exists()
#
# def __str__(self):
# return self.hostname
. Output only the next line. | info['asn_count'] = aut_num.objects.count() |
Predict the next line for this snippet: <|code_start|># file: address/urls.py
app_name = 'static'
urlpatterns = [
url(
r'^(?P<router_id>[0-9]+)/create/ipv6_static/$',
<|code_end|>
with the help of current file imports:
from django.conf.urls import url
from django.contrib.auth import views as auth_views
from static import views
and context from other files:
# Path: static/views.py
# def ipv6_static_create(request, router_id):
# def ipv6_static_edit(request, ipv6_static_id):
# def ipv4_static_create(request, router_id):
# def ipv4_static_edit(request, ipv4_static_id):
, which may contain function names, class names, or code. Output only the next line. | views.ipv6_static_create, |
Predict the next line for this snippet: <|code_start|>
def create_aut_num(asn):
test_asn = aut_num.objects.create(asn=asn,
name='Test ASN',
contact='test@test.com',
)
return test_asn
def create_neighbor(test_router, aut_num, peer_ip):
test_neighbor = neighbor.objects.create(router=test_router,
aut_num=aut_num,
peer_ip=peer_ip,
soft_inbound=True,
)
return test_neighbor
class AddressViewTests(TestCase):
def setUp(self):
test_user = User.objects.get_or_create(username='testuser')[0]
self.client.force_login(test_user)
def test_config_view_with_one_ios_neighbor(self):
"""
Create a test IOS router, with one ipv4 and one ipv6 neighbors
then check config view.
"""
<|code_end|>
with the help of current file imports:
from django.test import TestCase
from django.urls import reverse
from django.contrib.auth.models import User
from netdevice.tests import create_router, create_interface
from bgp.models import aut_num, neighbor
and context from other files:
# Path: netdevice/tests.py
# def create_router(network_os_name):
# nos = network_os.objects.get(name=network_os_name)
# local_aut_num = aut_num.objects.create(asn=65000, name='Test ASN')
# test_router = router.objects.create(routing_id='1.1.1.1',
# hostname='test-router',
# ibgp=True,
# network_os=nos,
# local_aut_num=local_aut_num,
# )
#
# return test_router
#
# def create_interface(test_router):
# test_interface = interface.objects.create(router=test_router,
# name='ge-0/0/0',
# description="A test description.",
# mtu=9000,
# dot1q=True,
# )
#
# test_logical_interface = logical_interface.objects.create(interface=test_interface,
# name='10',
# description="A logical test description.",
# mtu=4170,
# vlan=10,
# physical_interface=False,
# ldp=True,
# inet_dhcp_client=False,
# inet6_dhcp_client=False,
# )
#
# return test_logical_interface
#
# Path: bgp/models.py
# class aut_num(models.Model):
# """
# Autonomous System Number - Used in BGPv4 to represent an
# administrative domain where internet prefixes
# are exchanged.
#
# asn: The actual autonomous system number of someone we neighbor.
# [65000]
# name: A specific company or personal name for the peer.
# [123 ISP Inc.]
# contact: An email address to go along with the name.
# [john.smith@example.com]
#
# Example string: 65000: 123 ISP Inc. (john.smith@example.com)
# """
#
# asn = models.BigIntegerField(unique=False)
# name = models.CharField(max_length=255)
# contact = models.EmailField(blank=True)
# vrf = models.ForeignKey(
# 'netdevice.vrf',
# on_delete=models.CASCADE,
# null=True,
# blank=True
# )
# class Meta:
# unique_together = ("asn", "vrf")
#
# def __str__(self):
# return str(self.asn) + ": " + self.name + " (" + self.contact + ")"
#
# class neighbor(models.Model):
# """
# BGP Neighbor - Peering sesssions with our neighbors over BGP.
#
# router: Router that the peer session is tied to.
# aut_num: ASN that the peer session is tied to.
# peer_ip: IP Address of BGP neighbor.
# [203.0.113.1]
# soft_inbound: Boolean value for if soft-reconfiguration inbound is
# enabled on the peer session.
# [True]
#
# Example string: PeeringBuddy - Router1 203.0.113.1
# """
#
# router = models.ForeignKey(
# 'netdevice.router',
# on_delete=models.CASCADE
# )
# vrf = models.ForeignKey(
# 'netdevice.vrf',
# on_delete=models.CASCADE,
# null=True,
# blank=True
# )
# aut_num = models.ForeignKey('aut_num', on_delete=models.CASCADE)
# peer_ip = models.GenericIPAddressField(unpack_ipv4=True)
# soft_inbound = models.BooleanField(default=True)
#
# def __str__(self):
# asn_router = self.aut_num.name + " - " + self.router.hostname + " "
# return asn_router + self.peer_ip
, which may contain function names, class names, or code. Output only the next line. | test_router = create_router('ios') |
Continue the code snippet: <|code_start|># file: bgp/tests.py
def create_aut_num(asn):
test_asn = aut_num.objects.create(asn=asn,
name='Test ASN',
contact='test@test.com',
)
return test_asn
def create_neighbor(test_router, aut_num, peer_ip):
<|code_end|>
. Use current file imports:
from django.test import TestCase
from django.urls import reverse
from django.contrib.auth.models import User
from netdevice.tests import create_router, create_interface
from bgp.models import aut_num, neighbor
and context (classes, functions, or code) from other files:
# Path: netdevice/tests.py
# def create_router(network_os_name):
# nos = network_os.objects.get(name=network_os_name)
# local_aut_num = aut_num.objects.create(asn=65000, name='Test ASN')
# test_router = router.objects.create(routing_id='1.1.1.1',
# hostname='test-router',
# ibgp=True,
# network_os=nos,
# local_aut_num=local_aut_num,
# )
#
# return test_router
#
# def create_interface(test_router):
# test_interface = interface.objects.create(router=test_router,
# name='ge-0/0/0',
# description="A test description.",
# mtu=9000,
# dot1q=True,
# )
#
# test_logical_interface = logical_interface.objects.create(interface=test_interface,
# name='10',
# description="A logical test description.",
# mtu=4170,
# vlan=10,
# physical_interface=False,
# ldp=True,
# inet_dhcp_client=False,
# inet6_dhcp_client=False,
# )
#
# return test_logical_interface
#
# Path: bgp/models.py
# class aut_num(models.Model):
# """
# Autonomous System Number - Used in BGPv4 to represent an
# administrative domain where internet prefixes
# are exchanged.
#
# asn: The actual autonomous system number of someone we neighbor.
# [65000]
# name: A specific company or personal name for the peer.
# [123 ISP Inc.]
# contact: An email address to go along with the name.
# [john.smith@example.com]
#
# Example string: 65000: 123 ISP Inc. (john.smith@example.com)
# """
#
# asn = models.BigIntegerField(unique=False)
# name = models.CharField(max_length=255)
# contact = models.EmailField(blank=True)
# vrf = models.ForeignKey(
# 'netdevice.vrf',
# on_delete=models.CASCADE,
# null=True,
# blank=True
# )
# class Meta:
# unique_together = ("asn", "vrf")
#
# def __str__(self):
# return str(self.asn) + ": " + self.name + " (" + self.contact + ")"
#
# class neighbor(models.Model):
# """
# BGP Neighbor - Peering sesssions with our neighbors over BGP.
#
# router: Router that the peer session is tied to.
# aut_num: ASN that the peer session is tied to.
# peer_ip: IP Address of BGP neighbor.
# [203.0.113.1]
# soft_inbound: Boolean value for if soft-reconfiguration inbound is
# enabled on the peer session.
# [True]
#
# Example string: PeeringBuddy - Router1 203.0.113.1
# """
#
# router = models.ForeignKey(
# 'netdevice.router',
# on_delete=models.CASCADE
# )
# vrf = models.ForeignKey(
# 'netdevice.vrf',
# on_delete=models.CASCADE,
# null=True,
# blank=True
# )
# aut_num = models.ForeignKey('aut_num', on_delete=models.CASCADE)
# peer_ip = models.GenericIPAddressField(unpack_ipv4=True)
# soft_inbound = models.BooleanField(default=True)
#
# def __str__(self):
# asn_router = self.aut_num.name + " - " + self.router.hostname + " "
# return asn_router + self.peer_ip
. Output only the next line. | test_neighbor = neighbor.objects.create(router=test_router, |
Given the following code snippet before the placeholder: <|code_start|># file: netdevice/serializers.py
class Ipv6StaticSerializer(serializers.ModelSerializer):
class Meta:
model = ipv6_static
fields = ('__all__')
class Ipv4StaticSerializer(serializers.ModelSerializer):
class Meta:
<|code_end|>
, predict the next line using imports from the current file:
from rest_framework import serializers
from static.models import ipv6_static, ipv4_static
and context including class names, function names, and sometimes code from other files:
# Path: static/models.py
# class ipv6_static(models.Model):
# """
# IPv6 Static Routes - Routes set by the user in a given router.
#
# router: The router to place this static route.
# network: The network address of the route. [2001:db8::]
# cidr: The CIDR length of this static route. [64]
# next-hop: Next-hop device of this static route. [2001:db8:1:1::1]
#
# Example string: Router1 2001:db8:: next-hop 2001:db8:1:1::1
# """
#
# router = models.ForeignKey('netdevice.router', on_delete=models.CASCADE, null=True, blank=True)
# vrf = models.ForeignKey(
# 'netdevice.vrf',
# on_delete=models.CASCADE,
# null=True,
# blank=True
# )
# network = models.GenericIPAddressField(unpack_ipv4=False)
# cidr = models.PositiveSmallIntegerField(default=64)
# next_hop = models.GenericIPAddressField(unpack_ipv4=True)
#
# def __str__(self):
# return self.router.hostname + " " + str(self.network) + "/" + str(self.cidr) + " next-hop " + str(self.next_hop)
#
# class ipv4_static(models.Model):
# """
# IPv4 Static Routes - Routes set by the user in a given router
#
# router: The router to place this static route.
# network: The network address of the route. [198.51.100.0]
# cidr: The CIDR length of this static route. [24]
# next-hop: Next-hop device of this static route. [198.51.100.1]
#
# Example string: Router1 198.51.100.0/24 next-hop 198.51.100.1
# """
#
# router = models.ForeignKey('netdevice.router', on_delete=models.CASCADE, null=True, blank=True)
# vrf = models.ForeignKey(
# 'netdevice.vrf',
# on_delete=models.CASCADE,
# null=True,
# blank=True
# )
# network = models.GenericIPAddressField(unpack_ipv4=True)
# cidr = models.PositiveSmallIntegerField(default=24)
# next_hop = models.GenericIPAddressField(unpack_ipv4=True)
#
# def subnet_mask(self):
# host_bits = 32 - int(self.cidr)
# netmask = socket.inet_ntoa(struct.pack('!I', (1 << 32) - (1 << host_bits)))
# return netmask
#
# def __str__(self):
# return self.router.hostname + " " + str(self.network) + "/" + str(self.cidr) + " next-hop " + str(self.next_hop)
. Output only the next line. | model = ipv4_static |
Next line prediction: <|code_start|># file: netdevice/urls.py
app_name = 'netdevice'
urlpatterns = [
url(
r'^create/router/$',
<|code_end|>
. Use current file imports:
(from django.conf.urls import url
from django.contrib.auth import views as auth_views
from netdevice import views)
and context including class names, function names, or small code snippets from other files:
# Path: netdevice/views.py
# def router_detail(request, router_id):
# def router_create(request):
# def router_edit(request, router_id):
# def router_config(request, router_id):
# def vrf_list(request):
# def vrf_detail(request, vrf_id):
# def vrf_create(request):
# def vrf_edit(request, vrf_id):
# def interface_create(request, router_id):
# def interface_edit(request, interface_id):
# def logical_interface_create(request, interface_id):
# def logical_interface_edit(request, logical_interface_id):
. Output only the next line. | views.router_create, |
Given the code snippet: <|code_start|># file: bgp/forms.py
class ASNForm(forms.ModelForm):
class Meta:
model = aut_num
fields = ('__all__')
class NeighborForm(forms.ModelForm):
class Meta:
<|code_end|>
, generate the next line using the imports in this file:
from django import forms
from bgp.models import aut_num, neighbor
and context (functions, classes, or occasionally code) from other files:
# Path: bgp/models.py
# class aut_num(models.Model):
# """
# Autonomous System Number - Used in BGPv4 to represent an
# administrative domain where internet prefixes
# are exchanged.
#
# asn: The actual autonomous system number of someone we neighbor.
# [65000]
# name: A specific company or personal name for the peer.
# [123 ISP Inc.]
# contact: An email address to go along with the name.
# [john.smith@example.com]
#
# Example string: 65000: 123 ISP Inc. (john.smith@example.com)
# """
#
# asn = models.BigIntegerField(unique=False)
# name = models.CharField(max_length=255)
# contact = models.EmailField(blank=True)
# vrf = models.ForeignKey(
# 'netdevice.vrf',
# on_delete=models.CASCADE,
# null=True,
# blank=True
# )
# class Meta:
# unique_together = ("asn", "vrf")
#
# def __str__(self):
# return str(self.asn) + ": " + self.name + " (" + self.contact + ")"
#
# class neighbor(models.Model):
# """
# BGP Neighbor - Peering sesssions with our neighbors over BGP.
#
# router: Router that the peer session is tied to.
# aut_num: ASN that the peer session is tied to.
# peer_ip: IP Address of BGP neighbor.
# [203.0.113.1]
# soft_inbound: Boolean value for if soft-reconfiguration inbound is
# enabled on the peer session.
# [True]
#
# Example string: PeeringBuddy - Router1 203.0.113.1
# """
#
# router = models.ForeignKey(
# 'netdevice.router',
# on_delete=models.CASCADE
# )
# vrf = models.ForeignKey(
# 'netdevice.vrf',
# on_delete=models.CASCADE,
# null=True,
# blank=True
# )
# aut_num = models.ForeignKey('aut_num', on_delete=models.CASCADE)
# peer_ip = models.GenericIPAddressField(unpack_ipv4=True)
# soft_inbound = models.BooleanField(default=True)
#
# def __str__(self):
# asn_router = self.aut_num.name + " - " + self.router.hostname + " "
# return asn_router + self.peer_ip
. Output only the next line. | model = neighbor |
Predict the next line for this snippet: <|code_start|> }
return render(request, 'bgp/asn_list.html', context)
def aut_num_detail(request, aut_num_id):
aut_num_obj = get_object_or_404(aut_num, pk=aut_num_id)
return render(request, 'bgp/aut_num.html', {'aut_num': aut_num_obj})
def aut_num_create(request):
if request.method == "POST":
form = ASNForm(request.POST)
if form.is_valid():
asn = form.save()
return redirect('bgp:aut_num_detail', aut_num_id=asn.pk)
else:
form = ASNForm()
return render(request, 'op_webgui/generic_edit.html', {'form': form})
def aut_num_edit(request, aut_num_id):
asn = get_object_or_404(aut_num, pk=aut_num_id)
if request.method == "POST":
form = ASNForm(request.POST, instance=asn)
if form.is_valid():
asn = form.save()
return redirect('bgp:aut_num_detail', aut_num_id=asn.pk)
else:
form = ASNForm(instance=asn)
return render(request, 'op_webgui/generic_edit.html', {'form': form})
def neighbor_create(request, router_id):
<|code_end|>
with the help of current file imports:
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.shortcuts import get_object_or_404, render, redirect
from netdevice.models import router
from bgp.models import aut_num, neighbor
from bgp.forms import ASNForm, NeighborForm
and context from other files:
# Path: netdevice/models.py
# class router(models.Model):
# """
# Router - A network device that moves packets around.
# routing_id: An IP address the router will use as identification and routing decisions. [203.0.113.1]
# hostname: The (DNS) hostname of the router, domain included. [Router1.isp]
# ibgp: Boolean value to build an iBGP mesh with every router in the database. [True]
# network_os: The network operating system and subsequent template this router is tied too.
# service_ssh: Boolean value to enable SSHv2 on the router. [True]
# service_netconf: Boolean value to enable NETCONF on the router. [True]
# local_aut_num: Local autonomous system number for the router.
# Example string: Router1
# """
#
# routing_id = models.GenericIPAddressField(unpack_ipv4=True)
# hostname = models.CharField(max_length=255)
# ibgp = models.BooleanField()
# network_os = models.ForeignKey('network_os', on_delete=models.CASCADE)
# service_ssh = models.BooleanField(default=True)
# service_netconf = models.BooleanField(default=True)
# local_aut_num = models.ForeignKey('bgp.aut_num', on_delete=models.CASCADE)
#
# def ldp_exists(self):
# return self.interface_set.filter(logical_interface__ldp=True).exists()
#
# def __str__(self):
# return self.hostname
#
# Path: bgp/models.py
# class aut_num(models.Model):
# """
# Autonomous System Number - Used in BGPv4 to represent an
# administrative domain where internet prefixes
# are exchanged.
#
# asn: The actual autonomous system number of someone we neighbor.
# [65000]
# name: A specific company or personal name for the peer.
# [123 ISP Inc.]
# contact: An email address to go along with the name.
# [john.smith@example.com]
#
# Example string: 65000: 123 ISP Inc. (john.smith@example.com)
# """
#
# asn = models.BigIntegerField(unique=False)
# name = models.CharField(max_length=255)
# contact = models.EmailField(blank=True)
# vrf = models.ForeignKey(
# 'netdevice.vrf',
# on_delete=models.CASCADE,
# null=True,
# blank=True
# )
# class Meta:
# unique_together = ("asn", "vrf")
#
# def __str__(self):
# return str(self.asn) + ": " + self.name + " (" + self.contact + ")"
#
# class neighbor(models.Model):
# """
# BGP Neighbor - Peering sesssions with our neighbors over BGP.
#
# router: Router that the peer session is tied to.
# aut_num: ASN that the peer session is tied to.
# peer_ip: IP Address of BGP neighbor.
# [203.0.113.1]
# soft_inbound: Boolean value for if soft-reconfiguration inbound is
# enabled on the peer session.
# [True]
#
# Example string: PeeringBuddy - Router1 203.0.113.1
# """
#
# router = models.ForeignKey(
# 'netdevice.router',
# on_delete=models.CASCADE
# )
# vrf = models.ForeignKey(
# 'netdevice.vrf',
# on_delete=models.CASCADE,
# null=True,
# blank=True
# )
# aut_num = models.ForeignKey('aut_num', on_delete=models.CASCADE)
# peer_ip = models.GenericIPAddressField(unpack_ipv4=True)
# soft_inbound = models.BooleanField(default=True)
#
# def __str__(self):
# asn_router = self.aut_num.name + " - " + self.router.hostname + " "
# return asn_router + self.peer_ip
#
# Path: bgp/forms.py
# class ASNForm(forms.ModelForm):
#
# class Meta:
# model = aut_num
# fields = ('__all__')
#
# class NeighborForm(forms.ModelForm):
#
# class Meta:
# model = neighbor
# fields = ('__all__')
, which may contain function names, class names, or code. Output only the next line. | router_obj = get_object_or_404(router, pk=router_id) |
Based on the snippet: <|code_start|> if form.is_valid():
asn = form.save()
return redirect('bgp:aut_num_detail', aut_num_id=asn.pk)
else:
form = ASNForm()
return render(request, 'op_webgui/generic_edit.html', {'form': form})
def aut_num_edit(request, aut_num_id):
asn = get_object_or_404(aut_num, pk=aut_num_id)
if request.method == "POST":
form = ASNForm(request.POST, instance=asn)
if form.is_valid():
asn = form.save()
return redirect('bgp:aut_num_detail', aut_num_id=asn.pk)
else:
form = ASNForm(instance=asn)
return render(request, 'op_webgui/generic_edit.html', {'form': form})
def neighbor_create(request, router_id):
router_obj = get_object_or_404(router, pk=router_id)
if request.method == "POST":
form = NeighborForm(request.POST)
if form.is_valid():
neighbor_obj = form.save()
return redirect('netdevice:router_detail', router_id=neighbor_obj.router.pk)
else:
form = NeighborForm(initial={'router': router_obj})
return render(request, 'op_webgui/generic_edit.html', {'form': form})
def neighbor_edit(request, neighbor_id):
<|code_end|>
, predict the immediate next line with the help of imports:
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.shortcuts import get_object_or_404, render, redirect
from netdevice.models import router
from bgp.models import aut_num, neighbor
from bgp.forms import ASNForm, NeighborForm
and context (classes, functions, sometimes code) from other files:
# Path: netdevice/models.py
# class router(models.Model):
# """
# Router - A network device that moves packets around.
# routing_id: An IP address the router will use as identification and routing decisions. [203.0.113.1]
# hostname: The (DNS) hostname of the router, domain included. [Router1.isp]
# ibgp: Boolean value to build an iBGP mesh with every router in the database. [True]
# network_os: The network operating system and subsequent template this router is tied too.
# service_ssh: Boolean value to enable SSHv2 on the router. [True]
# service_netconf: Boolean value to enable NETCONF on the router. [True]
# local_aut_num: Local autonomous system number for the router.
# Example string: Router1
# """
#
# routing_id = models.GenericIPAddressField(unpack_ipv4=True)
# hostname = models.CharField(max_length=255)
# ibgp = models.BooleanField()
# network_os = models.ForeignKey('network_os', on_delete=models.CASCADE)
# service_ssh = models.BooleanField(default=True)
# service_netconf = models.BooleanField(default=True)
# local_aut_num = models.ForeignKey('bgp.aut_num', on_delete=models.CASCADE)
#
# def ldp_exists(self):
# return self.interface_set.filter(logical_interface__ldp=True).exists()
#
# def __str__(self):
# return self.hostname
#
# Path: bgp/models.py
# class aut_num(models.Model):
# """
# Autonomous System Number - Used in BGPv4 to represent an
# administrative domain where internet prefixes
# are exchanged.
#
# asn: The actual autonomous system number of someone we neighbor.
# [65000]
# name: A specific company or personal name for the peer.
# [123 ISP Inc.]
# contact: An email address to go along with the name.
# [john.smith@example.com]
#
# Example string: 65000: 123 ISP Inc. (john.smith@example.com)
# """
#
# asn = models.BigIntegerField(unique=False)
# name = models.CharField(max_length=255)
# contact = models.EmailField(blank=True)
# vrf = models.ForeignKey(
# 'netdevice.vrf',
# on_delete=models.CASCADE,
# null=True,
# blank=True
# )
# class Meta:
# unique_together = ("asn", "vrf")
#
# def __str__(self):
# return str(self.asn) + ": " + self.name + " (" + self.contact + ")"
#
# class neighbor(models.Model):
# """
# BGP Neighbor - Peering sesssions with our neighbors over BGP.
#
# router: Router that the peer session is tied to.
# aut_num: ASN that the peer session is tied to.
# peer_ip: IP Address of BGP neighbor.
# [203.0.113.1]
# soft_inbound: Boolean value for if soft-reconfiguration inbound is
# enabled on the peer session.
# [True]
#
# Example string: PeeringBuddy - Router1 203.0.113.1
# """
#
# router = models.ForeignKey(
# 'netdevice.router',
# on_delete=models.CASCADE
# )
# vrf = models.ForeignKey(
# 'netdevice.vrf',
# on_delete=models.CASCADE,
# null=True,
# blank=True
# )
# aut_num = models.ForeignKey('aut_num', on_delete=models.CASCADE)
# peer_ip = models.GenericIPAddressField(unpack_ipv4=True)
# soft_inbound = models.BooleanField(default=True)
#
# def __str__(self):
# asn_router = self.aut_num.name + " - " + self.router.hostname + " "
# return asn_router + self.peer_ip
#
# Path: bgp/forms.py
# class ASNForm(forms.ModelForm):
#
# class Meta:
# model = aut_num
# fields = ('__all__')
#
# class NeighborForm(forms.ModelForm):
#
# class Meta:
# model = neighbor
# fields = ('__all__')
. Output only the next line. | neighbor_obj = get_object_or_404(neighbor, pk=neighbor_id) |
Given the following code snippet before the placeholder: <|code_start|>
def asn_list(request):
asns = aut_num.objects.order_by('asn')
asn_count = asns.count()
paginator = Paginator(asns, 20)
page = request.GET.get('page')
try:
asn_list = paginator.page(page)
except PageNotAnInteger:
asn_list = paginator.page(1)
except EmptyPage:
asn_list = paginator.page(paginator.num_pages)
context = {
'asn_list': asn_list,
'asn_count': asn_count,
}
return render(request, 'bgp/asn_list.html', context)
def aut_num_detail(request, aut_num_id):
aut_num_obj = get_object_or_404(aut_num, pk=aut_num_id)
return render(request, 'bgp/aut_num.html', {'aut_num': aut_num_obj})
def aut_num_create(request):
if request.method == "POST":
<|code_end|>
, predict the next line using imports from the current file:
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.shortcuts import get_object_or_404, render, redirect
from netdevice.models import router
from bgp.models import aut_num, neighbor
from bgp.forms import ASNForm, NeighborForm
and context including class names, function names, and sometimes code from other files:
# Path: netdevice/models.py
# class router(models.Model):
# """
# Router - A network device that moves packets around.
# routing_id: An IP address the router will use as identification and routing decisions. [203.0.113.1]
# hostname: The (DNS) hostname of the router, domain included. [Router1.isp]
# ibgp: Boolean value to build an iBGP mesh with every router in the database. [True]
# network_os: The network operating system and subsequent template this router is tied too.
# service_ssh: Boolean value to enable SSHv2 on the router. [True]
# service_netconf: Boolean value to enable NETCONF on the router. [True]
# local_aut_num: Local autonomous system number for the router.
# Example string: Router1
# """
#
# routing_id = models.GenericIPAddressField(unpack_ipv4=True)
# hostname = models.CharField(max_length=255)
# ibgp = models.BooleanField()
# network_os = models.ForeignKey('network_os', on_delete=models.CASCADE)
# service_ssh = models.BooleanField(default=True)
# service_netconf = models.BooleanField(default=True)
# local_aut_num = models.ForeignKey('bgp.aut_num', on_delete=models.CASCADE)
#
# def ldp_exists(self):
# return self.interface_set.filter(logical_interface__ldp=True).exists()
#
# def __str__(self):
# return self.hostname
#
# Path: bgp/models.py
# class aut_num(models.Model):
# """
# Autonomous System Number - Used in BGPv4 to represent an
# administrative domain where internet prefixes
# are exchanged.
#
# asn: The actual autonomous system number of someone we neighbor.
# [65000]
# name: A specific company or personal name for the peer.
# [123 ISP Inc.]
# contact: An email address to go along with the name.
# [john.smith@example.com]
#
# Example string: 65000: 123 ISP Inc. (john.smith@example.com)
# """
#
# asn = models.BigIntegerField(unique=False)
# name = models.CharField(max_length=255)
# contact = models.EmailField(blank=True)
# vrf = models.ForeignKey(
# 'netdevice.vrf',
# on_delete=models.CASCADE,
# null=True,
# blank=True
# )
# class Meta:
# unique_together = ("asn", "vrf")
#
# def __str__(self):
# return str(self.asn) + ": " + self.name + " (" + self.contact + ")"
#
# class neighbor(models.Model):
# """
# BGP Neighbor - Peering sesssions with our neighbors over BGP.
#
# router: Router that the peer session is tied to.
# aut_num: ASN that the peer session is tied to.
# peer_ip: IP Address of BGP neighbor.
# [203.0.113.1]
# soft_inbound: Boolean value for if soft-reconfiguration inbound is
# enabled on the peer session.
# [True]
#
# Example string: PeeringBuddy - Router1 203.0.113.1
# """
#
# router = models.ForeignKey(
# 'netdevice.router',
# on_delete=models.CASCADE
# )
# vrf = models.ForeignKey(
# 'netdevice.vrf',
# on_delete=models.CASCADE,
# null=True,
# blank=True
# )
# aut_num = models.ForeignKey('aut_num', on_delete=models.CASCADE)
# peer_ip = models.GenericIPAddressField(unpack_ipv4=True)
# soft_inbound = models.BooleanField(default=True)
#
# def __str__(self):
# asn_router = self.aut_num.name + " - " + self.router.hostname + " "
# return asn_router + self.peer_ip
#
# Path: bgp/forms.py
# class ASNForm(forms.ModelForm):
#
# class Meta:
# model = aut_num
# fields = ('__all__')
#
# class NeighborForm(forms.ModelForm):
#
# class Meta:
# model = neighbor
# fields = ('__all__')
. Output only the next line. | form = ASNForm(request.POST) |
Predict the next line after this snippet: <|code_start|> return render(request, 'bgp/asn_list.html', context)
def aut_num_detail(request, aut_num_id):
aut_num_obj = get_object_or_404(aut_num, pk=aut_num_id)
return render(request, 'bgp/aut_num.html', {'aut_num': aut_num_obj})
def aut_num_create(request):
if request.method == "POST":
form = ASNForm(request.POST)
if form.is_valid():
asn = form.save()
return redirect('bgp:aut_num_detail', aut_num_id=asn.pk)
else:
form = ASNForm()
return render(request, 'op_webgui/generic_edit.html', {'form': form})
def aut_num_edit(request, aut_num_id):
asn = get_object_or_404(aut_num, pk=aut_num_id)
if request.method == "POST":
form = ASNForm(request.POST, instance=asn)
if form.is_valid():
asn = form.save()
return redirect('bgp:aut_num_detail', aut_num_id=asn.pk)
else:
form = ASNForm(instance=asn)
return render(request, 'op_webgui/generic_edit.html', {'form': form})
def neighbor_create(request, router_id):
router_obj = get_object_or_404(router, pk=router_id)
if request.method == "POST":
<|code_end|>
using the current file's imports:
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.shortcuts import get_object_or_404, render, redirect
from netdevice.models import router
from bgp.models import aut_num, neighbor
from bgp.forms import ASNForm, NeighborForm
and any relevant context from other files:
# Path: netdevice/models.py
# class router(models.Model):
# """
# Router - A network device that moves packets around.
# routing_id: An IP address the router will use as identification and routing decisions. [203.0.113.1]
# hostname: The (DNS) hostname of the router, domain included. [Router1.isp]
# ibgp: Boolean value to build an iBGP mesh with every router in the database. [True]
# network_os: The network operating system and subsequent template this router is tied too.
# service_ssh: Boolean value to enable SSHv2 on the router. [True]
# service_netconf: Boolean value to enable NETCONF on the router. [True]
# local_aut_num: Local autonomous system number for the router.
# Example string: Router1
# """
#
# routing_id = models.GenericIPAddressField(unpack_ipv4=True)
# hostname = models.CharField(max_length=255)
# ibgp = models.BooleanField()
# network_os = models.ForeignKey('network_os', on_delete=models.CASCADE)
# service_ssh = models.BooleanField(default=True)
# service_netconf = models.BooleanField(default=True)
# local_aut_num = models.ForeignKey('bgp.aut_num', on_delete=models.CASCADE)
#
# def ldp_exists(self):
# return self.interface_set.filter(logical_interface__ldp=True).exists()
#
# def __str__(self):
# return self.hostname
#
# Path: bgp/models.py
# class aut_num(models.Model):
# """
# Autonomous System Number - Used in BGPv4 to represent an
# administrative domain where internet prefixes
# are exchanged.
#
# asn: The actual autonomous system number of someone we neighbor.
# [65000]
# name: A specific company or personal name for the peer.
# [123 ISP Inc.]
# contact: An email address to go along with the name.
# [john.smith@example.com]
#
# Example string: 65000: 123 ISP Inc. (john.smith@example.com)
# """
#
# asn = models.BigIntegerField(unique=False)
# name = models.CharField(max_length=255)
# contact = models.EmailField(blank=True)
# vrf = models.ForeignKey(
# 'netdevice.vrf',
# on_delete=models.CASCADE,
# null=True,
# blank=True
# )
# class Meta:
# unique_together = ("asn", "vrf")
#
# def __str__(self):
# return str(self.asn) + ": " + self.name + " (" + self.contact + ")"
#
# class neighbor(models.Model):
# """
# BGP Neighbor - Peering sesssions with our neighbors over BGP.
#
# router: Router that the peer session is tied to.
# aut_num: ASN that the peer session is tied to.
# peer_ip: IP Address of BGP neighbor.
# [203.0.113.1]
# soft_inbound: Boolean value for if soft-reconfiguration inbound is
# enabled on the peer session.
# [True]
#
# Example string: PeeringBuddy - Router1 203.0.113.1
# """
#
# router = models.ForeignKey(
# 'netdevice.router',
# on_delete=models.CASCADE
# )
# vrf = models.ForeignKey(
# 'netdevice.vrf',
# on_delete=models.CASCADE,
# null=True,
# blank=True
# )
# aut_num = models.ForeignKey('aut_num', on_delete=models.CASCADE)
# peer_ip = models.GenericIPAddressField(unpack_ipv4=True)
# soft_inbound = models.BooleanField(default=True)
#
# def __str__(self):
# asn_router = self.aut_num.name + " - " + self.router.hostname + " "
# return asn_router + self.peer_ip
#
# Path: bgp/forms.py
# class ASNForm(forms.ModelForm):
#
# class Meta:
# model = aut_num
# fields = ('__all__')
#
# class NeighborForm(forms.ModelForm):
#
# class Meta:
# model = neighbor
# fields = ('__all__')
. Output only the next line. | form = NeighborForm(request.POST) |
Continue the code snippet: <|code_start|># file: address/forms.py
class IPv6AddressForm(forms.ModelForm):
class Meta:
model = ipv6_address
fields = ('__all__')
class IPv4AddressForm(forms.ModelForm):
class Meta:
<|code_end|>
. Use current file imports:
from django import forms
from address.models import ipv6_address, ipv4_address
and context (classes, functions, or code) from other files:
# Path: address/models.py
# class ipv6_address(models.Model):
# """
# IPv6 Addresses - 128 bit Internet Protocol Addresses
# interface: The logical interface the IP is tied to. (optional)
# host: IP Address itself
# [2001:db8:1:1::1]
# cidr: The CIDR (Classless Inter-Domain Routing)
# notation of mask length
# [64]
# Example string: 2001:db8:1:1::1/64
# """
#
# interface = models.ForeignKey(
# 'netdevice.logical_interface',
# on_delete=models.CASCADE,
# null=True,
# blank=True
# )
# host = models.GenericIPAddressField(unpack_ipv4=False)
# cidr = models.PositiveSmallIntegerField(default=64)
#
# def __str__(self):
# return str(self.host) + "/" + str(self.cidr)
#
# class ipv4_address(models.Model):
# """
# IPv4 Addresses - 32 bit Internet Protocol Addresses
# interface: The logical interface the IP is tied to. (optional)
# host: IP Address itself
# [198.51.100.0]
# cidr: The CIDR (Classless Inter-Domain Routing)
# notation of mask length
# [24]
# Example string: 198.51.100.0/24
# """
#
# interface = models.ForeignKey(
# 'netdevice.logical_interface',
# on_delete=models.CASCADE,
# null=True,
# blank=True
# )
# host = models.GenericIPAddressField(unpack_ipv4=True)
# cidr = models.PositiveSmallIntegerField(default=24)
#
# def subnet_mask(self):
# host_bits = 32 - int(self.cidr)
# bitmask = struct.pack('!I', (1 << 32) - (1 << host_bits))
# netmask = socket.inet_ntoa(bitmask)
# return netmask
#
# def __str__(self):
# return str(self.host) + "/" + str(self.cidr)
. Output only the next line. | model = ipv4_address |
Based on the snippet: <|code_start|># file: address/serializers.py
class Ipv6AddressSerializer(serializers.ModelSerializer):
class Meta:
model = ipv6_address
fields = ('__all__')
class Ipv4AddressSerializer(serializers.ModelSerializer):
class Meta:
<|code_end|>
, predict the immediate next line with the help of imports:
from rest_framework import serializers
from address.models import ipv6_address, ipv4_address
and context (classes, functions, sometimes code) from other files:
# Path: address/models.py
# class ipv6_address(models.Model):
# """
# IPv6 Addresses - 128 bit Internet Protocol Addresses
# interface: The logical interface the IP is tied to. (optional)
# host: IP Address itself
# [2001:db8:1:1::1]
# cidr: The CIDR (Classless Inter-Domain Routing)
# notation of mask length
# [64]
# Example string: 2001:db8:1:1::1/64
# """
#
# interface = models.ForeignKey(
# 'netdevice.logical_interface',
# on_delete=models.CASCADE,
# null=True,
# blank=True
# )
# host = models.GenericIPAddressField(unpack_ipv4=False)
# cidr = models.PositiveSmallIntegerField(default=64)
#
# def __str__(self):
# return str(self.host) + "/" + str(self.cidr)
#
# class ipv4_address(models.Model):
# """
# IPv4 Addresses - 32 bit Internet Protocol Addresses
# interface: The logical interface the IP is tied to. (optional)
# host: IP Address itself
# [198.51.100.0]
# cidr: The CIDR (Classless Inter-Domain Routing)
# notation of mask length
# [24]
# Example string: 198.51.100.0/24
# """
#
# interface = models.ForeignKey(
# 'netdevice.logical_interface',
# on_delete=models.CASCADE,
# null=True,
# blank=True
# )
# host = models.GenericIPAddressField(unpack_ipv4=True)
# cidr = models.PositiveSmallIntegerField(default=24)
#
# def subnet_mask(self):
# host_bits = 32 - int(self.cidr)
# bitmask = struct.pack('!I', (1 << 32) - (1 << host_bits))
# netmask = socket.inet_ntoa(bitmask)
# return netmask
#
# def __str__(self):
# return str(self.host) + "/" + str(self.cidr)
. Output only the next line. | model = ipv4_address |
Continue the code snippet: <|code_start|>
def create_v4_static(test_router, network):
v4_route = ipv4_static.objects.create(router=test_router,
network=network,
cidr=16,
next_hop='172.16.0.1',
)
return v4_route
def create_v6_static(test_router, network):
v6_route = ipv6_static.objects.create(router=test_router,
network=network,
cidr=48,
next_hop='2001:db8::1',
)
return v6_route
class StaticViewTest(TestCase):
def setUp(self):
self.client.force_login(User.objects.get_or_create(username='testuser')[0])
def test_config_view_with_a_single_ios_static_route(self):
"""
Create an IOS router, interface, and IP addresses, then check the configuration template output.
"""
<|code_end|>
. Use current file imports:
from django.test import TestCase
from django.urls import reverse
from django.contrib.auth.models import User
from netdevice.tests import create_router
from static.models import ipv6_static, ipv4_static
and context (classes, functions, or code) from other files:
# Path: netdevice/tests.py
# def create_router(network_os_name):
# nos = network_os.objects.get(name=network_os_name)
# local_aut_num = aut_num.objects.create(asn=65000, name='Test ASN')
# test_router = router.objects.create(routing_id='1.1.1.1',
# hostname='test-router',
# ibgp=True,
# network_os=nos,
# local_aut_num=local_aut_num,
# )
#
# return test_router
#
# Path: static/models.py
# class ipv6_static(models.Model):
# """
# IPv6 Static Routes - Routes set by the user in a given router.
#
# router: The router to place this static route.
# network: The network address of the route. [2001:db8::]
# cidr: The CIDR length of this static route. [64]
# next-hop: Next-hop device of this static route. [2001:db8:1:1::1]
#
# Example string: Router1 2001:db8:: next-hop 2001:db8:1:1::1
# """
#
# router = models.ForeignKey('netdevice.router', on_delete=models.CASCADE, null=True, blank=True)
# vrf = models.ForeignKey(
# 'netdevice.vrf',
# on_delete=models.CASCADE,
# null=True,
# blank=True
# )
# network = models.GenericIPAddressField(unpack_ipv4=False)
# cidr = models.PositiveSmallIntegerField(default=64)
# next_hop = models.GenericIPAddressField(unpack_ipv4=True)
#
# def __str__(self):
# return self.router.hostname + " " + str(self.network) + "/" + str(self.cidr) + " next-hop " + str(self.next_hop)
#
# class ipv4_static(models.Model):
# """
# IPv4 Static Routes - Routes set by the user in a given router
#
# router: The router to place this static route.
# network: The network address of the route. [198.51.100.0]
# cidr: The CIDR length of this static route. [24]
# next-hop: Next-hop device of this static route. [198.51.100.1]
#
# Example string: Router1 198.51.100.0/24 next-hop 198.51.100.1
# """
#
# router = models.ForeignKey('netdevice.router', on_delete=models.CASCADE, null=True, blank=True)
# vrf = models.ForeignKey(
# 'netdevice.vrf',
# on_delete=models.CASCADE,
# null=True,
# blank=True
# )
# network = models.GenericIPAddressField(unpack_ipv4=True)
# cidr = models.PositiveSmallIntegerField(default=24)
# next_hop = models.GenericIPAddressField(unpack_ipv4=True)
#
# def subnet_mask(self):
# host_bits = 32 - int(self.cidr)
# netmask = socket.inet_ntoa(struct.pack('!I', (1 << 32) - (1 << host_bits)))
# return netmask
#
# def __str__(self):
# return self.router.hostname + " " + str(self.network) + "/" + str(self.cidr) + " next-hop " + str(self.next_hop)
. Output only the next line. | test_router = create_router('ios') |
Here is a snippet: <|code_start|># file: static/tests.py
def create_v4_static(test_router, network):
v4_route = ipv4_static.objects.create(router=test_router,
network=network,
cidr=16,
next_hop='172.16.0.1',
)
return v4_route
def create_v6_static(test_router, network):
<|code_end|>
. Write the next line using the current file imports:
from django.test import TestCase
from django.urls import reverse
from django.contrib.auth.models import User
from netdevice.tests import create_router
from static.models import ipv6_static, ipv4_static
and context from other files:
# Path: netdevice/tests.py
# def create_router(network_os_name):
# nos = network_os.objects.get(name=network_os_name)
# local_aut_num = aut_num.objects.create(asn=65000, name='Test ASN')
# test_router = router.objects.create(routing_id='1.1.1.1',
# hostname='test-router',
# ibgp=True,
# network_os=nos,
# local_aut_num=local_aut_num,
# )
#
# return test_router
#
# Path: static/models.py
# class ipv6_static(models.Model):
# """
# IPv6 Static Routes - Routes set by the user in a given router.
#
# router: The router to place this static route.
# network: The network address of the route. [2001:db8::]
# cidr: The CIDR length of this static route. [64]
# next-hop: Next-hop device of this static route. [2001:db8:1:1::1]
#
# Example string: Router1 2001:db8:: next-hop 2001:db8:1:1::1
# """
#
# router = models.ForeignKey('netdevice.router', on_delete=models.CASCADE, null=True, blank=True)
# vrf = models.ForeignKey(
# 'netdevice.vrf',
# on_delete=models.CASCADE,
# null=True,
# blank=True
# )
# network = models.GenericIPAddressField(unpack_ipv4=False)
# cidr = models.PositiveSmallIntegerField(default=64)
# next_hop = models.GenericIPAddressField(unpack_ipv4=True)
#
# def __str__(self):
# return self.router.hostname + " " + str(self.network) + "/" + str(self.cidr) + " next-hop " + str(self.next_hop)
#
# class ipv4_static(models.Model):
# """
# IPv4 Static Routes - Routes set by the user in a given router
#
# router: The router to place this static route.
# network: The network address of the route. [198.51.100.0]
# cidr: The CIDR length of this static route. [24]
# next-hop: Next-hop device of this static route. [198.51.100.1]
#
# Example string: Router1 198.51.100.0/24 next-hop 198.51.100.1
# """
#
# router = models.ForeignKey('netdevice.router', on_delete=models.CASCADE, null=True, blank=True)
# vrf = models.ForeignKey(
# 'netdevice.vrf',
# on_delete=models.CASCADE,
# null=True,
# blank=True
# )
# network = models.GenericIPAddressField(unpack_ipv4=True)
# cidr = models.PositiveSmallIntegerField(default=24)
# next_hop = models.GenericIPAddressField(unpack_ipv4=True)
#
# def subnet_mask(self):
# host_bits = 32 - int(self.cidr)
# netmask = socket.inet_ntoa(struct.pack('!I', (1 << 32) - (1 << host_bits)))
# return netmask
#
# def __str__(self):
# return self.router.hostname + " " + str(self.network) + "/" + str(self.cidr) + " next-hop " + str(self.next_hop)
, which may include functions, classes, or code. Output only the next line. | v6_route = ipv6_static.objects.create(router=test_router, |
Given the code snippet: <|code_start|># file: bgp/urls.py
app_name = 'bgp'
urlpatterns = [
url(
r'^asn/$',
<|code_end|>
, generate the next line using the imports in this file:
from django.conf.urls import url
from django.contrib.auth import views as auth_views
from bgp import views
and context (functions, classes, or occasionally code) from other files:
# Path: bgp/views.py
# def asn_list(request):
# def aut_num_detail(request, aut_num_id):
# def aut_num_create(request):
# def aut_num_edit(request, aut_num_id):
# def neighbor_create(request, router_id):
# def neighbor_edit(request, neighbor_id):
. Output only the next line. | views.asn_list, |
Based on the snippet: <|code_start|># file: config_gen/views.py
def index(request):
context = {}
return render(request, 'config_gen/index.html', context)
def router_config(request, router_id):
<|code_end|>
, predict the immediate next line with the help of imports:
from django.shortcuts import get_object_or_404, render
from netdevice.models import router
and context (classes, functions, sometimes code) from other files:
# Path: netdevice/models.py
# class router(models.Model):
# """
# Router - A network device that moves packets around.
# routing_id: An IP address the router will use as identification and routing decisions. [203.0.113.1]
# hostname: The (DNS) hostname of the router, domain included. [Router1.isp]
# ibgp: Boolean value to build an iBGP mesh with every router in the database. [True]
# network_os: The network operating system and subsequent template this router is tied too.
# service_ssh: Boolean value to enable SSHv2 on the router. [True]
# service_netconf: Boolean value to enable NETCONF on the router. [True]
# local_aut_num: Local autonomous system number for the router.
# Example string: Router1
# """
#
# routing_id = models.GenericIPAddressField(unpack_ipv4=True)
# hostname = models.CharField(max_length=255)
# ibgp = models.BooleanField()
# network_os = models.ForeignKey('network_os', on_delete=models.CASCADE)
# service_ssh = models.BooleanField(default=True)
# service_netconf = models.BooleanField(default=True)
# local_aut_num = models.ForeignKey('bgp.aut_num', on_delete=models.CASCADE)
#
# def ldp_exists(self):
# return self.interface_set.filter(logical_interface__ldp=True).exists()
#
# def __str__(self):
# return self.hostname
. Output only the next line. | router_obj = get_object_or_404(router, pk=router_id) |
Predict the next line after this snippet: <|code_start|># file: address/tests.py
def create_v4_address(logical_interface, address):
v4_address = ipv4_address.objects.create(interface=logical_interface,
host=address,
cidr=24,
)
return v4_address
def create_v6_address(logical_interface, address):
v6_address = ipv6_address.objects.create(interface=logical_interface,
host=address,
cidr=64,
)
return v6_address
class AddressViewTests(TestCase):
def setUp(self):
test_user = User.objects.get_or_create(username='testuser')[0]
self.client.force_login(test_user)
def test_config_view_with_one_ios_address(self):
"""
Create a test IOS router, with one ipv4 and one ipv6 address
then check config view.
"""
<|code_end|>
using the current file's imports:
from django.test import TestCase
from django.urls import reverse
from django.contrib.auth.models import User
from netdevice.tests import create_router, create_interface
from address.models import ipv6_address, ipv4_address
and any relevant context from other files:
# Path: netdevice/tests.py
# def create_router(network_os_name):
# nos = network_os.objects.get(name=network_os_name)
# local_aut_num = aut_num.objects.create(asn=65000, name='Test ASN')
# test_router = router.objects.create(routing_id='1.1.1.1',
# hostname='test-router',
# ibgp=True,
# network_os=nos,
# local_aut_num=local_aut_num,
# )
#
# return test_router
#
# def create_interface(test_router):
# test_interface = interface.objects.create(router=test_router,
# name='ge-0/0/0',
# description="A test description.",
# mtu=9000,
# dot1q=True,
# )
#
# test_logical_interface = logical_interface.objects.create(interface=test_interface,
# name='10',
# description="A logical test description.",
# mtu=4170,
# vlan=10,
# physical_interface=False,
# ldp=True,
# inet_dhcp_client=False,
# inet6_dhcp_client=False,
# )
#
# return test_logical_interface
#
# Path: address/models.py
# class ipv6_address(models.Model):
# """
# IPv6 Addresses - 128 bit Internet Protocol Addresses
# interface: The logical interface the IP is tied to. (optional)
# host: IP Address itself
# [2001:db8:1:1::1]
# cidr: The CIDR (Classless Inter-Domain Routing)
# notation of mask length
# [64]
# Example string: 2001:db8:1:1::1/64
# """
#
# interface = models.ForeignKey(
# 'netdevice.logical_interface',
# on_delete=models.CASCADE,
# null=True,
# blank=True
# )
# host = models.GenericIPAddressField(unpack_ipv4=False)
# cidr = models.PositiveSmallIntegerField(default=64)
#
# def __str__(self):
# return str(self.host) + "/" + str(self.cidr)
#
# class ipv4_address(models.Model):
# """
# IPv4 Addresses - 32 bit Internet Protocol Addresses
# interface: The logical interface the IP is tied to. (optional)
# host: IP Address itself
# [198.51.100.0]
# cidr: The CIDR (Classless Inter-Domain Routing)
# notation of mask length
# [24]
# Example string: 198.51.100.0/24
# """
#
# interface = models.ForeignKey(
# 'netdevice.logical_interface',
# on_delete=models.CASCADE,
# null=True,
# blank=True
# )
# host = models.GenericIPAddressField(unpack_ipv4=True)
# cidr = models.PositiveSmallIntegerField(default=24)
#
# def subnet_mask(self):
# host_bits = 32 - int(self.cidr)
# bitmask = struct.pack('!I', (1 << 32) - (1 << host_bits))
# netmask = socket.inet_ntoa(bitmask)
# return netmask
#
# def __str__(self):
# return str(self.host) + "/" + str(self.cidr)
. Output only the next line. | test_router = create_router('ios') |
Next line prediction: <|code_start|>
def create_v4_address(logical_interface, address):
v4_address = ipv4_address.objects.create(interface=logical_interface,
host=address,
cidr=24,
)
return v4_address
def create_v6_address(logical_interface, address):
v6_address = ipv6_address.objects.create(interface=logical_interface,
host=address,
cidr=64,
)
return v6_address
class AddressViewTests(TestCase):
def setUp(self):
test_user = User.objects.get_or_create(username='testuser')[0]
self.client.force_login(test_user)
def test_config_view_with_one_ios_address(self):
"""
Create a test IOS router, with one ipv4 and one ipv6 address
then check config view.
"""
test_router = create_router('ios')
<|code_end|>
. Use current file imports:
(from django.test import TestCase
from django.urls import reverse
from django.contrib.auth.models import User
from netdevice.tests import create_router, create_interface
from address.models import ipv6_address, ipv4_address)
and context including class names, function names, or small code snippets from other files:
# Path: netdevice/tests.py
# def create_router(network_os_name):
# nos = network_os.objects.get(name=network_os_name)
# local_aut_num = aut_num.objects.create(asn=65000, name='Test ASN')
# test_router = router.objects.create(routing_id='1.1.1.1',
# hostname='test-router',
# ibgp=True,
# network_os=nos,
# local_aut_num=local_aut_num,
# )
#
# return test_router
#
# def create_interface(test_router):
# test_interface = interface.objects.create(router=test_router,
# name='ge-0/0/0',
# description="A test description.",
# mtu=9000,
# dot1q=True,
# )
#
# test_logical_interface = logical_interface.objects.create(interface=test_interface,
# name='10',
# description="A logical test description.",
# mtu=4170,
# vlan=10,
# physical_interface=False,
# ldp=True,
# inet_dhcp_client=False,
# inet6_dhcp_client=False,
# )
#
# return test_logical_interface
#
# Path: address/models.py
# class ipv6_address(models.Model):
# """
# IPv6 Addresses - 128 bit Internet Protocol Addresses
# interface: The logical interface the IP is tied to. (optional)
# host: IP Address itself
# [2001:db8:1:1::1]
# cidr: The CIDR (Classless Inter-Domain Routing)
# notation of mask length
# [64]
# Example string: 2001:db8:1:1::1/64
# """
#
# interface = models.ForeignKey(
# 'netdevice.logical_interface',
# on_delete=models.CASCADE,
# null=True,
# blank=True
# )
# host = models.GenericIPAddressField(unpack_ipv4=False)
# cidr = models.PositiveSmallIntegerField(default=64)
#
# def __str__(self):
# return str(self.host) + "/" + str(self.cidr)
#
# class ipv4_address(models.Model):
# """
# IPv4 Addresses - 32 bit Internet Protocol Addresses
# interface: The logical interface the IP is tied to. (optional)
# host: IP Address itself
# [198.51.100.0]
# cidr: The CIDR (Classless Inter-Domain Routing)
# notation of mask length
# [24]
# Example string: 198.51.100.0/24
# """
#
# interface = models.ForeignKey(
# 'netdevice.logical_interface',
# on_delete=models.CASCADE,
# null=True,
# blank=True
# )
# host = models.GenericIPAddressField(unpack_ipv4=True)
# cidr = models.PositiveSmallIntegerField(default=24)
#
# def subnet_mask(self):
# host_bits = 32 - int(self.cidr)
# bitmask = struct.pack('!I', (1 << 32) - (1 << host_bits))
# netmask = socket.inet_ntoa(bitmask)
# return netmask
#
# def __str__(self):
# return str(self.host) + "/" + str(self.cidr)
. Output only the next line. | test_interface = create_interface(test_router) |
Predict the next line after this snippet: <|code_start|># file: address/tests.py
def create_v4_address(logical_interface, address):
v4_address = ipv4_address.objects.create(interface=logical_interface,
host=address,
cidr=24,
)
return v4_address
def create_v6_address(logical_interface, address):
<|code_end|>
using the current file's imports:
from django.test import TestCase
from django.urls import reverse
from django.contrib.auth.models import User
from netdevice.tests import create_router, create_interface
from address.models import ipv6_address, ipv4_address
and any relevant context from other files:
# Path: netdevice/tests.py
# def create_router(network_os_name):
# nos = network_os.objects.get(name=network_os_name)
# local_aut_num = aut_num.objects.create(asn=65000, name='Test ASN')
# test_router = router.objects.create(routing_id='1.1.1.1',
# hostname='test-router',
# ibgp=True,
# network_os=nos,
# local_aut_num=local_aut_num,
# )
#
# return test_router
#
# def create_interface(test_router):
# test_interface = interface.objects.create(router=test_router,
# name='ge-0/0/0',
# description="A test description.",
# mtu=9000,
# dot1q=True,
# )
#
# test_logical_interface = logical_interface.objects.create(interface=test_interface,
# name='10',
# description="A logical test description.",
# mtu=4170,
# vlan=10,
# physical_interface=False,
# ldp=True,
# inet_dhcp_client=False,
# inet6_dhcp_client=False,
# )
#
# return test_logical_interface
#
# Path: address/models.py
# class ipv6_address(models.Model):
# """
# IPv6 Addresses - 128 bit Internet Protocol Addresses
# interface: The logical interface the IP is tied to. (optional)
# host: IP Address itself
# [2001:db8:1:1::1]
# cidr: The CIDR (Classless Inter-Domain Routing)
# notation of mask length
# [64]
# Example string: 2001:db8:1:1::1/64
# """
#
# interface = models.ForeignKey(
# 'netdevice.logical_interface',
# on_delete=models.CASCADE,
# null=True,
# blank=True
# )
# host = models.GenericIPAddressField(unpack_ipv4=False)
# cidr = models.PositiveSmallIntegerField(default=64)
#
# def __str__(self):
# return str(self.host) + "/" + str(self.cidr)
#
# class ipv4_address(models.Model):
# """
# IPv4 Addresses - 32 bit Internet Protocol Addresses
# interface: The logical interface the IP is tied to. (optional)
# host: IP Address itself
# [198.51.100.0]
# cidr: The CIDR (Classless Inter-Domain Routing)
# notation of mask length
# [24]
# Example string: 198.51.100.0/24
# """
#
# interface = models.ForeignKey(
# 'netdevice.logical_interface',
# on_delete=models.CASCADE,
# null=True,
# blank=True
# )
# host = models.GenericIPAddressField(unpack_ipv4=True)
# cidr = models.PositiveSmallIntegerField(default=24)
#
# def subnet_mask(self):
# host_bits = 32 - int(self.cidr)
# bitmask = struct.pack('!I', (1 << 32) - (1 << host_bits))
# netmask = socket.inet_ntoa(bitmask)
# return netmask
#
# def __str__(self):
# return str(self.host) + "/" + str(self.cidr)
. Output only the next line. | v6_address = ipv6_address.objects.create(interface=logical_interface, |
Predict the next line after this snippet: <|code_start|># file: bgp/serializers.py
class AutNumSerializer(serializers.ModelSerializer):
class Meta:
model = aut_num
fields = ('__all__')
class NeighborSerializer(serializers.ModelSerializer):
class Meta:
<|code_end|>
using the current file's imports:
from rest_framework import serializers
from bgp.models import aut_num, neighbor
and any relevant context from other files:
# Path: bgp/models.py
# class aut_num(models.Model):
# """
# Autonomous System Number - Used in BGPv4 to represent an
# administrative domain where internet prefixes
# are exchanged.
#
# asn: The actual autonomous system number of someone we neighbor.
# [65000]
# name: A specific company or personal name for the peer.
# [123 ISP Inc.]
# contact: An email address to go along with the name.
# [john.smith@example.com]
#
# Example string: 65000: 123 ISP Inc. (john.smith@example.com)
# """
#
# asn = models.BigIntegerField(unique=False)
# name = models.CharField(max_length=255)
# contact = models.EmailField(blank=True)
# vrf = models.ForeignKey(
# 'netdevice.vrf',
# on_delete=models.CASCADE,
# null=True,
# blank=True
# )
# class Meta:
# unique_together = ("asn", "vrf")
#
# def __str__(self):
# return str(self.asn) + ": " + self.name + " (" + self.contact + ")"
#
# class neighbor(models.Model):
# """
# BGP Neighbor - Peering sesssions with our neighbors over BGP.
#
# router: Router that the peer session is tied to.
# aut_num: ASN that the peer session is tied to.
# peer_ip: IP Address of BGP neighbor.
# [203.0.113.1]
# soft_inbound: Boolean value for if soft-reconfiguration inbound is
# enabled on the peer session.
# [True]
#
# Example string: PeeringBuddy - Router1 203.0.113.1
# """
#
# router = models.ForeignKey(
# 'netdevice.router',
# on_delete=models.CASCADE
# )
# vrf = models.ForeignKey(
# 'netdevice.vrf',
# on_delete=models.CASCADE,
# null=True,
# blank=True
# )
# aut_num = models.ForeignKey('aut_num', on_delete=models.CASCADE)
# peer_ip = models.GenericIPAddressField(unpack_ipv4=True)
# soft_inbound = models.BooleanField(default=True)
#
# def __str__(self):
# asn_router = self.aut_num.name + " - " + self.router.hostname + " "
# return asn_router + self.peer_ip
. Output only the next line. | model = neighbor |
Predict the next line after this snippet: <|code_start|># file: static/views.py
def ipv6_static_create(request, router_id):
router_obj = get_object_or_404(router, pk=router_id)
if request.method == "POST":
form = IPv6StaticForm(request.POST)
if form.is_valid():
ipv6_static_obj = form.save()
return redirect('netdevice:router_detail', router_id=ipv6_static_obj.router.pk)
else:
form = IPv6StaticForm(initial={'router': router_obj})
return render(request, 'op_webgui/generic_edit.html', {'form': form})
def ipv6_static_edit(request, ipv6_static_id):
<|code_end|>
using the current file's imports:
from django.shortcuts import get_object_or_404, render, redirect
from netdevice.models import router
from static.models import ipv6_static, ipv4_static
from static.forms import IPv6StaticForm, IPv4StaticForm
and any relevant context from other files:
# Path: netdevice/models.py
# class router(models.Model):
# """
# Router - A network device that moves packets around.
# routing_id: An IP address the router will use as identification and routing decisions. [203.0.113.1]
# hostname: The (DNS) hostname of the router, domain included. [Router1.isp]
# ibgp: Boolean value to build an iBGP mesh with every router in the database. [True]
# network_os: The network operating system and subsequent template this router is tied too.
# service_ssh: Boolean value to enable SSHv2 on the router. [True]
# service_netconf: Boolean value to enable NETCONF on the router. [True]
# local_aut_num: Local autonomous system number for the router.
# Example string: Router1
# """
#
# routing_id = models.GenericIPAddressField(unpack_ipv4=True)
# hostname = models.CharField(max_length=255)
# ibgp = models.BooleanField()
# network_os = models.ForeignKey('network_os', on_delete=models.CASCADE)
# service_ssh = models.BooleanField(default=True)
# service_netconf = models.BooleanField(default=True)
# local_aut_num = models.ForeignKey('bgp.aut_num', on_delete=models.CASCADE)
#
# def ldp_exists(self):
# return self.interface_set.filter(logical_interface__ldp=True).exists()
#
# def __str__(self):
# return self.hostname
#
# Path: static/models.py
# class ipv6_static(models.Model):
# """
# IPv6 Static Routes - Routes set by the user in a given router.
#
# router: The router to place this static route.
# network: The network address of the route. [2001:db8::]
# cidr: The CIDR length of this static route. [64]
# next-hop: Next-hop device of this static route. [2001:db8:1:1::1]
#
# Example string: Router1 2001:db8:: next-hop 2001:db8:1:1::1
# """
#
# router = models.ForeignKey('netdevice.router', on_delete=models.CASCADE, null=True, blank=True)
# vrf = models.ForeignKey(
# 'netdevice.vrf',
# on_delete=models.CASCADE,
# null=True,
# blank=True
# )
# network = models.GenericIPAddressField(unpack_ipv4=False)
# cidr = models.PositiveSmallIntegerField(default=64)
# next_hop = models.GenericIPAddressField(unpack_ipv4=True)
#
# def __str__(self):
# return self.router.hostname + " " + str(self.network) + "/" + str(self.cidr) + " next-hop " + str(self.next_hop)
#
# class ipv4_static(models.Model):
# """
# IPv4 Static Routes - Routes set by the user in a given router
#
# router: The router to place this static route.
# network: The network address of the route. [198.51.100.0]
# cidr: The CIDR length of this static route. [24]
# next-hop: Next-hop device of this static route. [198.51.100.1]
#
# Example string: Router1 198.51.100.0/24 next-hop 198.51.100.1
# """
#
# router = models.ForeignKey('netdevice.router', on_delete=models.CASCADE, null=True, blank=True)
# vrf = models.ForeignKey(
# 'netdevice.vrf',
# on_delete=models.CASCADE,
# null=True,
# blank=True
# )
# network = models.GenericIPAddressField(unpack_ipv4=True)
# cidr = models.PositiveSmallIntegerField(default=24)
# next_hop = models.GenericIPAddressField(unpack_ipv4=True)
#
# def subnet_mask(self):
# host_bits = 32 - int(self.cidr)
# netmask = socket.inet_ntoa(struct.pack('!I', (1 << 32) - (1 << host_bits)))
# return netmask
#
# def __str__(self):
# return self.router.hostname + " " + str(self.network) + "/" + str(self.cidr) + " next-hop " + str(self.next_hop)
#
# Path: static/forms.py
# class IPv6StaticForm(forms.ModelForm):
#
# class Meta:
# model = ipv6_static
# fields = ('__all__')
#
# class IPv4StaticForm(forms.ModelForm):
#
# class Meta:
# model = ipv4_static
# fields = ('__all__')
. Output only the next line. | ipv6_static_obj = get_object_or_404(ipv6_static, pk=ipv6_static_id) |
Based on the snippet: <|code_start|># file: static/views.py
def ipv6_static_create(request, router_id):
router_obj = get_object_or_404(router, pk=router_id)
if request.method == "POST":
<|code_end|>
, predict the immediate next line with the help of imports:
from django.shortcuts import get_object_or_404, render, redirect
from netdevice.models import router
from static.models import ipv6_static, ipv4_static
from static.forms import IPv6StaticForm, IPv4StaticForm
and context (classes, functions, sometimes code) from other files:
# Path: netdevice/models.py
# class router(models.Model):
# """
# Router - A network device that moves packets around.
# routing_id: An IP address the router will use as identification and routing decisions. [203.0.113.1]
# hostname: The (DNS) hostname of the router, domain included. [Router1.isp]
# ibgp: Boolean value to build an iBGP mesh with every router in the database. [True]
# network_os: The network operating system and subsequent template this router is tied too.
# service_ssh: Boolean value to enable SSHv2 on the router. [True]
# service_netconf: Boolean value to enable NETCONF on the router. [True]
# local_aut_num: Local autonomous system number for the router.
# Example string: Router1
# """
#
# routing_id = models.GenericIPAddressField(unpack_ipv4=True)
# hostname = models.CharField(max_length=255)
# ibgp = models.BooleanField()
# network_os = models.ForeignKey('network_os', on_delete=models.CASCADE)
# service_ssh = models.BooleanField(default=True)
# service_netconf = models.BooleanField(default=True)
# local_aut_num = models.ForeignKey('bgp.aut_num', on_delete=models.CASCADE)
#
# def ldp_exists(self):
# return self.interface_set.filter(logical_interface__ldp=True).exists()
#
# def __str__(self):
# return self.hostname
#
# Path: static/models.py
# class ipv6_static(models.Model):
# """
# IPv6 Static Routes - Routes set by the user in a given router.
#
# router: The router to place this static route.
# network: The network address of the route. [2001:db8::]
# cidr: The CIDR length of this static route. [64]
# next-hop: Next-hop device of this static route. [2001:db8:1:1::1]
#
# Example string: Router1 2001:db8:: next-hop 2001:db8:1:1::1
# """
#
# router = models.ForeignKey('netdevice.router', on_delete=models.CASCADE, null=True, blank=True)
# vrf = models.ForeignKey(
# 'netdevice.vrf',
# on_delete=models.CASCADE,
# null=True,
# blank=True
# )
# network = models.GenericIPAddressField(unpack_ipv4=False)
# cidr = models.PositiveSmallIntegerField(default=64)
# next_hop = models.GenericIPAddressField(unpack_ipv4=True)
#
# def __str__(self):
# return self.router.hostname + " " + str(self.network) + "/" + str(self.cidr) + " next-hop " + str(self.next_hop)
#
# class ipv4_static(models.Model):
# """
# IPv4 Static Routes - Routes set by the user in a given router
#
# router: The router to place this static route.
# network: The network address of the route. [198.51.100.0]
# cidr: The CIDR length of this static route. [24]
# next-hop: Next-hop device of this static route. [198.51.100.1]
#
# Example string: Router1 198.51.100.0/24 next-hop 198.51.100.1
# """
#
# router = models.ForeignKey('netdevice.router', on_delete=models.CASCADE, null=True, blank=True)
# vrf = models.ForeignKey(
# 'netdevice.vrf',
# on_delete=models.CASCADE,
# null=True,
# blank=True
# )
# network = models.GenericIPAddressField(unpack_ipv4=True)
# cidr = models.PositiveSmallIntegerField(default=24)
# next_hop = models.GenericIPAddressField(unpack_ipv4=True)
#
# def subnet_mask(self):
# host_bits = 32 - int(self.cidr)
# netmask = socket.inet_ntoa(struct.pack('!I', (1 << 32) - (1 << host_bits)))
# return netmask
#
# def __str__(self):
# return self.router.hostname + " " + str(self.network) + "/" + str(self.cidr) + " next-hop " + str(self.next_hop)
#
# Path: static/forms.py
# class IPv6StaticForm(forms.ModelForm):
#
# class Meta:
# model = ipv6_static
# fields = ('__all__')
#
# class IPv4StaticForm(forms.ModelForm):
#
# class Meta:
# model = ipv4_static
# fields = ('__all__')
. Output only the next line. | form = IPv6StaticForm(request.POST) |
Here is a snippet: <|code_start|>
def ipv6_static_create(request, router_id):
router_obj = get_object_or_404(router, pk=router_id)
if request.method == "POST":
form = IPv6StaticForm(request.POST)
if form.is_valid():
ipv6_static_obj = form.save()
return redirect('netdevice:router_detail', router_id=ipv6_static_obj.router.pk)
else:
form = IPv6StaticForm(initial={'router': router_obj})
return render(request, 'op_webgui/generic_edit.html', {'form': form})
def ipv6_static_edit(request, ipv6_static_id):
ipv6_static_obj = get_object_or_404(ipv6_static, pk=ipv6_static_id)
if request.method == "POST":
form = IPv6StaticForm(request.POST, instance=ipv6_static_obj)
if form.is_valid():
ipv6_static_obj = form.save()
return redirect('netdevice:router_detail', router_id=ipv6_static_obj.router.pk)
else:
form = IPv6StaticForm(instance=ipv6_static_obj)
return render(request, 'op_webgui/generic_edit.html', {'form': form})
def ipv4_static_create(request, router_id):
router_obj = get_object_or_404(router, pk=router_id)
if request.method == "POST":
<|code_end|>
. Write the next line using the current file imports:
from django.shortcuts import get_object_or_404, render, redirect
from netdevice.models import router
from static.models import ipv6_static, ipv4_static
from static.forms import IPv6StaticForm, IPv4StaticForm
and context from other files:
# Path: netdevice/models.py
# class router(models.Model):
# """
# Router - A network device that moves packets around.
# routing_id: An IP address the router will use as identification and routing decisions. [203.0.113.1]
# hostname: The (DNS) hostname of the router, domain included. [Router1.isp]
# ibgp: Boolean value to build an iBGP mesh with every router in the database. [True]
# network_os: The network operating system and subsequent template this router is tied too.
# service_ssh: Boolean value to enable SSHv2 on the router. [True]
# service_netconf: Boolean value to enable NETCONF on the router. [True]
# local_aut_num: Local autonomous system number for the router.
# Example string: Router1
# """
#
# routing_id = models.GenericIPAddressField(unpack_ipv4=True)
# hostname = models.CharField(max_length=255)
# ibgp = models.BooleanField()
# network_os = models.ForeignKey('network_os', on_delete=models.CASCADE)
# service_ssh = models.BooleanField(default=True)
# service_netconf = models.BooleanField(default=True)
# local_aut_num = models.ForeignKey('bgp.aut_num', on_delete=models.CASCADE)
#
# def ldp_exists(self):
# return self.interface_set.filter(logical_interface__ldp=True).exists()
#
# def __str__(self):
# return self.hostname
#
# Path: static/models.py
# class ipv6_static(models.Model):
# """
# IPv6 Static Routes - Routes set by the user in a given router.
#
# router: The router to place this static route.
# network: The network address of the route. [2001:db8::]
# cidr: The CIDR length of this static route. [64]
# next-hop: Next-hop device of this static route. [2001:db8:1:1::1]
#
# Example string: Router1 2001:db8:: next-hop 2001:db8:1:1::1
# """
#
# router = models.ForeignKey('netdevice.router', on_delete=models.CASCADE, null=True, blank=True)
# vrf = models.ForeignKey(
# 'netdevice.vrf',
# on_delete=models.CASCADE,
# null=True,
# blank=True
# )
# network = models.GenericIPAddressField(unpack_ipv4=False)
# cidr = models.PositiveSmallIntegerField(default=64)
# next_hop = models.GenericIPAddressField(unpack_ipv4=True)
#
# def __str__(self):
# return self.router.hostname + " " + str(self.network) + "/" + str(self.cidr) + " next-hop " + str(self.next_hop)
#
# class ipv4_static(models.Model):
# """
# IPv4 Static Routes - Routes set by the user in a given router
#
# router: The router to place this static route.
# network: The network address of the route. [198.51.100.0]
# cidr: The CIDR length of this static route. [24]
# next-hop: Next-hop device of this static route. [198.51.100.1]
#
# Example string: Router1 198.51.100.0/24 next-hop 198.51.100.1
# """
#
# router = models.ForeignKey('netdevice.router', on_delete=models.CASCADE, null=True, blank=True)
# vrf = models.ForeignKey(
# 'netdevice.vrf',
# on_delete=models.CASCADE,
# null=True,
# blank=True
# )
# network = models.GenericIPAddressField(unpack_ipv4=True)
# cidr = models.PositiveSmallIntegerField(default=24)
# next_hop = models.GenericIPAddressField(unpack_ipv4=True)
#
# def subnet_mask(self):
# host_bits = 32 - int(self.cidr)
# netmask = socket.inet_ntoa(struct.pack('!I', (1 << 32) - (1 << host_bits)))
# return netmask
#
# def __str__(self):
# return self.router.hostname + " " + str(self.network) + "/" + str(self.cidr) + " next-hop " + str(self.next_hop)
#
# Path: static/forms.py
# class IPv6StaticForm(forms.ModelForm):
#
# class Meta:
# model = ipv6_static
# fields = ('__all__')
#
# class IPv4StaticForm(forms.ModelForm):
#
# class Meta:
# model = ipv4_static
# fields = ('__all__')
, which may include functions, classes, or code. Output only the next line. | form = IPv4StaticForm(request.POST) |
Next line prediction: <|code_start|># file: address/urls.py
app_name = 'address'
urlpatterns = [
url(
r'^(?P<logical_interface_id>[0-9]+)/create/ipv6_address/$',
<|code_end|>
. Use current file imports:
(from django.conf.urls import url
from django.contrib.auth import views as auth_views
from address import views)
and context including class names, function names, or small code snippets from other files:
# Path: address/views.py
# def ipv6_address_create(request, logical_interface_id):
# def ipv6_address_edit(request, ipv6_address_id):
# def ipv4_address_create(request, logical_interface_id):
# def ipv4_address_edit(request, ipv4_address_id):
. Output only the next line. | views.ipv6_address_create, |
Continue the code snippet: <|code_start|> 'history': r.history,
'content': r.text,
'relme': [],
'url': sourceURL
}
if r.status_code == requests.codes.ok: # pylint: disable=no-member
dom = BeautifulSoup(r.text, _html_parser)
for link in dom.find_all('a', rel='me'):
rel = link.get('rel')
href = link.get('href')
if rel is not None and href is not None:
url = urlparse(href)
if url is not None and url.scheme in ('http', 'https'):
result['relme'].append(cleanURL(href))
return result
def confirmRelMe(profileURL, resourceURL, profileRelMes=None, resourceRelMes=None):
"""Determine if a given :resourceURL: is authoritative for the :profileURL:
TODO add https/http filtering for those who wish to limit/restrict urls to match fully
TODO add code to ensure that each item in the redirect chain is authoritative
:param profileURL: URL of the user
:param resourceURL: URL of the resource to validate
:param profileRelMes: optional list of rel="me" links within the profile URL
:param resourceRelMes: optional list of rel="me" links found within resource URL
:rtype: True if confirmed
"""
result = False
<|code_end|>
. Use current file imports:
from urllib.parse import urlparse
from bs4 import BeautifulSoup
from .tools import normalizeURL, cleanURL
import requests
and context (classes, functions, or code) from other files:
# Path: src/ronkyuu/tools.py
# def normalizeURL(targetURL):
# """Return the last URL (of any redirections) of a valid URL
# """
# result = None
# ok, chain = getURLChain(targetURL)
# if ok:
# if len(chain) > 0:
# result = chain[-1]
# else:
# result = targetURL
# return result
#
# def cleanURL(targetURL):
# """Return from the given URL a "clean" URL that follows the RFC guidelines
# """
# scheme, netloc, path, query, fragment = urlsplit(targetURL)
# if len(path) == 0:
# path = '/'
# return urlunsplit((scheme, netloc, path, query, fragment))
. Output only the next line. | profile = normalizeURL(profileURL) |
Based on the snippet: <|code_start|># http://dreev.es -> [301] -> http://ai.eecs.umich.edu/people/dreeves/
# https://twitter.com/dreev -> [rel-me] -> http://t.co/PlBCqLVndT -> [301] -> http://dreev.es -> [301] -> http://ai.eecs.umich.edu/people/dreeves/
#
def findRelMe(sourceURL):
"""Find all <a /> elements in the given html for a post.
If any have an href attribute that is rel="me" then include
it in the result.
:param sourceURL: the URL for the post we are scanning
:rtype: dictionary of RelMe references
"""
r = requests.get(sourceURL)
result = {'status': r.status_code,
'headers': r.headers,
'history': r.history,
'content': r.text,
'relme': [],
'url': sourceURL
}
if r.status_code == requests.codes.ok: # pylint: disable=no-member
dom = BeautifulSoup(r.text, _html_parser)
for link in dom.find_all('a', rel='me'):
rel = link.get('rel')
href = link.get('href')
if rel is not None and href is not None:
url = urlparse(href)
if url is not None and url.scheme in ('http', 'https'):
<|code_end|>
, predict the immediate next line with the help of imports:
from urllib.parse import urlparse
from bs4 import BeautifulSoup
from .tools import normalizeURL, cleanURL
import requests
and context (classes, functions, sometimes code) from other files:
# Path: src/ronkyuu/tools.py
# def normalizeURL(targetURL):
# """Return the last URL (of any redirections) of a valid URL
# """
# result = None
# ok, chain = getURLChain(targetURL)
# if ok:
# if len(chain) > 0:
# result = chain[-1]
# else:
# result = targetURL
# return result
#
# def cleanURL(targetURL):
# """Return from the given URL a "clean" URL that follows the RFC guidelines
# """
# scheme, netloc, path, query, fragment = urlsplit(targetURL)
# if len(path) == 0:
# path = '/'
# return urlunsplit((scheme, netloc, path, query, fragment))
. Output only the next line. | result['relme'].append(cleanURL(href)) |
Predict the next line after this snippet: <|code_start|># processing stops)
def findMentions(sourceURL, targetURL=None, exclude_domains=None, content=None, test_urls=True, headers=None, timeout=None):
"""Find all <a /> elements in the given html for a post. Only scan html element matching all criteria in look_in.
optionally the content to be scanned can be given as an argument.
If any have an href attribute that is not from the
one of the items in exclude_domains, append it to our lists.
:param sourceURL: the URL for the post we are scanning
:param exclude_domains: a list of domains to exclude from the search
:type exclude_domains: list
:param content: the content to be scanned for mentions
:param look_in: dictionary with name, id and class_. only element matching all of these will be scanned
:param test_urls: optional flag to test URLs for validation
:param headers: optional headers to send with any web requests
:type headers: dict
:param timeout: optional timeout for web requests
:type timeout float
:rtype: dictionary of Mentions
"""
__doc__ = None # pylint: disable=redefined-builtin
if exclude_domains is None:
exclude_domains = []
if headers is None:
headers = {}
if test_urls:
<|code_end|>
using the current file's imports:
from urllib.parse import urlparse, urljoin
from bs4 import BeautifulSoup
from .validators import URLValidator
from .tools import parse_link_header
import requests
and any relevant context from other files:
# Path: src/ronkyuu/validators.py
# class URLValidator(RegexValidator): # pylint: disable=R0903
# """URL Validation using a regular expression
# """
# regex = re.compile(
# r'^(?:[a-z0-9\.\-]*)://' # scheme is validated separately
# r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain...
# r'localhost|' # localhost...
# r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|' # ...or ipv4
# r'\[?[A-F0-9]*:[A-F0-9:]+\]?)' # ...or ipv6
# r'(?::\d+)?' # optional port
# r'(?:/?|[/?]\S+)$', re.IGNORECASE)
# message = 'Enter a valid URL.'
# # check only http and https
# schemes = ['http', 'https']
#
# def __init__(self, schemes=None, **kwargs):
# super(URLValidator, self).__init__(**kwargs)
# if schemes is not None:
# self.schemes = schemes
#
# def __call__(self, value):
# e = ValueError(self.message)
# # Check for None, and empty string
# if value in (None, ''):
# raise e
# value = str(value)
# # Check first if the scheme is valid
# scheme = value.split('://')[0].lower()
# if scheme not in self.schemes:
# raise e
#
# # Then check full URL
# try:
# super(URLValidator, self).__call__(value)
# except ValueError:
# # Trivial case failed. Try for possible IDN domain
# if value:
# scheme, netloc, path, query, fragment = urlsplit(value)
# try:
# netloc = netloc.encode('idna').decode('ascii') # IDN -> ACE
# except UnicodeError: # invalid domain part
# raise e
# url = urlunsplit((scheme, netloc, path, query, fragment))
# super(URLValidator, self).__call__(url)
# else:
# raise e
# else:
# url = value
#
# Path: src/ronkyuu/tools.py
# def parse_link_header(link):
# """takes the link header as a string and returns a dictionary with rel values as keys and urls as values
# :param link: link header as a string
# :rtype: dictionary {rel_name: rel_value}
# """
# rel_dict = {}
# for rels in link.split(','):
# rel_break = quoted_split(rels, ';')
# try:
# rel_url = re.search('<(.+?)>', rel_break[0]).group(1)
# rel_names = quoted_split(rel_break[1], '=')[-1]
# if rel_names.startswith('"') and rel_names.endswith('"'):
# rel_names = rel_names[1:-1]
# for name in rel_names.split():
# rel_dict[name] = rel_url
# except (AttributeError, IndexError):
# pass
#
# return rel_dict
. Output only the next line. | URLValidator(message='invalid source URL')(sourceURL) |
Using the snippet: <|code_start|>
def discoverEndpoint(sourceURL, test_urls=True, headers=None, timeout=None, request=None, debug=False):
"""Discover any WebMention endpoint for a given URL.
:param link: URL to discover WebMention endpoint
:param test_urls: optional flag to test URLs for validation
:param headers: optional headers to send with any web requests
:type headers dict
:param timeout: optional timeout for web requests
:type timeout float
:param request: optional Requests request object to avoid another GET
:rtype: tuple (status_code, URL, [debug])
"""
if headers is None:
headers = {}
if test_urls:
URLValidator(message='invalid URL')(sourceURL)
# status, webmention
endpointURL = None
debugOutput = []
try:
if request is not None:
targetRequest = request
else:
targetRequest = requests.get(sourceURL, verify=False, headers=headers, timeout=timeout)
returnCode = targetRequest.status_code
debugOutput.append('%s %s' % (returnCode, sourceURL))
if returnCode == requests.codes.ok: # pylint: disable=no-member
try:
<|code_end|>
, determine the next line of code. You have imports:
from urllib.parse import urlparse, urljoin
from bs4 import BeautifulSoup
from .validators import URLValidator
from .tools import parse_link_header
import requests
and context (class names, function names, or code) available:
# Path: src/ronkyuu/validators.py
# class URLValidator(RegexValidator): # pylint: disable=R0903
# """URL Validation using a regular expression
# """
# regex = re.compile(
# r'^(?:[a-z0-9\.\-]*)://' # scheme is validated separately
# r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain...
# r'localhost|' # localhost...
# r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|' # ...or ipv4
# r'\[?[A-F0-9]*:[A-F0-9:]+\]?)' # ...or ipv6
# r'(?::\d+)?' # optional port
# r'(?:/?|[/?]\S+)$', re.IGNORECASE)
# message = 'Enter a valid URL.'
# # check only http and https
# schemes = ['http', 'https']
#
# def __init__(self, schemes=None, **kwargs):
# super(URLValidator, self).__init__(**kwargs)
# if schemes is not None:
# self.schemes = schemes
#
# def __call__(self, value):
# e = ValueError(self.message)
# # Check for None, and empty string
# if value in (None, ''):
# raise e
# value = str(value)
# # Check first if the scheme is valid
# scheme = value.split('://')[0].lower()
# if scheme not in self.schemes:
# raise e
#
# # Then check full URL
# try:
# super(URLValidator, self).__call__(value)
# except ValueError:
# # Trivial case failed. Try for possible IDN domain
# if value:
# scheme, netloc, path, query, fragment = urlsplit(value)
# try:
# netloc = netloc.encode('idna').decode('ascii') # IDN -> ACE
# except UnicodeError: # invalid domain part
# raise e
# url = urlunsplit((scheme, netloc, path, query, fragment))
# super(URLValidator, self).__call__(url)
# else:
# raise e
# else:
# url = value
#
# Path: src/ronkyuu/tools.py
# def parse_link_header(link):
# """takes the link header as a string and returns a dictionary with rel values as keys and urls as values
# :param link: link header as a string
# :rtype: dictionary {rel_name: rel_value}
# """
# rel_dict = {}
# for rels in link.split(','):
# rel_break = quoted_split(rels, ';')
# try:
# rel_url = re.search('<(.+?)>', rel_break[0]).group(1)
# rel_names = quoted_split(rel_break[1], '=')[-1]
# if rel_names.startswith('"') and rel_names.endswith('"'):
# rel_names = rel_names[1:-1]
# for name in rel_names.split():
# rel_dict[name] = rel_url
# except (AttributeError, IndexError):
# pass
#
# return rel_dict
. Output only the next line. | linkHeader = parse_link_header(targetRequest.headers['link']) |
Predict the next line after this snippet: <|code_start|># Licensed under the GPLv3 - see LICENSE
class ParserDictSetup:
@staticmethod
def create_parser(index, default):
def parser(words):
return words[index]
return parser
@staticmethod
def get_default(index, default):
return default
@staticmethod
def random_name(index, default):
return index
class TestHeaderParserBase(ParserDictSetup):
def setup_class(cls):
cls.hp = {'0': (0, 'default0'),
'1': (1, 'default1')}
class H(HeaderParserBase):
<|code_end|>
using the current file's imports:
import pytest
from ..header import ParserDict, HeaderParserBase, HeaderParser
and any relevant context from other files:
# Path: baseband/base/header.py
# class ParserDict:
# """Create a lazily evaluated dictionary of parsers, setters, or defaults.
#
# Implemented as a non-data descriptor. When first called on an instance,
# it will create a dict under the name of itself in the instance's
# ``__dict__``, which means that any further attribute access will return
# that dict instead of this descriptor.
#
# Parameters
# ----------
# function : callable
# Function that can be used to create a parser or setter, or get the
# default, based on a header keyword description. Typically one of
# ``make_parser``, ``make_setter``, or ``get_default``.
#
# """
#
# def __init__(self, function):
# self.function = function
#
# def __set_name__(self, owner, name):
# self.name = name
# self.__doc__ = f"Lazily evaluated dict of {name}"
#
# def __get__(self, instance, cls=None):
# if instance is None:
# return self
# # Create dict of functions/defaults.
# d = {key: self.function(*definition)
# for key, definition in instance.items()}
# # Override ourselves on the instance.
# setattr(instance, self.name, d)
# return d
#
# def __repr__(self):
# return f"{self.__class__.__name__}({self.function}"
#
# class HeaderParserBase(dict):
# """Parser & setter for header keywords.
#
# A dictionary of header keywords, with values that describe how they are
# encoded in a given header. Initialisation is as a normal dict,
# with (ordered) key, value pairs, with each value a tuple containing
# information that describes how the value is encoded, and any default.
#
# The actual implementation is done by instances of
# `~baseband.base.header.ParserDict` called ``parsers``, ``setters``, and
# ``defaults``, which return functions that get a given keyword from
# header words, set the corresponding part of the header words to a value,
# or return the default value (if defined). To speed up access to those,
# they are precalculated on first access rather than calculated on the fly.
#
# """
# def copy(self):
# return self.__class__(self)
#
# def __or__(self, other):
# if not isinstance(other, type(self)):
# return NotImplemented
#
# if sys.version_info >= (3, 9): # pragma: no cover
# return self.__class__(super().__or__(other))
#
# result = self.__class__(self)
# result.update(other)
# return result
#
# # Backwards compatibility for code written for baseband < 4.0.
# __add__ = __or__
#
# def _clear_caches(self):
# """Clear the caches of the parser dicts. To be done on any change."""
# for key in set(self.__dict__):
# if isinstance(self.__class__.__dict__[key], ParserDict):
# del self.__dict__[key]
#
# class HeaderParser(HeaderParserBase):
# """Parser & setter for VLBI header keywords.
#
# A dictionary of header keywords, with values that describe how they are
# encoded in a given VLBI header. Initialisation is as a normal dict,
# with (ordered) key, value pairs, with each value a tuple containing:
#
# word_index : int
# Index into the header words for this key.
# bit_index : int
# Index to the starting bit of the part used for this key.
# bit_length : int
# Number of bits.
# default : int or bool or None
# Possible default value to use in initialisation (e.g., a sync pattern).
#
# The class provides dict-like properties ``parsers``, ``setters``, and
# ``defaults``, which return functions that get a given keyword from header
# words, set the corresponding part of the header words to a value, or
# return the default value (if defined). To speed up access to those,
# they are precalculated on first access rather than calculated on the fly.
#
# """
# parsers = ParserDict(make_parser)
# setters = ParserDict(make_setter)
# defaults = ParserDict(get_default)
. Output only the next line. | parsers = ParserDict(cls.create_parser) |
Predict the next line for this snippet: <|code_start|># Licensed under the GPLv3 - see LICENSE
class ParserDictSetup:
@staticmethod
def create_parser(index, default):
def parser(words):
return words[index]
return parser
@staticmethod
def get_default(index, default):
return default
@staticmethod
def random_name(index, default):
return index
class TestHeaderParserBase(ParserDictSetup):
def setup_class(cls):
cls.hp = {'0': (0, 'default0'),
'1': (1, 'default1')}
<|code_end|>
with the help of current file imports:
import pytest
from ..header import ParserDict, HeaderParserBase, HeaderParser
and context from other files:
# Path: baseband/base/header.py
# class ParserDict:
# """Create a lazily evaluated dictionary of parsers, setters, or defaults.
#
# Implemented as a non-data descriptor. When first called on an instance,
# it will create a dict under the name of itself in the instance's
# ``__dict__``, which means that any further attribute access will return
# that dict instead of this descriptor.
#
# Parameters
# ----------
# function : callable
# Function that can be used to create a parser or setter, or get the
# default, based on a header keyword description. Typically one of
# ``make_parser``, ``make_setter``, or ``get_default``.
#
# """
#
# def __init__(self, function):
# self.function = function
#
# def __set_name__(self, owner, name):
# self.name = name
# self.__doc__ = f"Lazily evaluated dict of {name}"
#
# def __get__(self, instance, cls=None):
# if instance is None:
# return self
# # Create dict of functions/defaults.
# d = {key: self.function(*definition)
# for key, definition in instance.items()}
# # Override ourselves on the instance.
# setattr(instance, self.name, d)
# return d
#
# def __repr__(self):
# return f"{self.__class__.__name__}({self.function}"
#
# class HeaderParserBase(dict):
# """Parser & setter for header keywords.
#
# A dictionary of header keywords, with values that describe how they are
# encoded in a given header. Initialisation is as a normal dict,
# with (ordered) key, value pairs, with each value a tuple containing
# information that describes how the value is encoded, and any default.
#
# The actual implementation is done by instances of
# `~baseband.base.header.ParserDict` called ``parsers``, ``setters``, and
# ``defaults``, which return functions that get a given keyword from
# header words, set the corresponding part of the header words to a value,
# or return the default value (if defined). To speed up access to those,
# they are precalculated on first access rather than calculated on the fly.
#
# """
# def copy(self):
# return self.__class__(self)
#
# def __or__(self, other):
# if not isinstance(other, type(self)):
# return NotImplemented
#
# if sys.version_info >= (3, 9): # pragma: no cover
# return self.__class__(super().__or__(other))
#
# result = self.__class__(self)
# result.update(other)
# return result
#
# # Backwards compatibility for code written for baseband < 4.0.
# __add__ = __or__
#
# def _clear_caches(self):
# """Clear the caches of the parser dicts. To be done on any change."""
# for key in set(self.__dict__):
# if isinstance(self.__class__.__dict__[key], ParserDict):
# del self.__dict__[key]
#
# class HeaderParser(HeaderParserBase):
# """Parser & setter for VLBI header keywords.
#
# A dictionary of header keywords, with values that describe how they are
# encoded in a given VLBI header. Initialisation is as a normal dict,
# with (ordered) key, value pairs, with each value a tuple containing:
#
# word_index : int
# Index into the header words for this key.
# bit_index : int
# Index to the starting bit of the part used for this key.
# bit_length : int
# Number of bits.
# default : int or bool or None
# Possible default value to use in initialisation (e.g., a sync pattern).
#
# The class provides dict-like properties ``parsers``, ``setters``, and
# ``defaults``, which return functions that get a given keyword from header
# words, set the corresponding part of the header words to a value, or
# return the default value (if defined). To speed up access to those,
# they are precalculated on first access rather than calculated on the fly.
#
# """
# parsers = ParserDict(make_parser)
# setters = ParserDict(make_setter)
# defaults = ParserDict(get_default)
, which may contain function names, class names, or code. Output only the next line. | class H(HeaderParserBase): |
Predict the next line after this snippet: <|code_start|>
class TestHeaderParserBase(ParserDictSetup):
def setup_class(cls):
cls.hp = {'0': (0, 'default0'),
'1': (1, 'default1')}
class H(HeaderParserBase):
parsers = ParserDict(cls.create_parser)
indices = ParserDict(cls.random_name)
defaults = ParserDict(cls.get_default)
cls.H = H
def test_parserdict(self):
assert self.H.parsers.name == 'parsers'
assert self.H.indices.name == 'indices'
assert repr(self.H.parsers).startswith('ParserDict')
assert 'Lazily evaluated' in self.H.defaults.__doc__
def test_init(self):
h = self.H(self.hp)
words = ['first', 'second']
assert h.parsers['0'](words) == 'first'
assert h.defaults['1'] == 'default1'
assert h.indices['1'] == 1
class TestHeaderParser:
def setup_class(cls):
<|code_end|>
using the current file's imports:
import pytest
from ..header import ParserDict, HeaderParserBase, HeaderParser
and any relevant context from other files:
# Path: baseband/base/header.py
# class ParserDict:
# """Create a lazily evaluated dictionary of parsers, setters, or defaults.
#
# Implemented as a non-data descriptor. When first called on an instance,
# it will create a dict under the name of itself in the instance's
# ``__dict__``, which means that any further attribute access will return
# that dict instead of this descriptor.
#
# Parameters
# ----------
# function : callable
# Function that can be used to create a parser or setter, or get the
# default, based on a header keyword description. Typically one of
# ``make_parser``, ``make_setter``, or ``get_default``.
#
# """
#
# def __init__(self, function):
# self.function = function
#
# def __set_name__(self, owner, name):
# self.name = name
# self.__doc__ = f"Lazily evaluated dict of {name}"
#
# def __get__(self, instance, cls=None):
# if instance is None:
# return self
# # Create dict of functions/defaults.
# d = {key: self.function(*definition)
# for key, definition in instance.items()}
# # Override ourselves on the instance.
# setattr(instance, self.name, d)
# return d
#
# def __repr__(self):
# return f"{self.__class__.__name__}({self.function}"
#
# class HeaderParserBase(dict):
# """Parser & setter for header keywords.
#
# A dictionary of header keywords, with values that describe how they are
# encoded in a given header. Initialisation is as a normal dict,
# with (ordered) key, value pairs, with each value a tuple containing
# information that describes how the value is encoded, and any default.
#
# The actual implementation is done by instances of
# `~baseband.base.header.ParserDict` called ``parsers``, ``setters``, and
# ``defaults``, which return functions that get a given keyword from
# header words, set the corresponding part of the header words to a value,
# or return the default value (if defined). To speed up access to those,
# they are precalculated on first access rather than calculated on the fly.
#
# """
# def copy(self):
# return self.__class__(self)
#
# def __or__(self, other):
# if not isinstance(other, type(self)):
# return NotImplemented
#
# if sys.version_info >= (3, 9): # pragma: no cover
# return self.__class__(super().__or__(other))
#
# result = self.__class__(self)
# result.update(other)
# return result
#
# # Backwards compatibility for code written for baseband < 4.0.
# __add__ = __or__
#
# def _clear_caches(self):
# """Clear the caches of the parser dicts. To be done on any change."""
# for key in set(self.__dict__):
# if isinstance(self.__class__.__dict__[key], ParserDict):
# del self.__dict__[key]
#
# class HeaderParser(HeaderParserBase):
# """Parser & setter for VLBI header keywords.
#
# A dictionary of header keywords, with values that describe how they are
# encoded in a given VLBI header. Initialisation is as a normal dict,
# with (ordered) key, value pairs, with each value a tuple containing:
#
# word_index : int
# Index into the header words for this key.
# bit_index : int
# Index to the starting bit of the part used for this key.
# bit_length : int
# Number of bits.
# default : int or bool or None
# Possible default value to use in initialisation (e.g., a sync pattern).
#
# The class provides dict-like properties ``parsers``, ``setters``, and
# ``defaults``, which return functions that get a given keyword from header
# words, set the corresponding part of the header words to a value, or
# return the default value (if defined). To speed up access to those,
# they are precalculated on first access rather than calculated on the fly.
#
# """
# parsers = ParserDict(make_parser)
# setters = ParserDict(make_setter)
# defaults = ParserDict(get_default)
. Output only the next line. | cls.header_parser = HeaderParser( |
Given the code snippet: <|code_start|> mask : list of int
For each entry in ``pattern`` a bit mask with bits set for
the parts that are invariant.
"""
if invariants is None:
invariants = self.invariants()
if not invariants:
raise ValueError("cannot create an invariant_mask without "
"some invariants")
if isinstance(self, type):
# If we are called as a classmethod, first get an instance
# with all defaults set. This will be our pattern.
self = self(None, **kwargs)
for invariant in invariants:
value = self._header_parser.defaults[invariant]
if value is None:
raise ValueError('can only set as invariant a header '
'part that has a default.')
self[invariant] = value
# Create an all-zero version and set bits for all invariants.
mask = self.__class__(None, **kwargs)
for invariant in invariants:
mask[invariant] = True
return self.words, mask.words
<|code_end|>
, generate the next line using the imports in this file:
import sys
import struct
import warnings
import functools
import numpy as np
from copy import copy
from astropy.utils import sharedmethod
from .utils import fixedvalue
and context (functions, classes, or occasionally code) from other files:
# Path: baseband/base/utils.py
# class fixedvalue(classproperty):
# """Property that is fixed for all instances of a class.
#
# Based on `astropy.utils.decorators.classproperty`, but with
# a setter that passes if the value is identical to the fixed
# value, and otherwise raises a `ValueError`.
# """
# def __set__(self, instance, value):
# fixed_value = self.__get__(instance, type(instance))
# if value != fixed_value:
# raise ValueError(
# f"'{self.fget.__name__}' can only be set to {fixed_value}.")
. Output only the next line. | @fixedvalue |
Based on the snippet: <|code_start|># Licensed under the GPLv3 - see LICENSE
class TestRawOffsets:
@pytest.mark.parametrize('frame_nbytes', [0, 10, 100])
def test_plain(self, frame_nbytes):
<|code_end|>
, predict the immediate next line with the help of imports:
import pytest
from ..offsets import RawOffsets
and context (classes, functions, sometimes code) from other files:
# Path: baseband/base/offsets.py
# class RawOffsets:
# """File offset tracker.
#
# Keeps track of offsets from expected file position as a
# function of frame number, by keeping a joint list, of the
# first frame number beyond which a certain offset will hold.
#
# The offset for a given frame number is retrieved via ``__getitem__``,
# while new offsets are added via ``__setitem__`` (keeping the
# list of frame numbers minimal for identical offsets).
#
# Parameters
# ----------
# frame_nr : list
# Frame number for which one has offsets.
# offset : list
# Corresponding offsets.
# frame_nbytes : int
# Possible frame size to include in all returned offsets, i.e.,
# output will be ``offset + index * frame_nbytes``. Default: 0.
#
# Examples
# --------
# The usage is best seen through an example::
#
# >>> from baseband.base.offsets import RawOffsets
# >>> offsets = RawOffsets([6], [5])
# >>> offsets[3] # Implicitly 0 before first entry
# 0
# >>> offsets[10] # Assumed the same as 6
# 5
# >>> offsets[10] = 9 # But suppose we find 10 has 9.
# >>> offsets[10] # Then it takes that
# 9
# >>> offsets[9] # But before is still 5.
# 5
# >>> offsets[8] = 9 # But if we find 8 has 9 too.
# >>> offsets[9] # Then 9 is the same.
# 9
# >>> offsets # And the list is kept minimal.
# RawOffsets(frame_nr=[6, 8], offset=[5, 9], frame_nbytes=0)
# >>> offsets[9] = 9 # This is a no-op.
# >>> offsets[10] = 10 # But this is not.
# >>> offsets
# RawOffsets(frame_nr=[6, 8, 10], offset=[5, 9, 10], frame_nbytes=0)
#
# Similarly, if a frame size is passed in::
#
# >>> offsets = RawOffsets([6, 8, 10], [5, 9, 10], frame_nbytes=1000)
# >>> offsets
# RawOffsets(frame_nr=[6, 8, 10], offset=[5, 9, 10], frame_nbytes=1000)
# >>> offsets[1]
# 1000
# >>> offsets[8]
# 8009
# >>> offsets[8] = 8005 # This removes the offset for 9.
# >>> offsets[8]
# 8005
# >>> offsets
# RawOffsets(frame_nr=[6, 10], offset=[5, 10], frame_nbytes=1000)
#
# """
#
# def __init__(self, frame_nr=None, offset=None, frame_nbytes=0):
# if frame_nr is None:
# frame_nr = []
# if offset is None:
# offset = []
# if len(frame_nr) != len(offset):
# raise ValueError('must have equal number of frame numbers '
# 'and offsets.')
# self.frame_nr = frame_nr
# self.offset = offset
# self.frame_nbytes = operator.index(frame_nbytes)
#
# def __getitem__(self, frame_nr):
# # Keep default case of no offsets as fast as possible.
# base = frame_nr * self.frame_nbytes
# if not self.frame_nr:
# return base
# # Find first index for which frame_nr < value-at-index,
# # hence the offset at the previous index is the one we need.
# index = bisect.bisect_right(self.frame_nr, frame_nr)
# return base if index == 0 else base + self.offset[index - 1]
#
# def __setitem__(self, frame_nr, offset):
# # Get the offset from expected.
# offset -= frame_nr * self.frame_nbytes
# # Find first index for which frame_nr < value-at-index.
# # Hence, this is where we should be if we do not yet exist.
# index = bisect.bisect_right(self.frame_nr, frame_nr)
# # If the entry already exists (should not really happen),
# # and the new value is different, replace it.
# if index > 0 and self.frame_nr[index-1] == frame_nr:
# if self.offset[index-1] == offset:
# return
#
# # Best to *remove* the entry, since the new value may
# # be consistent with one of the surrounding values,
# # in which case we can shorten our list.
# self.frame_nr.pop(index-1)
# self.offset.pop(index-1)
# index -= 1
#
# # If the offset at the next location is the same as ours,
# # then we can keep everything consistent by just moving the
# # frame number to our value.
# if index < len(self) and self.offset[index] == offset:
# self.frame_nr[index] = frame_nr
# elif offset != (self.offset[index-1] if index > 0 else 0):
# # Otherwise, if we add new information, insert ourserlves.
# self.frame_nr.insert(index, frame_nr)
# self.offset.insert(index, offset)
#
# def __len__(self):
# return len(self.frame_nr)
#
# def __repr__(self):
# return ('{0}(frame_nr={1}, offset={2}, frame_nbytes={3})'
# .format(type(self).__name__, self.frame_nr, self.offset,
# self.frame_nbytes))
. Output only the next line. | ro = RawOffsets(frame_nbytes=frame_nbytes) |
Using the snippet: <|code_start|>def main(bot, *args, **kwargs):
"""
kot
Stupid cat memes from http://kotomatrix.ru
"""
matricies = json.loads(bot.store.get('kot_matricies').decode() or '[]')
curr_index = int(bot.store.get('kot_index') or 0)
if curr_index >= len(matricies):
response = requests.get('http://kotomatrix.ru/rand/')
matricies = list(set(re.findall(
"http://kotomatrix.ru/images/.*.jpg",
response.content.decode('utf-8')
)))
bot.store.set('kot_matricies', json.dumps(matricies))
curr_index = 0
matrix = matricies[curr_index]
ext = matrix.split('.')[2]
chat_id = kwargs.pop('chat_id')
bot.pre_send(chat_id=chat_id, action='upload_photo')
bot.call(
'sendPhoto',
'POST',
data = {'chat_id': chat_id},
files = {'photo': (
'file.{}'.format(ext),
<|code_end|>
, determine the next line of code. You have imports:
import re
import requests
import json
from modules.utils.data import prepare_binary_from_url
and context (class names, function names, or code) available:
# Path: modules/utils/data.py
# def prepare_binary_from_url(url, verify=True):
# try:
# content = requests.get(url, timeout=(1, 3), verify=verify).content
# except RequestException:
# pass
# else:
# return BytesIO(content)
. Output only the next line. | prepare_binary_from_url(matrix), |
Next line prediction: <|code_start|>
async def main(bot, *args, **kwargs):
"""
btc
Get latest bitcoin price
"""
tickers = [
{'name': 'CEX.IO', 'url': 'https://cex.io/api/ticker/BTC/USD', 'field': 'last', 'sign': '$'},
{'name': 'Bitstamp', 'url': 'https://www.bitstamp.net/api/v2/ticker/btcusd/', 'field': 'last', 'sign': '$'},
{'name': 'BTC-E', 'url': 'https://btc-e.com/api/3/ticker/btc_usd', 'field': 'btc_usd.last', 'sign': '$'},
{'name': 'BTC-E', 'url': 'https://btc-e.com/api/3/ticker/btc_rur', 'field': 'btc_rur.last', 'sign': '₽'}
]
for ticker in tickers:
try:
<|code_end|>
. Use current file imports:
(import json
from modules.utils import http)
and context including class names, function names, or small code snippets from other files:
# Path: modules/utils/http.py
# async def pre_send(bot, chat_id: Optional[str]=None, action: str='typing') -> None:
# async def send(bot, chat_id: Optional[str]=None, text: Optional[str]=None, data: dict={}) -> None:
# async def call(bot, method_name: str, http_method: str, **kwargs):
# async def perform_request(url, method, params={}):
. Output only the next line. | response_body = await http.perform_request(ticker['url'], 'GET') |
Given snippet: <|code_start|> headers = {'Authorization': 'Basic {}'.format(auth.decode('utf-8'))}
# Cache return response to decrease number of requests to the bing api
if last_query != query:
# TODO: use `params` here, investigate 'Query is not of type String' error from azure
try:
azure_response = requests.get('https://api.datamarket.azure.com/Bing/Search/v1/Image?Market=%27ru-RU%27&Adult=%27Moderate%27&Query=%27{}%27&$format=json&$top=20'.format(query), headers=headers, timeout=(1, 2)).content
except requests.exceptions.Timeout:
return response(bot, 'Can not get results', chat_id)
except RequestException:
return response(bot, 'Can not get results')
setattr(bot, 'img_last_response_{}'.format(chat_id), azure_response)
else:
azure_response = getattr(bot, 'img_last_response_{}'.format(chat_id))
try:
search_data = json.loads(azure_response.decode('utf-8'))
except ValueError:
return response(bot, 'Can not get results', chat_id)
results = search_data.get('d', {}).get('results', [])
if len(results) >= i + 1:
while results[i - 1 if i > 1 else i:]:
setattr(bot, 'img_last_num_{}'.format(chat_id), i)
if len(results) <= i:
return response(bot, 'No such images', chat_id)
url = results[i]['MediaUrl']
ext = url.rsplit('.', 1)[1]
if ext.lower() in ('jpg', 'jpeg', 'gif', 'png'):
file_id = check_store(bot, url)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import json
import base64
import requests
from datetime import datetime, timedelta
from requests.exceptions import RequestException
from modules.utils.data import prepare_binary_from_url
and context:
# Path: modules/utils/data.py
# def prepare_binary_from_url(url, verify=True):
# try:
# content = requests.get(url, timeout=(1, 3), verify=verify).content
# except RequestException:
# pass
# else:
# return BytesIO(content)
which might include code, classes, or functions. Output only the next line. | photo = file_id if file_id else prepare_binary_from_url(url) |
Given snippet: <|code_start|>
def main(bot, *args, **kwargs):
"""
webm
Return random webm from csgoanime.
See also: img
"""
last_dt = bot.store.get('webm_dt')
if last_dt is not None and float(last_dt.decode()) > time.time() - 60:
return 'Let me get some rest.'
bot.store.set('webm_dt', time.time())
chat_id = kwargs.get('chat_id')
resp = requests.get('http://csgoani.me')
if resp.status_code != 200:
return 'Error getting data'
urls = re.findall(r'http.*\.webm', resp.content.decode())
print(urls)
if not urls:
return 'Error getting data'
url = urls[0]
file_id = bot.store.get(url)
data = {'chat_id': chat_id, 'disable_notification': True}
if file_id:
data.update(video=file_id)
files = None
else:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import re
import time
import requests
from moviepy.editor import *
from modules.utils.data import download_file
and context:
# Path: modules/utils/data.py
# def download_file(url, max_length=20 * 1024 * 1024, headers={}):
# try:
# length = requests.head(url).headers.get('content-length', 0)
# if int(length) > max_length:
# return
# r = requests.get(url, timeout=(1, 3), stream=True, headers=headers)
# ext = url.rsplit('.', 1)[1]
# file_name = '{}.{}'.format(uuid.uuid4(), ext)
# with open(file_name, 'wb') as f:
# shutil.copyfileobj(r.raw, f)
# return file_name
# except RequestException:
# return
which might include code, classes, or functions. Output only the next line. | file_name = download_file(url, headers={'Referer': resp.url}) |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
class UtilsTestCase(unittest.TestCase):
def test_clean_text_should_remove_inappropriate_chars(self):
line = u'This :;requirement? # !is @only = $necessary %when ^you &place *your (1st ;order |with us, Mr -. а также кириллица 何か'
expected = u'This requirement is only necessary when you place your 1st order with us, Mr -. а также кириллица 何か'
<|code_end|>
, predict the next line using imports from the current file:
import unittest
from modules.utils import text
and context including class names, function names, and sometimes code from other files:
# Path: modules/utils/text.py
# def clean_text(text):
. Output only the next line. | self.assertEqual(text.clean_text(line), expected) |
Here is a snippet: <|code_start|> set(re.findall("/files/thumb/.*?.jpg", response.content.decode('utf-8'))))
matricies = list(
map(lambda x: 'https://picachoo.ru{}'.format(x.replace('/thumb', '')), matricies))
bot.store.set('picachoo_matricies', json.dumps(matricies))
curr_page += 1
curr_index = 0
if not user_page is None and not user_index is None:
curr_index = user_index % len(matricies)
try:
matrix = matricies[curr_index]
except IndexError:
return 'Page not found'
ext = matrix.split('.')[2]
chat_id = kwargs.pop('chat_id')
bot.pre_send(chat_id=chat_id, action='upload_photo')
if user_page is None and user_index is None:
bot.store.set('picachoo_index', curr_index + 1)
bot.store.set('picachoo_page', curr_page)
bot.call(
'sendPhoto',
'POST',
data={'chat_id': chat_id},
files={'photo': (
'file.{}'.format(ext),
<|code_end|>
. Write the next line using the current file imports:
import re
import requests
import json
from modules.utils.data import prepare_binary_from_url
and context from other files:
# Path: modules/utils/data.py
# def prepare_binary_from_url(url, verify=True):
# try:
# content = requests.get(url, timeout=(1, 3), verify=verify).content
# except RequestException:
# pass
# else:
# return BytesIO(content)
, which may include functions, classes, or code. Output only the next line. | prepare_binary_from_url(matrix, verify=False), |
Continue the code snippet: <|code_start|>
async def main(bot, *args, **kwargs):
update = kwargs.get('update', {})
message_id = update.get('message', {}).get('message_id')
# message_id is always even for one-to-one chats and odd for group chats, so let's calculate hash instead of returning raw value
roll_id = int(hashlib.sha1(str(message_id).encode('utf-8')).hexdigest(), 16) % (10 ** 8)
<|code_end|>
. Use current file imports:
import hashlib
from modules.utils import http
and context (classes, functions, or code) from other files:
# Path: modules/utils/http.py
# async def pre_send(bot, chat_id: Optional[str]=None, action: str='typing') -> None:
# async def send(bot, chat_id: Optional[str]=None, text: Optional[str]=None, data: dict={}) -> None:
# async def call(bot, method_name: str, http_method: str, **kwargs):
# async def perform_request(url, method, params={}):
. Output only the next line. | await http.send(bot, chat_id=kwargs.get('chat_id'), text=str(roll_id), data={'reply_to_message_id': message_id}) |
Given the code snippet: <|code_start|>
async def main(bot, *args, **kwargs):
"""
bm
Random news from http://breakingmad.me/
"""
news_id = random.randint(3,9524)
try:
<|code_end|>
, generate the next line using the imports in this file:
import json
import random
import sys
import re
from modules.utils import http
and context (functions, classes, or occasionally code) from other files:
# Path: modules/utils/http.py
# async def pre_send(bot, chat_id: Optional[str]=None, action: str='typing') -> None:
# async def send(bot, chat_id: Optional[str]=None, text: Optional[str]=None, data: dict={}) -> None:
# async def call(bot, method_name: str, http_method: str, **kwargs):
# async def perform_request(url, method, params={}):
. Output only the next line. | response_body = await http.perform_request("http://breakingmad.me/ru/{}.json".format(news_id), 'GET') |
Given snippet: <|code_start|>
async def main(bot, *args, **kwargs):
"""
bash [query]
Search for quote on http://bash.im/
If no query specified, return random quote.
"""
path = 'index' if args else 'random'
params = {'text': ' '.join(args).encode('windows-1251')} if args else {}
url = 'http://bash.im/{}'.format(path)
try:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import random
import sys
from lxml import html
from modules.utils import http
and context:
# Path: modules/utils/http.py
# async def pre_send(bot, chat_id: Optional[str]=None, action: str='typing') -> None:
# async def send(bot, chat_id: Optional[str]=None, text: Optional[str]=None, data: dict={}) -> None:
# async def call(bot, method_name: str, http_method: str, **kwargs):
# async def perform_request(url, method, params={}):
which might include code, classes, or functions. Output only the next line. | response_body = await http.perform_request(url, 'GET', params=params) |
Here is a snippet: <|code_start|>
def main(bot, message, update, *args, **kwargs):
chat_id = kwargs.get('chat_id')
message = message.strip()
message_id = update.get('message', {}).get('message_id')
for url in re.findall(r'http.*\.webm', message):
file_id = bot.store.get(url)
data = {
'chat_id': chat_id,
'reply_to_message_id': message_id,
'disable_notification': True
}
if file_id:
data.update(video=file_id)
files = None
else:
<|code_end|>
. Write the next line using the current file imports:
import os
import re
from moviepy.editor import *
from modules.utils.data import download_file
and context from other files:
# Path: modules/utils/data.py
# def download_file(url, max_length=20 * 1024 * 1024, headers={}):
# try:
# length = requests.head(url).headers.get('content-length', 0)
# if int(length) > max_length:
# return
# r = requests.get(url, timeout=(1, 3), stream=True, headers=headers)
# ext = url.rsplit('.', 1)[1]
# file_name = '{}.{}'.format(uuid.uuid4(), ext)
# with open(file_name, 'wb') as f:
# shutil.copyfileobj(r.raw, f)
# return file_name
# except RequestException:
# return
, which may include functions, classes, or code. Output only the next line. | file_name = download_file(url) |
Given the code snippet: <|code_start|>
async def main(bot, *args, **kwargs):
"""
usd
Get latest USD/RUB quote
"""
try:
url = 'https://ru.investing.com/currencies/usd-rub'
<|code_end|>
, generate the next line using the imports in this file:
from modules.utils import http
from lxml import html
and context (functions, classes, or occasionally code) from other files:
# Path: modules/utils/http.py
# async def pre_send(bot, chat_id: Optional[str]=None, action: str='typing') -> None:
# async def send(bot, chat_id: Optional[str]=None, text: Optional[str]=None, data: dict={}) -> None:
# async def call(bot, method_name: str, http_method: str, **kwargs):
# async def perform_request(url, method, params={}):
. Output only the next line. | response_body = await http.perform_request(url, 'GET') |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
class BaseModuleTestCase(unittest.TestCase):
def setUp(self):
self.bot = MagicMock()
class UserCowsayTestCase(BaseModuleTestCase):
@patch('os.popen')
def test_run_module_with_args_should_call_bot_send(self, popen):
user_cowsay.main(self.bot, 'test', 'message')
self.assertEqual(self.bot.send.call_count, 1)
def test_run_module_without_args_should_return_none(self):
user_cowsay.main(self.bot)
self.assertEqual(self.bot.send.call_count, 0)
class UserDateTestCase(BaseModuleTestCase):
@freeze_time('2015-12-14 12:13:14')
def test_run_module_without_args_should_return_current_datetime(self):
<|code_end|>
with the help of current file imports:
import unittest
from unittest.mock import patch, MagicMock
from freezegun import freeze_time
from modules.utils import text
from modules import user_cowsay, user_date, user_g
and context from other files:
# Path: modules/utils/text.py
# def clean_text(text):
#
# Path: modules/user_date.py
# async def main(bot, *args, **kwargs):
#
# Path: modules/user_g.py
# def main(bot, *args, **kwargs):
, which may contain function names, class names, or code. Output only the next line. | self.assertEqual(user_date.main(self.bot), '2015-12-14 12:13:14') |
Predict the next line for this snippet: <|code_start|>class UserCowsayTestCase(BaseModuleTestCase):
@patch('os.popen')
def test_run_module_with_args_should_call_bot_send(self, popen):
user_cowsay.main(self.bot, 'test', 'message')
self.assertEqual(self.bot.send.call_count, 1)
def test_run_module_without_args_should_return_none(self):
user_cowsay.main(self.bot)
self.assertEqual(self.bot.send.call_count, 0)
class UserDateTestCase(BaseModuleTestCase):
@freeze_time('2015-12-14 12:13:14')
def test_run_module_without_args_should_return_current_datetime(self):
self.assertEqual(user_date.main(self.bot), '2015-12-14 12:13:14')
def test_run_module_with_args_should_return_dating_text(self):
self.assertEqual(user_date.main(self.bot, 'username'), 'обдумав свои чувства, пригласил на свидание username')
class UserGoogleTestCase(BaseModuleTestCase):
def setUp(self):
super(UserGoogleTestCase, self).setUp()
self.bot.settings.google_api_key = 'api-key'
@patch('modules.user_g.requests.get', lambda *args, **kwargs: MagicMock(content=b'{"responseData": {"results": [{"titleNoFormatting": "hello", "content": "content <b>of the</b> result", "url": "http://example.com"}]}}'))
def test_run_module_with_args_should_return_search_result(self):
<|code_end|>
with the help of current file imports:
import unittest
from unittest.mock import patch, MagicMock
from freezegun import freeze_time
from modules.utils import text
from modules import user_cowsay, user_date, user_g
and context from other files:
# Path: modules/utils/text.py
# def clean_text(text):
#
# Path: modules/user_date.py
# async def main(bot, *args, **kwargs):
#
# Path: modules/user_g.py
# def main(bot, *args, **kwargs):
, which may contain function names, class names, or code. Output only the next line. | self.assertEqual(user_g.main(self.bot, 'green', 'apples'), 'hello\ncontent of the result\nhttp://example.com') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.